import { EventsAPI, InvokeOptions, PermissionSpec, ExecutionTarget, InvokeAPI, PlatformServices, PluginContextDescriptor, UIFacade, RunResult } from '@kb-labs/plugin-contracts'; import { IResourceBroker } from '@kb-labs/core-resource-broker'; import { AdapterMiddlewareDecl } from '@kb-labs/core-platform'; /** * Events API implementation */ /** * Event emitter function type */ type EventEmitterFn = (event: string, payload?: unknown) => Promise; interface CreateEventsAPIOptions { pluginId: string; emitter: EventEmitterFn; } /** * Create EventsAPI for publishing events */ declare function createEventsAPI(options: CreateEventsAPIOptions): EventsAPI; /** * Create a no-op events API (for when events are disabled) */ declare function createNoopEventsAPI(): EventsAPI; /** * Invoke API implementation */ /** * Plugin invoker function type */ type PluginInvokerFn = (pluginId: string, input?: unknown, options?: InvokeOptions) => Promise; interface CreateInvokeAPIOptions { permissions: PermissionSpec; invoker: PluginInvokerFn; auditTargetExecution?: (params: { method: 'invoke'; target: ExecutionTarget; targetPluginId: string; }) => Promise | void; } /** * Create InvokeAPI for calling other plugins */ declare function createInvokeAPI(options: CreateInvokeAPIOptions): InvokeAPI; /** * Create a no-op invoke API (for when invoke is disabled) */ declare function createNoopInvokeAPI(): InvokeAPI; /** Wrap an adapter instance with additional behaviour. Returns the wrapped adapter. */ type AdapterMiddlewareFn = (adapter: T, ctx: MiddlewareContext) => T; interface MiddlewareContext { readonly permissions: PermissionSpec; readonly pluginId: string; readonly lifecycle: AdapterLifecycle; } /** Lifecycle hooks available to middleware. Registered during wrap(), called by the platform. */ interface AdapterLifecycle { onReady(fn: () => void | Promise): void; onDispose(fn: () => void | Promise): void; /** Subscribe to a platform lifecycle event (e.g. 'resource-broker:quota-reset:llm'). */ on(event: string, fn: (...args: unknown[]) => void): void; } /** * Platform adapter pipeline. * * Two phases: * 1. assemblePlatform() — system-level: broker → analytics → router → PII (once at startup) * 2. applyPluginGovernance() — per-plugin: adapter middlewares → governance (per context) */ /** Minimal logger shape required for diagnostic emission. Structurally compatible with ILogger. */ interface DiagLogger { debug(msg: string, meta?: Record): void; } /** * Per-adapter router configuration, keyed by adapter name. * Passed to `routerFactory` when building the platform-level pipeline. */ type PlatformConfig = Partial>; /** * A resolved adapter middleware, ready to be applied in the pipeline. * Loader resolves the handler module and populates this from AdapterMiddlewareDecl. */ interface LoadedMiddleware { /** Source declaration (from AdapterManifest). */ readonly decl: AdapterMiddlewareDecl; /** Resolved wrap function. */ readonly fn: AdapterMiddlewareFn; } /** * Build the platform-level pipeline for all adapters (once at startup). * * Applies four factory stages from ADAPTER_REGISTRY in order, for each adapter: * 1. resourceBrokerFactory — innermost: rate limiting / queuing (e.g. QueuedLLM) * 2. analyticsFactory — wraps queue so tracking fires before enqueue * 3. routerFactory — outermost routing layer (e.g. LLMRouter with tier dispatch) * 4. postAssemblyFactory — outermost wrap (e.g. PII redaction) * * Stage order rationale: QueuedLLM.complete() routes through broker.enqueue() → executor, * NOT through this.realLLM. The executor is registered before assembly with the raw adapter. * If analytics/router wrap the raw adapter BEFORE QueuedLLM wraps them, those wrappers * are bypassed for complete() calls (executor captures raw). By making broker innermost, * analytics and router correctly intercept every call before it reaches the queue. * * Analytics instance is taken from `raw.analytics` — set it in the container * before calling this function. * * The result is a fully assembled PlatformServices that can be passed to * `applyPluginGovernance()` for each plugin. * * @param raw - Raw platform services (analytics must already be set) * @param config - Per-adapter config keyed by adapter name * @param broker - ResourceBroker instance for rate limiting / queuing */ declare function assemblePlatform(raw: PlatformServices, config: PlatformConfig, broker: IResourceBroker, diagLogger?: DiagLogger): PlatformServices; /** * Sandbox runner for executing plugins * * Supports two modes: * - In-process: For trusted plugins or development * - Subprocess: For sandboxed execution * * Runner layer is host-agnostic - it returns RunResult with raw data. * Host layer (CLI, REST, etc.) wraps this into host-specific format. */ interface RunInProcessOptions { descriptor: PluginContextDescriptor; platform: PlatformServices; ui: UIFacade; pluginInvoker?: PluginInvokerFn; eventEmitter?: EventEmitterFn; handlerPath: string; input: unknown; signal?: AbortSignal; cwd: string; outdir?: string; /** Resolved adapter middlewares to apply before governance. */ adapterMiddlewares?: LoadedMiddleware[]; } interface RunInSubprocessOptions { descriptor: PluginContextDescriptor; socketPath: string; platformAuthToken?: string; handlerPath: string; input: unknown; timeoutMs?: number; signal?: AbortSignal; cwd: string; outdir?: string; onLog?: (entry: { level: string; message: string; stream: 'stdout' | 'stderr'; lineNo: number; timestamp: string; meta?: Record; }) => void; } /** * Run plugin handler in the current process (no sandbox) * * Returns raw handler result wrapped in RunResult with execution metadata. * Host layer is responsible for transforming this into host-specific format. * * @returns RunResult with raw data from handler and execution metadata */ declare function runInProcess(options: RunInProcessOptions): Promise>; /** * Run plugin handler in a subprocess (sandboxed) * * Returns raw handler result wrapped in RunResult with execution metadata. * Host layer is responsible for transforming this into host-specific format. * * @returns RunResult with raw data from handler and execution metadata */ declare function runInSubprocess(options: RunInSubprocessOptions): Promise>; export { type AdapterMiddlewareFn as A, type EventEmitterFn as E, type LoadedMiddleware as L, type MiddlewareContext as M, type PluginInvokerFn as P, type RunInProcessOptions as R, type RunInSubprocessOptions as a, runInSubprocess as b, assemblePlatform as c, type PlatformConfig as d, createEventsAPI as e, createInvokeAPI as f, createNoopEventsAPI as g, createNoopInvokeAPI as h, runInProcess as r };