@kb-labs/core-runtime 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2267 @@
1
+ import { CreateEnvironmentRequest, EnvironmentDescriptor, EnvironmentStatusResult, EnvironmentLease, MaterializeWorkspaceRequest, WorkspaceDescriptor, AttachWorkspaceRequest, WorkspaceAttachment, WorkspaceStatusResult, WorkspaceProviderCapabilities, CaptureSnapshotRequest, SnapshotDescriptor, RestoreSnapshotRequest, RestoreSnapshotResult, SnapshotStatusResult, SnapshotGarbageCollectRequest, SnapshotGarbageCollectResult, SnapshotProviderCapabilities, IExecutionBackend, ExecutionRequest, ExecutionResult, CreateRunRequest, RunRecord, IAnalytics, IVectorStore, ILLM, IEmbeddings, ICache, IConfig, IStorage, ILogger, IEventBus, IInvoke, IArtifacts, ILogReader, IWorkflowEngine, IJobScheduler, ICronManager, IResourceManager, TenantQuotas, ResourceType, ResourceSlot, ResourceAvailability, JobDefinition, JobHandle, CronExpression, JobFilter, CronHandler, CronJob, WorkflowOptions, WorkflowRun, WorkflowFilter, VectorFilter, VectorSearchResult, VectorRecord, LLMOptions, LLMResponse, LLMProtocolCapabilities, LLMMessage, LLMToolCallOptions, LLMToolCallResponse } from '@kb-labs/core-platform';
2
+ import { IResourceBroker, RateLimitConfig, RateLimitPreset } from '@kb-labs/core-resource-broker';
3
+ import { AnalyticsContext, IStorage as IStorage$1, StorageMetadata, ISQLDatabase, SQLQueryResult, SQLTransaction, IDocumentDatabase, BaseDocument, DocumentFilter, FindOptions, DocumentUpdate } from '@kb-labs/core-platform/adapters';
4
+ export { BulkTransfer, BulkTransferHelper, BulkTransferOptions, CircuitOpenError, IPCServer, IPCTransport, ITransport, OPERATION_TIMEOUTS, PendingRequest, TimeoutError, TransportConfig, TransportError, UnixSocketConfig, UnixSocketServer, UnixSocketServerConfig, UnixSocketTransport, createIPCServer, createIPCTransport, createUnixSocketTransport, getOperationTimeout, isRetryableError, selectTimeout } from '@kb-labs/core-ipc';
5
+ import { AdapterCall, AdapterResponse, AdapterType, AdapterCallContext } from '@kb-labs/core-platform/serializable';
6
+ export { createNoOpPlatform } from '@kb-labs/core-platform/noop';
7
+
8
+ /**
9
+ * @module @kb-labs/core-runtime/environment-manager
10
+ * Runtime manager for long-lived environment providers.
11
+ */
12
+
13
+ interface EnvironmentManagerOptions {
14
+ janitorIntervalMs?: number;
15
+ janitorBatchSize?: number;
16
+ }
17
+ /**
18
+ * Environment manager facade over `environment` adapter token.
19
+ *
20
+ * Keeps provider access in one place and centralizes diagnostics.
21
+ */
22
+ declare class EnvironmentManager {
23
+ private readonly platform;
24
+ private readonly store?;
25
+ private readonly janitorIntervalMs;
26
+ private readonly janitorBatchSize;
27
+ private janitorTimer?;
28
+ constructor(platform: Pick<PlatformContainer, 'getAdapter' | 'logger'>, options?: EnvironmentManagerOptions);
29
+ /**
30
+ * Check whether environment provider is configured.
31
+ */
32
+ hasProvider(): boolean;
33
+ /**
34
+ * Create environment using configured provider.
35
+ */
36
+ createEnvironment(request: CreateEnvironmentRequest): Promise<EnvironmentDescriptor>;
37
+ /**
38
+ * Get environment status.
39
+ */
40
+ getEnvironmentStatus(environmentId: string): Promise<EnvironmentStatusResult>;
41
+ /**
42
+ * Destroy environment.
43
+ */
44
+ destroyEnvironment(environmentId: string, reason?: string): Promise<void>;
45
+ /**
46
+ * Renew environment lease if provider supports it.
47
+ */
48
+ renewEnvironmentLease(environmentId: string, ttlMs: number): Promise<EnvironmentLease>;
49
+ /**
50
+ * Start periodic cleanup for expired leases.
51
+ */
52
+ startJanitor(): void;
53
+ /**
54
+ * Stop janitor timer.
55
+ */
56
+ shutdown(): Promise<void>;
57
+ /**
58
+ * Cleanup expired active leases.
59
+ */
60
+ cleanupExpiredLeases(now?: Date): Promise<number>;
61
+ private getProviderOrThrow;
62
+ private persistLeaseState;
63
+ private appendEvent;
64
+ private safePersist;
65
+ }
66
+
67
+ /**
68
+ * @module @kb-labs/core-runtime/workspace-manager
69
+ * Runtime manager for workspace providers.
70
+ */
71
+
72
+ declare class WorkspaceManager {
73
+ private readonly platform;
74
+ constructor(platform: Pick<PlatformContainer, 'getAdapter'>);
75
+ /**
76
+ * Check whether workspace provider is configured.
77
+ */
78
+ hasProvider(): boolean;
79
+ /**
80
+ * Materialize a workspace.
81
+ */
82
+ materializeWorkspace(request: MaterializeWorkspaceRequest): Promise<WorkspaceDescriptor>;
83
+ /**
84
+ * Attach workspace to environment.
85
+ */
86
+ attachWorkspace(request: AttachWorkspaceRequest): Promise<WorkspaceAttachment>;
87
+ /**
88
+ * Release workspace attachment.
89
+ */
90
+ releaseWorkspace(workspaceId: string, environmentId?: string): Promise<void>;
91
+ /**
92
+ * Get workspace lifecycle status.
93
+ */
94
+ getWorkspaceStatus(workspaceId: string): Promise<WorkspaceStatusResult>;
95
+ /**
96
+ * Read provider capabilities.
97
+ */
98
+ getCapabilities(): WorkspaceProviderCapabilities;
99
+ /**
100
+ * Shutdown manager resources (reserved for future internal workers).
101
+ */
102
+ shutdown(): Promise<void>;
103
+ private getProviderOrThrow;
104
+ }
105
+
106
+ /**
107
+ * @module @kb-labs/core-runtime/snapshot-manager
108
+ * Runtime manager for snapshot providers.
109
+ */
110
+
111
+ declare class SnapshotManager {
112
+ private readonly platform;
113
+ constructor(platform: Pick<PlatformContainer, 'getAdapter'>);
114
+ /**
115
+ * Check whether snapshot provider is configured.
116
+ */
117
+ hasProvider(): boolean;
118
+ /**
119
+ * Capture a new snapshot.
120
+ */
121
+ captureSnapshot(request: CaptureSnapshotRequest): Promise<SnapshotDescriptor>;
122
+ /**
123
+ * Restore an existing snapshot.
124
+ */
125
+ restoreSnapshot(request: RestoreSnapshotRequest): Promise<RestoreSnapshotResult>;
126
+ /**
127
+ * Read snapshot status.
128
+ */
129
+ getSnapshotStatus(snapshotId: string): Promise<SnapshotStatusResult>;
130
+ /**
131
+ * Delete snapshot by id.
132
+ */
133
+ deleteSnapshot(snapshotId: string): Promise<void>;
134
+ /**
135
+ * Run garbage collection if provider supports it.
136
+ */
137
+ garbageCollectSnapshots(request?: SnapshotGarbageCollectRequest): Promise<SnapshotGarbageCollectResult>;
138
+ /**
139
+ * Read provider capabilities.
140
+ */
141
+ getCapabilities(): SnapshotProviderCapabilities;
142
+ /**
143
+ * Shutdown manager resources (reserved for future internal workers).
144
+ */
145
+ shutdown(): Promise<void>;
146
+ private getProviderOrThrow;
147
+ }
148
+
149
+ /**
150
+ * @module @kb-labs/core-runtime/run-executor
151
+ * Bridge between run orchestration and execution backend.
152
+ */
153
+
154
+ /**
155
+ * Request for run step execution.
156
+ */
157
+ interface RunStepExecutionRequest {
158
+ runId: string;
159
+ stepId: string;
160
+ environmentId?: string;
161
+ execution: ExecutionRequest;
162
+ }
163
+ /**
164
+ * Run executor that enriches execution metadata with run/environment context.
165
+ */
166
+ declare class RunExecutor {
167
+ private readonly executionBackend;
168
+ private readonly logger;
169
+ constructor(executionBackend: IExecutionBackend, logger: {
170
+ debug(message: string, meta?: Record<string, unknown>): void;
171
+ });
172
+ /**
173
+ * Execute one run step through the shared execution backend.
174
+ */
175
+ executeStep(request: RunStepExecutionRequest): Promise<ExecutionResult>;
176
+ }
177
+
178
+ /**
179
+ * @module @kb-labs/core-runtime/run-orchestrator
180
+ * Minimal run state machine orchestration skeleton.
181
+ */
182
+
183
+ /**
184
+ * Full-cycle start request (MVP skeleton).
185
+ */
186
+ interface StartFullCycleRequest {
187
+ run: CreateRunRequest;
188
+ environment: CreateEnvironmentRequest;
189
+ firstStep?: RunStepExecutionRequest['execution'];
190
+ }
191
+ /**
192
+ * In-memory orchestrator skeleton for phase 2 wiring.
193
+ */
194
+ declare class RunOrchestrator {
195
+ private readonly environmentManager;
196
+ private readonly runExecutor;
197
+ private readonly logger;
198
+ private readonly runs;
199
+ constructor(environmentManager: EnvironmentManager, runExecutor: RunExecutor, logger: {
200
+ debug(message: string, meta?: Record<string, unknown>): void;
201
+ });
202
+ /**
203
+ * Create run record in memory.
204
+ */
205
+ createRun(input: CreateRunRequest): RunRecord;
206
+ /**
207
+ * Read run from in-memory store.
208
+ */
209
+ getRun(runId: string): RunRecord | undefined;
210
+ /**
211
+ * Start minimal full-cycle flow.
212
+ * queue -> provisioning -> executing -> completed/failed
213
+ */
214
+ startFullCycle(request: StartFullCycleRequest): Promise<RunRecord>;
215
+ private transition;
216
+ private getRunOrThrow;
217
+ }
218
+
219
+ /**
220
+ * @module @kb-labs/core-runtime/container
221
+ * Platform DI container.
222
+ */
223
+
224
+ /**
225
+ * Core adapter types (known at compile time).
226
+ * These are the primary adapters that plugins see.
227
+ */
228
+ interface CoreAdapterTypes {
229
+ analytics: IAnalytics;
230
+ vectorStore: IVectorStore;
231
+ llm: ILLM;
232
+ embeddings: IEmbeddings;
233
+ cache: ICache;
234
+ config: IConfig;
235
+ storage: IStorage;
236
+ logger: ILogger;
237
+ eventBus: IEventBus;
238
+ invoke: IInvoke;
239
+ artifacts: IArtifacts;
240
+ }
241
+ /**
242
+ * All adapter types (core + extensions).
243
+ * Extensions can be any type, not known at compile time.
244
+ */
245
+ type AdapterTypes = CoreAdapterTypes & {
246
+ [key: string]: unknown;
247
+ };
248
+ /**
249
+ * Platform lifecycle phase.
250
+ */
251
+ type PlatformLifecyclePhase = 'start' | 'ready' | 'beforeShutdown' | 'shutdown';
252
+ /**
253
+ * Platform lifecycle event context.
254
+ */
255
+ interface PlatformLifecycleContext {
256
+ phase: PlatformLifecyclePhase;
257
+ cwd?: string;
258
+ isChildProcess?: boolean;
259
+ reason?: string;
260
+ error?: unknown;
261
+ metadata?: Record<string, unknown>;
262
+ }
263
+ /**
264
+ * Platform lifecycle hooks.
265
+ */
266
+ interface PlatformLifecycleHooks {
267
+ onStart?(context: PlatformLifecycleContext): void | Promise<void>;
268
+ onReady?(context: PlatformLifecycleContext): void | Promise<void>;
269
+ onBeforeShutdown?(context: PlatformLifecycleContext): void | Promise<void>;
270
+ onShutdown?(context: PlatformLifecycleContext): void | Promise<void>;
271
+ onError?(error: unknown, phase: PlatformLifecyclePhase, context: PlatformLifecycleContext): void | Promise<void>;
272
+ }
273
+ /**
274
+ * Platform DI container.
275
+ * Provides access to all platform services through lazy-loaded getters.
276
+ */
277
+ declare class PlatformContainer {
278
+ private adapters;
279
+ private lifecycleHooks;
280
+ private initialized;
281
+ /**
282
+ * Set an adapter instance.
283
+ *
284
+ * Supports both core adapters (type-safe) and extension adapters (generic).
285
+ *
286
+ * @example
287
+ * ```typescript
288
+ * // Core adapter (type-safe)
289
+ * platform.setAdapter('logger', pinoLogger); // Type: ILogger
290
+ *
291
+ * // Extension adapter (requires explicit type)
292
+ * platform.setAdapter('logRingBuffer', ringBuffer); // Type: LogRingBufferAdapter
293
+ * ```
294
+ *
295
+ * @param key - Adapter key
296
+ * @param instance - Adapter instance
297
+ */
298
+ setAdapter<K extends keyof CoreAdapterTypes>(key: K, instance: CoreAdapterTypes[K]): void;
299
+ setAdapter<T = unknown>(key: string, instance: T): void;
300
+ /**
301
+ * Get an adapter instance.
302
+ *
303
+ * Two overloads:
304
+ * 1. Core adapters (logger, db, etc.) - type-safe, returns typed instance
305
+ * 2. Extension adapters (logRingBuffer, logPersistence, etc.) - generic, requires explicit type
306
+ *
307
+ * @example
308
+ * ```typescript
309
+ * // Core adapter (type-safe)
310
+ * const logger = platform.getAdapter('logger'); // ILogger | undefined
311
+ *
312
+ * // Extension adapter (requires explicit type)
313
+ * const buffer = platform.getAdapter<ILogRingBuffer>('logRingBuffer');
314
+ * ```
315
+ *
316
+ * @param key - Adapter key
317
+ */
318
+ getAdapter<K extends keyof CoreAdapterTypes>(key: K): CoreAdapterTypes[K] | undefined;
319
+ getAdapter<T = unknown>(key: string): T | undefined;
320
+ /**
321
+ * Check if an adapter is explicitly configured (not using fallback).
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * // Core adapter
326
+ * if (platform.hasAdapter('logger')) { ... }
327
+ *
328
+ * // Extension adapter
329
+ * if (platform.hasAdapter('logRingBuffer')) { ... }
330
+ * ```
331
+ *
332
+ * @param key - Adapter key
333
+ */
334
+ hasAdapter<K extends keyof CoreAdapterTypes>(key: K): boolean;
335
+ hasAdapter(key: string): boolean;
336
+ /**
337
+ * List all adapter names.
338
+ * Useful for debugging and discovery.
339
+ */
340
+ listAdapters(): string[];
341
+ /**
342
+ * Register platform lifecycle hooks.
343
+ * If hooks with this id already exist, they are replaced.
344
+ */
345
+ registerLifecycleHooks(id: string, hooks: PlatformLifecycleHooks): void;
346
+ /**
347
+ * Unregister platform lifecycle hooks by id.
348
+ */
349
+ unregisterLifecycleHooks(id: string): void;
350
+ /**
351
+ * List registered lifecycle hook ids.
352
+ */
353
+ listLifecycleHookIds(): string[];
354
+ /**
355
+ * Emit lifecycle phase to registered hooks.
356
+ */
357
+ emitLifecyclePhase(phase: PlatformLifecyclePhase, context?: Omit<PlatformLifecycleContext, 'phase'>): Promise<void>;
358
+ /**
359
+ * Emit lifecycle error to registered onError hooks.
360
+ */
361
+ emitLifecycleError(error: unknown, phase: PlatformLifecyclePhase, context?: Omit<PlatformLifecycleContext, 'phase'>): Promise<void>;
362
+ /**
363
+ * Check if a service is explicitly configured (not using fallback).
364
+ * @param service - Service name (e.g., 'llm', 'vectorStore', 'workflows')
365
+ * @returns true if service is configured, false if using NoOp/fallback
366
+ */
367
+ isConfigured(service: string): boolean;
368
+ /**
369
+ * Get list of all configured services (adapters + core features).
370
+ * Used for validating plugin platform requirements.
371
+ */
372
+ getConfiguredServices(): Set<string>;
373
+ /** Analytics adapter (fallback: NoOpAnalytics) */
374
+ get analytics(): IAnalytics;
375
+ /** Vector store adapter (fallback: MemoryVectorStore) */
376
+ get vectorStore(): IVectorStore;
377
+ /** LLM adapter (fallback: MockLLM) */
378
+ get llm(): ILLM;
379
+ /** Embeddings adapter (fallback: MockEmbeddings) */
380
+ get embeddings(): IEmbeddings;
381
+ /** Cache adapter (fallback: MemoryCache) */
382
+ get cache(): ICache;
383
+ /** Config adapter (fallback: NoOpConfig) */
384
+ get config(): IConfig;
385
+ /** Storage adapter (fallback: MemoryStorage) */
386
+ get storage(): IStorage;
387
+ /** Logger adapter (fallback: ConsoleLogger) */
388
+ get logger(): ILogger;
389
+ /** Event bus adapter (fallback: MemoryEventBus) */
390
+ get eventBus(): IEventBus;
391
+ /** Inter-plugin invocation adapter (fallback: NoOpInvoke) */
392
+ get invoke(): IInvoke;
393
+ /** Artifact storage adapter (fallback: MemoryArtifacts) */
394
+ get artifacts(): IArtifacts;
395
+ private _logQueryService?;
396
+ /**
397
+ * Unified log query service.
398
+ * Automatically uses configured backends (logPersistence, logRingBuffer).
399
+ *
400
+ * @example
401
+ * ```typescript
402
+ * // Query logs
403
+ * const result = await platform.logs.query({ level: 'error' });
404
+ *
405
+ * // Get log by ID
406
+ * const log = await platform.logs.getById('log-123');
407
+ *
408
+ * // Full-text search
409
+ * const results = await platform.logs.search('authentication failed');
410
+ *
411
+ * // Subscribe to real-time stream
412
+ * const unsubscribe = platform.logs.subscribe((log) => console.log(log));
413
+ * ```
414
+ */
415
+ get logs(): ILogReader;
416
+ private _workflows?;
417
+ private _jobs?;
418
+ private _cron?;
419
+ private _resources?;
420
+ private _resourceBroker?;
421
+ private _socketServer?;
422
+ private _executionBackend?;
423
+ private _environmentManager?;
424
+ private _workspaceManager?;
425
+ private _snapshotManager?;
426
+ private _runExecutor?;
427
+ private _runOrchestrator?;
428
+ /** Workflow engine (throws if not initialized) */
429
+ get workflows(): IWorkflowEngine;
430
+ /** Job scheduler (throws if not initialized) */
431
+ get jobs(): IJobScheduler;
432
+ /** Cron manager (throws if not initialized) */
433
+ get cron(): ICronManager;
434
+ /** Resource manager (throws if not initialized) */
435
+ get resources(): IResourceManager;
436
+ /**
437
+ * Resource broker for rate limiting, queueing, and retry.
438
+ * @throws Error if not initialized
439
+ */
440
+ get resourceBroker(): IResourceBroker;
441
+ /**
442
+ * Check if resource broker is initialized.
443
+ */
444
+ get hasResourceBroker(): boolean;
445
+ /**
446
+ * Initialize core features.
447
+ * Called internally by initPlatform().
448
+ */
449
+ initCoreFeatures(workflows: IWorkflowEngine, jobs: IJobScheduler, cron: ICronManager, resources: IResourceManager): void;
450
+ /**
451
+ * Initialize resource broker.
452
+ * Called internally by initPlatform().
453
+ */
454
+ initResourceBroker(broker: IResourceBroker): void;
455
+ /**
456
+ * Initialize Unix socket server.
457
+ * Called internally by initPlatform() in parent process.
458
+ */
459
+ initSocketServer(server: {
460
+ getSocketPath(): string;
461
+ }): void;
462
+ /**
463
+ * Get socket path for IPC communication.
464
+ * Returns undefined if not running in parent process.
465
+ */
466
+ getSocketPath(): string | undefined;
467
+ /**
468
+ * Initialize execution backend.
469
+ * Called internally by initPlatform() AFTER adapters, BEFORE core features.
470
+ *
471
+ * @param backend - ExecutionBackend instance (from @kb-labs/plugin-execution)
472
+ */
473
+ initExecutionBackend(backend: IExecutionBackend): void;
474
+ /**
475
+ * Get execution backend.
476
+ * Returns the initialized backend or throws if not initialized.
477
+ *
478
+ * @throws Error if ExecutionBackend not initialized via initPlatform()
479
+ * @returns ExecutionBackend instance
480
+ */
481
+ get executionBackend(): IExecutionBackend;
482
+ /**
483
+ * Check if execution backend is initialized.
484
+ */
485
+ get hasExecutionBackend(): boolean;
486
+ /**
487
+ * Initialize orchestration services.
488
+ * Called internally by initPlatform() after ExecutionBackend init.
489
+ */
490
+ initOrchestrationServices(environmentManager: EnvironmentManager, runExecutor: RunExecutor, runOrchestrator: RunOrchestrator): void;
491
+ /**
492
+ * Initialize infrastructure capability services.
493
+ * Called internally by initPlatform().
494
+ */
495
+ initCapabilityServices(workspaceManager: WorkspaceManager, snapshotManager: SnapshotManager): void;
496
+ /**
497
+ * Environment manager service.
498
+ */
499
+ get environmentManager(): EnvironmentManager;
500
+ /**
501
+ * Workspace manager service.
502
+ */
503
+ get workspaceManager(): WorkspaceManager;
504
+ /**
505
+ * Snapshot manager service.
506
+ */
507
+ get snapshotManager(): SnapshotManager;
508
+ /**
509
+ * Run executor service.
510
+ */
511
+ get runExecutor(): RunExecutor;
512
+ /**
513
+ * Run orchestrator service.
514
+ */
515
+ get runOrchestrator(): RunOrchestrator;
516
+ /**
517
+ * Check if platform is initialized.
518
+ */
519
+ get isInitialized(): boolean;
520
+ /**
521
+ * Reset platform to initial state.
522
+ * Clears all adapters and core features.
523
+ * Used primarily for testing.
524
+ */
525
+ reset(): void;
526
+ /**
527
+ * Shutdown platform gracefully.
528
+ * Closes all resources, stops workers, cleanup.
529
+ */
530
+ shutdown(): Promise<void>;
531
+ }
532
+ /**
533
+ * Type augmentation for process to track platform singleton.
534
+ * This makes TypeScript aware of our platform storage.
535
+ */
536
+ declare global {
537
+ var __KB_PLATFORM_SINGLETON__: PlatformContainer | undefined;
538
+ }
539
+ /**
540
+ * Global platform container singleton.
541
+ *
542
+ * Uses Symbol.for() + process for TRUE cross-realm singleton:
543
+ * - Works across CJS (CLI bin.cjs) and ESM (sandbox workers)
544
+ * - All worker threads share the same process object
545
+ * - Each Docker container gets its own process (correct isolation!)
546
+ *
547
+ * This ensures:
548
+ * ✅ One QdrantVectorStore instance per Node.js process
549
+ * ✅ One Logger instance per Node.js process
550
+ * ✅ One Analytics adapter per Node.js process
551
+ * ✅ All sandbox workers share adapters (resource efficiency)
552
+ * ✅ Docker containers are isolated (security for paranoid mode)
553
+ */
554
+ declare const platform: PlatformContainer;
555
+
556
+ /**
557
+ * @module @kb-labs/core-runtime/config
558
+ * Platform configuration types.
559
+ */
560
+
561
+ /**
562
+ * Adapter value type.
563
+ * - string: Single adapter package path
564
+ * - string[]: Multiple adapter packages (first = primary/default, others available via adapterLoader)
565
+ * - null: NoOp adapter
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * // Single adapter
570
+ * llm: "@kb-labs/adapters-openai"
571
+ *
572
+ * // Multiple adapters (multi-provider setup)
573
+ * llm: ["@kb-labs/adapters-openai", "@kb-labs/adapters-vibeproxy"]
574
+ *
575
+ * // NoOp/disabled
576
+ * analytics: null
577
+ * ```
578
+ */
579
+ type AdapterValue = string | string[] | null;
580
+ /**
581
+ * Platform adapter configuration.
582
+ * Each key is the adapter name, value can be:
583
+ * - string: Single adapter package path
584
+ * - string[]: Multiple adapters (first = primary, rest available via routing/options)
585
+ * - null: NoOp adapter
586
+ */
587
+ interface AdaptersConfig {
588
+ /** Analytics adapter package(s) (e.g., "@kb-labs/analytics-adapter" or ["@kb-labs/analytics-file", "@kb-labs/analytics-posthog"]) */
589
+ analytics?: AdapterValue;
590
+ /** Vector store adapter package(s) (e.g., "@kb-labs/adapters-qdrant") */
591
+ vectorStore?: AdapterValue;
592
+ /** LLM adapter package(s) (e.g., "@kb-labs/adapters-openai" or ["@kb-labs/adapters-openai", "@kb-labs/adapters-vibeproxy"]) */
593
+ llm?: AdapterValue;
594
+ /** Embeddings adapter package(s) (e.g., "@kb-labs/adapters-openai/embeddings") */
595
+ embeddings?: AdapterValue;
596
+ /** Cache adapter package(s) (e.g., "@kb-labs/adapters-redis") */
597
+ cache?: AdapterValue;
598
+ /** Storage adapter package(s) (e.g., "@kb-labs/adapters-fs") */
599
+ storage?: AdapterValue;
600
+ /** Logger adapter package(s) (e.g., "@kb-labs/adapters-pino") */
601
+ logger?: AdapterValue;
602
+ /** Event bus adapter package(s) */
603
+ eventBus?: AdapterValue;
604
+ /** Environment provider adapter package(s) (e.g., "@kb-labs/adapters-environment-docker") */
605
+ environment?: AdapterValue;
606
+ /** Workspace provider adapter package(s) (e.g., "@kb-labs/adapters-workspace-localfs") */
607
+ workspace?: AdapterValue;
608
+ /** Snapshot provider adapter package(s) (e.g., "@kb-labs/adapters-snapshot-localfs") */
609
+ snapshot?: AdapterValue;
610
+ }
611
+ /**
612
+ * Resource manager configuration.
613
+ */
614
+ interface ResourcesConfig {
615
+ /** Default quotas for tenants without explicit quotas */
616
+ defaultQuotas?: Partial<TenantQuotas>;
617
+ }
618
+ /**
619
+ * Job scheduler configuration.
620
+ */
621
+ interface JobsConfig {
622
+ /** Maximum concurrent jobs per tenant */
623
+ maxConcurrent?: number;
624
+ /** Poll interval in milliseconds for job queue */
625
+ pollInterval?: number;
626
+ }
627
+ /**
628
+ * Workflow engine configuration.
629
+ */
630
+ interface WorkflowsConfig {
631
+ /** Maximum concurrent workflows per tenant */
632
+ maxConcurrent?: number;
633
+ /** Default workflow timeout in milliseconds */
634
+ defaultTimeout?: number;
635
+ }
636
+ /**
637
+ * Execution backend configuration.
638
+ * Determines how plugins execute (in-process, worker-pool, remote).
639
+ */
640
+ interface ExecutionConfig {
641
+ /**
642
+ * Execution mode:
643
+ * - 'auto' (default): Auto-detect from environment (EXECUTION_MODE, KUBERNETES_SERVICE_HOST)
644
+ * - 'in-process': Same process, no isolation (dev mode, fast iteration)
645
+ * - 'worker-pool': Worker pool with fault isolation (production, single-node)
646
+ * - 'remote': Remote executor service (Phase 3, distributed fleet)
647
+ * @default 'auto'
648
+ */
649
+ mode?: 'auto' | 'in-process' | 'worker-pool' | 'remote';
650
+ /**
651
+ * Worker pool options (used when mode=worker-pool or auto-detected).
652
+ */
653
+ workerPool?: {
654
+ /** Minimum workers to keep alive @default 2 */
655
+ min?: number;
656
+ /** Maximum concurrent workers @default 10 */
657
+ max?: number;
658
+ /** Max requests per worker before recycling @default 1000 */
659
+ maxRequestsPerWorker?: number;
660
+ /** Max worker uptime before recycling (ms) @default 1800000 (30min) */
661
+ maxUptimeMsPerWorker?: number;
662
+ /** Max concurrent requests per plugin (optional) */
663
+ maxConcurrentPerPlugin?: number;
664
+ /** Warmup policy */
665
+ warmup?: {
666
+ /**
667
+ * Warmup mode (matches plugin-execution types):
668
+ * - 'none': No warmup (cold start on first request)
669
+ * - 'top-n': Warmup top N most-used handlers
670
+ * - 'marked': Warmup handlers marked with warmup: true in manifest
671
+ * @default 'none'
672
+ */
673
+ mode?: 'none' | 'top-n' | 'marked';
674
+ /** Warmup top N most used handlers (for top-n mode) @default 5 */
675
+ topN?: number;
676
+ /** Max handlers to warmup (safety limit) @default 20 */
677
+ maxHandlers?: number;
678
+ };
679
+ };
680
+ /**
681
+ * Remote executor options (used when mode=remote, Phase 3).
682
+ */
683
+ remote?: {
684
+ /** Remote executor service endpoint (gRPC or HTTP) */
685
+ endpoint?: string;
686
+ };
687
+ }
688
+ /**
689
+ * Resource broker configuration for rate limiting and queue management.
690
+ */
691
+ interface ResourceBrokerConfig {
692
+ /**
693
+ * Use distributed backend via StateBroker.
694
+ * false = InMemoryRateLimitBackend (single process)
695
+ * true = StateBrokerRateLimitBackend (distributed, requires StateBroker daemon)
696
+ * @default false
697
+ */
698
+ distributed?: boolean;
699
+ /**
700
+ * LLM resource configuration.
701
+ */
702
+ llm?: {
703
+ /** Rate limits (preset name or custom config) */
704
+ rateLimits?: RateLimitConfig | RateLimitPreset;
705
+ /** Maximum retry attempts */
706
+ maxRetries?: number;
707
+ /** Request timeout in ms */
708
+ timeout?: number;
709
+ };
710
+ /**
711
+ * Embeddings resource configuration.
712
+ */
713
+ embeddings?: {
714
+ /** Rate limits (preset name or custom config) */
715
+ rateLimits?: RateLimitConfig | RateLimitPreset;
716
+ /** Maximum retry attempts */
717
+ maxRetries?: number;
718
+ /** Request timeout in ms */
719
+ timeout?: number;
720
+ };
721
+ /**
722
+ * Vector store resource configuration.
723
+ */
724
+ vectorStore?: {
725
+ /** Maximum concurrent requests */
726
+ maxConcurrent?: number;
727
+ /** Maximum retry attempts */
728
+ maxRetries?: number;
729
+ /** Request timeout in ms */
730
+ timeout?: number;
731
+ };
732
+ }
733
+ /**
734
+ * Core features configuration.
735
+ */
736
+ interface CoreFeaturesConfig {
737
+ /** Resource manager configuration */
738
+ resources?: ResourcesConfig;
739
+ /** Job scheduler configuration */
740
+ jobs?: JobsConfig;
741
+ /** Workflow engine configuration */
742
+ workflows?: WorkflowsConfig;
743
+ /** Resource broker configuration */
744
+ resourceBroker?: ResourceBrokerConfig;
745
+ }
746
+ /**
747
+ * Full platform configuration.
748
+ */
749
+ interface PlatformConfig {
750
+ /** Adapter packages configuration */
751
+ adapters?: AdaptersConfig;
752
+ /** Optional adapter-specific configuration passed to createAdapter(config) */
753
+ adapterOptions?: Partial<Record<keyof AdaptersConfig, unknown>>;
754
+ /** Core features configuration */
755
+ core?: CoreFeaturesConfig;
756
+ /** Execution backend configuration (NEW: unified plugin execution) */
757
+ execution?: ExecutionConfig;
758
+ }
759
+
760
+ /**
761
+ * @module @kb-labs/core-runtime/loader
762
+ * Platform initialization and adapter loading.
763
+ */
764
+
765
+ /**
766
+ * Initialize the platform with configuration.
767
+ * Loads adapters and initializes core features.
768
+ *
769
+ * @param config - Platform configuration
770
+ * @param cwd - Workspace root directory (defaults to process.cwd())
771
+ * @returns Initialized platform container
772
+ *
773
+ * @example
774
+ * ```typescript
775
+ * await initPlatform({
776
+ * adapters: {
777
+ * analytics: '@kb-labs/analytics-adapter',
778
+ * vectorStore: '@kb-labs/adapters-qdrant',
779
+ * llm: '@kb-labs/adapters-openai',
780
+ * },
781
+ * core: {
782
+ * resources: { defaultQuotas: { ... } },
783
+ * jobs: { maxConcurrent: 10 },
784
+ * },
785
+ * });
786
+ * ```
787
+ */
788
+ declare function initPlatform(config?: PlatformConfig, cwd?: string, uiProvider?: (hostType: string) => any): Promise<PlatformContainer>;
789
+ /**
790
+ * Reset the platform to initial state (for testing).
791
+ * Clears all adapters and core features.
792
+ * Platform will use NoOp fallbacks until re-initialized.
793
+ *
794
+ * @example
795
+ * ```typescript
796
+ * // Before test
797
+ * resetPlatform();
798
+ * await initPlatform({ adapters: { llm: mockLLM } });
799
+ *
800
+ * // After test
801
+ * resetPlatform();
802
+ * ```
803
+ */
804
+ declare function resetPlatform(): void;
805
+
806
+ /**
807
+ * @module @kb-labs/core-runtime/discover-adapters
808
+ * Auto-discovery of adapters from workspace packages.
809
+ *
810
+ * Similar to CLI plugin discovery, this scans kb-labs-adapters/packages/*
811
+ * and loads adapters by file path (not package name).
812
+ */
813
+ /**
814
+ * Discovered adapter info
815
+ */
816
+ interface DiscoveredAdapter {
817
+ /** Package name (e.g., "@kb-labs/adapters-openai") */
818
+ packageName: string;
819
+ /** Absolute path to package root */
820
+ pkgRoot: string;
821
+ /** Adapter factory function */
822
+ createAdapter: (config?: any) => any;
823
+ /** Adapter module (full exports) */
824
+ module: any;
825
+ }
826
+ /**
827
+ * Discover adapters from workspace packages.
828
+ * Scans kb-labs-adapters/packages/* and loads built adapters.
829
+ *
830
+ * @param cwd - Workspace root directory
831
+ * @returns Map of package names to adapter info
832
+ *
833
+ * @example
834
+ * ```typescript
835
+ * const adapters = await discoverAdapters('/Users/kb-labs');
836
+ * const openai = adapters.get('@kb-labs/adapters-openai');
837
+ * if (openai) {
838
+ * const llm = openai.createAdapter({ model: 'gpt-4' });
839
+ * }
840
+ * ```
841
+ */
842
+ declare function discoverAdapters(cwd: string): Promise<Map<string, DiscoveredAdapter>>;
843
+ /**
844
+ * Resolve adapter path - tries discovery first, falls back to package name import.
845
+ *
846
+ * @param adapterPath - Package name or file path
847
+ * @param cwd - Workspace root directory
848
+ * @returns Adapter factory function
849
+ *
850
+ * @example
851
+ * ```typescript
852
+ * // Try to discover first (workspace)
853
+ * const adapter = await resolveAdapter('@kb-labs/adapters-openai', cwd);
854
+ *
855
+ * // Falls back to dynamic import if not found in workspace
856
+ * const adapter = await resolveAdapter('@kb-labs/adapters-openai', cwd);
857
+ * ```
858
+ */
859
+ declare function resolveAdapter(adapterPath: string, cwd: string): Promise<((config?: any) => any) | null>;
860
+
861
+ /**
862
+ * @module @kb-labs/core-runtime/analytics-context
863
+ * Auto-detection of analytics context (source, actor, runId) for event enrichment.
864
+ *
865
+ * See ADR-0040: Analytics V1 Auto-Enrichment
866
+ */
867
+
868
+ /**
869
+ * Create AnalyticsContext with auto-detection of source, actor, and runId.
870
+ *
871
+ * Detection logic:
872
+ * - **Source**: Reads package.json from cwd for product name and version
873
+ * - **Actor**: Detects from CI environment variables or git config
874
+ * - CI mode: Checks CI=true, GITHUB_ACTIONS, GITLAB_CI, etc.
875
+ * - User mode: Executes `git config user.name` and `git config user.email`
876
+ * - **RunId**: Generates unique UUID per execution (correlates events in single CLI invocation)
877
+ * - **Context**: Adds workspace path, git branch (if available)
878
+ *
879
+ * @param cwd - Workspace root directory
880
+ * @returns AnalyticsContext with auto-populated metadata
881
+ *
882
+ * @example
883
+ * ```typescript
884
+ * const context = await createAnalyticsContext('/path/to/workspace');
885
+ * // {
886
+ * // source: { product: '@kb-labs/cli', version: '1.0.0' },
887
+ * // runId: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
888
+ * // actor: { type: 'user', id: 'user@example.com', name: 'John Doe' },
889
+ * // ctx: { workspace: '/path/to/workspace', branch: 'main' }
890
+ * // }
891
+ * ```
892
+ */
893
+ declare function createAnalyticsContext(cwd: string): Promise<AnalyticsContext>;
894
+
895
+ /**
896
+ * @module @kb-labs/core-runtime/core/resource-manager
897
+ * In-memory resource manager with quota enforcement.
898
+ */
899
+
900
+ interface ResourceManagerConfig {
901
+ /** Default quotas for new tenants */
902
+ defaultQuotas?: Partial<TenantQuotas>;
903
+ /** Slot expiration check interval in ms (default: 30000) */
904
+ expirationCheckInterval?: number;
905
+ }
906
+ /**
907
+ * In-memory resource manager with quota enforcement.
908
+ * Tracks resource slots per tenant and enforces limits.
909
+ */
910
+ declare class ResourceManager implements IResourceManager {
911
+ private cache;
912
+ private logger;
913
+ private slots;
914
+ private tenantSlots;
915
+ private quotas;
916
+ private defaultQuotas;
917
+ private idCounter;
918
+ private expirationTimer?;
919
+ constructor(cache: ICache, logger: ILogger, config?: ResourceManagerConfig);
920
+ /**
921
+ * Acquire a resource slot for a tenant.
922
+ * Returns null if quota exceeded.
923
+ *
924
+ * @param resource - Type of resource to acquire
925
+ * @param tenantId - Tenant identifier
926
+ * @param timeout - Optional slot expiration timeout in ms
927
+ * @returns Resource slot if available, null if quota exceeded
928
+ */
929
+ acquireSlot(resource: ResourceType, tenantId: string, timeout?: number): Promise<ResourceSlot | null>;
930
+ /**
931
+ * Release a previously acquired resource slot.
932
+ * Frees up quota for the tenant.
933
+ *
934
+ * @param slot - Slot to release
935
+ */
936
+ releaseSlot(slot: ResourceSlot): Promise<void>;
937
+ /**
938
+ * Get resource availability statistics.
939
+ * If tenantId provided, returns tenant-specific stats.
940
+ * Otherwise, returns global platform stats.
941
+ *
942
+ * @param resource - Type of resource
943
+ * @param tenantId - Optional tenant filter
944
+ * @returns Resource availability stats
945
+ */
946
+ getAvailability(resource: ResourceType, tenantId?: string): Promise<ResourceAvailability>;
947
+ /**
948
+ * Set custom quotas for a tenant.
949
+ * Merges with default quotas and persists to cache.
950
+ *
951
+ * @param tenantId - Tenant identifier
952
+ * @param quotas - Partial quotas to update
953
+ */
954
+ setQuota(tenantId: string, quotas: Partial<TenantQuotas>): Promise<void>;
955
+ /**
956
+ * Get quota configuration for a tenant.
957
+ * Returns defaults if no custom quotas set.
958
+ *
959
+ * @param tenantId - Tenant identifier
960
+ * @returns Tenant quota configuration
961
+ */
962
+ getQuota(tenantId: string): Promise<TenantQuotas>;
963
+ /**
964
+ * Get count of active slots for a resource type and tenant.
965
+ */
966
+ private getResourceCount;
967
+ /**
968
+ * Get max allowed for a resource type from quotas.
969
+ */
970
+ private getMaxForResource;
971
+ /**
972
+ * Clean up expired slots.
973
+ */
974
+ private cleanupExpiredSlots;
975
+ /**
976
+ * Stop the expiration timer (for cleanup).
977
+ */
978
+ dispose(): void;
979
+ /**
980
+ * Get current stats (for monitoring).
981
+ */
982
+ getStats(): {
983
+ totalSlots: number;
984
+ slotsByResource: Record<ResourceType, number>;
985
+ tenantCount: number;
986
+ };
987
+ }
988
+
989
+ /**
990
+ * @module @kb-labs/core-runtime/core/job-scheduler
991
+ * In-memory job scheduler with queue and execution.
992
+ */
993
+
994
+ interface JobSchedulerConfig {
995
+ /** Maximum concurrent jobs globally (default: 10) */
996
+ maxConcurrent?: number;
997
+ /** Queue poll interval in ms (default: 1000) */
998
+ pollInterval?: number;
999
+ /** Default job timeout in ms (default: 300000 = 5min) */
1000
+ defaultTimeout?: number;
1001
+ }
1002
+ /**
1003
+ * Job handler function type.
1004
+ */
1005
+ type JobHandler = (payload: unknown) => Promise<unknown>;
1006
+ /**
1007
+ * In-memory job scheduler with queue processing.
1008
+ */
1009
+ declare class JobScheduler implements IJobScheduler {
1010
+ private resources;
1011
+ private events;
1012
+ private logger;
1013
+ private jobs;
1014
+ private queue;
1015
+ private handlers;
1016
+ private running;
1017
+ private idCounter;
1018
+ private pollTimer?;
1019
+ private readonly config;
1020
+ constructor(resources: IResourceManager, events: IEventBus, logger: ILogger, config?: JobSchedulerConfig);
1021
+ /**
1022
+ * Register a job handler for a job type.
1023
+ */
1024
+ registerHandler(type: string, handler: JobHandler): void;
1025
+ /**
1026
+ * Unregister a job handler.
1027
+ */
1028
+ unregisterHandler(type: string): void;
1029
+ submit(job: JobDefinition): Promise<JobHandle>;
1030
+ schedule(job: JobDefinition, schedule: CronExpression | Date): Promise<JobHandle>;
1031
+ cancel(jobId: string): Promise<boolean>;
1032
+ getStatus(jobId: string): Promise<JobHandle | null>;
1033
+ list(filter?: JobFilter): Promise<JobHandle[]>;
1034
+ /**
1035
+ * Add job to queue.
1036
+ */
1037
+ private enqueue;
1038
+ /**
1039
+ * Process queued jobs.
1040
+ */
1041
+ private processQueue;
1042
+ /**
1043
+ * Execute a single job.
1044
+ */
1045
+ private executeJob;
1046
+ /**
1047
+ * Convert internal job to public handle.
1048
+ */
1049
+ private toHandle;
1050
+ /**
1051
+ * Stop the scheduler (for cleanup).
1052
+ */
1053
+ dispose(): void;
1054
+ /**
1055
+ * Get scheduler stats (for monitoring).
1056
+ */
1057
+ getStats(): {
1058
+ totalJobs: number;
1059
+ queueLength: number;
1060
+ runningCount: number;
1061
+ byStatus: Record<string, number>;
1062
+ };
1063
+ }
1064
+
1065
+ /**
1066
+ * @module @kb-labs/core-runtime/core/cron-manager
1067
+ * Cron job manager with scheduling support.
1068
+ */
1069
+
1070
+ /**
1071
+ * In-memory cron manager with scheduling.
1072
+ */
1073
+ declare class CronManager implements ICronManager {
1074
+ private logger;
1075
+ private jobs;
1076
+ constructor(logger: ILogger);
1077
+ register(id: string, schedule: CronExpression, handler: CronHandler): void;
1078
+ unregister(id: string): void;
1079
+ list(): CronJob[];
1080
+ trigger(id: string): Promise<void>;
1081
+ pause(id: string): void;
1082
+ resume(id: string): void;
1083
+ /**
1084
+ * Schedule the next execution of a cron job.
1085
+ */
1086
+ private scheduleNext;
1087
+ /**
1088
+ * Execute a cron job.
1089
+ */
1090
+ private executeJob;
1091
+ /**
1092
+ * Stop all cron jobs (for cleanup).
1093
+ */
1094
+ dispose(): void;
1095
+ /**
1096
+ * Get stats (for monitoring).
1097
+ */
1098
+ getStats(): {
1099
+ totalJobs: number;
1100
+ activeJobs: number;
1101
+ pausedJobs: number;
1102
+ };
1103
+ }
1104
+
1105
+ /**
1106
+ * @module @kb-labs/core-runtime/core/workflow-engine
1107
+ * In-memory workflow engine with step execution.
1108
+ */
1109
+
1110
+ interface WorkflowEngineConfig {
1111
+ /** Maximum concurrent workflows globally (default: 5) */
1112
+ maxConcurrent?: number;
1113
+ /** Default workflow timeout in ms (default: 300000 = 5min) */
1114
+ defaultTimeout?: number;
1115
+ }
1116
+ /**
1117
+ * Workflow definition (registered workflows).
1118
+ */
1119
+ interface WorkflowDefinition {
1120
+ id: string;
1121
+ name: string;
1122
+ steps: WorkflowStepDefinition[];
1123
+ }
1124
+ /**
1125
+ * Workflow step definition.
1126
+ */
1127
+ interface WorkflowStepDefinition {
1128
+ id: string;
1129
+ name: string;
1130
+ handler: (input: unknown, context: WorkflowStepContext) => Promise<unknown>;
1131
+ continueOnError?: boolean;
1132
+ timeout?: number;
1133
+ }
1134
+ /**
1135
+ * Context passed to step handlers.
1136
+ */
1137
+ interface WorkflowStepContext {
1138
+ workflowId: string;
1139
+ runId: string;
1140
+ stepId: string;
1141
+ tenantId: string;
1142
+ previousStepOutput?: unknown;
1143
+ }
1144
+ /**
1145
+ * In-memory workflow engine.
1146
+ */
1147
+ declare class WorkflowEngine implements IWorkflowEngine {
1148
+ private resources;
1149
+ private storage;
1150
+ private events;
1151
+ private logger;
1152
+ private runs;
1153
+ private definitions;
1154
+ private running;
1155
+ private idCounter;
1156
+ private readonly config;
1157
+ constructor(resources: IResourceManager, storage: IStorage, events: IEventBus, logger: ILogger, config?: WorkflowEngineConfig);
1158
+ /**
1159
+ * Register a workflow definition.
1160
+ */
1161
+ registerWorkflow(definition: WorkflowDefinition): void;
1162
+ /**
1163
+ * Unregister a workflow definition.
1164
+ */
1165
+ unregisterWorkflow(workflowId: string): void;
1166
+ execute(workflowId: string, input: unknown, options?: WorkflowOptions): Promise<WorkflowRun>;
1167
+ getStatus(runId: string): Promise<WorkflowRun | null>;
1168
+ cancel(runId: string): Promise<void>;
1169
+ retry(runId: string, fromStep?: string): Promise<WorkflowRun>;
1170
+ list(filter?: WorkflowFilter): Promise<WorkflowRun[]>;
1171
+ /**
1172
+ * Execute a single workflow step.
1173
+ */
1174
+ private executeStep;
1175
+ /**
1176
+ * Mark run as failed.
1177
+ */
1178
+ private failRun;
1179
+ /**
1180
+ * Schedule a workflow retry based on policy.
1181
+ */
1182
+ private scheduleRetry;
1183
+ /**
1184
+ * Persist workflow run to storage.
1185
+ */
1186
+ private persistRun;
1187
+ /**
1188
+ * Convert internal run to public representation.
1189
+ */
1190
+ private toPublicRun;
1191
+ /**
1192
+ * Stop all workflows (for cleanup).
1193
+ */
1194
+ dispose(): void;
1195
+ /**
1196
+ * Get engine stats (for monitoring).
1197
+ */
1198
+ getStats(): {
1199
+ totalRuns: number;
1200
+ runningCount: number;
1201
+ registeredWorkflows: number;
1202
+ byStatus: Record<string, number>;
1203
+ };
1204
+ }
1205
+
1206
+ /**
1207
+ * @module @kb-labs/core-runtime/transport
1208
+ * Abstract transport layer for cross-process adapter communication.
1209
+ *
1210
+ * Provides a transport-agnostic interface for sending adapter calls
1211
+ * between parent and child processes. Implementations can use:
1212
+ * - IPC (process.send/process.on('message'))
1213
+ * - HTTP REST API
1214
+ * - Docker exec
1215
+ * - gRPC
1216
+ * - WebSockets
1217
+ *
1218
+ * @example
1219
+ * ```typescript
1220
+ * import { ITransport, IPCTransport } from '@kb-labs/core-runtime/transport';
1221
+ *
1222
+ * const transport: ITransport = new IPCTransport();
1223
+ * const response = await transport.send({
1224
+ * type: 'adapter:call',
1225
+ * requestId: 'uuid-123',
1226
+ * adapter: 'vectorStore',
1227
+ * method: 'search',
1228
+ * args: [[0.1, 0.2, 0.3], 10],
1229
+ * });
1230
+ * ```
1231
+ */
1232
+
1233
+ /**
1234
+ * Abstract transport for sending adapter calls.
1235
+ *
1236
+ * Implementations must handle:
1237
+ * - Reliable message delivery
1238
+ * - Timeout enforcement
1239
+ * - Error propagation
1240
+ * - Resource cleanup
1241
+ *
1242
+ * Thread-safety: Implementations must be safe to call concurrently
1243
+ * from multiple async contexts.
1244
+ */
1245
+ interface ITransport {
1246
+ /**
1247
+ * Send adapter call and await response.
1248
+ *
1249
+ * @param call - Adapter method call to send
1250
+ * @returns Response with result or error
1251
+ * @throws TransportError if communication fails
1252
+ * @throws TimeoutError if timeout exceeded
1253
+ * @throws SerializationError if message cannot be serialized
1254
+ *
1255
+ * @example
1256
+ * ```typescript
1257
+ * const call: AdapterCall = {
1258
+ * type: 'adapter:call',
1259
+ * requestId: 'uuid-123',
1260
+ * adapter: 'vectorStore',
1261
+ * method: 'search',
1262
+ * args: [[0.1, 0.2, 0.3], 10],
1263
+ * timeout: 5000,
1264
+ * };
1265
+ *
1266
+ * const response = await transport.send(call);
1267
+ * if (response.error) {
1268
+ * throw deserialize(response.error);
1269
+ * }
1270
+ * return deserialize(response.result);
1271
+ * ```
1272
+ */
1273
+ send(call: AdapterCall): Promise<AdapterResponse>;
1274
+ /**
1275
+ * Close transport and cleanup resources.
1276
+ *
1277
+ * After close():
1278
+ * - No new calls can be sent
1279
+ * - Pending calls are rejected with TransportError
1280
+ * - Listeners/connections are cleaned up
1281
+ *
1282
+ * @example
1283
+ * ```typescript
1284
+ * await transport.close();
1285
+ * // All pending calls rejected
1286
+ * // transport.send() will throw TransportError
1287
+ * ```
1288
+ */
1289
+ close(): Promise<void>;
1290
+ /**
1291
+ * Check if transport is closed.
1292
+ */
1293
+ isClosed(): boolean;
1294
+ }
1295
+
1296
+ /**
1297
+ * @module @kb-labs/core-runtime/proxy
1298
+ * Generic base class for remote adapter proxies.
1299
+ *
1300
+ * This class provides the foundation for all IPC proxy adapters.
1301
+ * It handles serialization, transport, and error propagation automatically.
1302
+ *
1303
+ * @example
1304
+ * ```typescript
1305
+ * import { RemoteAdapter } from '@kb-labs/core-runtime/proxy';
1306
+ * import type { IVectorStore } from '@kb-labs/core-platform';
1307
+ *
1308
+ * class VectorStoreProxy extends RemoteAdapter<IVectorStore> implements IVectorStore {
1309
+ * constructor(transport: ITransport) {
1310
+ * super('vectorStore', transport);
1311
+ * }
1312
+ *
1313
+ * async search(query: number[], limit: number): Promise<VectorSearchResult[]> {
1314
+ * return this.callRemote('search', [query, limit]) as Promise<VectorSearchResult[]>;
1315
+ * }
1316
+ * }
1317
+ * ```
1318
+ */
1319
+
1320
+ /**
1321
+ * Generic base class for remote adapter proxies.
1322
+ *
1323
+ * Automatically handles:
1324
+ * - Method call serialization
1325
+ * - Transport communication
1326
+ * - Response deserialization
1327
+ * - Error propagation
1328
+ * - Context propagation (traceId, pluginId, etc.)
1329
+ *
1330
+ * Type parameter T should be the adapter interface (e.g., IVectorStore).
1331
+ */
1332
+ declare abstract class RemoteAdapter<T> {
1333
+ private readonly adapterName;
1334
+ private readonly transport;
1335
+ private context?;
1336
+ /**
1337
+ * Create a remote adapter proxy.
1338
+ *
1339
+ * @param adapterName - Name of the adapter (e.g., 'vectorStore', 'cache')
1340
+ * @param transport - Transport layer for IPC communication
1341
+ * @param context - Optional execution context for tracing/debugging
1342
+ */
1343
+ constructor(adapterName: AdapterType, transport: ITransport, context?: AdapterCallContext);
1344
+ /**
1345
+ * Set execution context for this adapter.
1346
+ * Context is included in all subsequent adapter calls for tracing/debugging.
1347
+ *
1348
+ * @param context - Execution context (traceId, pluginId, sessionId, etc.)
1349
+ *
1350
+ * @example
1351
+ * ```typescript
1352
+ * proxy.setContext({
1353
+ * traceId: 'trace-abc',
1354
+ * pluginId: '@kb-labs/mind',
1355
+ * sessionId: 'session-xyz',
1356
+ * });
1357
+ * ```
1358
+ */
1359
+ setContext(context: AdapterCallContext): void;
1360
+ /**
1361
+ * Get current execution context.
1362
+ */
1363
+ getContext(): AdapterCallContext | undefined;
1364
+ /**
1365
+ * Call a method on the remote adapter (in parent process).
1366
+ *
1367
+ * This method:
1368
+ * 1. Generates a unique request ID
1369
+ * 2. Serializes the method arguments
1370
+ * 3. Sends the call via transport
1371
+ * 4. Waits for response
1372
+ * 5. Deserializes and returns the result (or throws error)
1373
+ *
1374
+ * @param method - Method name to call on the adapter
1375
+ * @param args - Method arguments (will be serialized)
1376
+ * @param timeout - Optional timeout in milliseconds (overrides transport default)
1377
+ * @returns Promise resolving to deserialized result
1378
+ * @throws Error if remote method throws or communication fails
1379
+ *
1380
+ * @example
1381
+ * ```typescript
1382
+ * // In VectorStoreProxy.search():
1383
+ * return this.callRemote('search', [query, limit, filter]);
1384
+ *
1385
+ * // With custom timeout for bulk operations:
1386
+ * return this.callRemote('upsert', [vectors], 120000); // 2 min timeout
1387
+ * ```
1388
+ */
1389
+ protected callRemote(method: string, args: unknown[], timeout?: number): Promise<unknown>;
1390
+ /**
1391
+ * Get the adapter name this proxy represents.
1392
+ */
1393
+ protected getAdapterName(): AdapterType;
1394
+ /**
1395
+ * Get the transport used by this proxy.
1396
+ * Useful for advanced use cases (e.g., checking if transport is closed).
1397
+ */
1398
+ protected getTransport(): ITransport;
1399
+ }
1400
+
1401
+ /**
1402
+ * @module @kb-labs/core-runtime/proxy
1403
+ * IPC proxy for IVectorStore adapter.
1404
+ *
1405
+ * This proxy forwards all vector store operations to the parent process
1406
+ * via IPC. The parent process owns the real QdrantVectorStore instance.
1407
+ *
1408
+ * Benefits:
1409
+ * - Single QdrantVectorStore instance (shared across all sandbox workers)
1410
+ * - Reduced memory usage (no duplicate connections)
1411
+ * - Reduced connection count (5 instead of 250 for 50 workers)
1412
+ *
1413
+ * @example
1414
+ * ```typescript
1415
+ * import { VectorStoreProxy, createIPCTransport } from '@kb-labs/core-runtime';
1416
+ *
1417
+ * // In child process (sandbox worker)
1418
+ * const transport = createIPCTransport();
1419
+ * const vectorStore = new VectorStoreProxy(transport);
1420
+ *
1421
+ * // Use like normal IVectorStore
1422
+ * const results = await vectorStore.search([0.1, 0.2, 0.3], 10);
1423
+ * ```
1424
+ */
1425
+
1426
+ /**
1427
+ * IPC proxy for IVectorStore adapter.
1428
+ *
1429
+ * All method calls are forwarded to the parent process via IPC.
1430
+ * The parent process executes the call on the real vector store
1431
+ * (e.g., QdrantVectorStore) and returns the result.
1432
+ *
1433
+ * From the caller's perspective, this behaves identically to a
1434
+ * local vector store - the IPC layer is completely transparent.
1435
+ */
1436
+ declare class VectorStoreProxy extends RemoteAdapter<IVectorStore> implements IVectorStore {
1437
+ private static readonly BULK_OPERATION_TIMEOUT;
1438
+ private readonly bulkTransferOptions;
1439
+ /**
1440
+ * Create a vector store proxy.
1441
+ *
1442
+ * @param transport - IPC transport to communicate with parent
1443
+ */
1444
+ constructor(transport: ITransport);
1445
+ /**
1446
+ * Search for similar vectors.
1447
+ *
1448
+ * @param query - Query embedding vector
1449
+ * @param limit - Maximum number of results
1450
+ * @param filter - Optional metadata filter
1451
+ * @returns Promise resolving to search results
1452
+ */
1453
+ search(query: number[], limit: number, filter?: VectorFilter): Promise<VectorSearchResult[]>;
1454
+ /**
1455
+ * Insert or update vectors.
1456
+ * Uses BulkTransfer for large payloads to avoid IPC backpressure.
1457
+ *
1458
+ * @param vectors - Vector records to upsert
1459
+ */
1460
+ upsert(vectors: VectorRecord[]): Promise<void>;
1461
+ /**
1462
+ * Delete vectors by IDs.
1463
+ * Uses extended timeout for bulk deletions.
1464
+ *
1465
+ * @param ids - Vector IDs to delete
1466
+ */
1467
+ delete(ids: string[]): Promise<void>;
1468
+ /**
1469
+ * Upsert vectors with chunk metadata (used by Mind RAG).
1470
+ * Uses extended timeout for bulk operations.
1471
+ *
1472
+ * @param scope - Scope ID
1473
+ * @param vectors - Vector records to upsert
1474
+ */
1475
+ upsertChunks(scope: string, vectors: VectorRecord[]): Promise<void>;
1476
+ /**
1477
+ * Count total vectors in collection.
1478
+ *
1479
+ * @returns Promise resolving to vector count
1480
+ */
1481
+ count(): Promise<number>;
1482
+ /**
1483
+ * Get vectors by IDs.
1484
+ * IDs argument is usually small, passed directly through IPC.
1485
+ * Uses BulkTransfer only for large result sets.
1486
+ *
1487
+ * @param ids - Vector IDs to retrieve
1488
+ * @returns Promise resolving to vector records
1489
+ */
1490
+ get(ids: string[]): Promise<VectorRecord[]>;
1491
+ /**
1492
+ * Query vectors by metadata filter.
1493
+ * Filter argument is small, passed directly through IPC.
1494
+ * Uses BulkTransfer only for potentially large result sets.
1495
+ *
1496
+ * @param filter - Metadata filter to apply
1497
+ * @returns Promise resolving to matching vector records
1498
+ */
1499
+ query(filter: VectorFilter): Promise<VectorRecord[]>;
1500
+ /**
1501
+ * Clear all vectors from collection.
1502
+ * Uses extended timeout for bulk deletion.
1503
+ */
1504
+ clear(): Promise<void>;
1505
+ /**
1506
+ * Initialize the vector store.
1507
+ * Called during platform initialization.
1508
+ */
1509
+ initialize(): Promise<void>;
1510
+ /**
1511
+ * Close connections and cleanup resources.
1512
+ */
1513
+ close(): Promise<void>;
1514
+ }
1515
+ /**
1516
+ * Create a VectorStore proxy with IPC transport.
1517
+ *
1518
+ * @param transport - IPC transport to use
1519
+ * @returns VectorStore proxy instance
1520
+ *
1521
+ * @example
1522
+ * ```typescript
1523
+ * import { createVectorStoreProxy, createIPCTransport } from '@kb-labs/core-runtime';
1524
+ *
1525
+ * const transport = createIPCTransport();
1526
+ * const vectorStore = createVectorStoreProxy(transport);
1527
+ * ```
1528
+ */
1529
+ declare function createVectorStoreProxy(transport: ITransport): VectorStoreProxy;
1530
+
1531
+ /**
1532
+ * @module @kb-labs/core-runtime/proxy
1533
+ * IPC proxy for ICache adapter.
1534
+ *
1535
+ * This proxy forwards all cache operations to the parent process via IPC.
1536
+ * The parent process owns the real cache adapter (e.g., RedisCacheAdapter).
1537
+ *
1538
+ * Benefits:
1539
+ * - Single cache instance (shared across all sandbox workers)
1540
+ * - Reduced memory usage (no duplicate Redis connections)
1541
+ * - Reduced connection count (5 instead of 250 for 50 workers)
1542
+ *
1543
+ * @example
1544
+ * ```typescript
1545
+ * import { CacheProxy, createIPCTransport } from '@kb-labs/core-runtime';
1546
+ *
1547
+ * // In child process (sandbox worker)
1548
+ * const transport = createIPCTransport();
1549
+ * const cache = new CacheProxy(transport);
1550
+ *
1551
+ * // Use like normal ICache
1552
+ * await cache.set('key', { foo: 'bar' }, 60000);
1553
+ * const value = await cache.get('key');
1554
+ * ```
1555
+ */
1556
+
1557
+ /**
1558
+ * IPC proxy for ICache adapter.
1559
+ *
1560
+ * All method calls are forwarded to the parent process via IPC.
1561
+ * The parent process executes the call on the real cache adapter
1562
+ * (e.g., RedisCacheAdapter) and returns the result.
1563
+ *
1564
+ * From the caller's perspective, this behaves identically to a
1565
+ * local cache - the IPC layer is completely transparent.
1566
+ */
1567
+ declare class CacheProxy extends RemoteAdapter<ICache> implements ICache {
1568
+ /**
1569
+ * Create a cache proxy.
1570
+ *
1571
+ * @param transport - IPC transport to communicate with parent
1572
+ */
1573
+ constructor(transport: ITransport);
1574
+ /**
1575
+ * Get a value from cache.
1576
+ *
1577
+ * @param key - Cache key
1578
+ * @returns Cached value or null if not found/expired
1579
+ */
1580
+ get<T>(key: string): Promise<T | null>;
1581
+ /**
1582
+ * Set a value in cache.
1583
+ *
1584
+ * @param key - Cache key
1585
+ * @param value - Value to cache
1586
+ * @param ttl - Time to live in milliseconds (optional)
1587
+ */
1588
+ set<T>(key: string, value: T, ttl?: number): Promise<void>;
1589
+ /**
1590
+ * Delete a value from cache.
1591
+ *
1592
+ * @param key - Cache key
1593
+ */
1594
+ delete(key: string): Promise<void>;
1595
+ /**
1596
+ * Clear cache entries matching a pattern.
1597
+ *
1598
+ * @param pattern - Glob pattern (e.g., 'user:*')
1599
+ */
1600
+ clear(pattern?: string): Promise<void>;
1601
+ /**
1602
+ * Add member to sorted set with score.
1603
+ *
1604
+ * @param key - Sorted set key
1605
+ * @param score - Numeric score (typically timestamp)
1606
+ * @param member - Member to add
1607
+ */
1608
+ zadd(key: string, score: number, member: string): Promise<void>;
1609
+ /**
1610
+ * Get members from sorted set by score range.
1611
+ *
1612
+ * @param key - Sorted set key
1613
+ * @param min - Minimum score (inclusive)
1614
+ * @param max - Maximum score (inclusive)
1615
+ * @returns Array of members in score order
1616
+ */
1617
+ zrangebyscore(key: string, min: number, max: number): Promise<string[]>;
1618
+ /**
1619
+ * Remove member from sorted set.
1620
+ *
1621
+ * @param key - Sorted set key
1622
+ * @param member - Member to remove
1623
+ */
1624
+ zrem(key: string, member: string): Promise<void>;
1625
+ /**
1626
+ * Set key-value pair only if key does not exist (atomic operation).
1627
+ *
1628
+ * @param key - Cache key
1629
+ * @param value - Value to set
1630
+ * @param ttl - Time to live in milliseconds (optional)
1631
+ * @returns true if value was set, false if key already exists
1632
+ */
1633
+ setIfNotExists<T>(key: string, value: T, ttl?: number): Promise<boolean>;
1634
+ }
1635
+ /**
1636
+ * Create a Cache proxy with IPC transport.
1637
+ *
1638
+ * @param transport - IPC transport to use
1639
+ * @returns Cache proxy instance
1640
+ *
1641
+ * @example
1642
+ * ```typescript
1643
+ * import { createCacheProxy, createIPCTransport } from '@kb-labs/core-runtime';
1644
+ *
1645
+ * const transport = createIPCTransport();
1646
+ * const cache = createCacheProxy(transport);
1647
+ * ```
1648
+ */
1649
+ declare function createCacheProxy(transport: ITransport): CacheProxy;
1650
+
1651
+ /**
1652
+ * @module @kb-labs/core-runtime/proxy
1653
+ * IPC proxy for ILLM adapter.
1654
+ *
1655
+ * This proxy forwards all LLM operations to the parent process via IPC.
1656
+ * The parent process owns the real LLM adapter (e.g., OpenAILLM).
1657
+ *
1658
+ * Benefits:
1659
+ * - Single LLM instance (shared rate limiter across all workers)
1660
+ * - Reduced memory usage (no duplicate API clients)
1661
+ * - Centralized quota enforcement (tenant rate limits)
1662
+ *
1663
+ * Note: true token-by-token streaming is not supported over IPC.
1664
+ * This proxy falls back to complete() and emits a single chunk.
1665
+ *
1666
+ * @example
1667
+ * ```typescript
1668
+ * import { LLMProxy, createIPCTransport } from '@kb-labs/core-runtime';
1669
+ *
1670
+ * // In child process (sandbox worker)
1671
+ * const transport = createIPCTransport();
1672
+ * const llm = new LLMProxy(transport);
1673
+ *
1674
+ * // Use like normal ILLM
1675
+ * const response = await llm.complete('What is TypeScript?', {
1676
+ * model: 'gpt-4',
1677
+ * temperature: 0.7,
1678
+ * maxTokens: 500,
1679
+ * });
1680
+ * ```
1681
+ */
1682
+
1683
+ /**
1684
+ * IPC proxy for ILLM adapter.
1685
+ *
1686
+ * All method calls are forwarded to the parent process via IPC.
1687
+ * The parent process executes the call on the real LLM adapter
1688
+ * (e.g., OpenAILLM) and returns the result.
1689
+ *
1690
+ * **Limitation**: true token-by-token `stream()` is not supported over IPC.
1691
+ * Streaming requires bidirectional communication which is not
1692
+ * currently implemented. This proxy falls back to `complete()`.
1693
+ */
1694
+ declare class LLMProxy extends RemoteAdapter<ILLM> implements ILLM {
1695
+ /**
1696
+ * Create an LLM proxy.
1697
+ *
1698
+ * @param transport - IPC transport to communicate with parent
1699
+ */
1700
+ constructor(transport: ITransport);
1701
+ /**
1702
+ * Generate a completion for the given prompt.
1703
+ *
1704
+ * @param prompt - Text prompt
1705
+ * @param options - Optional generation options
1706
+ * @returns LLM response with content and token usage
1707
+ */
1708
+ complete(prompt: string, options?: LLMOptions): Promise<LLMResponse>;
1709
+ getProtocolCapabilities(): LLMProtocolCapabilities;
1710
+ /**
1711
+ * Stream a completion for the given prompt.
1712
+ *
1713
+ * **Fallback over IPC**: Uses complete() and emits a single chunk.
1714
+ *
1715
+ * Streaming requires bidirectional communication which is not
1716
+ * currently implemented in the IPC protocol. This fallback preserves
1717
+ * API compatibility for callers expecting AsyncIterable<string>.
1718
+ *
1719
+ * @param prompt - Text prompt
1720
+ * @param options - Optional generation options
1721
+ * @returns Async iterable with a single chunk from complete()
1722
+ */
1723
+ stream(prompt: string, options?: LLMOptions): AsyncIterable<string>;
1724
+ /**
1725
+ * Chat with native tool calling support.
1726
+ *
1727
+ * Forwards tool calling request to parent process via IPC.
1728
+ *
1729
+ * @param messages - Conversation history
1730
+ * @param options - Options including tools and tool choice
1731
+ * @returns LLM response with optional tool calls
1732
+ */
1733
+ chatWithTools(messages: LLMMessage[], options: LLMToolCallOptions): Promise<LLMToolCallResponse>;
1734
+ }
1735
+
1736
+ /**
1737
+ * @module @kb-labs/core-runtime/proxy
1738
+ * IPC proxy for IEmbeddings adapter.
1739
+ *
1740
+ * This proxy forwards all embeddings operations to the parent process via IPC.
1741
+ * The parent process owns the real embeddings adapter (e.g., OpenAIEmbeddings).
1742
+ *
1743
+ * Benefits:
1744
+ * - Single embeddings instance (shared rate limiter across all workers)
1745
+ * - Reduced memory usage (no duplicate API clients)
1746
+ * - Centralized quota enforcement (tenant rate limits)
1747
+ *
1748
+ * @example
1749
+ * ```typescript
1750
+ * import { EmbeddingsProxy, createIPCTransport } from '@kb-labs/core-runtime';
1751
+ *
1752
+ * // In child process (sandbox worker)
1753
+ * const transport = createIPCTransport();
1754
+ * const embeddings = new EmbeddingsProxy(transport);
1755
+ *
1756
+ * // Use like normal IEmbeddings
1757
+ * const vector = await embeddings.embed('Hello world');
1758
+ * const vectors = await embeddings.embedBatch(['foo', 'bar', 'baz']);
1759
+ * console.log('Dimensions:', embeddings.dimensions); // 1536
1760
+ * ```
1761
+ */
1762
+
1763
+ /**
1764
+ * IPC proxy for IEmbeddings adapter.
1765
+ *
1766
+ * All method calls are forwarded to the parent process via IPC.
1767
+ * The parent process executes the call on the real embeddings adapter
1768
+ * (e.g., OpenAIEmbeddings) and returns the result.
1769
+ *
1770
+ * The `dimensions` property is fetched once during initialization
1771
+ * and cached locally for performance.
1772
+ */
1773
+ declare class EmbeddingsProxy extends RemoteAdapter<IEmbeddings> implements IEmbeddings {
1774
+ private _dimensions?;
1775
+ /**
1776
+ * Create an embeddings proxy.
1777
+ *
1778
+ * @param transport - IPC transport to communicate with parent
1779
+ * @param dimensions - Optional dimensions override (avoids IPC call)
1780
+ */
1781
+ constructor(transport: ITransport, dimensions?: number);
1782
+ /**
1783
+ * Generate embedding vector for a single text.
1784
+ *
1785
+ * @param text - Input text
1786
+ * @returns Embedding vector
1787
+ */
1788
+ embed(text: string): Promise<number[]>;
1789
+ /**
1790
+ * Generate embedding vectors for multiple texts.
1791
+ *
1792
+ * @param texts - Array of input texts
1793
+ * @returns Array of embedding vectors (same order as input)
1794
+ */
1795
+ embedBatch(texts: string[]): Promise<number[][]>;
1796
+ /**
1797
+ * Dimension of the embedding vectors.
1798
+ *
1799
+ * This value is fetched once from the parent on first access
1800
+ * and cached locally for performance.
1801
+ */
1802
+ get dimensions(): number;
1803
+ /**
1804
+ * Initialize dimensions by fetching from parent.
1805
+ *
1806
+ * This is called automatically by initPlatform() in child process.
1807
+ * If you create EmbeddingsProxy manually, call this method before
1808
+ * accessing the `dimensions` property.
1809
+ *
1810
+ * @returns Dimensions value
1811
+ *
1812
+ * @example
1813
+ * ```typescript
1814
+ * const proxy = new EmbeddingsProxy(transport);
1815
+ * await proxy.getDimensions(); // Fetch once
1816
+ * console.log(proxy.dimensions); // Now safe to access
1817
+ * ```
1818
+ */
1819
+ getDimensions(): Promise<number>;
1820
+ }
1821
+
1822
+ /**
1823
+ * @module @kb-labs/core-runtime/proxy
1824
+ * IPC proxy for IStorage adapter.
1825
+ *
1826
+ * This proxy forwards all storage operations to the parent process via IPC.
1827
+ * The parent process owns the real storage adapter (e.g., FilesystemStorageAdapter).
1828
+ *
1829
+ * Benefits:
1830
+ * - Single storage instance (consistent file access across all workers)
1831
+ * - Reduced memory usage (no duplicate file handles)
1832
+ * - No race conditions (centralized file access)
1833
+ *
1834
+ * Note: Buffer serialization is handled automatically by the IPC layer.
1835
+ *
1836
+ * @example
1837
+ * ```typescript
1838
+ * import { StorageProxy, createIPCTransport } from '@kb-labs/core-runtime';
1839
+ *
1840
+ * // In child process (sandbox worker)
1841
+ * const transport = createIPCTransport();
1842
+ * const storage = new StorageProxy(transport);
1843
+ *
1844
+ * // Use like normal IStorage
1845
+ * await storage.write('.kb/data.json', Buffer.from('{"foo":"bar"}'));
1846
+ * const data = await storage.read('.kb/data.json');
1847
+ * const files = await storage.list('.kb/');
1848
+ * ```
1849
+ */
1850
+
1851
+ /**
1852
+ * IPC proxy for IStorage adapter.
1853
+ *
1854
+ * All method calls are forwarded to the parent process via IPC.
1855
+ * The parent process executes the call on the real storage adapter
1856
+ * (e.g., FilesystemStorageAdapter) and returns the result.
1857
+ *
1858
+ * Buffer serialization/deserialization is handled automatically
1859
+ * by the IPC serializer (Buffer → base64 → Buffer).
1860
+ */
1861
+ declare class StorageProxy extends RemoteAdapter<IStorage$1> implements IStorage$1 {
1862
+ /**
1863
+ * Create a storage proxy.
1864
+ *
1865
+ * @param transport - IPC transport to communicate with parent
1866
+ */
1867
+ constructor(transport: ITransport);
1868
+ /**
1869
+ * Read file contents.
1870
+ *
1871
+ * @param path - File path
1872
+ * @returns File contents or null if not found
1873
+ */
1874
+ read(path: string): Promise<Buffer | null>;
1875
+ /**
1876
+ * Write file contents.
1877
+ *
1878
+ * @param path - File path
1879
+ * @param data - File contents
1880
+ */
1881
+ write(path: string, data: Buffer): Promise<void>;
1882
+ /**
1883
+ * Delete a file.
1884
+ *
1885
+ * @param path - File path
1886
+ */
1887
+ delete(path: string): Promise<void>;
1888
+ /**
1889
+ * List files matching a prefix.
1890
+ *
1891
+ * @param prefix - Path prefix (e.g., 'docs/')
1892
+ * @returns Array of file paths
1893
+ */
1894
+ list(prefix: string): Promise<string[]>;
1895
+ /**
1896
+ * Check if a file exists.
1897
+ *
1898
+ * @param path - File path
1899
+ * @returns True if file exists, false otherwise
1900
+ */
1901
+ exists(path: string): Promise<boolean>;
1902
+ /**
1903
+ * Get file metadata.
1904
+ * Optional method - implements IStorage.stat().
1905
+ *
1906
+ * @param path - File path
1907
+ * @returns File metadata or null if not found
1908
+ */
1909
+ stat?(path: string): Promise<StorageMetadata | null>;
1910
+ /**
1911
+ * Copy file within storage.
1912
+ * Optional method - implements IStorage.copy().
1913
+ *
1914
+ * @param sourcePath - Source file path
1915
+ * @param destPath - Destination file path
1916
+ */
1917
+ copy?(sourcePath: string, destPath: string): Promise<void>;
1918
+ /**
1919
+ * Move file within storage.
1920
+ * Optional method - implements IStorage.move().
1921
+ *
1922
+ * @param sourcePath - Source file path
1923
+ * @param destPath - Destination file path
1924
+ */
1925
+ move?(sourcePath: string, destPath: string): Promise<void>;
1926
+ /**
1927
+ * List files with metadata.
1928
+ * Optional method - implements IStorage.listWithMetadata().
1929
+ *
1930
+ * @param prefix - Path prefix (e.g., 'docs/')
1931
+ * @returns Array of file metadata
1932
+ */
1933
+ listWithMetadata?(prefix: string): Promise<StorageMetadata[]>;
1934
+ }
1935
+ /**
1936
+ * Create a Storage proxy with IPC transport.
1937
+ *
1938
+ * @param transport - IPC transport to use
1939
+ * @returns Storage proxy instance
1940
+ *
1941
+ * @example
1942
+ * ```typescript
1943
+ * import { createStorageProxy, createIPCTransport } from '@kb-labs/core-runtime';
1944
+ *
1945
+ * const transport = createIPCTransport();
1946
+ * const storage = createStorageProxy(transport);
1947
+ * ```
1948
+ */
1949
+ declare function createStorageProxy(transport: ITransport): StorageProxy;
1950
+
1951
+ /**
1952
+ * @module @kb-labs/core-runtime/proxy
1953
+ * IPC proxy for ISQLDatabase adapter.
1954
+ *
1955
+ * This proxy forwards all SQL database operations to the parent process via IPC.
1956
+ * The parent process owns the real SQL adapter (e.g., SQLiteAdapter).
1957
+ *
1958
+ * Benefits:
1959
+ * - Single database connection (consistent data access across all workers)
1960
+ * - Reduced memory usage (no duplicate connections)
1961
+ * - No race conditions (centralized transaction management)
1962
+ *
1963
+ * @example
1964
+ * ```typescript
1965
+ * import { SQLDatabaseProxy, createIPCTransport } from '@kb-labs/core-runtime';
1966
+ *
1967
+ * // In child process (sandbox worker)
1968
+ * const transport = createIPCTransport();
1969
+ * const db = new SQLDatabaseProxy(transport);
1970
+ *
1971
+ * // Use like normal ISQLDatabase
1972
+ * const result = await db.query('SELECT * FROM users WHERE id = ?', [123]);
1973
+ * console.log(result.rows);
1974
+ *
1975
+ * // Transactions
1976
+ * const tx = await db.transaction();
1977
+ * await tx.query('INSERT INTO users (name) VALUES (?)', ['Alice']);
1978
+ * await tx.commit();
1979
+ * ```
1980
+ */
1981
+
1982
+ /**
1983
+ * IPC proxy for ISQLDatabase adapter.
1984
+ *
1985
+ * All method calls are forwarded to the parent process via IPC.
1986
+ * The parent process executes the call on the real SQL adapter
1987
+ * (e.g., SQLiteAdapter, PostgreSQLAdapter) and returns the result.
1988
+ */
1989
+ declare class SQLDatabaseProxy extends RemoteAdapter<ISQLDatabase> implements ISQLDatabase {
1990
+ /**
1991
+ * Create a SQL database proxy.
1992
+ *
1993
+ * @param transport - IPC transport to communicate with parent
1994
+ */
1995
+ constructor(transport: ITransport);
1996
+ /**
1997
+ * Execute a SQL query.
1998
+ *
1999
+ * @param sql - SQL query string
2000
+ * @param params - Query parameters
2001
+ * @returns Query result
2002
+ */
2003
+ query<T = unknown>(sql: string, params?: unknown[]): Promise<SQLQueryResult<T>>;
2004
+ /**
2005
+ * Begin a SQL transaction.
2006
+ *
2007
+ * @returns Transaction proxy object
2008
+ */
2009
+ transaction(): Promise<SQLTransaction>;
2010
+ /**
2011
+ * Close the database connection.
2012
+ */
2013
+ close(): Promise<void>;
2014
+ }
2015
+ /**
2016
+ * Create a SQL database proxy with IPC transport.
2017
+ *
2018
+ * @param transport - IPC transport to use
2019
+ * @returns SQL database proxy instance
2020
+ *
2021
+ * @example
2022
+ * ```typescript
2023
+ * import { createSQLDatabaseProxy, createIPCTransport } from '@kb-labs/core-runtime';
2024
+ *
2025
+ * const transport = createIPCTransport();
2026
+ * const db = createSQLDatabaseProxy(transport);
2027
+ * ```
2028
+ */
2029
+ declare function createSQLDatabaseProxy(transport: ITransport): SQLDatabaseProxy;
2030
+
2031
+ /**
2032
+ * @module @kb-labs/core-runtime/proxy
2033
+ * IPC proxy for IDocumentDatabase adapter.
2034
+ *
2035
+ * This proxy forwards all document database operations to the parent process via IPC.
2036
+ * The parent process owns the real document adapter (e.g., MongoDBAdapter).
2037
+ *
2038
+ * Benefits:
2039
+ * - Single database connection (consistent data access across all workers)
2040
+ * - Reduced memory usage (no duplicate connections)
2041
+ * - No race conditions (centralized transaction management)
2042
+ *
2043
+ * @example
2044
+ * ```typescript
2045
+ * import { DocumentDatabaseProxy, createIPCTransport } from '@kb-labs/core-runtime';
2046
+ *
2047
+ * // In child process (sandbox worker)
2048
+ * const transport = createIPCTransport();
2049
+ * const db = new DocumentDatabaseProxy(transport);
2050
+ *
2051
+ * // Use like normal IDocumentDatabase
2052
+ * const users = await db.find('users', { age: { $gt: 18 } }, { limit: 10 });
2053
+ * console.log(users);
2054
+ *
2055
+ * // Update by ID
2056
+ * const updated = await db.updateById('users', '123', { $set: { active: true } });
2057
+ * ```
2058
+ */
2059
+
2060
+ /**
2061
+ * IPC proxy for IDocumentDatabase adapter.
2062
+ *
2063
+ * All method calls are forwarded to the parent process via IPC.
2064
+ * The parent process executes the call on the real document adapter
2065
+ * (e.g., MongoDBAdapter) and returns the result.
2066
+ */
2067
+ declare class DocumentDatabaseProxy extends RemoteAdapter<IDocumentDatabase> implements IDocumentDatabase {
2068
+ /**
2069
+ * Create a document database proxy.
2070
+ *
2071
+ * @param transport - IPC transport to communicate with parent
2072
+ */
2073
+ constructor(transport: ITransport);
2074
+ /**
2075
+ * Find documents matching a filter.
2076
+ *
2077
+ * @param collection - Collection name
2078
+ * @param filter - Query filter
2079
+ * @param options - Find options (limit, skip, sort)
2080
+ * @returns Array of matching documents
2081
+ */
2082
+ find<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>, options?: FindOptions): Promise<T[]>;
2083
+ /**
2084
+ * Find a single document by ID.
2085
+ *
2086
+ * @param collection - Collection name
2087
+ * @param id - Document ID
2088
+ * @returns Document or null if not found
2089
+ */
2090
+ findById<T extends BaseDocument>(collection: string, id: string): Promise<T | null>;
2091
+ /**
2092
+ * Insert a single document.
2093
+ *
2094
+ * @param collection - Collection name
2095
+ * @param document - Document to insert (id, createdAt, updatedAt will be added)
2096
+ * @returns Inserted document with generated fields
2097
+ */
2098
+ insertOne<T extends BaseDocument>(collection: string, document: Omit<T, 'id' | 'createdAt' | 'updatedAt'>): Promise<T>;
2099
+ /**
2100
+ * Update documents matching a filter.
2101
+ *
2102
+ * @param collection - Collection name
2103
+ * @param filter - Query filter
2104
+ * @param update - Update operations
2105
+ * @returns Number of documents updated
2106
+ */
2107
+ updateMany<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>, update: DocumentUpdate<T>): Promise<number>;
2108
+ /**
2109
+ * Update a single document by ID.
2110
+ *
2111
+ * @param collection - Collection name
2112
+ * @param id - Document ID
2113
+ * @param update - Update operations
2114
+ * @returns Updated document or null if not found
2115
+ */
2116
+ updateById<T extends BaseDocument>(collection: string, id: string, update: DocumentUpdate<T>): Promise<T | null>;
2117
+ /**
2118
+ * Delete documents matching a filter.
2119
+ *
2120
+ * @param collection - Collection name
2121
+ * @param filter - Query filter
2122
+ * @returns Number of documents deleted
2123
+ */
2124
+ deleteMany<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>): Promise<number>;
2125
+ /**
2126
+ * Delete a single document by ID.
2127
+ *
2128
+ * @param collection - Collection name
2129
+ * @param id - Document ID
2130
+ * @returns True if deleted, false if not found
2131
+ */
2132
+ deleteById(collection: string, id: string): Promise<boolean>;
2133
+ /**
2134
+ * Count documents matching a filter.
2135
+ *
2136
+ * @param collection - Collection name
2137
+ * @param filter - Query filter
2138
+ * @returns Number of matching documents
2139
+ */
2140
+ count<T extends BaseDocument>(collection: string, filter: DocumentFilter<T>): Promise<number>;
2141
+ /**
2142
+ * Close the database connection.
2143
+ */
2144
+ close(): Promise<void>;
2145
+ }
2146
+ /**
2147
+ * Create a document database proxy with IPC transport.
2148
+ *
2149
+ * @param transport - IPC transport to use
2150
+ * @returns Document database proxy instance
2151
+ *
2152
+ * @example
2153
+ * ```typescript
2154
+ * import { createDocumentDatabaseProxy, createIPCTransport } from '@kb-labs/core-runtime';
2155
+ *
2156
+ * const transport = createIPCTransport();
2157
+ * const db = createDocumentDatabaseProxy(transport);
2158
+ * ```
2159
+ */
2160
+ declare function createDocumentDatabaseProxy(transport: ITransport): DocumentDatabaseProxy;
2161
+
2162
+ /**
2163
+ * @module @kb-labs/core-runtime/proxy/create-proxy-platform
2164
+ * Create platform container with proxy adapters for subprocess execution.
2165
+ *
2166
+ * This function creates a PlatformContainer where all adapters are proxies
2167
+ * that forward calls to the parent process via IPC (Unix socket).
2168
+ *
2169
+ * Used in subprocess workers to access real platform services from parent.
2170
+ */
2171
+
2172
+ interface CreateProxyPlatformOptions {
2173
+ /**
2174
+ * Path to Unix socket for IPC communication.
2175
+ * Should match the socket path used by UnixSocketServer in parent process.
2176
+ * Default: /tmp/kb-ipc.sock
2177
+ */
2178
+ socketPath?: string;
2179
+ /**
2180
+ * Logger for subprocess (can be noop or local file logger).
2181
+ * Note: This logger is NOT proxied - logs are local to subprocess.
2182
+ */
2183
+ logger?: ILogger;
2184
+ /**
2185
+ * Custom transport (for testing).
2186
+ * If not provided, UnixSocketTransport will be created.
2187
+ */
2188
+ transport?: ITransport;
2189
+ }
2190
+ /**
2191
+ * Create platform container with proxy adapters.
2192
+ *
2193
+ * All adapters (except logger) forward calls to parent process via IPC.
2194
+ * This allows subprocess handlers to access real platform services.
2195
+ *
2196
+ * @param options - Configuration options
2197
+ * @returns Platform container with proxy adapters
2198
+ *
2199
+ * @example
2200
+ * ```typescript
2201
+ * // In subprocess (worker-script.ts)
2202
+ * import { createProxyPlatform } from '@kb-labs/core-runtime/proxy';
2203
+ *
2204
+ * const platform = await createProxyPlatform({
2205
+ * socketPath: process.env.KB_IPC_SOCKET_PATH,
2206
+ * logger: createFileLogger('/tmp/worker.log'),
2207
+ * });
2208
+ *
2209
+ * // Now handlers can use real platform services
2210
+ * await platform.cache.set('key', 'value');
2211
+ * const result = await platform.llm.complete({ prompt: 'Hello' });
2212
+ * ```
2213
+ */
2214
+ declare function createProxyPlatform(options?: CreateProxyPlatformOptions): Promise<PlatformContainer>;
2215
+ /**
2216
+ * Close proxy platform and disconnect from parent.
2217
+ *
2218
+ * Should be called when subprocess is shutting down.
2219
+ *
2220
+ * @param platform - Platform container created by createProxyPlatform()
2221
+ *
2222
+ * @example
2223
+ * ```typescript
2224
+ * const platform = await createProxyPlatform();
2225
+ * // ... use platform ...
2226
+ * await closeProxyPlatform(platform);
2227
+ * ```
2228
+ */
2229
+ declare function closeProxyPlatform(platform: PlatformContainer): Promise<void>;
2230
+
2231
+ interface MonitoringSnapshot {
2232
+ resource: ResourceType;
2233
+ availability?: ResourceAvailability;
2234
+ quota?: TenantQuotas;
2235
+ tenantId?: string;
2236
+ ts: string;
2237
+ }
2238
+ interface MonitoringOptions {
2239
+ resources?: ResourceType[];
2240
+ tenantId?: string;
2241
+ }
2242
+ declare function getMonitoringSnapshot(options?: MonitoringOptions): Promise<MonitoringSnapshot[]>;
2243
+ type DegradedLevel = 'normal' | 'degraded' | 'critical';
2244
+ interface DegradedStatus {
2245
+ level: DegradedLevel;
2246
+ ts: string;
2247
+ reason?: string;
2248
+ }
2249
+ interface DegradedOptions extends MonitoringOptions {
2250
+ thresholds?: {
2251
+ degraded?: number;
2252
+ critical?: number;
2253
+ };
2254
+ }
2255
+ declare function getDegradedStatus(options?: DegradedOptions): Promise<DegradedStatus>;
2256
+
2257
+ /**
2258
+ * @module @kb-labs/core-runtime/use-cases/start-full-cycle
2259
+ * Unified one-click full-cycle entrypoint.
2260
+ */
2261
+
2262
+ /**
2263
+ * Start full-cycle run through configured run orchestrator.
2264
+ */
2265
+ declare function startFullCycle(platform: Pick<PlatformContainer, 'runOrchestrator'>, request: StartFullCycleRequest): Promise<RunRecord>;
2266
+
2267
+ export { type AdapterTypes, type AdaptersConfig, CacheProxy, type CoreAdapterTypes, type CoreFeaturesConfig, type CreateProxyPlatformOptions, CronManager, type DegradedLevel, type DegradedOptions, type DegradedStatus, type DiscoveredAdapter, DocumentDatabaseProxy, EmbeddingsProxy, EnvironmentManager, type ExecutionConfig, type JobHandler, JobScheduler, type JobSchedulerConfig, type JobsConfig, LLMProxy, type MonitoringOptions, type MonitoringSnapshot, type PlatformConfig, PlatformContainer, type PlatformLifecycleContext, type PlatformLifecycleHooks, type PlatformLifecyclePhase, RemoteAdapter, type ResourceBrokerConfig, ResourceManager, type ResourceManagerConfig, type ResourcesConfig, RunExecutor, RunOrchestrator, type RunStepExecutionRequest, SQLDatabaseProxy, SnapshotManager, type StartFullCycleRequest, StorageProxy, VectorStoreProxy, type WorkflowDefinition, WorkflowEngine, type WorkflowEngineConfig, type WorkflowStepContext, type WorkflowStepDefinition, type WorkflowsConfig, WorkspaceManager, closeProxyPlatform, createAnalyticsContext, createCacheProxy, createDocumentDatabaseProxy, createProxyPlatform, createSQLDatabaseProxy, createStorageProxy, createVectorStoreProxy, discoverAdapters, getDegradedStatus, getMonitoringSnapshot, initPlatform, platform, resetPlatform, resolveAdapter, startFullCycle };