import { CleanupFn, LifecycleAPI, Logger, CacheAdapter, StateAPI, ArtifactsAPI, PermissionSpec, ShellAPI, WorkflowsAPI, ExecutionTarget, JobsAPI, EnvironmentCreateRequest, EnvironmentInfo, EnvironmentStatusInfo, EnvironmentLeaseInfo, EnvironmentAPI, WorkspaceAPI, WorkspaceMaterializeRequest, WorkspaceInfo, WorkspaceAttachRequest, WorkspaceAttachmentInfo, WorkspaceStatusInfo, SnapshotAPI, SnapshotCaptureRequest, SnapshotInfo, SnapshotRestoreRequest, SnapshotRestoreInfo, SnapshotStatusInfo, SnapshotGarbageCollectRequest, SnapshotGarbageCollectInfo, PluginAPI, PluginContextDescriptor, PlatformServices, UIFacade, PluginContextV3, TraceContext, FSShim, FetchShim, EnvShim, RuntimeAPI, LLMAdapter, EmbeddingsAdapter, VectorStoreAdapter, StorageAdapter, RunResult, CommandResult, CommandResultWithMeta } from '@kb-labs/plugin-contracts'; export { CleanupFn, CommandError, CommandFailure, CommandResult, CommandResultWithMeta, CommandSuccess, ExecutionMeta, HostContext, HostType, PermissionSpec, PlatformServices, PluginAPI, PluginContextDescriptor, PluginContextV3, PluginServices, RunResult, RuntimeAPI, Spinner, StandardMeta, TraceContext, UIFacade } from '@kb-labs/plugin-contracts'; import { E as EventEmitterFn, P as PluginInvokerFn, L as LoadedMiddleware, c as assemblePlatform, A as AdapterMiddlewareFn, M as MiddlewareContext } from './runner-B7GNc6fB.js'; export { d as PlatformConfig, R as RunInProcessOptions, a as RunInSubprocessOptions, e as createEventsAPI, f as createInvokeAPI, g as createNoopEventsAPI, h as createNoopInvokeAPI, r as runInProcess, b as runInSubprocess } from './runner-B7GNc6fB.js'; import * as _kb_labs_core_platform from '@kb-labs/core-platform'; import { IWorkflowEngine, RawMiddlewareDecl, ILogger as ILogger$1, ILLM, IAnalytics, AnalyticsLLM, IEmbeddings, AnalyticsEmbeddings, IVectorStore, AnalyticsVectorStore, AnalyticsCache, AnalyticsStorage, INotifier } from '@kb-labs/core-platform'; export { RawMiddlewareDecl } from '@kb-labs/core-platform'; import * as _kb_labs_core_platform_adapters from '@kb-labs/core-platform/adapters'; import { IProcessExecutor, ProcessExecutionIdentity, ILogger, ProcessBackendCapabilities, GovernedProcessRequest, ProcessResult, IDocumentDatabase, IKVStore } from '@kb-labs/core-platform/adapters'; import * as _kb_labs_core_ipc from '@kb-labs/core-ipc'; import { LLMProxy, EmbeddingsProxy, VectorStoreProxy, CacheProxy, StorageProxy, EventBusProxy, ConfigProxy, DocumentDatabaseProxy, KVStoreProxy } from '@kb-labs/core-ipc'; import * as _kb_labs_core_resource_broker from '@kb-labs/core-resource-broker'; import { IResourceBroker } from '@kb-labs/core-resource-broker'; import { LLMRouter } from '@kb-labs/llm-router'; /** * Lifecycle API implementation */ /** * Create LifecycleAPI with cleanup stack */ declare function createLifecycleAPI(cleanupStack: Array): LifecycleAPI; /** * Execute cleanup functions in LIFO order */ declare function executeCleanup(cleanupStack: Array, logger: Logger, timeoutMs?: number): Promise; /** * State API implementation */ interface CreateStateAPIOptions { pluginId: string; tenantId?: string; cache: CacheAdapter; } /** * Create StateAPI with tenant-aware key prefixing */ declare function createStateAPI(options: CreateStateAPIOptions): StateAPI; /** * Artifacts API implementation */ interface CreateArtifactsAPIOptions { outdir: string; } /** * Create ArtifactsAPI for managing output files */ declare function createArtifactsAPI(options: CreateArtifactsAPIOptions): ArtifactsAPI; /** Governed ShellAPI facade. Native spawning belongs to IProcessExecutor. */ interface CreateShellAPIOptions { permissions: PermissionSpec; cwd: string; processExecutor?: IProcessExecutor; processIdentity?: ProcessExecutionIdentity; signal?: AbortSignal; } declare function createShellAPI(options: CreateShellAPIOptions): ShellAPI; /** * Workflows API implementation * * Adapter from simplified WorkflowsAPI to full IWorkflowEngine interface. */ interface CreateWorkflowsAPIOptions { tenantId?: string; engine: IWorkflowEngine; permissions?: PermissionSpec; auditTargetExecution?: (params: { method: 'workflow'; target: ExecutionTarget; workflowId: string; }) => Promise | void; } /** * Create WorkflowsAPI adapter * * Maps simplified plugin API to full workflow engine interface. */ declare function createWorkflowsAPI(options: CreateWorkflowsAPIOptions): WorkflowsAPI; /** * Create a no-op workflows API (for when workflow engine is not available) */ declare function createNoopWorkflowsAPI(): WorkflowsAPI; /** * Jobs API implementation * * HTTP client adapter for Workflow Service Jobs API. * Makes REST API calls instead of in-process manager calls. */ interface CreateJobsAPIOptions { tenantId?: string; workflowServiceUrl: string; permissions?: PermissionSpec; } /** * Create JobsAPI HTTP client * * Makes REST API calls to Workflow Service instead of in-process calls. */ declare function createJobsAPI(options: CreateJobsAPIOptions): JobsAPI; /** * Create noop JobsAPI (when job scheduler is not available) */ declare function createNoopJobsAPI(): JobsAPI; /** * Environment API implementation. * * Adapter from plugin-facing EnvironmentAPI to runtime EnvironmentManager. */ interface EnvironmentManagerClient { createEnvironment(request: EnvironmentCreateRequest): Promise; getEnvironmentStatus(environmentId: string): Promise; destroyEnvironment(environmentId: string, reason?: string): Promise; renewEnvironmentLease(environmentId: string, ttlMs: number): Promise; } interface CreateEnvironmentAPIOptions { permissions?: PermissionSpec; manager: EnvironmentManagerClient; } /** * Create plugin EnvironmentAPI backed by runtime EnvironmentManager. */ declare function createEnvironmentAPI(options: CreateEnvironmentAPIOptions): EnvironmentAPI; /** * Create noop EnvironmentAPI (when environment manager is not available). */ declare function createNoopEnvironmentAPI(): EnvironmentAPI; /** * Workspace API implementation. * * Adapter from plugin-facing WorkspaceAPI to runtime WorkspaceManager. */ interface WorkspaceManagerClient { materializeWorkspace(request: WorkspaceMaterializeRequest): Promise; attachWorkspace(request: WorkspaceAttachRequest): Promise; releaseWorkspace(workspaceId: string, environmentId?: string): Promise; getWorkspaceStatus(workspaceId: string): Promise; } interface CreateWorkspaceAPIOptions { permissions?: PermissionSpec; manager: WorkspaceManagerClient; } /** * Create plugin WorkspaceAPI backed by runtime WorkspaceManager. */ declare function createWorkspaceAPI(options: CreateWorkspaceAPIOptions): WorkspaceAPI; /** * Create noop WorkspaceAPI (when workspace manager is not available). */ declare function createNoopWorkspaceAPI(): WorkspaceAPI; /** * Snapshot API implementation. * * Adapter from plugin-facing SnapshotAPI to runtime SnapshotManager. */ interface SnapshotManagerClient { captureSnapshot(request: SnapshotCaptureRequest): Promise; restoreSnapshot(request: SnapshotRestoreRequest): Promise; getSnapshotStatus(snapshotId: string): Promise; deleteSnapshot(snapshotId: string): Promise; garbageCollectSnapshots(request?: SnapshotGarbageCollectRequest): Promise; } interface CreateSnapshotAPIOptions { permissions?: PermissionSpec; manager: SnapshotManagerClient; } /** * Create plugin SnapshotAPI backed by runtime SnapshotManager. */ declare function createSnapshotAPI(options: CreateSnapshotAPIOptions): SnapshotAPI; /** * Create noop SnapshotAPI (when snapshot manager is not available). */ declare function createNoopSnapshotAPI(): SnapshotAPI; /** * Plugin API implementations */ interface CreatePluginAPIOptions { pluginId: string; handlerId?: string; tenantId?: string; cwd: string; outdir: string; permissions: PermissionSpec; processExecutor?: IProcessExecutor; processIdentity?: ProcessExecutionIdentity; signal?: AbortSignal; cache: CacheAdapter; eventEmitter?: EventEmitterFn; pluginInvoker?: PluginInvokerFn; workflowEngine?: IWorkflowEngine; /** * Workflow Service base URL for Jobs/Cron HTTP APIs * @example "http://localhost:3000" */ workflowServiceUrl?: string; /** * Environment manager facade for long-lived environment lifecycle operations. */ environmentManager?: { createEnvironment(request: EnvironmentCreateRequest): Promise; getEnvironmentStatus(environmentId: string): Promise; destroyEnvironment(environmentId: string, reason?: string): Promise; renewEnvironmentLease(environmentId: string, ttlMs: number): Promise; }; /** * Workspace manager facade for workspace lifecycle operations. */ workspaceManager?: { materializeWorkspace(request: WorkspaceMaterializeRequest): Promise; attachWorkspace(request: WorkspaceAttachRequest): Promise; releaseWorkspace(workspaceId: string, environmentId?: string): Promise; getWorkspaceStatus(workspaceId: string): Promise; }; /** * Snapshot manager facade for snapshot lifecycle operations. */ snapshotManager?: { captureSnapshot(request: SnapshotCaptureRequest): Promise; restoreSnapshot(request: SnapshotRestoreRequest): Promise; getSnapshotStatus(snapshotId: string): Promise; deleteSnapshot(snapshotId: string): Promise; garbageCollectSnapshots(request?: SnapshotGarbageCollectRequest): Promise; }; analytics?: { track(event: string, properties?: Record): Promise; }; eventBus?: { publish(topic: string, event: T): Promise; }; logger?: { debug?: (message: string, meta?: Record) => void; warn?: (message: string, meta?: Record) => void; }; cleanupStack: Array; } /** * Create the complete PluginAPI */ declare function createPluginAPI(options: CreatePluginAPIOptions): PluginAPI; /** * Plugin Context Factory * * Creates the full PluginContextV3 from a descriptor and platform services. */ interface CreateContextOptions { /** * Plugin context descriptor (from IPC) */ descriptor: PluginContextDescriptor; /** * Platform services */ platform: PlatformServices; /** * UI facade for output */ ui: UIFacade; /** * Abort signal for cancellation */ signal?: AbortSignal; /** * Event emitter function (optional) */ eventEmitter?: EventEmitterFn; /** * Plugin invoker function (optional) */ pluginInvoker?: PluginInvokerFn; /** * Current working directory (from WorkspaceLease) */ cwd: string; /** * Output directory for artifacts (optional) */ outdir?: string; /** * Resolved adapter middlewares from loaded adapter manifests. * Applied in slot/priority order before system governance. */ adapterMiddlewares?: LoadedMiddleware[]; } interface CreateContextResult { /** * The created context */ context: PluginContextV3; /** * Cleanup stack (for executing cleanups after handler completes) */ cleanupStack: Array; /** * Request ID for this execution */ requestId: string; /** * Trace ID (propagated or new) */ traceId: string; /** * Span ID (unique to this execution) */ spanId: string; } /** * Create a full PluginContextV3 */ declare function createPluginContextV3(options: CreateContextOptions): CreateContextResult; /** * TraceContext implementation */ interface CreateTraceContextOptions { traceId: string; spanId: string; parentSpanId?: string; logger: Logger; } /** * Create a TraceContext implementation */ declare function createTraceContext(options: CreateTraceContextOptions): TraceContext; /** * Streaming UI — wraps UIFacade to also emit log lines through eventEmitter. * * Used in workflow context to stream plugin UI output to clients in real-time. * When eventEmitter is provided (workflow host), every info/success/warn/error/write call * also fires a 'log.line' event that flows through: * eventEmitter → onLog callback → EventBus → SSE → Studio/CLI * * Symmetric to StreamingLogger but for UI output. */ declare function createStreamingUI(base: UIFacade, emitter: EventEmitterFn): UIFacade; /** * Sandboxed filesystem implementation * * Security model: * - Plugins declare what they WANT in manifest (allow-list) * - Platform enforces hardcoded security patterns (deny-list below) * - Users can further restrict via kb.config.json (future) */ interface CreateFSShimOptions { permissions: PermissionSpec; cwd: string; outdir?: string; } /** * Create a sandboxed filesystem shim */ declare function createFSShim(options: CreateFSShimOptions): FSShim; /** * Sandboxed fetch implementation with URL whitelist */ interface CreateFetchShimOptions { permissions: PermissionSpec; } /** * Create a sandboxed fetch with URL whitelist */ declare function createFetchShim(options: CreateFetchShimOptions): FetchShim; /** * Sandboxed environment variable access */ interface CreateEnvShimOptions { permissions: PermissionSpec; } /** * Create a sandboxed env access function * * Non-whitelisted vars return undefined (no error thrown). */ declare function createEnvShim(options: CreateEnvShimOptions): EnvShim; /** * Runtime shims for sandboxed plugin execution */ interface CreateRuntimeAPIOptions { permissions: PermissionSpec; cwd: string; outdir?: string; } /** * Create the complete RuntimeAPI with all shims */ declare function createRuntimeAPI(options: CreateRuntimeAPIOptions): RuntimeAPI; /** * ID generation utilities */ /** * Generate a unique ID (16 bytes hex = 32 chars) */ declare function createId(): string; /** * Generate a short ID (8 bytes hex = 16 chars) */ declare function createShortId(): string; /** * Extract trace ID from a composite request ID * Format: {traceId}:{spanId} */ declare function extractTraceId(requestId: string): string; /** * Create a composite request ID from trace and span IDs */ declare function createRequestId(traceId: string, spanId: string): string; interface ProcessSnapshot { cpuMs: number; memoryMb: number; processCount: number; } declare abstract class NodeProcessBackend implements IProcessExecutor { private readonly logger?; protected readonly active: Set; private readonly cancellers; private shuttingDown; constructor(logger?: ILogger | undefined); abstract capabilities(): ProcessBackendCapabilities; protected configureProcess(_pid: number, _request: GovernedProcessRequest): () => void; private treePids; protected snapshot(pid: number): ProcessSnapshot; execute(request: GovernedProcessRequest): Promise; private runOnce; cancel(processId: string, reason?: 'cancelled' | 'shutdown'): Promise; shutdown(): Promise; } declare class DarwinProcessBackend extends NodeProcessBackend { capabilities(): ProcessBackendCapabilities; } declare class LinuxProcessBackend extends NodeProcessBackend { private readonly cgroupRoot; private cgroupAvailable; capabilities(): ProcessBackendCapabilities; protected configureProcess(pid: number, request: GovernedProcessRequest): () => void; } type ProcessErrorCode = 'PROCESS_TIMEOUT' | 'PROCESS_CANCELLED' | 'PROCESS_MEMORY_LIMIT' | 'PROCESS_CPU_LIMIT' | 'PROCESS_LIMIT' | 'PROCESS_OUTPUT_LIMIT' | 'PROCESS_ADMISSION_TIMEOUT' | 'PROCESS_SPAWN_FAILED'; declare class GovernedProcessError extends Error { readonly code: ProcessErrorCode; readonly details: Record; constructor(code: ProcessErrorCode, message: string, details?: Record); } /** Adds ResourceBroker admission around the OS executor without changing ShellAPI. */ declare class BrokeredProcessExecutor implements IProcessExecutor { private readonly broker; private readonly delegate; private readonly logger?; constructor(broker: IResourceBroker, delegate: IProcessExecutor, logger?: ILogger | undefined); capabilities(): _kb_labs_core_platform_adapters.ProcessBackendCapabilities; execute(request: GovernedProcessRequest): Promise; shutdown(): Promise; cancel(processId: string, reason?: 'cancelled' | 'shutdown'): Promise; } declare function createDefaultProcessExecutor(logger?: ILogger): IProcessExecutor; /** * Governed Platform Services * * Backward-compatible entry point. All logic lives in pipeline.ts + adapter-registry.ts. */ /** * @deprecated Use applyPluginGovernance() from pipeline.ts directly. * Kept for backward compatibility. */ declare function createGovernedPlatformServices(raw: PlatformServices, permissions: PermissionSpec, pluginId: string): PlatformServices; /** * Resolve raw middleware declarations into loaded middleware functions. * * Called once per InProcessBackend and cached; not called on every plugin execution. * Skips entries where the handler file cannot be imported (logs a warning, does not throw). */ declare function resolveAdapterMiddlewares(rawDecls: RawMiddlewareDecl[], logger?: { warn(msg: string, meta?: Record): void; }): Promise; /** * Returns the assemblyHook required by launchPlatform() and runService(). * * Wraps raw platform adapters with the full assembly pipeline: * resourceBrokerFactory → analyticsFactory → routerFactory → postAssemblyFactory * * @param getLogger - Optional lazy getter for a diagnostic logger. Evaluated * at hook execution time (during initPlatform), not at call time. Pass * `() => platform.logger` to emit assembly diagnostics when KB_DEBUG=true. * Services that don't need assembly diagnostics can omit this. * * Pass the result as `assemblyHook` in PlatformLaunchOptions or ServiceConfig. * Sandbox IPC workers that call initPlatform directly do not need this. */ declare function makeAssemblyHook(getLogger?: () => Parameters[3]): (raw: object, broker: unknown, cfg: Partial>) => Partial>; /** * Single source of truth for all platform adapters. * * Adding a new field to PluginServices causes a compile error here. * Platform-only fields (e.g. serviceTransport) live in PlatformServices only * and must NOT be in this registry — they are excluded from plugin context. * until a corresponding entry is added. Each entry declares (in pipeline order): * - analyticsFactory: optional tracking wrap (before router) * - routerFactory: optional platform-level routing (LLMRouter, etc.) * - resourceBrokerFactory: optional rate limiting / queuing * - postAssemblyFactory: optional outermost wrap (e.g. PII redaction) * - governance: plugin-level permission enforcement * - ipc: how the adapter crosses the process boundary * * Pipeline per adapter (left → right, applied by assemblePlatform): * raw → [analyticsFactory] → [routerFactory] → [resourceBrokerFactory] → [postAssemblyFactory] → [governance] → plugin */ declare const ADAPTER_REGISTRY: { logger: { governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "local"; }; }; llm: { analyticsFactory: (raw: ILLM, analytics: IAnalytics) => AnalyticsLLM; routerFactory: (raw: ILLM, config: unknown) => LLMRouter; resourceBrokerFactory: (raw: ILLM, broker: unknown) => _kb_labs_core_resource_broker.QueuedLLM; postAssemblyFactory: (raw: ILLM, config: unknown) => LLMAdapter; governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => LLMProxy; }; }; embeddings: { analyticsFactory: (raw: IEmbeddings, analytics: IAnalytics) => AnalyticsEmbeddings; resourceBrokerFactory: (raw: IEmbeddings, broker: unknown) => _kb_labs_core_resource_broker.QueuedEmbeddings; governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => EmbeddingsProxy; }; }; vectorStore: { analyticsFactory: (raw: IVectorStore, analytics: IAnalytics) => AnalyticsVectorStore; resourceBrokerFactory: (raw: IVectorStore, broker: unknown) => _kb_labs_core_resource_broker.QueuedVectorStore; governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => VectorStoreProxy; }; }; cache: { analyticsFactory: (raw: CacheAdapter, analytics: IAnalytics) => AnalyticsCache; governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => CacheProxy; }; }; storage: { analyticsFactory: (raw: StorageAdapter, analytics: IAnalytics) => AnalyticsStorage; governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => StorageProxy; }; }; analytics: { governance: { strategy: "pass-through"; }; ipc: { strategy: "noop"; create: () => { track: () => Promise; identify: () => Promise; flush: () => Promise; }; }; }; eventBus: { governance: { strategy: "pass-through"; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => EventBusProxy; }; }; config: { governance: { strategy: "pass-through"; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => ConfigProxy; }; }; invoke: { governance: { strategy: "pass-through"; }; ipc: { strategy: "noop"; create: () => { call: () => Promise<{ success: false; error: string; }>; isAvailable: () => Promise; }; }; }; documentDatabase: { governance: { strategy: "wrap"; fn: (adapter: any, ctx: MiddlewareContext) => _kb_labs_core_platform.IDocumentDatabase; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => DocumentDatabaseProxy; }; }; kvStore: { governance: { strategy: "wrap"; fn: (adapter: any, ctx: MiddlewareContext) => _kb_labs_core_platform.IKVStore; }; ipc: { strategy: "proxy"; create: (t: _kb_labs_core_ipc.ITransport) => KVStoreProxy; }; }; logs: { governance: { strategy: "pass-through"; }; ipc: { strategy: "noop"; create: () => { query: () => Promise<{ logs: never[]; total: number; hasMore: boolean; source: "buffer"; }>; getById: () => Promise; search: () => Promise<{ logs: never[]; total: number; hasMore: boolean; }>; subscribe: () => () => void; getStats: () => Promise<{}>; getCapabilities: () => { hasBuffer: boolean; hasPersistence: boolean; hasSearch: boolean; hasStreaming: boolean; }; }; }; }; notifier: { governance: { strategy: "wrap"; fn: AdapterMiddlewareFn; }; ipc: { strategy: "absent"; }; }; artifacts: { governance: { strategy: "pass-through"; }; ipc: { strategy: "absent"; }; }; snapshotManager: { governance: { strategy: "pass-through"; }; ipc: { strategy: "absent"; }; }; }; type AdapterRegistryKey = keyof typeof ADAPTER_REGISTRY; declare const ADAPTER_REGISTRY_KEYS: AdapterRegistryKey[]; /** * @module @kb-labs/plugin-runtime/platform/database-governance * * Per-plugin governance for the document database and KV store adapters. * * The platform — not the adapter — owns access control. An adapter receives * the raw `IDocumentDatabase` / `IKVStore` and we wrap it once per plugin * with: * * - **Collection / key namespacing.** Plugin `auth` writing `"users"` * transparently lands on `auth__users`; plugin `billing` writing * `"users"` lands on `billing__users`. Two plugins never collide on * a naive name. For KV the prefix is `:`. * - **Permission enforcement.** Reads are allowed on a collection only * if it's in `owns` or covered by a `read` `access` grant. Writes * require `write`. `ensureCollection` is a separate `ddl` privilege. * Without the corresponding sub-permission the adapter is replaced * with a deny stub. * - **Cross-plugin grants.** An `access` entry references `{collection, * owner, ops}`. The runtime trusts the install-time validator to have * rejected grants without a matching `exports.collections` entry on * the owner manifest; the wrapper itself only enforces the local view. * * Names cannot contain `__` (the namespace separator). `validateName` * rejects them at construction time so a typo can't smuggle a write into * another plugin's namespace. */ /** * Wrap `IDocumentDatabase` for one plugin. Every method maps the * user-visible collection name to the storage name and enforces the * read/write/ddl distinction. * * Returns a deny-stub when the plugin did not declare * `permissions.platform.database.document`. */ declare function wrapDocumentDatabase(raw: IDocumentDatabase, pluginId: string, permissions: PermissionSpec): IDocumentDatabase; /** * Wrap `IKVStore` for one plugin. Keys are transparently prefixed with * `:`. `scan` strips the prefix back off so the plugin sees the * keys it actually wrote. Cross-plugin access is not supported. * * Returns a deny-stub if `permissions.platform.database.kvStore` is absent. */ declare function wrapKVStore(raw: IKVStore, pluginId: string, permissions: PermissionSpec): IKVStore; /** * Result of validating a plugin's database grants against the set of * installed plugins. * * `valid: true` means every cross-plugin `access` entry has a matching * `exports.collections` declaration on the owner with the requested ops. * `valid: false` carries a human-readable list of mismatches. */ interface DatabaseGrantValidation { valid: boolean; errors: string[]; } /** Minimal manifest shape the validator needs — keeps it decoupled from full ManifestV3. */ interface ManifestForGrantValidation { id: string; permissions?: PermissionSpec; exports?: { collections?: Array<{ name: string; ops?: Array<'read' | 'write'>; }>; }; } /** * Validate a candidate plugin's database access grants against the manifests * of every plugin currently in the installation set (including itself). * * Rules enforced: * - Every `access` grant must reference a plugin in `installedPlugins`. * - The referenced plugin must declare a matching `exports.collections` * entry — same `name`, and the export's `ops` must be a superset of the * consumer's requested `ops`. * - The grant's `owner` field must match the manifest id (catches typos * like `auth-svc` vs `auth`). * * Self-grants (owner = candidate.id) are rejected — use `owns` instead. * * The validator is pure: it doesn't touch the filesystem or the runtime. * Plug it into the install pipeline (kb-create install, marketplace * install) to fail-fast before the plugin ever reaches the platform. */ declare function validateDatabaseGrants(candidate: ManifestForGrantValidation, installedPlugins: ReadonlyArray): DatabaseGrantValidation; /** * CLI Host Wrapper * * Transforms RunResult from runner layer into CLI-specific CommandResultWithMeta. */ /** * Wrap RunResult from runner into CLI-specific CommandResultWithMeta * * CLI commands can return either: * - CommandResult with ok, result, meta * - T directly (data only, defaults to exitCode: 0) * - void/undefined (defaults to exitCode: 0) * * @param runResult - Result from runInProcess/runInSubprocess * @param descriptor - Plugin context descriptor for additional metadata * @returns CommandResultWithMeta for CLI consumption */ declare function wrapCliResult(runResult: RunResult | T | void>, descriptor: PluginContextDescriptor): CommandResultWithMeta; /** * REST Host Wrapper * * Transforms RunResult from runner layer into REST-specific response format. */ /** * REST response with optional metadata headers */ interface RestResultWithMeta { /** * Response data (to be serialized as JSON body) */ data: T; /** * Headers to add to response */ headers: { 'X-Plugin-Id': string; 'X-Plugin-Version': string; 'X-Request-Id': string; 'X-Duration-Ms': string; [key: string]: string; }; } /** * Wrap RunResult from runner into REST-specific response * * REST handlers return data directly (T), which becomes the response body. * Execution metadata is exposed via HTTP headers. * * @param runResult - Result from runInProcess/runInSubprocess * @returns RestResultWithMeta with data and metadata headers */ declare function wrapRestResult(runResult: RunResult): RestResultWithMeta; /** * Extract just the data from RunResult (simple case) * * Use when you don't need metadata headers. */ declare function unwrapRestData(runResult: RunResult): T; export { ADAPTER_REGISTRY_KEYS, BrokeredProcessExecutor, type CreateContextOptions, type CreateContextResult, type CreateFSShimOptions, type CreatePluginAPIOptions, type CreateRuntimeAPIOptions, type CreateTraceContextOptions, DarwinProcessBackend, EventEmitterFn, GovernedProcessError, LinuxProcessBackend, LoadedMiddleware, type ManifestForGrantValidation, PluginInvokerFn, type RestResultWithMeta, assemblePlatform, createArtifactsAPI, createDefaultProcessExecutor, createEnvShim, createEnvironmentAPI, createFSShim, createFetchShim, createGovernedPlatformServices, createId, createJobsAPI, createLifecycleAPI, createNoopEnvironmentAPI, createNoopJobsAPI, createNoopSnapshotAPI, createNoopWorkflowsAPI, createNoopWorkspaceAPI, createPluginAPI, createPluginContextV3, createRequestId, createRuntimeAPI, createShellAPI, createShortId, createSnapshotAPI, createStateAPI, createStreamingUI, createTraceContext, createWorkflowsAPI, createWorkspaceAPI, executeCleanup, extractTraceId, makeAssemblyHook, resolveAdapterMiddlewares, unwrapRestData, validateDatabaseGrants, wrapCliResult, wrapDocumentDatabase, wrapKVStore, wrapRestResult };