substrate-ai 0.1.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,1389 @@
1
+ import pino from "pino";
2
+ import { z } from "zod";
3
+
4
+ //#region src/core/types.d.ts
5
+ /**
6
+ * Core types for Substrate
7
+ * Shared type definitions used across all modules
8
+ */
9
+ /** Unique identifier for a task in the DAG */
10
+ /**
11
+ * Core types for Substrate
12
+ * Shared type definitions used across all modules
13
+ */
14
+ /** Unique identifier for a task in the DAG */
15
+ type TaskId = string;
16
+ /** Unique identifier for a worker/agent instance */
17
+ type WorkerId = string;
18
+ /** Unique identifier for a registered agent type */
19
+ type AgentId = string;
20
+ /** Status of an individual task */
21
+ type TaskStatus = 'pending' | 'ready' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' | 'blocked';
22
+ /** Status of an orchestration session */
23
+ type SessionStatus = 'initializing' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled';
24
+ /** Billing mode for a worker/agent */
25
+ type BillingMode = 'subscription' | 'api' | 'free';
26
+ /** Severity level for errors and log messages */
27
+ type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
28
+ /** Task priority level */
29
+ type TaskPriority = 'low' | 'normal' | 'high' | 'critical';
30
+ /** Agent capability descriptor */
31
+ interface AgentCapability {
32
+ name: string;
33
+ version: string;
34
+ supportedTaskTypes: string[];
35
+ billingMode: BillingMode;
36
+ maxConcurrency: number;
37
+ }
38
+ /** Task graph node definition */
39
+ interface TaskNode {
40
+ id: TaskId;
41
+ title: string;
42
+ description: string;
43
+ agentId?: AgentId;
44
+ status: TaskStatus;
45
+ priority: TaskPriority;
46
+ dependencies: TaskId[];
47
+ metadata: Record<string, unknown>;
48
+ createdAt: Date;
49
+ startedAt?: Date;
50
+ completedAt?: Date;
51
+ }
52
+ /** Session configuration */
53
+ interface SessionConfig {
54
+ id: string;
55
+ name: string;
56
+ projectRoot: string;
57
+ taskGraphPath: string;
58
+ maxConcurrency: number;
59
+ budgetCap?: number;
60
+ billingMode: BillingMode;
61
+ }
62
+ /** Cost tracking record */
63
+ interface CostRecord {
64
+ taskId: TaskId;
65
+ agentId: AgentId;
66
+ sessionId: string;
67
+ tokens: number;
68
+ estimatedCost: number;
69
+ billingMode: BillingMode;
70
+ timestamp: Date;
71
+ } //#endregion
72
+ //#region src/core/errors.d.ts
73
+
74
+ //# sourceMappingURL=types.d.ts.map
75
+ /**
76
+ * Error definitions for Substrate
77
+ * Provides structured error hierarchy for all toolkit operations
78
+ */
79
+ /** Base error class for all Substrate errors */
80
+ declare class AdtError extends Error {
81
+ readonly code: string;
82
+ readonly context: Record<string, unknown>;
83
+ constructor(message: string, code: string, context?: Record<string, unknown>);
84
+ toJSON(): Record<string, unknown>;
85
+ }
86
+ /** Error thrown when task configuration is invalid */
87
+ declare class TaskConfigError extends AdtError {
88
+ constructor(message: string, context?: Record<string, unknown>);
89
+ }
90
+ /** Error thrown when a worker/agent operation fails */
91
+ declare class WorkerError extends AdtError {
92
+ constructor(message: string, context?: Record<string, unknown>);
93
+ }
94
+ /** Error thrown when a worker/agent cannot be found */
95
+ declare class WorkerNotFoundError extends AdtError {
96
+ constructor(agentId: string);
97
+ }
98
+ /** Error thrown when a task graph is invalid */
99
+ declare class TaskGraphError extends AdtError {
100
+ constructor(message: string, context?: Record<string, unknown>);
101
+ }
102
+ /** Error thrown when a task graph has cycles (deadlock) */
103
+ declare class TaskGraphCycleError extends TaskGraphError {
104
+ constructor(cycle: string[]);
105
+ }
106
+ /** Error thrown when a budget limit is exceeded */
107
+ declare class BudgetExceededError extends AdtError {
108
+ constructor(limit: number, current: number, context?: Record<string, unknown>);
109
+ }
110
+ /** Error thrown when git operations fail */
111
+ declare class GitError extends AdtError {
112
+ constructor(message: string, context?: Record<string, unknown>);
113
+ }
114
+ /** Error thrown when configuration is invalid or missing */
115
+ declare class ConfigError extends AdtError {
116
+ constructor(message: string, context?: Record<string, unknown>);
117
+ }
118
+ /** Error thrown when state recovery fails */
119
+ declare class RecoveryError extends AdtError {
120
+ constructor(message: string, context?: Record<string, unknown>);
121
+ }
122
+ /** Error thrown when a config file uses an incompatible format version */
123
+ declare class ConfigIncompatibleFormatError extends AdtError {
124
+ constructor(message: string, context?: Record<string, unknown>);
125
+ }
126
+ /** Error thrown when a task graph file uses an incompatible format version */
127
+ declare class TaskGraphIncompatibleFormatError extends AdtError {
128
+ constructor(message: string, context?: Record<string, unknown>);
129
+ }
130
+
131
+ //#endregion
132
+ //#region src/utils/logger.d.ts
133
+ //# sourceMappingURL=errors.d.ts.map
134
+ /** Logger configuration options */
135
+ interface LoggerOptions {
136
+ level?: string;
137
+ name?: string;
138
+ pretty?: boolean;
139
+ }
140
+ /**
141
+ * Create a named logger instance
142
+ * @param name - Logger name (module identifier)
143
+ * @param options - Optional logger configuration overrides
144
+ */
145
+ declare function createLogger(name: string, options?: LoggerOptions): pino.Logger;
146
+ /** Root application logger */
147
+ declare const logger: pino.Logger<never, boolean>;
148
+ /** Create a child logger with additional context */
149
+ declare function childLogger(parent: pino.Logger, bindings: Record<string, unknown>): pino.Logger;
150
+
151
+ //#endregion
152
+ //#region src/utils/helpers.d.ts
153
+ //# sourceMappingURL=logger.d.ts.map
154
+ /**
155
+ * General utility helpers for Substrate
156
+ */
157
+ /**
158
+ * Sleep for a given number of milliseconds
159
+ * @param ms - Milliseconds to sleep
160
+ */
161
+ declare function sleep(ms: number): Promise<void>;
162
+ /**
163
+ * Assert that a value is defined (not null or undefined)
164
+ * @param value - Value to check
165
+ * @param message - Error message if undefined
166
+ */
167
+ declare function assertDefined<T>(value: T | null | undefined, message: string): asserts value is T;
168
+ /**
169
+ * Format a duration in milliseconds to a human-readable string
170
+ * @param ms - Duration in milliseconds
171
+ */
172
+ declare function formatDuration(ms: number): string;
173
+ /**
174
+ * Generate a unique identifier using crypto.randomUUID()
175
+ * @param prefix - Optional prefix for the ID
176
+ */
177
+ declare function generateId(prefix?: string): string;
178
+ /**
179
+ * Deep clone an object using structuredClone.
180
+ * Supports most built-in types (Date, Map, Set, ArrayBuffer, etc.)
181
+ * but does NOT support functions, DOM nodes, or symbols as keys.
182
+ * @param obj - Object to clone
183
+ */
184
+ declare function deepClone<T>(obj: T): T;
185
+ /**
186
+ * Check if a value is a plain object (not an array, Date, or other special object)
187
+ * @param value - Value to check
188
+ */
189
+ declare function isPlainObject(value: unknown): value is Record<string, unknown>;
190
+ /**
191
+ * Retry an async operation with exponential backoff
192
+ * @param fn - Async function to retry
193
+ * @param maxRetries - Maximum number of retries
194
+ * @param baseDelayMs - Base delay in milliseconds (doubles each retry)
195
+ */
196
+ declare function withRetry<T>(fn: () => Promise<T>, maxRetries?: number, baseDelayMs?: number): Promise<T>;
197
+
198
+ //#endregion
199
+ //#region src/modules/config/config-schema.d.ts
200
+ //# sourceMappingURL=helpers.d.ts.map
201
+
202
+ declare const SubstrateConfigSchema: z.ZodObject<{
203
+ config_format_version: z.ZodEnum<{
204
+ 1: "1";
205
+ }>;
206
+ task_graph_version: z.ZodOptional<z.ZodEnum<{
207
+ 1: "1";
208
+ }>>;
209
+ global: z.ZodObject<{
210
+ log_level: z.ZodEnum<{
211
+ fatal: "fatal";
212
+ error: "error";
213
+ warn: "warn";
214
+ info: "info";
215
+ debug: "debug";
216
+ trace: "trace";
217
+ }>;
218
+ max_concurrent_tasks: z.ZodNumber;
219
+ budget_cap_tokens: z.ZodNumber;
220
+ budget_cap_usd: z.ZodNumber;
221
+ workspace_dir: z.ZodOptional<z.ZodString>;
222
+ update_check: z.ZodOptional<z.ZodBoolean>;
223
+ }, z.core.$strict>;
224
+ providers: z.ZodObject<{
225
+ claude: z.ZodOptional<z.ZodObject<{
226
+ enabled: z.ZodBoolean;
227
+ cli_path: z.ZodOptional<z.ZodString>;
228
+ subscription_routing: z.ZodEnum<{
229
+ auto: "auto";
230
+ subscription: "subscription";
231
+ api: "api";
232
+ disabled: "disabled";
233
+ }>;
234
+ max_concurrent: z.ZodNumber;
235
+ rate_limit: z.ZodOptional<z.ZodObject<{
236
+ tokens: z.ZodNumber;
237
+ window_seconds: z.ZodNumber;
238
+ }, z.core.$strict>>;
239
+ api_key_env: z.ZodOptional<z.ZodString>;
240
+ api_billing: z.ZodBoolean;
241
+ }, z.core.$strict>>;
242
+ codex: z.ZodOptional<z.ZodObject<{
243
+ enabled: z.ZodBoolean;
244
+ cli_path: z.ZodOptional<z.ZodString>;
245
+ subscription_routing: z.ZodEnum<{
246
+ auto: "auto";
247
+ subscription: "subscription";
248
+ api: "api";
249
+ disabled: "disabled";
250
+ }>;
251
+ max_concurrent: z.ZodNumber;
252
+ rate_limit: z.ZodOptional<z.ZodObject<{
253
+ tokens: z.ZodNumber;
254
+ window_seconds: z.ZodNumber;
255
+ }, z.core.$strict>>;
256
+ api_key_env: z.ZodOptional<z.ZodString>;
257
+ api_billing: z.ZodBoolean;
258
+ }, z.core.$strict>>;
259
+ gemini: z.ZodOptional<z.ZodObject<{
260
+ enabled: z.ZodBoolean;
261
+ cli_path: z.ZodOptional<z.ZodString>;
262
+ subscription_routing: z.ZodEnum<{
263
+ auto: "auto";
264
+ subscription: "subscription";
265
+ api: "api";
266
+ disabled: "disabled";
267
+ }>;
268
+ max_concurrent: z.ZodNumber;
269
+ rate_limit: z.ZodOptional<z.ZodObject<{
270
+ tokens: z.ZodNumber;
271
+ window_seconds: z.ZodNumber;
272
+ }, z.core.$strict>>;
273
+ api_key_env: z.ZodOptional<z.ZodString>;
274
+ api_billing: z.ZodBoolean;
275
+ }, z.core.$strict>>;
276
+ }, z.core.$strict>;
277
+ cost_tracker: z.ZodOptional<z.ZodObject<{
278
+ enabled: z.ZodBoolean;
279
+ token_rates_provider: z.ZodEnum<{
280
+ builtin: "builtin";
281
+ custom: "custom";
282
+ }>;
283
+ track_planning_costs: z.ZodBoolean;
284
+ savings_reporting: z.ZodBoolean;
285
+ }, z.core.$strict>>;
286
+ budget: z.ZodOptional<z.ZodObject<{
287
+ default_task_budget_usd: z.ZodNumber;
288
+ default_session_budget_usd: z.ZodNumber;
289
+ planning_costs_count_against_budget: z.ZodBoolean;
290
+ warning_threshold_percent: z.ZodNumber;
291
+ }, z.core.$strict>>;
292
+ }, z.core.$strict>;
293
+ type SubstrateConfig = z.infer<typeof SubstrateConfigSchema>;
294
+
295
+ //#endregion
296
+ //#region src/core/event-bus.types.d.ts
297
+ /**
298
+ * Routing decision payload used in task:routed event.
299
+ * Mirrors RoutingDecision from src/modules/routing/routing-decision.ts
300
+ * but kept here as a plain interface to avoid circular module dependencies.
301
+ */
302
+ interface RoutingDecision {
303
+ taskId: string;
304
+ agent: string;
305
+ billingMode: 'subscription' | 'api' | 'unavailable';
306
+ model?: string;
307
+ rationale: string;
308
+ fallbackChain?: string[];
309
+ estimatedCostUsd?: number;
310
+ rateLimit?: {
311
+ tokensUsedInWindow: number;
312
+ limit: number;
313
+ };
314
+ }
315
+ /** Result of a completed task */
316
+ interface TaskResult$1 {
317
+ output?: string;
318
+ exitCode?: number;
319
+ tokensUsed?: number;
320
+ inputTokens?: number;
321
+ outputTokens?: number;
322
+ durationMs?: number;
323
+ costUsd?: number;
324
+ agent?: string;
325
+ }
326
+ /** Error payload for a failed task */
327
+ interface TaskError {
328
+ message: string;
329
+ code?: string;
330
+ stack?: string;
331
+ }
332
+ /**
333
+ * Complete typed map of all events emitted on the orchestrator event bus.
334
+ * Use `keyof OrchestratorEvents` to constrain event keys.
335
+ */
336
+ interface OrchestratorEvents {
337
+ /** Task has all dependencies satisfied and is ready to be assigned */
338
+ 'task:ready': {
339
+ taskId: TaskId;
340
+ taskType?: string;
341
+ };
342
+ /** A worker has begun execution of a task */
343
+ 'task:started': {
344
+ taskId: TaskId;
345
+ workerId: WorkerId;
346
+ agent: string;
347
+ };
348
+ /** Incremental progress report from a running task */
349
+ 'task:progress': {
350
+ taskId: TaskId;
351
+ message: string;
352
+ tokensUsed?: number;
353
+ };
354
+ /** Task has completed successfully */
355
+ 'task:complete': {
356
+ taskId: TaskId;
357
+ result: TaskResult$1;
358
+ taskType?: string;
359
+ };
360
+ /** Task has failed with an error */
361
+ 'task:failed': {
362
+ taskId: TaskId;
363
+ error: TaskError;
364
+ };
365
+ /** Task was cancelled */
366
+ 'task:cancelled': {
367
+ taskId: TaskId;
368
+ reason: string;
369
+ };
370
+ /** Task is being retried after a failure */
371
+ 'task:retrying': {
372
+ taskId: TaskId;
373
+ attempt: number;
374
+ maxAttempts: number;
375
+ };
376
+ /** A worker subprocess was spawned */
377
+ 'worker:spawned': {
378
+ workerId: WorkerId;
379
+ taskId: TaskId;
380
+ agent: string;
381
+ };
382
+ /** A worker subprocess was terminated */
383
+ 'worker:terminated': {
384
+ workerId: WorkerId;
385
+ reason: string;
386
+ };
387
+ /** Spending is approaching the configured budget limit */
388
+ 'budget:warning': {
389
+ taskId: TaskId;
390
+ currentSpend: number;
391
+ limit: number;
392
+ };
393
+ /** Spending has exceeded the configured budget limit */
394
+ 'budget:exceeded': {
395
+ taskId: TaskId;
396
+ spend: number;
397
+ limit: number;
398
+ };
399
+ /** Task is approaching its budget cap (80% threshold) */
400
+ 'budget:warning:task': {
401
+ taskId: TaskId;
402
+ currentCostUsd: number;
403
+ budgetUsd: number;
404
+ percentageUsed: number;
405
+ };
406
+ /** Task has exceeded its budget cap — force-terminate worker */
407
+ 'budget:exceeded:task': {
408
+ taskId: TaskId;
409
+ currentCostUsd: number;
410
+ budgetUsd: number;
411
+ };
412
+ /** Session-wide budget is approaching the cap (80% threshold) */
413
+ 'budget:warning:session': {
414
+ sessionId: string;
415
+ currentCostUsd: number;
416
+ budgetUsd: number;
417
+ percentageUsed: number;
418
+ };
419
+ /** Session-wide budget has been exceeded — terminate all workers */
420
+ 'session:budget:exceeded': {
421
+ sessionId: string;
422
+ currentCostUsd: number;
423
+ budgetUsd: number;
424
+ };
425
+ /** Budget cap has been set for a task */
426
+ 'task:budget-set': {
427
+ taskId: TaskId;
428
+ budgetUsd: number;
429
+ };
430
+ /** Budget cap has been set for a session */
431
+ 'session:budget-set': {
432
+ sessionId: string;
433
+ budgetUsd: number;
434
+ };
435
+ /** A task graph has been loaded and validated */
436
+ 'graph:loaded': {
437
+ sessionId: string;
438
+ taskCount: number;
439
+ readyCount: number;
440
+ };
441
+ /** All tasks in the graph have completed or failed */
442
+ 'graph:complete': {
443
+ totalTasks: number;
444
+ completedTasks: number;
445
+ failedTasks: number;
446
+ totalCostUsd: number;
447
+ };
448
+ /** Graph execution was cancelled */
449
+ 'graph:cancelled': {
450
+ cancelledTasks: number;
451
+ };
452
+ /** Graph execution was paused */
453
+ 'graph:paused': Record<string, never>;
454
+ /** Graph execution was resumed */
455
+ 'graph:resumed': Record<string, never>;
456
+ /** A git worktree was created for a task */
457
+ 'worktree:created': {
458
+ taskId: TaskId;
459
+ branchName: string;
460
+ worktreePath: string;
461
+ createdAt?: Date;
462
+ };
463
+ /** A task's worktree branch was merged */
464
+ 'worktree:merged': {
465
+ taskId: TaskId;
466
+ branch: string;
467
+ mergedFiles: string[];
468
+ };
469
+ /** A merge conflict was detected in a task's worktree */
470
+ 'worktree:conflict': {
471
+ taskId: TaskId;
472
+ branch: string;
473
+ conflictingFiles: string[];
474
+ };
475
+ /** A task's worktree was removed */
476
+ 'worktree:removed': {
477
+ taskId: TaskId;
478
+ branchName: string;
479
+ };
480
+ /** Plan generation has started */
481
+ 'plan:generating': {
482
+ agent: string;
483
+ description: string;
484
+ };
485
+ /** Plan generation has completed */
486
+ 'plan:generated': {
487
+ taskCount: number;
488
+ estimatedCost: number;
489
+ };
490
+ /** Plan was approved by the user */
491
+ 'plan:approved': {
492
+ taskCount: number;
493
+ };
494
+ /** Plan was rejected by the user */
495
+ 'plan:rejected': {
496
+ reason: string;
497
+ };
498
+ /** Plan is being refined based on feedback */
499
+ 'plan:refining': {
500
+ planId: string;
501
+ feedback: string;
502
+ currentVersion: number;
503
+ };
504
+ /** Plan refinement completed successfully */
505
+ 'plan:refined': {
506
+ planId: string;
507
+ newVersion: number;
508
+ taskCount: number;
509
+ };
510
+ /** Plan was rolled back to a previous version */
511
+ 'plan:rolled-back': {
512
+ planId: string;
513
+ fromVersion: number;
514
+ toVersion: number;
515
+ newVersion: number;
516
+ };
517
+ /** Plan refinement failed */
518
+ 'plan:refinement-failed': {
519
+ planId: string;
520
+ currentVersion: number;
521
+ error: string;
522
+ };
523
+ /** A task's cost has been recorded by the cost tracker */
524
+ 'cost:recorded': {
525
+ taskId: string;
526
+ sessionId: string;
527
+ costUsd: number;
528
+ savingsUsd: number;
529
+ billingMode: 'subscription' | 'api';
530
+ };
531
+ /** A task's metrics have been recorded by the monitor */
532
+ 'monitor:metrics_recorded': {
533
+ taskId: string;
534
+ agent: string;
535
+ taskType: string;
536
+ };
537
+ /** A routing recommendation has been generated by the monitor */
538
+ 'monitor:recommendation_generated': {
539
+ taskType: string;
540
+ recommendedAgent: string;
541
+ confidence: number;
542
+ };
543
+ /** Configuration has been reloaded */
544
+ 'config:reloaded': {
545
+ path: string;
546
+ previousConfig: SubstrateConfig;
547
+ newConfig: SubstrateConfig;
548
+ changedKeys: string[];
549
+ };
550
+ /** A task has been routed to an agent with billing mode decision */
551
+ 'task:routed': {
552
+ taskId: TaskId;
553
+ decision: RoutingDecision;
554
+ };
555
+ /** A provider has become unavailable */
556
+ 'provider:unavailable': {
557
+ provider: string;
558
+ reason: 'rate_limit' | 'disabled';
559
+ resetAtMs?: number;
560
+ };
561
+ /** A provider has become available */
562
+ 'provider:available': {
563
+ provider: string;
564
+ };
565
+ /** A newer version of the toolkit is available */
566
+ 'version:update_available': {
567
+ currentVersion: string;
568
+ latestVersion: string;
569
+ breaking: boolean;
570
+ };
571
+ /** A sub-agent subprocess was spawned by the dispatch engine */
572
+ 'agent:spawned': {
573
+ dispatchId: string;
574
+ agent: string;
575
+ taskType: string;
576
+ };
577
+ /** Incremental stdout data received from a running sub-agent */
578
+ 'agent:output': {
579
+ dispatchId: string;
580
+ data: string;
581
+ };
582
+ /** A sub-agent completed successfully */
583
+ 'agent:completed': {
584
+ dispatchId: string;
585
+ exitCode: number;
586
+ output: string;
587
+ };
588
+ /** A sub-agent exited with a non-zero code or encountered an error */
589
+ 'agent:failed': {
590
+ dispatchId: string;
591
+ error: string;
592
+ exitCode: number;
593
+ };
594
+ /** A sub-agent was killed because it exceeded its timeout */
595
+ 'agent:timeout': {
596
+ dispatchId: string;
597
+ timeoutMs: number;
598
+ };
599
+ /** Orchestrator has been fully initialized and is ready to process tasks */
600
+ 'orchestrator:ready': Record<string, never>;
601
+ /** Orchestrator shutdown has been initiated */
602
+ 'orchestrator:shutdown': {
603
+ reason: string;
604
+ };
605
+ /** Implementation orchestrator has started processing story keys */
606
+ 'orchestrator:started': {
607
+ storyKeys: string[];
608
+ pipelineRunId?: string;
609
+ };
610
+ /** A story phase has completed within the implementation orchestrator */
611
+ 'orchestrator:story-phase-complete': {
612
+ storyKey: string;
613
+ phase: string;
614
+ result: unknown;
615
+ };
616
+ /** A story has completed the full pipeline with SHIP_IT verdict */
617
+ 'orchestrator:story-complete': {
618
+ storyKey: string;
619
+ reviewCycles: number;
620
+ };
621
+ /** A story has been escalated after exceeding max review cycles */
622
+ 'orchestrator:story-escalated': {
623
+ storyKey: string;
624
+ lastVerdict: string;
625
+ reviewCycles: number;
626
+ issues: unknown[];
627
+ };
628
+ /** Implementation orchestrator has finished all stories */
629
+ 'orchestrator:complete': {
630
+ totalStories: number;
631
+ completed: number;
632
+ escalated: number;
633
+ failed: number;
634
+ };
635
+ /** Implementation orchestrator has been paused */
636
+ 'orchestrator:paused': Record<string, never>;
637
+ /** Implementation orchestrator has been resumed */
638
+ 'orchestrator:resumed': Record<string, never>;
639
+ } //#endregion
640
+ //#region src/core/event-bus.d.ts
641
+ //# sourceMappingURL=event-bus.types.d.ts.map
642
+ /**
643
+ * A typed publish-subscribe bus.
644
+ *
645
+ * All event names and payload types are enforced by the `OrchestratorEvents` map.
646
+ */
647
+ interface TypedEventBus {
648
+ /**
649
+ * Emit an event with a strongly-typed payload.
650
+ * Dispatch is synchronous — all registered handlers run before emit() returns.
651
+ */
652
+ emit<K extends keyof OrchestratorEvents>(event: K, payload: OrchestratorEvents[K]): void;
653
+ /**
654
+ * Subscribe to an event. The handler is called synchronously on each emit.
655
+ */
656
+ on<K extends keyof OrchestratorEvents>(event: K, handler: (payload: OrchestratorEvents[K]) => void): void;
657
+ /**
658
+ * Unsubscribe a previously registered handler.
659
+ * If the handler was not registered, this is a no-op.
660
+ */
661
+ off<K extends keyof OrchestratorEvents>(event: K, handler: (payload: OrchestratorEvents[K]) => void): void;
662
+ }
663
+ /**
664
+ * Concrete implementation of TypedEventBus backed by Node.js EventEmitter.
665
+ *
666
+ * @example
667
+ * const bus = new TypedEventBusImpl()
668
+ * bus.on('task:complete', ({ taskId, result }) => {
669
+ * console.log(`Task ${taskId} finished`)
670
+ * })
671
+ * bus.emit('task:complete', { taskId: 'abc', result: { exitCode: 0 } })
672
+ */
673
+
674
+ /**
675
+ * Create a new TypedEventBus instance.
676
+ *
677
+ * @example
678
+ * const bus = createEventBus()
679
+ */
680
+ declare function createEventBus(): TypedEventBus;
681
+
682
+ //#endregion
683
+ //#region src/core/orchestrator.d.ts
684
+ //# sourceMappingURL=event-bus.d.ts.map
685
+ /**
686
+ * Configuration required to initialize the orchestrator.
687
+ */
688
+ interface OrchestratorConfig {
689
+ /** Path to the SQLite database file (e.g., ".substrate/state.db") */
690
+ databasePath: string;
691
+ /** Working directory for the orchestrated project */
692
+ projectRoot: string;
693
+ /**
694
+ * Maximum number of concurrent worker tasks.
695
+ * @default 4
696
+ */
697
+ maxConcurrency?: number;
698
+ /**
699
+ * Budget cap in USD (0 = unlimited).
700
+ * @default 0
701
+ */
702
+ budgetCapUsd?: number;
703
+ /**
704
+ * Budget cap in tokens (0 = unlimited).
705
+ * @default 0
706
+ */
707
+ budgetCapTokens?: number;
708
+ /** Optional logger level override */
709
+ logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
710
+ /**
711
+ * Path to the substrate config file for hot-reload watching.
712
+ * If omitted, defaults to <projectRoot>/substrate.config.yaml
713
+ */
714
+ configPath?: string;
715
+ /**
716
+ * Enable config hot-reload via file watcher.
717
+ * When true (default), a file watcher is registered on the config file.
718
+ * Set to false to disable (e.g. in dry-run or --no-watch-config mode).
719
+ * @default true
720
+ */
721
+ enableConfigHotReload?: boolean;
722
+ /**
723
+ * Monitor agent configuration.
724
+ * If omitted, monitor agent is initialized with defaults.
725
+ */
726
+ monitor?: {
727
+ /**
728
+ * Path to the monitor SQLite database file.
729
+ * @default ':memory:' (in-memory, non-persistent) when not specified
730
+ */
731
+ databasePath?: string;
732
+ /**
733
+ * Number of days to retain task metrics.
734
+ * @default 90
735
+ */
736
+ retentionDays?: number;
737
+ /**
738
+ * Custom task type taxonomy for classification overrides.
739
+ */
740
+ customTaxonomy?: Record<string, string[]>;
741
+ /**
742
+ * Enable advisory routing recommendations based on performance data (AC6, FR68).
743
+ * When true, MonitorAgent.getRecommendation() returns recommendations for routing decisions.
744
+ * @default false
745
+ */
746
+ use_recommendations?: boolean;
747
+ /**
748
+ * Minimum success rate improvement (percentage points) required to generate a recommendation.
749
+ * @default 5.0
750
+ */
751
+ recommendation_threshold_percentage?: number;
752
+ /**
753
+ * Minimum number of tasks per (agent, task_type) pair before a recommendation is generated.
754
+ * @default 10
755
+ */
756
+ min_sample_size?: number;
757
+ /**
758
+ * Number of days of historical data to analyze for recommendations.
759
+ * @default 90
760
+ */
761
+ recommendation_history_days?: number;
762
+ };
763
+ }
764
+ /**
765
+ * Central orchestration engine — coordinates all modules via the event bus
766
+ * and dependency injection.
767
+ *
768
+ * Lifecycle:
769
+ * 1. Create via `createOrchestrator(config)`
770
+ * 2. Factory emits `orchestrator:ready` when initialization completes
771
+ * 3. Consumers interact with modules via the event bus or injected interfaces
772
+ * 4. On SIGTERM/SIGINT, graceful shutdown is triggered automatically
773
+ * 5. Call `shutdown()` explicitly for programmatic shutdown
774
+ */
775
+ interface Orchestrator {
776
+ /**
777
+ * The typed event bus for this orchestrator instance.
778
+ * Modules and consumers use this to subscribe to and emit events.
779
+ */
780
+ readonly eventBus: TypedEventBus;
781
+ /**
782
+ * Whether the orchestrator has been fully initialized.
783
+ */
784
+ readonly isReady: boolean;
785
+ /**
786
+ * Perform a graceful shutdown of all modules.
787
+ * Calls shutdown() on all services in reverse initialization order.
788
+ * Safe to call multiple times — subsequent calls are no-ops.
789
+ */
790
+ shutdown(): Promise<void>;
791
+ }
792
+
793
+ //#endregion
794
+ //#region src/core/orchestrator-impl.d.ts
795
+ //# sourceMappingURL=orchestrator.d.ts.map
796
+ /**
797
+ * Initialize the orchestrator with all modules wired via dependency injection.
798
+ *
799
+ * Steps performed:
800
+ * 1. Create the TypedEventBus
801
+ * 2. Create the SQLite database service
802
+ * 3. Instantiate all modules (TaskGraphEngine, RoutingEngine, WorkerManager,
803
+ * BudgetTracker, GitManager) with constructor injection
804
+ * 4. Register all modules in the ServiceRegistry
805
+ * 5. Call initialize() on all services in registration order
806
+ * 6. Register SIGTERM/SIGINT graceful shutdown handlers
807
+ * 7. Emit orchestrator:ready
808
+ *
809
+ * @param config - Orchestrator configuration
810
+ * @returns Initialized Orchestrator instance
811
+ */
812
+ declare function createOrchestrator(config: OrchestratorConfig): Promise<Orchestrator>;
813
+
814
+ //#endregion
815
+ //#region src/core/di.d.ts
816
+ //# sourceMappingURL=orchestrator-impl.d.ts.map
817
+ /**
818
+ * Dependency injection container and service registry.
819
+ *
820
+ * Provides:
821
+ * - BaseService interface with initialize/shutdown lifecycle
822
+ * - ServiceRegistry for registering and resolving services
823
+ *
824
+ * Design constraints (Architecture Section 19):
825
+ * - No direct module-to-module imports; all wiring happens here.
826
+ * - Modules communicate only via the Event Bus or injected interface dependencies.
827
+ * - Services must support initialize() and shutdown() lifecycle methods.
828
+ */
829
+ /**
830
+ * Lifecycle interface for all orchestrator services/modules.
831
+ * Every module must implement this to participate in graceful startup/shutdown.
832
+ */
833
+ interface BaseService {
834
+ /**
835
+ * Initialize the service — set up connections, subscribe to events, etc.
836
+ * Called after all services are constructed but before the orchestrator
837
+ * emits orchestrator:ready.
838
+ */
839
+ initialize(): Promise<void>;
840
+ /**
841
+ * Tear down the service gracefully.
842
+ * Called during orchestrator shutdown in reverse dependency order.
843
+ */
844
+ shutdown(): Promise<void>;
845
+ }
846
+ /**
847
+ * Simple service registry — stores named service instances for DI resolution.
848
+ *
849
+ * Services are registered by name and can be retrieved by name or iterated
850
+ * in registration order for lifecycle management.
851
+ *
852
+ * @example
853
+ * const registry = new ServiceRegistry()
854
+ * registry.register('taskGraph', taskGraphEngine)
855
+ * registry.register('workerManager', workerManager)
856
+ *
857
+ * // Initialize all services
858
+ * await registry.initializeAll()
859
+ *
860
+ * // Shutdown all services in reverse order
861
+ * await registry.shutdownAll()
862
+ */
863
+ declare class ServiceRegistry {
864
+ private readonly _services;
865
+ private readonly _order;
866
+ /**
867
+ * Register a named service. Registration order is preserved for lifecycle calls.
868
+ * @throws {Error} if a service with the same name is already registered.
869
+ */
870
+ register(name: string, service: BaseService): void;
871
+ /**
872
+ * Retrieve a registered service by name.
873
+ * @throws {Error} if no service with the given name is registered.
874
+ */
875
+ get(name: string): BaseService;
876
+ /**
877
+ * Returns true if a service with the given name is registered.
878
+ */
879
+ has(name: string): boolean;
880
+ /**
881
+ * Initialize all registered services in registration order.
882
+ * Fails fast on the first error — later services may depend on
883
+ * already-initialized ones, so continuing after a failure is unsafe.
884
+ * @throws the first initialization error encountered.
885
+ */
886
+ initializeAll(): Promise<void>;
887
+ /**
888
+ * Shut down all registered services in reverse registration order.
889
+ * Errors are collected and re-thrown as an AggregateError after all services
890
+ * have had a chance to shut down.
891
+ */
892
+ shutdownAll(): Promise<void>;
893
+ /** Return names of all registered services in registration order */
894
+ get serviceNames(): string[];
895
+ }
896
+
897
+ //#endregion
898
+ //#region src/adapters/types.d.ts
899
+ //# sourceMappingURL=di.d.ts.map
900
+ /**
901
+ * A spawn command descriptor that the orchestrator uses to invoke a CLI agent.
902
+ * Contains all information needed to execute an agent process.
903
+ */
904
+ interface SpawnCommand {
905
+ /** The binary to execute (e.g., "claude", "codex", "gemini") */
906
+ binary: string;
907
+ /** Arguments to pass to the binary */
908
+ args: string[];
909
+ /** Optional environment variable overrides */
910
+ env?: Record<string, string>;
911
+ /** Optional list of environment variable keys to unset in the child process */
912
+ unsetEnvKeys?: string[];
913
+ /** Working directory for the process */
914
+ cwd: string;
915
+ /** Optional data to pipe to stdin */
916
+ stdin?: string;
917
+ /** Optional timeout in milliseconds */
918
+ timeoutMs?: number;
919
+ }
920
+ /**
921
+ * Options passed to adapter methods for each invocation.
922
+ * Controls execution context for a specific task run.
923
+ */
924
+ interface AdapterOptions {
925
+ /** Path to the git worktree for this task */
926
+ worktreePath: string;
927
+ /** Billing mode to use for this execution */
928
+ billingMode: BillingMode;
929
+ /** Optional model identifier override */
930
+ model?: string;
931
+ /** Optional additional CLI flags to append */
932
+ additionalFlags?: string[];
933
+ /** Optional API key override (used when billingMode is 'api') */
934
+ apiKey?: string;
935
+ /** Optional maximum agentic turns (passed as --max-turns to Claude CLI) */
936
+ maxTurns?: number;
937
+ }
938
+ /**
939
+ * Capabilities reported by an adapter for this CLI agent.
940
+ * Used for routing and planning decisions.
941
+ */
942
+ interface AdapterCapabilities {
943
+ /** Whether the agent outputs structured JSON */
944
+ supportsJsonOutput: boolean;
945
+ /** Whether the agent supports streaming output */
946
+ supportsStreaming: boolean;
947
+ /** Whether the agent supports subscription-based billing */
948
+ supportsSubscriptionBilling: boolean;
949
+ /** Whether the agent supports API-key-based billing */
950
+ supportsApiBilling: boolean;
951
+ /** Whether the agent can generate task planning graphs */
952
+ supportsPlanGeneration: boolean;
953
+ /** Maximum context tokens the agent supports */
954
+ maxContextTokens: number;
955
+ /** Task types this agent can handle */
956
+ supportedTaskTypes: string[];
957
+ /** Programming languages the agent supports */
958
+ supportedLanguages: string[];
959
+ }
960
+ /**
961
+ * Result returned from an adapter health check.
962
+ * Indicates whether the CLI binary is present and functional.
963
+ */
964
+ interface AdapterHealthResult {
965
+ /** Whether the adapter is considered healthy and usable */
966
+ healthy: boolean;
967
+ /** Detected version string of the CLI binary */
968
+ version?: string;
969
+ /** Full path to the CLI binary, if resolved */
970
+ cliPath?: string;
971
+ /** Error message when healthy is false */
972
+ error?: string;
973
+ /** Detected billing mode(s) available for this adapter */
974
+ detectedBillingModes?: BillingMode[];
975
+ /** Whether the CLI supports headless/non-interactive mode */
976
+ supportsHeadless: boolean;
977
+ }
978
+ /**
979
+ * Parsed result from a task execution.
980
+ * Normalized representation from CLI agent JSON output.
981
+ */
982
+ interface TaskResult {
983
+ /** Task identifier this result belongs to */
984
+ taskId?: TaskId;
985
+ /** Whether the task completed successfully */
986
+ success: boolean;
987
+ /** Primary output content from the agent */
988
+ output: string;
989
+ /** Error message if the task failed */
990
+ error?: string;
991
+ /** Raw exit code from the CLI process */
992
+ exitCode: number;
993
+ /** Execution metadata */
994
+ metadata?: {
995
+ executionTime?: number;
996
+ tokensUsed?: TokenEstimate;
997
+ };
998
+ }
999
+ /**
1000
+ * Token usage estimate for budget tracking.
1001
+ */
1002
+ interface TokenEstimate {
1003
+ /** Estimated input tokens */
1004
+ input: number;
1005
+ /** Estimated output tokens */
1006
+ output: number;
1007
+ /** Total token estimate */
1008
+ total: number;
1009
+ }
1010
+ /**
1011
+ * Request input for plan generation.
1012
+ */
1013
+ interface PlanRequest {
1014
+ /** High-level goal or description of work to plan */
1015
+ goal: string;
1016
+ /** Additional context for the planning agent */
1017
+ context?: string;
1018
+ /** Maximum number of tasks to generate */
1019
+ maxTasks?: number;
1020
+ }
1021
+ /**
1022
+ * Parsed result from a plan generation invocation.
1023
+ */
1024
+ interface PlanParseResult {
1025
+ /** Whether plan generation succeeded */
1026
+ success: boolean;
1027
+ /** Parsed list of planned task descriptions */
1028
+ tasks: PlannedTask[];
1029
+ /** Error message if plan generation failed */
1030
+ error?: string;
1031
+ /** Raw output for debugging */
1032
+ rawOutput?: string;
1033
+ }
1034
+ /**
1035
+ * A single task entry in a generated plan.
1036
+ */
1037
+ interface PlannedTask {
1038
+ /** Task title */
1039
+ title: string;
1040
+ /** Detailed description */
1041
+ description: string;
1042
+ /** Estimated complexity (1-10) */
1043
+ complexity?: number;
1044
+ /** Other task titles this task depends on */
1045
+ dependencies?: string[];
1046
+ }
1047
+
1048
+ //#endregion
1049
+ //#region src/adapters/worker-adapter.d.ts
1050
+ //# sourceMappingURL=types.d.ts.map
1051
+ /**
1052
+ * WorkerAdapter — the interface every CLI agent adapter must implement.
1053
+ *
1054
+ * Adapters are responsible for:
1055
+ * 1. Verifying their CLI binary is installed and responsive (healthCheck)
1056
+ * 2. Constructing the spawn command to execute a task (buildCommand)
1057
+ * 3. Constructing the spawn command for plan generation (buildPlanningCommand)
1058
+ * 4. Parsing task result output from the CLI (parseOutput)
1059
+ * 5. Parsing plan result output from the CLI (parsePlanOutput)
1060
+ * 6. Estimating token usage for budget tracking (estimateTokens)
1061
+ * 7. Reporting their capabilities for routing decisions (getCapabilities)
1062
+ */
1063
+ interface WorkerAdapter {
1064
+ /**
1065
+ * Unique identifier for this adapter type.
1066
+ * Used as the Map key in AdapterRegistry.
1067
+ * @example "claude-code"
1068
+ */
1069
+ readonly id: AgentId;
1070
+ /**
1071
+ * Human-readable display name for the adapter.
1072
+ * @example "Claude Code"
1073
+ */
1074
+ readonly displayName: string;
1075
+ /**
1076
+ * Semantic version of this adapter implementation.
1077
+ * @example "1.0.0"
1078
+ */
1079
+ readonly adapterVersion: string;
1080
+ /**
1081
+ * Verify that the underlying CLI binary is installed, accessible, and
1082
+ * able to respond in headless/non-interactive mode.
1083
+ *
1084
+ * This method must NOT throw — failures should be captured in the returned
1085
+ * AdapterHealthResult.
1086
+ *
1087
+ * @returns A promise resolving to health check details
1088
+ *
1089
+ * @example
1090
+ * ```typescript
1091
+ * const result = await adapter.healthCheck()
1092
+ * if (!result.healthy) console.error(result.error)
1093
+ * ```
1094
+ */
1095
+ healthCheck(): Promise<AdapterHealthResult>;
1096
+ /**
1097
+ * Generate the spawn command to execute a coding task.
1098
+ *
1099
+ * The returned SpawnCommand must set `cwd` to options.worktreePath so the
1100
+ * CLI agent operates in the correct git worktree (NFR10).
1101
+ *
1102
+ * @param prompt Prompt or description of the task to execute
1103
+ * @param options Per-invocation execution options
1104
+ * @returns SpawnCommand ready to be executed by the orchestrator
1105
+ *
1106
+ * @example
1107
+ * ```typescript
1108
+ * const cmd = adapter.buildCommand('Fix the failing tests', { worktreePath: '/tmp/wt', billingMode: 'api' })
1109
+ * // spawn(cmd.binary, cmd.args, { cwd: cmd.cwd, env: { ...process.env, ...cmd.env } })
1110
+ * ```
1111
+ */
1112
+ buildCommand(prompt: string, options: AdapterOptions): SpawnCommand;
1113
+ /**
1114
+ * Generate the spawn command to invoke the CLI agent for plan generation.
1115
+ *
1116
+ * @param request Plan request with goal and context
1117
+ * @param options Per-invocation execution options
1118
+ * @returns SpawnCommand for the planning invocation
1119
+ */
1120
+ buildPlanningCommand(request: PlanRequest, options: AdapterOptions): SpawnCommand;
1121
+ /**
1122
+ * Parse the raw CLI process output into a normalized TaskResult.
1123
+ *
1124
+ * This method must handle all output variations including:
1125
+ * - Valid JSON stdout
1126
+ * - Non-JSON stdout (fallback)
1127
+ * - Non-zero exit codes
1128
+ * - Combined stdout + stderr
1129
+ *
1130
+ * @param stdout Standard output captured from the CLI process
1131
+ * @param stderr Standard error captured from the CLI process
1132
+ * @param exitCode Exit code from the CLI process
1133
+ * @returns Normalized TaskResult
1134
+ */
1135
+ parseOutput(stdout: string, stderr: string, exitCode: number): TaskResult;
1136
+ /**
1137
+ * Parse the raw CLI output from a planning invocation into a PlanParseResult.
1138
+ *
1139
+ * @param stdout Standard output from the planning invocation
1140
+ * @param stderr Standard error from the planning invocation
1141
+ * @param exitCode Exit code from the planning invocation
1142
+ * @returns Parsed plan result
1143
+ */
1144
+ parsePlanOutput(stdout: string, stderr: string, exitCode: number): PlanParseResult;
1145
+ /**
1146
+ * Estimate the token count for a given prompt string.
1147
+ *
1148
+ * Used for pre-execution budget checks. Implementations may use heuristics
1149
+ * (e.g., character count / 3) when exact tokenizers are unavailable.
1150
+ *
1151
+ * @param prompt The prompt text to estimate
1152
+ * @returns TokenEstimate with input, output, and total projections
1153
+ *
1154
+ * @example
1155
+ * ```typescript
1156
+ * const estimate = adapter.estimateTokens('Fix the failing tests in auth.ts')
1157
+ * if (estimate.total > budgetCap) throw new BudgetExceededError(...)
1158
+ * ```
1159
+ */
1160
+ estimateTokens(prompt: string): TokenEstimate;
1161
+ /**
1162
+ * Return the capabilities of this adapter's underlying CLI agent.
1163
+ *
1164
+ * The returned object is used by the orchestrator for:
1165
+ * - Routing decisions (which adapter handles which task type)
1166
+ * - Plan generation eligibility
1167
+ * - Budget mode selection
1168
+ *
1169
+ * @returns AdapterCapabilities for this agent
1170
+ */
1171
+ getCapabilities(): AdapterCapabilities;
1172
+ }
1173
+
1174
+ //#endregion
1175
+ //#region src/adapters/adapter-registry.d.ts
1176
+ //# sourceMappingURL=worker-adapter.d.ts.map
1177
+ /**
1178
+ * Result from a single adapter discovery attempt.
1179
+ */
1180
+ interface AdapterDiscoveryResult {
1181
+ /** Adapter id that was tried */
1182
+ adapterId: AgentId;
1183
+ /** Display name of the adapter */
1184
+ displayName: string;
1185
+ /** Health check result */
1186
+ healthResult: AdapterHealthResult;
1187
+ /** Whether the adapter was registered (healthy) */
1188
+ registered: boolean;
1189
+ }
1190
+ /**
1191
+ * Summary result from discoverAndRegister().
1192
+ */
1193
+ interface DiscoveryReport {
1194
+ /** Number of adapters successfully registered */
1195
+ registeredCount: number;
1196
+ /** Number of adapters that failed health checks */
1197
+ failedCount: number;
1198
+ /** Per-adapter detail results */
1199
+ results: AdapterDiscoveryResult[];
1200
+ }
1201
+ /**
1202
+ * AdapterRegistry manages the lifecycle of WorkerAdapter instances.
1203
+ *
1204
+ * Usage:
1205
+ * ```typescript
1206
+ * const registry = new AdapterRegistry()
1207
+ * const report = await registry.discoverAndRegister()
1208
+ * const claude = registry.get('claude-code')
1209
+ * ```
1210
+ */
1211
+ declare class AdapterRegistry {
1212
+ private readonly _adapters;
1213
+ /**
1214
+ * Register an adapter by its id.
1215
+ * Overwrites any existing adapter with the same id.
1216
+ */
1217
+ register(adapter: WorkerAdapter): void;
1218
+ /**
1219
+ * Retrieve a registered adapter by id.
1220
+ * @returns The adapter, or undefined if not registered
1221
+ */
1222
+ get(id: AgentId): WorkerAdapter | undefined;
1223
+ /**
1224
+ * Return all registered adapters as an array.
1225
+ */
1226
+ getAll(): WorkerAdapter[];
1227
+ /**
1228
+ * Return all registered adapters that support plan generation.
1229
+ */
1230
+ getPlanningCapable(): WorkerAdapter[];
1231
+ /**
1232
+ * Instantiate all built-in adapters, run health checks sequentially,
1233
+ * and register those that pass.
1234
+ *
1235
+ * Failed adapters are included in the report but do NOT prevent startup.
1236
+ *
1237
+ * @returns Discovery report with per-adapter results
1238
+ */
1239
+ discoverAndRegister(): Promise<DiscoveryReport>;
1240
+ }
1241
+
1242
+ //#endregion
1243
+ //#region src/adapters/claude-adapter.d.ts
1244
+ //# sourceMappingURL=adapter-registry.d.ts.map
1245
+ /**
1246
+ * Adapter for the Claude Code CLI agent.
1247
+ *
1248
+ * Capabilities: JSON output, streaming, both billing modes, plan generation.
1249
+ * Health check: runs `claude --version` to verify install.
1250
+ * Billing detection: detects subscription vs API via version output or env.
1251
+ */
1252
+ declare class ClaudeCodeAdapter implements WorkerAdapter {
1253
+ readonly id: AgentId;
1254
+ readonly displayName = "Claude Code";
1255
+ readonly adapterVersion = "1.0.0";
1256
+ /**
1257
+ * Verify the `claude` binary is installed and responsive.
1258
+ * Detects subscription vs API billing mode.
1259
+ */
1260
+ healthCheck(): Promise<AdapterHealthResult>;
1261
+ /**
1262
+ * Build spawn command for a coding task.
1263
+ * Uses: `claude -p <prompt> --model <model> --dangerously-skip-permissions --system-prompt <minimal>`
1264
+ */
1265
+ buildCommand(prompt: string, options: AdapterOptions): SpawnCommand;
1266
+ /**
1267
+ * Build spawn command for plan generation.
1268
+ * Appends a structured planning directive to the prompt.
1269
+ */
1270
+ buildPlanningCommand(request: PlanRequest, options: AdapterOptions): SpawnCommand;
1271
+ /**
1272
+ * Parse Claude CLI JSON stdout output into TaskResult.
1273
+ */
1274
+ parseOutput(stdout: string, stderr: string, exitCode: number): TaskResult;
1275
+ /**
1276
+ * Parse plan generation output from Claude.
1277
+ */
1278
+ parsePlanOutput(stdout: string, stderr: string, exitCode: number): PlanParseResult;
1279
+ /**
1280
+ * Estimate token count using character-based heuristic.
1281
+ * Approximation: 1 token ≈ 3 characters for English text.
1282
+ */
1283
+ estimateTokens(prompt: string): TokenEstimate;
1284
+ /**
1285
+ * Return Claude Code's capabilities.
1286
+ */
1287
+ getCapabilities(): AdapterCapabilities;
1288
+ private _detectBillingModes;
1289
+ private _buildPlanningPrompt;
1290
+ }
1291
+
1292
+ //#endregion
1293
+ //#region src/adapters/codex-adapter.d.ts
1294
+ //# sourceMappingURL=claude-adapter.d.ts.map
1295
+ /**
1296
+ * Adapter for the OpenAI Codex CLI agent.
1297
+ *
1298
+ * Codex CLI uses stdin for the prompt and outputs JSON when --json flag is used.
1299
+ * Codex supports subscription billing (via `codex login`) and API key billing.
1300
+ */
1301
+ declare class CodexCLIAdapter implements WorkerAdapter {
1302
+ readonly id: AgentId;
1303
+ readonly displayName = "Codex CLI";
1304
+ readonly adapterVersion = "1.0.0";
1305
+ /**
1306
+ * Verify the `codex` binary is installed and responsive.
1307
+ */
1308
+ healthCheck(): Promise<AdapterHealthResult>;
1309
+ /**
1310
+ * Build spawn command for a coding task.
1311
+ * Uses: `codex exec --json` with prompt delivered via stdin.
1312
+ */
1313
+ buildCommand(prompt: string, options: AdapterOptions): SpawnCommand;
1314
+ /**
1315
+ * Build spawn command for plan generation.
1316
+ * Uses codex exec with a JSON plan generation prompt via stdin.
1317
+ */
1318
+ buildPlanningCommand(request: PlanRequest, options: AdapterOptions): SpawnCommand;
1319
+ /**
1320
+ * Parse Codex CLI JSON output into a TaskResult.
1321
+ */
1322
+ parseOutput(stdout: string, stderr: string, exitCode: number): TaskResult;
1323
+ /**
1324
+ * Parse Codex plan generation output.
1325
+ */
1326
+ parsePlanOutput(stdout: string, stderr: string, exitCode: number): PlanParseResult;
1327
+ /**
1328
+ * Estimate token count using character-based heuristic.
1329
+ */
1330
+ estimateTokens(prompt: string): TokenEstimate;
1331
+ /**
1332
+ * Return Codex CLI capabilities.
1333
+ */
1334
+ getCapabilities(): AdapterCapabilities;
1335
+ private _buildPlanningPrompt;
1336
+ }
1337
+
1338
+ //#endregion
1339
+ //#region src/adapters/gemini-adapter.d.ts
1340
+ //# sourceMappingURL=codex-adapter.d.ts.map
1341
+ /**
1342
+ * Adapter for the Google Gemini CLI agent.
1343
+ *
1344
+ * Gemini CLI follows similar patterns to Claude Code: prompt via `-p` flag,
1345
+ * JSON output via `--output-format json`, and model via `--model`.
1346
+ */
1347
+ declare class GeminiCLIAdapter implements WorkerAdapter {
1348
+ readonly id: AgentId;
1349
+ readonly displayName = "Gemini CLI";
1350
+ readonly adapterVersion = "1.0.0";
1351
+ /**
1352
+ * Verify the `gemini` binary is installed and responsive.
1353
+ * Detects subscription vs API billing mode.
1354
+ */
1355
+ healthCheck(): Promise<AdapterHealthResult>;
1356
+ /**
1357
+ * Build spawn command for a coding task.
1358
+ * Uses: `gemini -p <prompt> --output-format json --model <model>`
1359
+ */
1360
+ buildCommand(prompt: string, options: AdapterOptions): SpawnCommand;
1361
+ /**
1362
+ * Build spawn command for plan generation.
1363
+ */
1364
+ buildPlanningCommand(request: PlanRequest, options: AdapterOptions): SpawnCommand;
1365
+ /**
1366
+ * Parse Gemini CLI JSON output into a TaskResult.
1367
+ */
1368
+ parseOutput(stdout: string, stderr: string, exitCode: number): TaskResult;
1369
+ /**
1370
+ * Parse Gemini plan generation output.
1371
+ */
1372
+ parsePlanOutput(stdout: string, stderr: string, exitCode: number): PlanParseResult;
1373
+ /**
1374
+ * Estimate token count using character-based heuristic.
1375
+ */
1376
+ estimateTokens(prompt: string): TokenEstimate;
1377
+ /**
1378
+ * Return Gemini CLI capabilities.
1379
+ */
1380
+ getCapabilities(): AdapterCapabilities;
1381
+ private _detectBillingModes;
1382
+ private _buildPlanningPrompt;
1383
+ }
1384
+
1385
+ //#endregion
1386
+ //# sourceMappingURL=gemini-adapter.d.ts.map
1387
+
1388
+ export { AdapterCapabilities, AdapterDiscoveryResult, AdapterHealthResult, AdapterOptions, AdapterRegistry, AdtError, AgentCapability, AgentId, BaseService, BillingMode, BudgetExceededError, ClaudeCodeAdapter, CodexCLIAdapter, ConfigError, ConfigIncompatibleFormatError, CostRecord, DiscoveryReport, GeminiCLIAdapter, GitError, LogLevel, Orchestrator, OrchestratorConfig, OrchestratorEvents, PlanParseResult, PlanRequest, PlannedTask, RecoveryError, ServiceRegistry, SessionConfig, SessionStatus, SpawnCommand, TaskConfigError, TaskGraphCycleError, TaskGraphError, TaskGraphIncompatibleFormatError, TaskId, TaskNode, TaskPriority, TaskResult, TaskStatus, TokenEstimate, TypedEventBus, WorkerAdapter, WorkerError, WorkerId, WorkerNotFoundError, assertDefined, childLogger, createEventBus, createLogger, createOrchestrator, deepClone, formatDuration, generateId, isPlainObject, logger, sleep, withRetry };
1389
+ //# sourceMappingURL=index.d.ts.map