KB LabsDocs

Overview

Last updated April 7, 2026


What @kb-labs/sdk exports and when to import what.

@kb-labs/sdk is the package plugins import from. It's a thin layer over @kb-labs/shared-command-kit, @kb-labs/plugin-contracts, and @kb-labs/perm-presets — mostly re-exports, with a handful of plugin-specific helpers on top.

The SDK groups its surface into five clusters:

  1. Handler definitionsdefineCommand, defineRoute, defineAction, defineWebhook, defineWebSocket.
  2. Runtime hooksusePlatform, useLLM, useCache, useStorage, useConfig, useLogger, useAnalytics, useEmbeddings, useVectorStore.
  3. Manifest helpersdefineManifest, defineCommandFlags, defineFlags.
  4. Permission primitivescombinePermissions(), the eight bundled presets, and the PermissionSpec type.
  5. TypesPluginContextV3, HostContext, ManifestV3, ILLM, ICache, IStorage, and friends.

Everything you need to author a plugin lives under @kb-labs/sdk. You should rarely need to import from the lower-level packages directly.

Handler definitions

One define* helper per host type. Each takes a definition object, validates the host at runtime, and returns a handler the sandbox runner can execute.

TypeScript
import {
  defineCommand,    // CLI commands (also works in workflow host)
  defineRoute,      // REST GET/POST/PUT/PATCH/DELETE routes
  defineAction,     // higher-level action endpoints
  defineWebhook,    // webhook event handlers
  defineWebSocket,  // WS channel handlers
} from '@kb-labs/sdk';

All five produce a handler with an execute(ctx, input) method. The runner imports the file specified in the manifest handler field, takes module.default ?? module, and calls .execute(...). A host guard inside each helper throws if the handler runs from the wrong context — for example, defineCommand refuses anything that isn't ctx.host === 'cli' || ctx.host === 'workflow'.

There are corresponding type guards for runtime host checks:

TypeScript
import { isCLIHost, isRESTHost, isWorkflowHost, isWebhookHost, isWSHost } from '@kb-labs/sdk';

See Commands, Routes, and the other per-host pages for the full shape of each definition.

Runtime hooks

The idiomatic way to talk to platform services from inside a handler. Every hook reads from a single global platform singleton — no context drilling, no dependency injection ceremony.

TypeScript
import {
  usePlatform,        // the whole singleton
  isPlatformConfigured,
  useLLM,             // ILLM | undefined
  isLLMAvailable,
  getLLMTier,
  useCache,           // ICache | undefined
  isCacheAvailable,
  useStorage,         // IStorage | undefined
  useVectorStore,     // IVectorStore | undefined
  isVectorStoreAvailable,
  useEmbeddings,      // IEmbeddings | undefined
  isEmbeddingsAvailable,
  useLogger,          // ILogger (always present)
  useLoggerWithContext,
  useAnalytics,       // IAnalytics | undefined
  trackAnalyticsEvent,
  useConfig,          // Promise<T | undefined>, auto-detected product scope
} from '@kb-labs/sdk';

All service hooks return undefined when the adapter isn't configured. useLogger is the exception — it always returns a logger (the platform provides a fallback). Check availability before using any service hook:

TypeScript
const cache = useCache();
if (cache) {
  const hit = await cache.get<Result>(key);
  if (hit) { return hit; }
}

See Hooks for the full API of every hook.

Manifest helpers

TypeScript
import {
  defineManifest,       // typed ManifestV3 builder
  defineCommandFlags,   // typed flag schemas for cli.commands[i].flags
  defineFlags,          // general-purpose typed flag schema
  generateExamples,     // build `examples: string[]` programmatically
} from '@kb-labs/sdk';

You can write the manifest as a plain object — the helpers exist to keep TypeScript honest. defineCommandFlags is the most commonly used one because it lets you author flags once and get both CLI parsing and type inference.

Permission primitives

All eight presets plus the builder, re-exported from @kb-labs/perm-presets:

TypeScript
import {
  combinePermissions,   // alias for `combine()` builder
  combinePresets,       // convenience: combinePresets(a, b, c)
  minimalPreset,
  gitWorkflowPreset,
  npmPublishPreset,
  fullEnvPreset,
  kbPlatformPreset,
  llmAccessPreset,
  vectorStorePreset,
  ciEnvironmentPreset,
  presets,              // namespace with all presets
  type PermissionPreset,
  type PresetBuilder,
  type PermissionSpec,
} from '@kb-labs/sdk';

The builder is chainable, merges string arrays as sets, and ends with .build() to produce a runtime-format spec ready to drop into your manifest. See Plugins → Permissions for the full model.

Types re-exported

Anything a plugin handler is likely to touch:

TypeScript
import type {
  // Plugin context
  PluginContextV3,
  PluginContextDescriptor,
  HostContext,
  HostType,
  PlatformServices,
  RuntimeAPI,
  PluginAPI,
  CleanupFn,
  // UI
  UIFacade,
  Colors,
  ColorFunction,
  SideBoxOptions,
  OutputSection,
  // Results
  CommandResult,
  // Manifest
  ManifestV3,
  PermissionSpec,
  // Shell
  ShellAPI,
  ExecResult,
  ExecOptions,
  // WebSocket
  WebSocketHostContext,
  WSMessage,
  WSSender,
  WSLifecycleEvent,
  WSInput,
  // Studio
  StudioConfig,
  StudioPageEntry,
  StudioMenuEntry,
  // Data contracts for REST responses
  TableData,
  TableRow,
  SelectData,
  SelectOptionItem,
  MetricData,
  ListData,
  ListItem,
} from '@kb-labs/sdk';

And the adapter interfaces from @kb-labs/core-platform:

TypeScript
import type {
  ILLM,
  LLMOptions,
  LLMResponse,
  LLMMessage,
  LLMTool,
  LLMToolCall,
  IAnalytics,
  IStorage,
  ICache,
  IEmbeddings,
  ILogger,
  IVectorStore,
  LLMTier,           // 'small' | 'medium' | 'large'
  UseLLMOptions,
} from '@kb-labs/sdk';

Other utilities

TypeScript
import {
  // UI primitives (re-exported from @kb-labs/shared-cli-ui)
  useLoader,
  TimingTracker,
  displayArtifacts,
  displayArtifactsCompact,
  displaySingleArtifact,
 
  // Environment schema
  defineEnv,
  parseEnvFromRuntime,
  type EnvSchema,
  type EnvDefinition,
 
  // Errors
  defineError,
  PluginError,
  commonErrors,
 
  // REST handler helpers
  defineHandler,
 
  // Tools (for LLM function-calling)
  createTool,
 
  // Repo introspection (from @kb-labs/core-sys)
  findRepoRoot,
  discoverSubRepoPaths,
 
  // Monitoring (from @kb-labs/core-runtime)
  getMonitoringSnapshot,
  getDegradedStatus,
 
  // Learning stores
  MemoryHistoryStore,
  MemoryFeedbackStore,
  FileHistoryStore,
  FileFeedbackStore,
} from '@kb-labs/sdk';

useLoader() is the spinner primitive used by every first-party plugin for "Generating commit plan…" style feedback. findRepoRoot() walks up from ctx.cwd until it hits a git repo — handy because ctx.cwd can be a nested subrepo in monorepo setups.

Test utilities

TypeScript
import { createTestContext } from '@kb-labs/sdk';

A minimal PluginContextV3 factory for unit tests. For full mock builders (stub LLM responses, assertions on platform calls, etc.), import from the @kb-labs/sdk/testing entrypoint instead. See Testing.

What's NOT in the SDK

  • defineJob, defineCron, defineWorkflow helpers — job/cron/workflow handlers are defined the same way as other handlers but there's no dedicated helper yet. Use the underlying CommandHandlerV3 interface directly.
  • Direct adapter construction. If you need to instantiate an OpenAIAdapter with custom options, that's an adapter concern — import from @kb-labs/adapters-llm-openai directly. The SDK only re-exports interfaces, not implementations.
  • HTTP clients for the REST API. If you're building a product that calls KB Labs (not a plugin that runs inside it), use the Product SDK instead.

Versioning

The SDK entrypoint — @kb-labs/sdk — is backward-compatible within a major version. The current line is 2.x; additions ship as minor releases, breaking changes wait for a major bump and get a migration note in Migration Guide.

Reading order

If you're learning the SDK:

  1. Quickstart — the smallest possible plugin.
  2. CommandsdefineCommand, flags, handler lifecycle.
  3. Hooks — the platform service surface.
  4. Handler Context — everything in ctx.
  5. LLM Tiers — when to use small, medium, large.
  6. TestingcreateTestContext and mock builders.