@aaac/runtime 0.0.1 → 0.1.1

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.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,806 @@
1
- declare const version = "0.0.1";
1
+ import { S as SdkAdapter, T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, O as ObserverEmitFn, P as PromptBuilderOptions, e as MemoryStore, M as MemoryRef, f as TaskRunResult } from './task-runner-CNj3Ujy0.js';
2
+ export { A as AdapterSendOptions, a as AgentExecutionRequest, g as AgentProgressEvent, C as CacheConfig, h as CandidateAgent, E as EnvelopeParams, I as InMemoryStore, R as RetryDecision, i as SplitPrompt, j as TaskRunOptions, k as buildCandidateAgents, l as buildRetryFollowUp, m as buildSplitTaskPrompt, n as buildTaskPrompt, o as createExecutionEnvelope, p as emitSessionClose, q as emitSessionOpen, r as emitSubagentClose, s as emitSubagentOpen, t as extractStructuredResult, u as renderAgentSystemPrompt, v as runTask, z as zodSchemaToPromptDescription, w as zodSchemaToYamlExample } from './task-runner-CNj3Ujy0.js';
3
+ import { z } from 'zod';
4
+ import { a as GuardrailRuleData, G as GuardrailHooks } from './guardrail-hooks-C8G5NGsj.js';
5
+ export { b as GuardrailCheckFunctions, c as GuardrailCheckResult, d as GuardrailRule, H as HookContext, e as HookResponse, f as createGuardrailHooks, g as createGuardrailHooksForAgent, h as createGuardrailHooksFromRules, i as getBlockingViolations, j as getWarnings, k as hasBlockingViolation } from './guardrail-hooks-C8G5NGsj.js';
6
+ import { G as GuardrailContext } from './context-B_bekYiE.js';
7
+ import { OperationIR, ComponentIR } from '@aaac/contracts';
8
+ export { ExecutionEnvelope } from '@aaac/observability';
2
9
 
3
- export { version };
10
+ /**
11
+ * ModelResolver — resolves a model_class to a concrete adapter + model pair.
12
+ *
13
+ * Resolution priority (highest wins):
14
+ * 1. AGENT_RUNTIME_MODEL_{FAST|STANDARD|THINKING} env var
15
+ * 2. AGENT_RUNTIME_MODEL env var (catch-all fallback)
16
+ * 3. agent-runtime.config.yaml model_mapping.<class>
17
+ * 4. CLI --adapter + adapter default model
18
+ */
19
+ type ModelClass = "fast" | "standard" | "thinking";
20
+ interface ResolvedModel {
21
+ adapter: string;
22
+ model?: string;
23
+ }
24
+ interface ModelResolver {
25
+ resolve(modelClass: ModelClass | undefined): ResolvedModel;
26
+ }
27
+ interface ModelMappingConfig {
28
+ fast?: {
29
+ adapter: string;
30
+ model?: string;
31
+ };
32
+ standard?: {
33
+ adapter: string;
34
+ model?: string;
35
+ };
36
+ thinking?: {
37
+ adapter: string;
38
+ model?: string;
39
+ };
40
+ }
41
+ interface ModelResolverOptions {
42
+ modelMapping?: ModelMappingConfig;
43
+ fallbackAdapter: string;
44
+ fallbackModel?: string;
45
+ env?: Record<string, string | undefined>;
46
+ }
47
+ declare function createModelResolver(options: ModelResolverOptions): ModelResolver;
48
+
49
+ /**
50
+ * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions
51
+ *
52
+ * Programmatic control flow that replaces LLM-driven step interpretation:
53
+ *
54
+ * 1. Load workflow contract (ordered steps)
55
+ * 2. Run plugin beforeWorkflow hooks
56
+ * 3. For each step:
57
+ * - delegate → call task-runner with followUp/retry recovery
58
+ * - gate → pause and wait for user input
59
+ * 4. Validate each result against handoff schema
60
+ * 5. Accumulate context between steps
61
+ * 6. Run plugin afterWorkflow hooks
62
+ */
63
+
64
+ /**
65
+ * A factory that creates independent SdkAdapter instances.
66
+ * Used by runWorkflow to allocate one adapter per parallel step,
67
+ * avoiding session-level serialization in stateful SDK adapters.
68
+ */
69
+ type SdkAdapterFactory = () => SdkAdapter;
70
+ /**
71
+ * Model-aware adapter factory. Accepts a model_class and returns an adapter
72
+ * configured for that capability level (possibly a different provider/model).
73
+ */
74
+ type ModelAwareSdkAdapterFactory = (modelClass?: ModelClass) => SdkAdapter | Promise<SdkAdapter>;
75
+ /** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */
76
+ type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;
77
+ interface DelegateStep {
78
+ readonly type: "delegate";
79
+ readonly task: string;
80
+ readonly from_agent: string;
81
+ readonly description: string;
82
+ readonly optional: boolean;
83
+ readonly max_retries: number;
84
+ readonly max_follow_ups?: number;
85
+ readonly depends_on?: readonly string[];
86
+ readonly retry?: {
87
+ readonly condition: string;
88
+ readonly fix_task: string;
89
+ readonly revalidate_task?: string;
90
+ };
91
+ }
92
+ interface GateStep {
93
+ readonly type: "gate";
94
+ readonly gate_kind: string;
95
+ readonly description: string;
96
+ readonly depends_on?: readonly string[];
97
+ }
98
+ type WorkflowStep = DelegateStep | GateStep;
99
+ interface WorkflowContractLike {
100
+ readonly id: string;
101
+ readonly description: string;
102
+ readonly steps: readonly WorkflowStep[];
103
+ }
104
+ interface WorkflowRunOptions {
105
+ user_request: string;
106
+ /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */
107
+ maxFollowUps?: number;
108
+ /** Override max full retry attempts per step. Default: from DSL step.max_retries */
109
+ maxRetries?: number;
110
+ /** Variables propagated to every TaskContext in the workflow (from WorkflowInvocation.context). */
111
+ variables?: Record<string, unknown>;
112
+ onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;
113
+ onStepComplete?: (event: StepCompleteEvent) => void;
114
+ onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;
115
+ /**
116
+ * Writable stream for real-time progress output during agent execution.
117
+ * Intermediate events from adapters are formatted and written here.
118
+ * Typical value: process.stderr.
119
+ */
120
+ progressOutput?: {
121
+ write(chunk: string): unknown;
122
+ };
123
+ /**
124
+ * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).
125
+ * When undefined, no spans are emitted (observer is optional — no-op).
126
+ * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.
127
+ */
128
+ observer?: ObserverEmitFn;
129
+ }
130
+ /** Typed handoff envelope for workflow input. */
131
+ interface HandoffInput<TType extends string = string, TPayload = unknown> {
132
+ readonly type: TType;
133
+ readonly version?: number;
134
+ readonly payload: TPayload;
135
+ }
136
+ /**
137
+ * Standard runtime invocation envelope. SDK-specific options (openaiThreadId,
138
+ * sessionId, etc.) belong on the adapter constructor — not here.
139
+ */
140
+ interface WorkflowInvocation<THandoffType extends string = string, TPayload = unknown> {
141
+ workflow: string;
142
+ /** Structured typed handoff input. Takes precedence over user_request if both are set. */
143
+ handoff?: HandoffInput<THandoffType, TPayload>;
144
+ /** Simple string input (convenience shorthand). */
145
+ user_request?: string;
146
+ runtime?: {
147
+ maxFollowUps?: number;
148
+ maxRetries?: number;
149
+ timeoutMs?: number;
150
+ readonly?: boolean;
151
+ dryRun?: boolean;
152
+ };
153
+ hooks?: {
154
+ onStepComplete?: (event: StepCompleteEvent) => void;
155
+ onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;
156
+ onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;
157
+ };
158
+ /**
159
+ * Writable stream for real-time progress output during agent execution.
160
+ * Intermediate events from adapters are formatted and written here.
161
+ * Typical value: process.stderr.
162
+ */
163
+ progressOutput?: {
164
+ write(chunk: string): unknown;
165
+ };
166
+ context?: {
167
+ cwd?: string;
168
+ environment?: "local" | "ci" | "remote";
169
+ artifacts?: Record<string, string>;
170
+ variables?: Record<string, unknown>;
171
+ };
172
+ /**
173
+ * Optional observer emit function for agent-axis spans (agent.session, agent.subagent).
174
+ * When undefined, no spans are emitted (observer is optional — no-op).
175
+ * Pass EventCollector.emit.bind(collector) to wire up the full observability pipeline.
176
+ */
177
+ observer?: ObserverEmitFn;
178
+ }
179
+ interface StepResult {
180
+ step_index: number;
181
+ task_id?: string;
182
+ gate_kind?: string;
183
+ outcome: TaskOutcome | {
184
+ status: "gate_approved";
185
+ } | {
186
+ status: "gate_rejected";
187
+ } | {
188
+ status: "skipped";
189
+ };
190
+ follow_ups_used: number;
191
+ retries_used: number;
192
+ elapsed_ms: number;
193
+ }
194
+ interface StepCompleteEvent {
195
+ workflow_id: string;
196
+ step_index: number;
197
+ step_type: "delegate" | "gate";
198
+ task_id?: string;
199
+ gate_kind?: string;
200
+ outcome_status: string;
201
+ follow_ups_used: number;
202
+ retries_used: number;
203
+ elapsed_ms: number;
204
+ }
205
+ interface WorkflowResult {
206
+ workflow_id: string;
207
+ status: "completed" | "escalated" | "gate_rejected" | "error";
208
+ steps: StepResult[];
209
+ total_elapsed_ms: number;
210
+ escalation_reason?: string;
211
+ error_message?: string;
212
+ }
213
+ interface WorkflowRegistries {
214
+ workflowRegistry?: Record<string, WorkflowContractLike>;
215
+ taskRegistry?: Record<string, TaskContractLike>;
216
+ agentRegistry?: Record<string, AgentContractLike>;
217
+ handoffSchemas?: Record<string, z.ZodType>;
218
+ }
219
+ /** @deprecated Use the WorkflowInvocation overload for typed handoff input. */
220
+ declare function runWorkflow(adapter: AdapterOrFactory, workflowId: string, options: WorkflowRunOptions, registries?: WorkflowRegistries): Promise<WorkflowResult>;
221
+ /** Structured invocation with typed handoff envelope. */
222
+ declare function runWorkflow(adapter: AdapterOrFactory, invocation: WorkflowInvocation, registries?: WorkflowRegistries): Promise<WorkflowResult>;
223
+ declare function buildGateEvaluationPrompt(step: GateStep, priorContext: string): string;
224
+ declare function parseGateEvaluationResponse(response: string): boolean;
225
+
226
+ /**
227
+ * Plugin Interface — extension points for user code injection
228
+ */
229
+
230
+ interface GuardrailResult {
231
+ matched: boolean;
232
+ guardrail_id: string;
233
+ severity: "critical" | "mandatory" | "warning" | "info";
234
+ action: "block" | "warn" | "shadow" | "info";
235
+ message: string;
236
+ }
237
+ interface PromptBuilderArgs {
238
+ agent: AgentContractLike;
239
+ task: TaskContractLike;
240
+ context: TaskContext;
241
+ options?: PromptBuilderOptions;
242
+ }
243
+ interface AgentPlugin {
244
+ readonly id: string;
245
+ beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;
246
+ afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
247
+ /**
248
+ * Enrich the structured TaskContext before prompt generation.
249
+ * Unlike beforeTask (which can skip a task by returning null),
250
+ * this hook is purely for context augmentation.
251
+ */
252
+ contextEnhancer?(taskId: string, context: TaskContext): TaskContext;
253
+ /**
254
+ * Lightweight prompt post-processor. Applied after the prompt is built.
255
+ * Use for appending instructions or modifying sections.
256
+ */
257
+ promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;
258
+ /**
259
+ * Full prompt builder override. If provided and returns a non-null string,
260
+ * replaces the default buildTaskPrompt output entirely.
261
+ * Receives the agent/task contracts and context so the plugin can build
262
+ * a completely custom prompt.
263
+ */
264
+ promptBuilder?(args: PromptBuilderArgs): string | null;
265
+ customGuardrails?: {
266
+ evaluateCommand?(command: string): GuardrailResult[];
267
+ evaluateFilePath?(filePath: string): GuardrailResult[];
268
+ evaluateFileContent?(filePath: string, content: string): GuardrailResult[];
269
+ };
270
+ beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;
271
+ afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;
272
+ }
273
+ declare class PluginRegistry {
274
+ private plugins;
275
+ register(plugin: AgentPlugin): void;
276
+ getAll(): readonly AgentPlugin[];
277
+ runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null>;
278
+ runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
279
+ applyContextEnhancers(taskId: string, context: TaskContext): TaskContext;
280
+ /**
281
+ * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,
282
+ * or null to use the default buildTaskPrompt.
283
+ */
284
+ applyPromptBuilder(args: PromptBuilderArgs): string | null;
285
+ applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string;
286
+ evaluateCommandGuardrails(command: string): GuardrailResult[];
287
+ evaluateFilePathGuardrails(filePath: string): GuardrailResult[];
288
+ evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[];
289
+ runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void>;
290
+ runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void>;
291
+ }
292
+ declare const pluginRegistry: PluginRegistry;
293
+
294
+ /**
295
+ * BoundResolver — runtime binding + policy resolution with per-agent isolation.
296
+ *
297
+ * Resolves artifact binding and guardrail/policy in one pass at runtime,
298
+ * producing a per-agent scoped ResolvedComponent. Reuses existing
299
+ * resolveBound(), buildGuardrailContext(), and agent scope resolution.
300
+ */
301
+
302
+ interface ArtifactBindingConfig {
303
+ source: string;
304
+ mappings?: Record<string, string>;
305
+ }
306
+ interface BoundResolveOptions {
307
+ /** Component identifier — used for cache keying. */
308
+ id: string;
309
+ /** Pre-resolved DSL (e.g. embedded from codegen). */
310
+ embeddedDsl?: Record<string, unknown>;
311
+ /** Path to DSL file — resolved via agent-contracts when no embeddedDsl. */
312
+ dslPath?: string;
313
+ /** Paths to software binding YAML files (guardrail_impl, etc.). */
314
+ bindingPaths?: string[];
315
+ /** Active guardrail policy name from DSL guardrail_policies. */
316
+ activeGuardrailPolicy?: string;
317
+ /** Artifact binding config — resolved via agent-contracts resolveBound(). */
318
+ artifactBinding?: ArtifactBindingConfig;
319
+ /** Path substitutions for artifact binding. */
320
+ paths?: Record<string, string>;
321
+ }
322
+ interface ResolvedComponent {
323
+ id: string;
324
+ dsl: Record<string, unknown>;
325
+ registries: WorkflowRegistries;
326
+ guardrails: {
327
+ perAgent: Map<string, GuardrailRuleData>;
328
+ };
329
+ diagnostics: Array<{
330
+ path?: string;
331
+ message: string;
332
+ severity?: string;
333
+ }>;
334
+ }
335
+ /**
336
+ * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side bindings.
337
+ */
338
+ declare function getEffectiveGuardrailIds(dsl: Record<string, unknown>, agentId: string): Set<string>;
339
+ declare function guardrailContextToRuleData(ctx: GuardrailContext, effectiveIds?: Set<string>): GuardrailRuleData;
340
+ declare function buildPerAgentGuardrails(dsl: Record<string, unknown>, guardrailCtx: GuardrailContext): Map<string, GuardrailRuleData>;
341
+ declare class BoundResolver {
342
+ private readonly cache;
343
+ /**
344
+ * Resolve binding + policy in one pass. Results are cached by component id.
345
+ */
346
+ resolve(opts: BoundResolveOptions): Promise<ResolvedComponent>;
347
+ /** Clear cached components (e.g. for testing). */
348
+ clearCache(): void;
349
+ }
350
+ /**
351
+ * Get guardrail rules for a specific agent from a ResolvedComponent.
352
+ * Falls back to embedded _guardrailRules when no per-agent rules exist.
353
+ */
354
+ declare function getGuardrailRulesForAgent(component: ResolvedComponent, agentId: string, fallbackDsl?: Record<string, unknown>): GuardrailRuleData | undefined;
355
+
356
+ /**
357
+ * Fluent Builder API for workflow invocation.
358
+ *
359
+ * Usage:
360
+ * const runtime = createRuntime({ adapter, registries });
361
+ * const result = await runtime
362
+ * .workflow("feature-implement")
363
+ * .handoff(handoffs.featureImplementationRequest({ ... }))
364
+ * .maxFollowUps(3)
365
+ * .onGate(async () => true)
366
+ * .run();
367
+ */
368
+
369
+ interface RuntimeConfig {
370
+ adapter: SdkAdapter;
371
+ registries?: WorkflowRegistries;
372
+ }
373
+ interface Runtime {
374
+ workflow(workflowId: string): WorkflowBuilder;
375
+ }
376
+ declare function createRuntime(config: RuntimeConfig): Runtime;
377
+ declare class WorkflowBuilder {
378
+ private adapter;
379
+ private invocation;
380
+ private registries;
381
+ constructor(adapter: SdkAdapter, workflowId: string, registries?: WorkflowRegistries);
382
+ /** Set a typed handoff envelope as input. */
383
+ handoff<T extends string>(input: HandoffInput<T>): this;
384
+ /** Set a simple string request (convenience shorthand). */
385
+ request(userRequest: string): this;
386
+ maxFollowUps(n: number): this;
387
+ maxRetries(n: number): this;
388
+ onStepComplete(cb: (event: StepCompleteEvent) => void): this;
389
+ onGate(cb: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>): this;
390
+ onOptionalStep(cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>): this;
391
+ /** Set progress output sink for real-time execution visibility. */
392
+ progressOutput(sink: {
393
+ write(chunk: string): unknown;
394
+ }): this;
395
+ run(): Promise<WorkflowResult>;
396
+ }
397
+
398
+ /**
399
+ * Plugin Loader — auto-discovers and registers user plugin files
400
+ *
401
+ * Discovery strategies (in priority order):
402
+ * 1. Config-based: `plugins` array in agent-runtime.config.yaml
403
+ * 2. Convention-based: scan `src/plugins/` for files exporting AgentPlugin
404
+ *
405
+ * Each discovered module is dynamically import()'d. Exports that satisfy the
406
+ * AgentPlugin interface (have an `id` string property) are registered with
407
+ * the pluginRegistry singleton.
408
+ */
409
+ interface PluginLoadResult {
410
+ loaded: number;
411
+ files: string[];
412
+ errors: Array<{
413
+ file: string;
414
+ error: string;
415
+ }>;
416
+ }
417
+ /**
418
+ * Load plugins from explicit paths (config-based discovery).
419
+ */
420
+ declare function loadPluginsFromPaths(paths: string[], baseDir: string): Promise<PluginLoadResult>;
421
+ /**
422
+ * Load plugins using convention-based directory scanning.
423
+ * Scans `<projectDir>/src/plugins/` by default.
424
+ */
425
+ declare function loadPluginsFromDirectory(dir: string): Promise<PluginLoadResult>;
426
+ /**
427
+ * Auto-discover and load plugins. Uses config-based paths if provided,
428
+ * otherwise falls back to convention-based scanning of src/plugins/.
429
+ */
430
+ declare function loadPlugins(options: {
431
+ pluginPaths?: string[];
432
+ projectDir: string;
433
+ }): Promise<PluginLoadResult>;
434
+
435
+ /**
436
+ * Runtime DSL Context — builds WorkflowRegistries from embedded DSL data,
437
+ * optionally merging with project-level DSL extensions.
438
+ *
439
+ * Default flow:
440
+ * CLI binary embeds resolved DSL data (from code generation) →
441
+ * loadDslContext() builds registries from it.
442
+ *
443
+ * Extended flow:
444
+ * Project provides a DSL that extends/overrides the embedded base →
445
+ * loadDslContext() merges via agent-contracts' mergeDsl() →
446
+ * builds registries from the merged result.
447
+ */
448
+
449
+ interface LoadDslOptions {
450
+ /**
451
+ * Pre-resolved DSL data embedded in the CLI binary.
452
+ * Produced by the code generator alongside TypeScript contracts.
453
+ * This is the default DSL — used as-is when no project extension exists.
454
+ */
455
+ embeddedDsl: Record<string, unknown>;
456
+ /**
457
+ * Path to a project-level DSL file that extends/overrides the embedded DSL.
458
+ * When provided, the project DSL is resolved (including its own extends chain)
459
+ * and merged with embeddedDsl via mergeDsl().
460
+ */
461
+ projectDslPath?: string;
462
+ /** Entities the CLI depends on — validated after merge. */
463
+ requiredEntities?: RequiredEntities;
464
+ }
465
+ interface RequiredEntities {
466
+ workflows?: string[];
467
+ tasks?: string[];
468
+ }
469
+ interface DslContext {
470
+ readonly registries: WorkflowRegistries;
471
+ readonly dsl: Record<string, unknown>;
472
+ readonly guardrailRules?: GuardrailRuleData;
473
+ }
474
+ declare class DslValidationError extends Error {
475
+ readonly missing: string[];
476
+ constructor(missing: string[]);
477
+ }
478
+ declare function buildGuardrailRulesFromDsl(dsl: Record<string, unknown>): GuardrailRuleData | undefined;
479
+ declare function buildRegistriesFromDsl(dsl: Record<string, unknown>): WorkflowRegistries;
480
+ /**
481
+ * Build a DslContext from embedded DSL data, optionally merging with
482
+ * a project-level DSL extension.
483
+ *
484
+ * Default (no projectDslPath):
485
+ * Builds registries directly from embeddedDsl — no filesystem access.
486
+ *
487
+ * Extended (with projectDslPath):
488
+ * Resolves the project DSL from filesystem, merges it over embeddedDsl
489
+ * via agent-contracts' mergeDsl(), then builds registries from the result.
490
+ */
491
+ declare function loadDslContext(options: LoadDslOptions): Promise<DslContext>;
492
+
493
+ /**
494
+ * Runtime JSON Schema → Zod converter.
495
+ *
496
+ * Mirrors the compile-time zodType Handlebars helper in
497
+ * generator/template-engine.ts but produces live z.ZodType
498
+ * objects instead of code strings.
499
+ */
500
+
501
+ /**
502
+ * Convert a JSON Schema definition to a Zod schema object at runtime.
503
+ *
504
+ * Supports the same subset as the compile-time zodType helper:
505
+ * object, array, string, number, integer, boolean, enum, const, allOf.
506
+ */
507
+ declare function jsonSchemaToZod(schema: Record<string, unknown>): z.ZodType;
508
+
509
+ /**
510
+ * Progress Sink — configurable output target for agent execution progress.
511
+ *
512
+ * Supports writing to stderr, file, or both (tee). File naming strategies
513
+ * allow single-file append, per-invocation unique files, or daily rotation.
514
+ */
515
+ interface ProgressSinkOptions {
516
+ /** Write to process.stderr. Default: false */
517
+ stderr?: boolean;
518
+ /** Base file path for log output. */
519
+ file?: string;
520
+ /**
521
+ * File naming strategy:
522
+ * - "single": always append to `file` (default)
523
+ * - "per-invocation": {dir}/{base}-{YYYY-MM-DDTHHmmss}-{label}{ext}
524
+ * - "daily": {dir}/{base}-{YYYY-MM-DD}{ext}
525
+ */
526
+ naming?: "single" | "per-invocation" | "daily";
527
+ /** Label for per-invocation naming (e.g. workflow ID). */
528
+ label?: string;
529
+ }
530
+ interface ProgressSink {
531
+ write(chunk: string): void;
532
+ close(): void;
533
+ /** Resolved file path (undefined if file output is disabled). */
534
+ readonly filePath?: string;
535
+ }
536
+ declare function createProgressSink(options: ProgressSinkOptions): ProgressSink;
537
+
538
+ interface FileMemoryStoreOptions {
539
+ baseDir?: string;
540
+ }
541
+ /**
542
+ * File-backed MemoryStore. Persists memory content as JSON files under
543
+ * `<baseDir>/` (default: `.agent-logs/memories/`).
544
+ */
545
+ declare class FileMemoryStore implements MemoryStore {
546
+ readonly baseDir: string;
547
+ constructor(options?: FileMemoryStoreOptions);
548
+ save(ref: MemoryRef, content: unknown): Promise<void>;
549
+ load(ref: MemoryRef): Promise<unknown | null>;
550
+ delete(ref: MemoryRef): Promise<void>;
551
+ }
552
+
553
+ interface RunLogEvent {
554
+ timestamp: string;
555
+ type: "operation_start" | "operation_end" | "operation_error" | "workflow_start" | "workflow_end" | "task_start" | "task_end" | "handoff";
556
+ runId: string;
557
+ operationName?: string;
558
+ agentId?: string;
559
+ data?: unknown;
560
+ durationMs?: number;
561
+ error?: string;
562
+ }
563
+ interface AgentLogWriterOptions {
564
+ baseDir?: string;
565
+ }
566
+ declare class AgentLogWriter {
567
+ readonly baseDir: string;
568
+ private memoryStore;
569
+ constructor(options?: AgentLogWriterOptions);
570
+ getMemoryStore(): FileMemoryStore;
571
+ writeRunEvent(runId: string, event: RunLogEvent): Promise<void>;
572
+ readRunLog(runId: string): Promise<RunLogEvent[]>;
573
+ writeHandoff(runId: string, step: string, data: unknown): Promise<void>;
574
+ readHandoff(runId: string, step: string): Promise<unknown | null>;
575
+ cleanOlderThan(maxAgeMs: number): Promise<{
576
+ deleted: number;
577
+ }>;
578
+ }
579
+
580
+ interface LibraryToolDefinition {
581
+ toolId: string;
582
+ description: string;
583
+ module: string;
584
+ exportName: string;
585
+ inputSchema?: Record<string, unknown>;
586
+ outputSchema?: Record<string, unknown>;
587
+ }
588
+ interface LibraryToolRegistry {
589
+ register(def: LibraryToolDefinition): void;
590
+ get(toolId: string): LibraryToolDefinition | undefined;
591
+ getAll(): LibraryToolDefinition[];
592
+ execute(toolId: string, input: unknown): Promise<unknown>;
593
+ }
594
+ declare function createLibraryToolRegistry(): LibraryToolRegistry;
595
+
596
+ /**
597
+ * Adapter Factory — public API for creating SDK adapters by name.
598
+ *
599
+ * Centralises the adapter-name → SDK-class mapping so that consumers
600
+ * no longer need a local switch statement with dynamic imports.
601
+ */
602
+
603
+ type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";
604
+ interface CreateAdapterOptions {
605
+ model?: string;
606
+ cwd?: string;
607
+ tools?: string[];
608
+ permissionMode?: PermissionMode;
609
+ guardrailHooks?: GuardrailHooks;
610
+ }
611
+ /**
612
+ * Create an SDK adapter instance by name.
613
+ *
614
+ * @param name - One of: "mock", "claude", "openai", "gemini"
615
+ * @param options - Adapter-specific configuration
616
+ */
617
+ declare function createAdapter(name: string, options?: CreateAdapterOptions): Promise<SdkAdapter>;
618
+
619
+ /**
620
+ * High-level execution APIs — executeTask / executeWorkflow
621
+ *
622
+ * Encapsulates the common boilerplate shared across all CLI consumers:
623
+ * 1. Adapter creation
624
+ * 2. DSL context loading (registries)
625
+ * 3. Progress sink setup
626
+ * 4. Task/workflow invocation with retry policy
627
+ *
628
+ * CLI consumers only need to provide:
629
+ * - domain-specific context (user_request)
630
+ * - adapter name + options
631
+ * - DSL blob (resolvedDsl from codegen)
632
+ */
633
+
634
+ interface ExecuteOptions {
635
+ adapter: string;
636
+ model?: string;
637
+ dsl: Record<string, unknown>;
638
+ projectDslPath?: string;
639
+ logFile?: string;
640
+ adapterOptions?: Partial<CreateAdapterOptions>;
641
+ maxFollowUps?: number;
642
+ maxRetries?: number;
643
+ /** Pre-resolved component from BoundResolver (skips runtime resolve). */
644
+ resolvedComponent?: ResolvedComponent;
645
+ /** Component id for BoundResolver cache keying. */
646
+ componentId?: string;
647
+ /** Software binding paths for runtime guardrail resolution. */
648
+ bindingPaths?: string[];
649
+ /** Active guardrail policy name. */
650
+ activeGuardrailPolicy?: string;
651
+ /** Artifact binding config for runtime resolveBound(). */
652
+ artifactBinding?: ArtifactBindingConfig;
653
+ /** Path substitutions for artifact binding. */
654
+ paths?: Record<string, string>;
655
+ }
656
+ interface TaskHookContext {
657
+ adapter: SdkAdapter;
658
+ registries: WorkflowRegistries;
659
+ taskId: string;
660
+ }
661
+ interface ExecuteTaskOptions extends ExecuteOptions {
662
+ request: string;
663
+ hooks?: {
664
+ beforeTask?: (ctx: TaskHookContext) => Promise<void>;
665
+ afterTask?: (result: TaskRunResult) => Promise<void>;
666
+ };
667
+ }
668
+ declare function executeTask(taskId: string, options: ExecuteTaskOptions): Promise<TaskRunResult>;
669
+ interface WorkflowHookContext {
670
+ adapter: SdkAdapter;
671
+ registries: WorkflowRegistries;
672
+ workflowId: string;
673
+ }
674
+ interface ExecuteWorkflowOptions extends ExecuteOptions {
675
+ request?: string;
676
+ handoff?: HandoffInput<string>;
677
+ context?: {
678
+ cwd?: string;
679
+ environment?: "local" | "ci" | "remote";
680
+ artifacts?: Record<string, string>;
681
+ variables?: Record<string, unknown>;
682
+ };
683
+ autoApproveGates?: boolean;
684
+ hooks?: {
685
+ beforeWorkflow?: (ctx: WorkflowHookContext) => Promise<void>;
686
+ afterWorkflow?: (result: WorkflowResult) => Promise<void>;
687
+ onStepComplete?: (event: StepCompleteEvent) => void;
688
+ onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;
689
+ onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;
690
+ };
691
+ }
692
+ declare function executeWorkflow(workflowId: string, options: ExecuteWorkflowOptions): Promise<WorkflowResult>;
693
+
694
+ interface OperationMemoryRefConfig {
695
+ output?: boolean;
696
+ input?: boolean;
697
+ provider?: string;
698
+ compat?: string;
699
+ }
700
+ interface MemoryStoreEntry {
701
+ result: unknown;
702
+ memoryRef: MemoryRef;
703
+ }
704
+ interface AaacInvocationContext {
705
+ runtime: AaacRuntime;
706
+ policy?: AaacPolicy;
707
+ observer?: AaacObserver;
708
+ parentRunId?: string;
709
+ abortSignal?: AbortSignal;
710
+ memoryRef?: MemoryRef;
711
+ memoryStore?: MemoryStore;
712
+ logWriter?: AgentLogWriter;
713
+ /** Populated when resuming from a previous memory_ref. */
714
+ resumedState?: unknown;
715
+ /** Current run ID for this invocation chain. */
716
+ runId?: string;
717
+ }
718
+ interface AaacRuntime {
719
+ runWorkflow(workflowId: string, options: Record<string, unknown>, input: unknown, ctx: AaacInvocationContext): Promise<unknown>;
720
+ runTask(taskId: string, options: Record<string, unknown>, input: unknown, ctx: AaacInvocationContext): Promise<unknown>;
721
+ }
722
+ interface AaacPolicy {
723
+ assertAllowed(operationName: string): void | Promise<void>;
724
+ }
725
+ interface AaacObserver {
726
+ onOperationStart?(operationName: string, input: unknown): void;
727
+ onOperationEnd?(operationName: string, output: unknown): void;
728
+ onOperationError?(operationName: string, error: Error): void;
729
+ /**
730
+ * Emit an agent-axis event to the observability pipeline.
731
+ * Structurally matches EventCollector.emit() from @aaac/observability.
732
+ * Pass an EventCollector instance to wire up the full pipeline.
733
+ * When undefined, emission is a no-op (observer is optional).
734
+ */
735
+ emit?: ObserverEmitFn;
736
+ }
737
+ type OperationHandler = (options: Record<string, unknown>, input: unknown, ctx: AaacInvocationContext) => Promise<unknown>;
738
+ interface RuntimeBinding {
739
+ execute(operationName: string, options: Record<string, unknown>, input: unknown, ctx: AaacInvocationContext): Promise<unknown>;
740
+ getOperationNames(): string[];
741
+ getOperationIR(name: string): OperationIR | undefined;
742
+ }
743
+ declare function createRuntimeBinding(component: ComponentIR, handlers?: Record<string, OperationHandler>): RuntimeBinding;
744
+
745
+ interface ComponentScope {
746
+ componentId: string;
747
+ componentIR: ComponentIR;
748
+ binding: RuntimeBinding;
749
+ toolsByAgent: Map<string, string[]>;
750
+ guardrailsByAgent: Map<string, unknown[]>;
751
+ libraryTools?: LibraryToolRegistry;
752
+ }
753
+ interface CreateComponentScopeOptions {
754
+ resolvedComponent?: ResolvedComponent;
755
+ libraryToolDefs?: LibraryToolDefinition[];
756
+ }
757
+ declare function createComponentScope(componentIR: ComponentIR, binding: RuntimeBinding, options?: CreateComponentScopeOptions): ComponentScope;
758
+
759
+ interface NavigationContextOptions {
760
+ configPath?: string;
761
+ embeddedDsl?: Record<string, unknown>;
762
+ projectDslPath?: string;
763
+ artifactBinding?: {
764
+ source: string;
765
+ mappings?: Record<string, string>;
766
+ };
767
+ paths?: Record<string, string>;
768
+ }
769
+ interface NavigationContext {
770
+ dsl: Record<string, unknown>;
771
+ navigationIndex: Record<string, unknown>;
772
+ diagnostics: Array<{
773
+ path: string;
774
+ message: string;
775
+ severity: string;
776
+ }>;
777
+ }
778
+ declare function buildNavigationContext(options: NavigationContextOptions): Promise<NavigationContext>;
779
+
780
+ interface ArtifactResolveOptions {
781
+ dsl: Record<string, unknown>;
782
+ artifactBinding?: {
783
+ source: string;
784
+ mappings?: Record<string, string>;
785
+ };
786
+ paths?: Record<string, string>;
787
+ }
788
+ interface ArtifactResolveResult {
789
+ dsl: Record<string, unknown>;
790
+ diagnostics: Array<{
791
+ path: string;
792
+ message: string;
793
+ severity: string;
794
+ }>;
795
+ }
796
+ declare function resolveArtifacts(options: ArtifactResolveOptions): Promise<ArtifactResolveResult>;
797
+
798
+ /**
799
+ * @aaac/runtime — public API
800
+ *
801
+ * Runtime bridge for executing agent-contracts workflows on Agent SDKs.
802
+ */
803
+ /** Package version string. */
804
+ declare const version: string;
805
+
806
+ export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, type AdapterOrFactory, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, type ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type BoundResolveOptions, BoundResolver, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type DelegateStep, type DslContext, DslValidationError, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GateStep, GuardrailHooks, type GuardrailResult, GuardrailRuleData, type HandoffInput, type LibraryToolDefinition, type LibraryToolRegistry, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, type ModelAwareSdkAdapterFactory, type ModelClass, type ModelMappingConfig, type ModelResolver, type ModelResolverOptions, type NavigationContext, type NavigationContextOptions, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProgressSink, type ProgressSinkOptions, type PromptBuilderArgs, PromptBuilderOptions, type RequiredEntities, type ResolvedComponent, type ResolvedModel, type RunLogEvent, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkAdapterFactory, type StepCompleteEvent, type StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, WorkflowBuilder, type WorkflowContractLike, type WorkflowHookContext, type WorkflowInvocation, type WorkflowRegistries, type WorkflowResult, type WorkflowRunOptions, type WorkflowStep, buildGateEvaluationPrompt, buildGuardrailRulesFromDsl, buildNavigationContext, buildPerAgentGuardrails, buildRegistriesFromDsl, createAdapter, createComponentScope, createLibraryToolRegistry, createModelResolver, createProgressSink, createRuntime, createRuntimeBinding, executeTask, executeWorkflow, getEffectiveGuardrailIds, getGuardrailRulesForAgent, guardrailContextToRuleData, jsonSchemaToZod, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, parseGateEvaluationResponse, pluginRegistry, resolveArtifacts, runWorkflow, version };