@aaac/runtime 0.1.4 → 0.1.6

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,94 @@
1
+ // src/lib/library-tool-sdk.ts
2
+ function buildSdkFunctionTools(registry) {
3
+ return registry.getAll().map((def) => ({
4
+ name: def.toolId,
5
+ description: def.description,
6
+ inputSchema: def.inputSchema ?? { type: "object", properties: {} },
7
+ handler: async (args) => {
8
+ const result = await registry.execute(def.toolId, args);
9
+ return typeof result === "string" ? result : JSON.stringify(result);
10
+ }
11
+ }));
12
+ }
13
+ async function buildClaudeMcpServer(registry) {
14
+ const tools = buildSdkFunctionTools(registry);
15
+ if (tools.length === 0) return void 0;
16
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
17
+ const toolFn = sdk.tool;
18
+ const createServer = sdk.createSdkMcpServer;
19
+ if (!toolFn || !createServer) return void 0;
20
+ const { z } = await import("zod");
21
+ const { jsonSchemaToZod } = await import("./schema-converter-LACA7P4O.js");
22
+ const sdkTools = tools.map(
23
+ (t) => toolFn({
24
+ name: t.name,
25
+ description: t.description,
26
+ inputSchema: jsonSchemaToZod(t.inputSchema),
27
+ execute: async (args) => {
28
+ return t.handler(
29
+ args ?? {}
30
+ );
31
+ }
32
+ })
33
+ );
34
+ return createServer(sdkTools);
35
+ }
36
+ async function buildOpenAIFunctionTools(registry) {
37
+ const tools = buildSdkFunctionTools(registry);
38
+ if (tools.length === 0) return [];
39
+ try {
40
+ const sdk = await import("@openai/agents");
41
+ const toolFn = sdk.tool;
42
+ if (toolFn) {
43
+ const { jsonSchemaToZod } = await import("./schema-converter-LACA7P4O.js");
44
+ return tools.map(
45
+ (t) => toolFn({
46
+ name: t.name,
47
+ description: t.description,
48
+ parameters: jsonSchemaToZod(t.inputSchema),
49
+ execute: async (_ctx, args) => {
50
+ return t.handler(
51
+ args ?? {}
52
+ );
53
+ }
54
+ })
55
+ );
56
+ }
57
+ } catch {
58
+ }
59
+ return tools.map((t) => ({
60
+ type: "function",
61
+ function: {
62
+ name: t.name,
63
+ description: t.description,
64
+ parameters: t.inputSchema
65
+ },
66
+ execute: async (args) => {
67
+ return t.handler(
68
+ args ?? {}
69
+ );
70
+ }
71
+ }));
72
+ }
73
+ async function buildAdkFunctionTools(registry) {
74
+ const tools = buildSdkFunctionTools(registry);
75
+ if (tools.length === 0) return [];
76
+ return tools.map((t) => ({
77
+ name: t.name,
78
+ description: t.description,
79
+ inputSchema: t.inputSchema,
80
+ execute: async (args) => {
81
+ return t.handler(
82
+ args ?? {}
83
+ );
84
+ }
85
+ }));
86
+ }
87
+
88
+ export {
89
+ buildSdkFunctionTools,
90
+ buildClaudeMcpServer,
91
+ buildOpenAIFunctionTools,
92
+ buildAdkFunctionTools
93
+ };
94
+ //# sourceMappingURL=chunk-LONLL3K2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/library-tool-sdk.ts"],"sourcesContent":["/**\n * Library Tool → SDK Function Tool conversion.\n *\n * Converts LibraryToolDefinition entries into SDK-native function tools\n * that each adapter can register with its respective LLM SDK.\n *\n * Each adapter receives tools in its native format:\n * - Claude Agent SDK: MCP tool via createSdkMcpServer + tool()\n * - OpenAI Agents SDK: function tool object\n * - Google ADK: FunctionDeclaration tool\n */\n\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\n\n/**\n * Adapter-agnostic function tool descriptor. Adapters convert this\n * into their SDK-specific tool format.\n */\nexport interface SdkFunctionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n handler: (args: Record<string, unknown>) => Promise<string>;\n}\n\n/**\n * Build adapter-agnostic function tool descriptors from a LibraryToolRegistry.\n * Each tool's handler calls registry.execute() and serialises the result.\n */\nexport function buildSdkFunctionTools(\n registry: LibraryToolRegistry,\n): SdkFunctionTool[] {\n return registry.getAll().map((def) => ({\n name: def.toolId,\n description: def.description,\n inputSchema: def.inputSchema ?? { type: \"object\", properties: {} },\n handler: async (args: Record<string, unknown>): Promise<string> => {\n const result = await registry.execute(def.toolId, args);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Claude Agent SDK — MCP server wrapping\n// ---------------------------------------------------------------------------\n\n/**\n * Build Claude MCP server tools from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` and `createSdkMcpServer` from the\n * Claude Agent SDK. Returns an MCP server instance to be passed\n * to query() via options.mcpServers.\n *\n * Returns undefined if no tools or if SDK functions are unavailable.\n */\nexport async function buildClaudeMcpServer(\n registry: LibraryToolRegistry,\n): Promise<unknown | undefined> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return undefined;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as Record<\n string,\n unknown\n >;\n const toolFn = sdk.tool as\n | ((def: Record<string, unknown>) => unknown)\n | undefined;\n const createServer = sdk.createSdkMcpServer as\n | ((tools: unknown[]) => unknown)\n | undefined;\n\n if (!toolFn || !createServer) return undefined;\n\n const { z } = await import(\"zod\");\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n\n const sdkTools = tools.map((t) =>\n toolFn({\n name: t.name,\n description: t.description,\n inputSchema: jsonSchemaToZod(t.inputSchema),\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }),\n );\n\n return createServer(sdkTools);\n}\n\n// ---------------------------------------------------------------------------\n// OpenAI Agents SDK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build OpenAI Agents SDK function tool objects from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` from @openai/agents if available.\n * Falls back to a raw function-tool shape that the SDK also accepts.\n */\nexport async function buildOpenAIFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n try {\n const sdk = (await import(\"@openai/agents\")) as Record<string, unknown>;\n const toolFn = sdk.tool as\n | ((def: Record<string, unknown>) => unknown)\n | undefined;\n\n if (toolFn) {\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n return tools.map((t) =>\n toolFn({\n name: t.name,\n description: t.description,\n parameters: jsonSchemaToZod(t.inputSchema),\n execute: async (_ctx: unknown, args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }),\n );\n }\n } catch {\n // SDK not available; fall through to raw format\n }\n\n return tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n },\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Google ADK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build Google ADK function tool objects from a LibraryToolRegistry.\n *\n * ADK's LlmAgent accepts tools as objects with a FunctionDeclaration shape\n * or as callable tool instances. We produce lightweight callable wrappers.\n */\nexport async function buildAdkFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n"],"mappings":";AA6BO,SAAS,sBACd,UACmB;AACnB,SAAO,SAAS,OAAO,EAAE,IAAI,CAAC,SAAS;AAAA,IACrC,MAAM,IAAI;AAAA,IACV,aAAa,IAAI;AAAA,IACjB,aAAa,IAAI,eAAe,EAAE,MAAM,UAAU,YAAY,CAAC,EAAE;AAAA,IACjE,SAAS,OAAO,SAAmD;AACjE,YAAM,SAAS,MAAM,SAAS,QAAQ,IAAI,QAAQ,IAAI;AACtD,aAAO,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,MAAM;AAAA,IACpE;AAAA,EACF,EAAE;AACJ;AAeA,eAAsB,qBACpB,UAC8B;AAC9B,QAAM,QAAQ,sBAAsB,QAAQ;AAC5C,MAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,QAAM,MAAO,MAAM,OAAO,gCAAgC;AAI1D,QAAM,SAAS,IAAI;AAGnB,QAAM,eAAe,IAAI;AAIzB,MAAI,CAAC,UAAU,CAAC,aAAc,QAAO;AAErC,QAAM,EAAE,EAAE,IAAI,MAAM,OAAO,KAAK;AAChC,QAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,gCAAuB;AAEhE,QAAM,WAAW,MAAM;AAAA,IAAI,CAAC,MAC1B,OAAO;AAAA,MACL,MAAM,EAAE;AAAA,MACR,aAAa,EAAE;AAAA,MACf,aAAa,gBAAgB,EAAE,WAAW;AAAA,MAC1C,SAAS,OAAO,SAAkB;AAChC,eAAO,EAAE;AAAA,UACN,QAAQ,CAAC;AAAA,QACZ;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,aAAa,QAAQ;AAC9B;AAYA,eAAsB,yBACpB,UACoB;AACpB,QAAM,QAAQ,sBAAsB,QAAQ;AAC5C,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAEhC,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,gBAAgB;AAC1C,UAAM,SAAS,IAAI;AAInB,QAAI,QAAQ;AACV,YAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,gCAAuB;AAChE,aAAO,MAAM;AAAA,QAAI,CAAC,MAChB,OAAO;AAAA,UACL,MAAM,EAAE;AAAA,UACR,aAAa,EAAE;AAAA,UACf,YAAY,gBAAgB,EAAE,WAAW;AAAA,UACzC,SAAS,OAAO,MAAe,SAAkB;AAC/C,mBAAO,EAAE;AAAA,cACN,QAAQ,CAAC;AAAA,YACZ;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM,EAAE;AAAA,MACR,aAAa,EAAE;AAAA,MACf,YAAY,EAAE;AAAA,IAChB;AAAA,IACA,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;AAYA,eAAsB,sBACpB,UACoB;AACpB,QAAM,QAAQ,sBAAsB,QAAQ;AAC5C,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAEhC,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,aAAa,EAAE;AAAA,IACf,aAAa,EAAE;AAAA,IACf,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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';
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, L as LibraryToolRegistry, f as TaskRunResult, g as LibraryToolDefinition } from './task-runner-R-_kW3U6.js';
2
+ export { A as AdapterSendOptions, a as AgentExecutionRequest, h as AgentProgressEvent, C as CacheConfig, i as CandidateAgent, E as EnvelopeParams, I as InMemoryStore, R as RetryDecision, j as SplitPrompt, k as TaskRunOptions, l as buildCandidateAgents, m as buildRetryFollowUp, n as buildSplitTaskPrompt, o as buildTaskPrompt, p as createExecutionEnvelope, q as createLibraryToolRegistry, r as emitSessionClose, s as emitSessionOpen, t as emitSubagentClose, u as emitSubagentOpen, v as emitToolchainClose, w as emitToolchainOpen, x as extractStructuredResult, y as renderAgentSystemPrompt, z as runTask, B as zodSchemaToPromptDescription, D as zodSchemaToYamlExample } from './task-runner-R-_kW3U6.js';
3
3
  import { z } from 'zod';
4
4
  import { a as GuardrailRuleData, G as GuardrailHooks } from './guardrail-hooks-C8G5NGsj.js';
5
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';
@@ -74,6 +74,13 @@ type SdkAdapterFactory = () => SdkAdapter;
74
74
  type ModelAwareSdkAdapterFactory = (modelClass?: ModelClass) => SdkAdapter | Promise<SdkAdapter>;
75
75
  /** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */
76
76
  type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;
77
+ /** Specification for what a step receives from a dependency. */
78
+ interface ReceiveSpec {
79
+ /** The task id of the dependency step to receive from. If omitted, alias is used as task id. */
80
+ readonly from?: string;
81
+ /** JSONPath-like dotted path to extract from the step result (e.g. "$.changed_files"). Simplified: just use dot notation like "changed_files" or "checks_performed". If omitted, entire result is received. */
82
+ readonly path?: string;
83
+ }
77
84
  interface DelegateStep {
78
85
  readonly type: "delegate";
79
86
  readonly task: string;
@@ -83,6 +90,8 @@ interface DelegateStep {
83
90
  readonly max_retries: number;
84
91
  readonly max_follow_ups?: number;
85
92
  readonly depends_on?: readonly string[];
93
+ readonly instruction?: string;
94
+ readonly receives?: Record<string, ReceiveSpec>;
86
95
  readonly retry?: {
87
96
  readonly condition: string;
88
97
  readonly fix_task: string;
@@ -318,6 +327,23 @@ interface BoundResolveOptions {
318
327
  artifactBinding?: ArtifactBindingConfig;
319
328
  /** Path substitutions for artifact binding. */
320
329
  paths?: Record<string, string>;
330
+ /** Path to toolchain-contracts.yaml. */
331
+ toolchainContractsPath?: string;
332
+ }
333
+ interface ResolvedToolchain {
334
+ id: string;
335
+ kind: "library" | "cli" | "component";
336
+ description?: string;
337
+ module?: string;
338
+ command?: string;
339
+ cli_contract?: string;
340
+ component_contract?: string;
341
+ artifacts: {
342
+ consumes: string[];
343
+ produces: string[];
344
+ };
345
+ operations?: string[];
346
+ source: "toolchain-contracts" | "agent-contracts" | "merged";
321
347
  }
322
348
  interface ResolvedComponent {
323
349
  id: string;
@@ -331,6 +357,8 @@ interface ResolvedComponent {
331
357
  message: string;
332
358
  severity?: string;
333
359
  }>;
360
+ toolchains?: Record<string, ResolvedToolchain>;
361
+ toolchainsByAgent?: Map<string, ResolvedToolchain[]>;
334
362
  }
335
363
  /**
336
364
  * Effective guardrail IDs for an agent: entity-side bindings ∪ scope-side bindings.
@@ -338,6 +366,7 @@ interface ResolvedComponent {
338
366
  declare function getEffectiveGuardrailIds(dsl: Record<string, unknown>, agentId: string): Set<string>;
339
367
  declare function guardrailContextToRuleData(ctx: GuardrailContext, effectiveIds?: Set<string>): GuardrailRuleData;
340
368
  declare function buildPerAgentGuardrails(dsl: Record<string, unknown>, guardrailCtx: GuardrailContext): Map<string, GuardrailRuleData>;
369
+ declare function deriveToolchainsForAgents(dsl: Record<string, unknown>, toolchains: Record<string, ResolvedToolchain>): Map<string, ResolvedToolchain[]>;
341
370
  declare class BoundResolver {
342
371
  private readonly cache;
343
372
  /**
@@ -577,21 +606,33 @@ declare class AgentLogWriter {
577
606
  }>;
578
607
  }
579
608
 
580
- interface LibraryToolDefinition {
581
- toolId: string;
609
+ /**
610
+ * Library Tool → SDK Function Tool conversion.
611
+ *
612
+ * Converts LibraryToolDefinition entries into SDK-native function tools
613
+ * that each adapter can register with its respective LLM SDK.
614
+ *
615
+ * Each adapter receives tools in its native format:
616
+ * - Claude Agent SDK: MCP tool via createSdkMcpServer + tool()
617
+ * - OpenAI Agents SDK: function tool object
618
+ * - Google ADK: FunctionDeclaration tool
619
+ */
620
+
621
+ /**
622
+ * Adapter-agnostic function tool descriptor. Adapters convert this
623
+ * into their SDK-specific tool format.
624
+ */
625
+ interface SdkFunctionTool {
626
+ name: string;
582
627
  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;
628
+ inputSchema: Record<string, unknown>;
629
+ handler: (args: Record<string, unknown>) => Promise<string>;
630
+ }
631
+ /**
632
+ * Build adapter-agnostic function tool descriptors from a LibraryToolRegistry.
633
+ * Each tool's handler calls registry.execute() and serialises the result.
634
+ */
635
+ declare function buildSdkFunctionTools(registry: LibraryToolRegistry): SdkFunctionTool[];
595
636
 
596
637
  /**
597
638
  * Adapter Factory — public API for creating SDK adapters by name.
@@ -803,4 +844,4 @@ declare function resolveArtifacts(options: ArtifactResolveOptions): Promise<Arti
803
844
  /** Package version string. */
804
845
  declare const version: string;
805
846
 
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 };
847
+ 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, LibraryToolDefinition, 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 ReceiveSpec, type RequiredEntities, type ResolvedComponent, type ResolvedModel, type ResolvedToolchain, type RunLogEvent, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkAdapterFactory, type SdkFunctionTool, 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, buildSdkFunctionTools, createAdapter, createComponentScope, createModelResolver, createProgressSink, createRuntime, createRuntimeBinding, deriveToolchainsForAgents, executeTask, executeWorkflow, getEffectiveGuardrailIds, getGuardrailRulesForAgent, guardrailContextToRuleData, jsonSchemaToZod, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, parseGateEvaluationResponse, pluginRegistry, resolveArtifacts, runWorkflow, version };
package/dist/index.js CHANGED
@@ -8,9 +8,15 @@ import {
8
8
  hasBlockingViolation,
9
9
  pluginRegistry
10
10
  } from "./chunk-MGRZBGQL.js";
11
+ import {
12
+ buildSdkFunctionTools
13
+ } from "./chunk-LONLL3K2.js";
11
14
  import {
12
15
  buildGuardrailContext
13
16
  } from "./chunk-LTZA6QWC.js";
17
+ import {
18
+ jsonSchemaToZod
19
+ } from "./chunk-ET6TGQRT.js";
14
20
 
15
21
  // src/index.ts
16
22
  import { createRequire } from "module";
@@ -199,6 +205,42 @@ function emitSubagentClose(observer, spanId, envelope, durationMs, status, agent
199
205
  }
200
206
  });
201
207
  }
208
+ function emitToolchainOpen(observer, parentSpanId, toolchainId, operation, artifactIds, componentId) {
209
+ if (!observer) return void 0;
210
+ const spanId = generateId();
211
+ observer({
212
+ source: "aaac-runtime",
213
+ eventType: "toolchain.execution",
214
+ lifecycle: "open",
215
+ spanId,
216
+ parentSpanId,
217
+ attributes: attrs({
218
+ axis: "toolchain",
219
+ "toolchain.id": toolchainId,
220
+ "toolchain.operation": operation,
221
+ "toolchain.artifact_ids": artifactIds.join(","),
222
+ "agent.component_id": componentId
223
+ })
224
+ });
225
+ return spanId;
226
+ }
227
+ function emitToolchainClose(observer, spanId, toolchainId, operation, durationMs, status, errorMessage) {
228
+ if (!observer) return;
229
+ observer({
230
+ source: "aaac-runtime",
231
+ eventType: "toolchain.execution",
232
+ lifecycle: "close",
233
+ spanId,
234
+ attributes: attrs({
235
+ axis: "toolchain",
236
+ "toolchain.id": toolchainId,
237
+ "toolchain.operation": operation,
238
+ "toolchain.status": status,
239
+ "toolchain.duration_ms": durationMs,
240
+ ...errorMessage ? { "toolchain.error": errorMessage } : {}
241
+ })
242
+ });
243
+ }
202
244
 
203
245
  // src/lib/task-runner.ts
204
246
  function getZodChecks(schema) {
@@ -716,10 +758,10 @@ async function runTask(adapter, taskId, context, options) {
716
758
  memoryRef,
717
759
  splitPrompt,
718
760
  agents,
719
- options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, maxFollowUps, attempt: 0 }
761
+ options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, maxFollowUps, attempt: 0 }
720
762
  });
721
763
  } else {
722
- fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow });
764
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools });
723
765
  }
724
766
  } catch (err) {
725
767
  const errDurationMs = Date.now() - taskExecStart;
@@ -914,7 +956,35 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
914
956
  const completed = /* @__PURE__ */ new Set();
915
957
  const stepResults = new Array(workflow.steps.length);
916
958
  const stepContexts = new Array(workflow.steps.length).fill("");
959
+ const stepOutputs = new Array(workflow.steps.length).fill(void 0);
917
960
  let abortResult;
961
+ function extractPath(obj, path) {
962
+ const cleanPath = path.startsWith("$.") ? path.slice(2) : path;
963
+ const segments = cleanPath.split(".");
964
+ let current = obj;
965
+ for (const seg of segments) {
966
+ if (current == null || typeof current !== "object") return void 0;
967
+ current = current[seg];
968
+ }
969
+ return current;
970
+ }
971
+ function projectHandoffs(stepIndex, step) {
972
+ if (!step.receives) return void 0;
973
+ const projected = {};
974
+ for (const [alias, spec] of Object.entries(step.receives)) {
975
+ const fromTaskId = spec.from ?? alias;
976
+ const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);
977
+ if (depIdx === -1) continue;
978
+ const output = stepOutputs[depIdx];
979
+ if (output === void 0) continue;
980
+ if (spec.path) {
981
+ projected[alias] = extractPath(output, spec.path);
982
+ } else {
983
+ projected[alias] = output;
984
+ }
985
+ }
986
+ return Object.keys(projected).length > 0 ? projected : void 0;
987
+ }
918
988
  function contextFor(stepIndex) {
919
989
  const deps = depsByIndex[stepIndex];
920
990
  if (deps.length === 0) return "";
@@ -926,8 +996,10 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
926
996
  if (step.type === "gate") {
927
997
  return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);
928
998
  }
999
+ const delegateStep = step;
929
1000
  if (step.optional) {
930
- const ctx = { user_request: options.user_request, prior_context: contextFor(i), variables: options.variables };
1001
+ const stepUserRequest2 = delegateStep.instruction ?? options.user_request;
1002
+ const ctx = { user_request: stepUserRequest2, prior_context: contextFor(i), variables: options.variables };
931
1003
  const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
932
1004
  if (!shouldRun) {
933
1005
  return {
@@ -940,11 +1012,23 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
940
1012
  };
941
1013
  }
942
1014
  }
1015
+ const stepUserRequest = delegateStep.instruction ?? options.user_request;
1016
+ let handoffInput;
1017
+ const projected = projectHandoffs(i, delegateStep);
1018
+ if (projected) {
1019
+ handoffInput = {
1020
+ type: "step-projection",
1021
+ payload: projected
1022
+ };
1023
+ } else if (i === 0 && invocationHandoff) {
1024
+ handoffInput = invocationHandoff;
1025
+ }
1026
+ const useLegacyContext = !delegateStep.receives;
943
1027
  const context = {
944
- user_request: options.user_request,
945
- prior_context: contextFor(i),
1028
+ user_request: stepUserRequest,
1029
+ ...useLegacyContext ? { prior_context: contextFor(i) } : {},
946
1030
  variables: options.variables,
947
- ...invocationHandoff ? { handoff_input: invocationHandoff } : {}
1031
+ ...handoffInput ? { handoff_input: handoffInput } : {}
948
1032
  };
949
1033
  const taskResult = await runTask(stepAdapter, step.task, context, {
950
1034
  maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,
@@ -1011,6 +1095,7 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
1011
1095
  emitStepEvent(options, workflow.id, i, step, result);
1012
1096
  if (result.outcome.status === "success") {
1013
1097
  const data = result.outcome.data;
1098
+ stepOutputs[i] = data;
1014
1099
  stepContexts[i] = `
1015
1100
 
1016
1101
  --- Step ${i + 1}: ${stepId(i)} ---
@@ -1169,81 +1254,6 @@ import YAML2 from "yaml";
1169
1254
  // src/lib/dsl-context.ts
1170
1255
  import { readFile } from "fs/promises";
1171
1256
  import YAML from "yaml";
1172
-
1173
- // src/lib/schema-converter.ts
1174
- import { z as z2 } from "zod";
1175
- function applyStringValidations(schema, def) {
1176
- let s = schema;
1177
- if (typeof def.minLength === "number") s = s.min(def.minLength);
1178
- if (typeof def.maxLength === "number") s = s.max(def.maxLength);
1179
- if (typeof def.pattern === "string") s = s.regex(new RegExp(def.pattern));
1180
- return s;
1181
- }
1182
- function applyNumberValidations(schema, def, isInteger) {
1183
- let n = schema;
1184
- if (isInteger) n = n.int();
1185
- if (typeof def.minimum === "number") n = n.min(def.minimum);
1186
- if (typeof def.maximum === "number") n = n.max(def.maximum);
1187
- return n;
1188
- }
1189
- function applyArrayValidations(schema, def) {
1190
- let a = schema;
1191
- if (typeof def.minItems === "number") a = a.min(def.minItems);
1192
- if (typeof def.maxItems === "number") a = a.max(def.maxItems);
1193
- return a;
1194
- }
1195
- function jsonSchemaToZod(schema) {
1196
- if (!schema || typeof schema !== "object") return z2.unknown();
1197
- if (schema.enum) {
1198
- const vals = schema.enum;
1199
- if (vals.length === 0) return z2.unknown();
1200
- return z2.enum(vals);
1201
- }
1202
- if (schema.const !== void 0) {
1203
- const val = schema.const;
1204
- if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
1205
- return z2.literal(val);
1206
- }
1207
- return z2.unknown();
1208
- }
1209
- const type = schema.type;
1210
- if (type === "string") return applyStringValidations(z2.string(), schema);
1211
- if (type === "integer") return applyNumberValidations(z2.number(), schema, true);
1212
- if (type === "number") return applyNumberValidations(z2.number(), schema, false);
1213
- if (type === "boolean") return z2.boolean();
1214
- if (type === "array") {
1215
- const items = schema.items;
1216
- const inner = items ? jsonSchemaToZod(items) : z2.unknown();
1217
- return applyArrayValidations(z2.array(inner), schema);
1218
- }
1219
- if (type === "object") {
1220
- const props = schema.properties;
1221
- if (!props) return z2.record(z2.string(), z2.unknown());
1222
- const required = new Set(schema.required ?? []);
1223
- const shape = {};
1224
- for (const [key, val] of Object.entries(props)) {
1225
- const fieldSchema = jsonSchemaToZod(val);
1226
- shape[key] = required.has(key) ? fieldSchema : fieldSchema.optional();
1227
- }
1228
- return z2.object(shape).passthrough();
1229
- }
1230
- if (schema.allOf) {
1231
- const parts = schema.allOf.map(jsonSchemaToZod);
1232
- if (parts.length === 0) return z2.unknown();
1233
- if (parts.length === 1) return parts[0];
1234
- let merged = parts[0];
1235
- for (let i = 1; i < parts.length; i++) {
1236
- const part = parts[i];
1237
- if (merged instanceof z2.ZodObject && part instanceof z2.ZodObject) {
1238
- merged = merged.merge(part);
1239
- }
1240
- }
1241
- return merged;
1242
- }
1243
- return z2.unknown();
1244
- }
1245
-
1246
- // src/lib/dsl-context.ts
1247
1257
  var DslValidationError = class extends Error {
1248
1258
  missing;
1249
1259
  constructor(missing) {
@@ -1492,6 +1502,71 @@ function buildPerAgentGuardrails(dsl, guardrailCtx) {
1492
1502
  function hasGuardrailRules(rules) {
1493
1503
  return rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0;
1494
1504
  }
1505
+ function mergeDerivedWithAgentTools(derivedTools, agentToolIds, allToolchains) {
1506
+ const merged = /* @__PURE__ */ new Map();
1507
+ for (const tc of derivedTools) {
1508
+ merged.set(tc.id, tc);
1509
+ }
1510
+ for (const toolId of agentToolIds) {
1511
+ if (!merged.has(toolId)) {
1512
+ if (allToolchains[toolId]) {
1513
+ merged.set(toolId, { ...allToolchains[toolId], source: "merged" });
1514
+ }
1515
+ } else {
1516
+ const existing = merged.get(toolId);
1517
+ merged.set(toolId, { ...existing, source: "merged" });
1518
+ }
1519
+ }
1520
+ return Array.from(merged.values());
1521
+ }
1522
+ function deriveToolchainsForAgents(dsl, toolchains) {
1523
+ const result = /* @__PURE__ */ new Map();
1524
+ const agents = dsl.agents ?? {};
1525
+ for (const [agentId, agent] of Object.entries(agents)) {
1526
+ const derivedTools = [];
1527
+ const canReadArtifacts = agent.can_read_artifacts ?? [];
1528
+ const canWriteArtifacts = agent.can_write_artifacts ?? [];
1529
+ const agentArtifacts = agent.artifacts;
1530
+ const readArtifacts = /* @__PURE__ */ new Set([
1531
+ ...canReadArtifacts,
1532
+ ...agentArtifacts?.consumes ?? []
1533
+ ]);
1534
+ const writeArtifacts = /* @__PURE__ */ new Set([
1535
+ ...canWriteArtifacts,
1536
+ ...agentArtifacts?.produces ?? []
1537
+ ]);
1538
+ for (const tc of Object.values(toolchains)) {
1539
+ let matched = false;
1540
+ for (const artifactId of tc.artifacts.consumes) {
1541
+ if (readArtifacts.has(artifactId) || writeArtifacts.has(artifactId)) {
1542
+ matched = true;
1543
+ break;
1544
+ }
1545
+ }
1546
+ if (!matched) {
1547
+ for (const artifactId of tc.artifacts.produces) {
1548
+ if (writeArtifacts.has(artifactId)) {
1549
+ matched = true;
1550
+ break;
1551
+ }
1552
+ }
1553
+ }
1554
+ if (matched) {
1555
+ derivedTools.push(tc);
1556
+ }
1557
+ }
1558
+ if (derivedTools.length > 0) {
1559
+ const agentTools = agent.can_execute_tools ?? [];
1560
+ const mergedTools = mergeDerivedWithAgentTools(
1561
+ derivedTools,
1562
+ agentTools,
1563
+ toolchains
1564
+ );
1565
+ result.set(agentId, mergedTools);
1566
+ }
1567
+ }
1568
+ return result;
1569
+ }
1495
1570
  var BoundResolver = class {
1496
1571
  cache = /* @__PURE__ */ new Map();
1497
1572
  /**
@@ -1545,12 +1620,43 @@ var BoundResolver = class {
1545
1620
  }
1546
1621
  }
1547
1622
  const perAgent = guardrailCtx.hasGuardrails ? buildPerAgentGuardrails(dsl, guardrailCtx) : /* @__PURE__ */ new Map();
1623
+ let toolchains;
1624
+ let toolchainsByAgent;
1625
+ if (opts.toolchainContractsPath) {
1626
+ const toolchainPkg = "@aaac/toolchain";
1627
+ const mod = await import(
1628
+ /* webpackIgnore: true */
1629
+ toolchainPkg
1630
+ );
1631
+ const tcDoc = await mod.loadToolchainContracts(opts.toolchainContractsPath);
1632
+ toolchains = {};
1633
+ for (const [id, tc] of Object.entries(tcDoc.toolchains)) {
1634
+ toolchains[id] = {
1635
+ id,
1636
+ kind: tc.kind,
1637
+ description: tc.description,
1638
+ module: tc.module,
1639
+ command: tc.command,
1640
+ cli_contract: tc.cli_contract,
1641
+ component_contract: tc.component_contract,
1642
+ artifacts: {
1643
+ consumes: [...tc.artifacts.consumes],
1644
+ produces: [...tc.artifacts.produces]
1645
+ },
1646
+ operations: tc.operations ? [...tc.operations] : void 0,
1647
+ source: "toolchain-contracts"
1648
+ };
1649
+ }
1650
+ toolchainsByAgent = deriveToolchainsForAgents(dsl, toolchains);
1651
+ }
1548
1652
  const component = {
1549
1653
  id: opts.id,
1550
1654
  dsl,
1551
1655
  registries: buildRegistriesFromDsl(dsl),
1552
1656
  guardrails: { perAgent },
1553
- diagnostics
1657
+ diagnostics,
1658
+ ...toolchains ? { toolchains } : {},
1659
+ ...toolchainsByAgent ? { toolchainsByAgent } : {}
1554
1660
  };
1555
1661
  this.cache.set(opts.id, component);
1556
1662
  return component;
@@ -1972,6 +2078,16 @@ function createLibraryToolRegistry() {
1972
2078
  if (!def) {
1973
2079
  throw new Error(`Library tool not found: ${toolId}`);
1974
2080
  }
2081
+ if (def.inputSchema) {
2082
+ const schema = jsonSchemaToZod(def.inputSchema);
2083
+ const result = schema.safeParse(input);
2084
+ if (!result.success) {
2085
+ throw new Error(
2086
+ `Input validation failed for tool "${toolId}": ${result.error.message}`
2087
+ );
2088
+ }
2089
+ input = result.data;
2090
+ }
1975
2091
  let mod = moduleCache.get(def.module);
1976
2092
  if (!mod) {
1977
2093
  try {
@@ -1990,7 +2106,17 @@ function createLibraryToolRegistry() {
1990
2106
  `Export "${def.exportName}" not found in module "${def.module}" for tool "${toolId}"`
1991
2107
  );
1992
2108
  }
1993
- return fn(input);
2109
+ const output = await fn(input);
2110
+ if (def.outputSchema) {
2111
+ const schema = jsonSchemaToZod(def.outputSchema);
2112
+ const result = schema.safeParse(output);
2113
+ if (!result.success) {
2114
+ throw new Error(
2115
+ `Output validation failed for tool "${toolId}": ${result.error.message}`
2116
+ );
2117
+ }
2118
+ }
2119
+ return output;
1994
2120
  }
1995
2121
  };
1996
2122
  }
@@ -2465,6 +2591,7 @@ export {
2465
2591
  buildPerAgentGuardrails,
2466
2592
  buildRegistriesFromDsl,
2467
2593
  buildRetryFollowUp,
2594
+ buildSdkFunctionTools,
2468
2595
  buildSplitTaskPrompt,
2469
2596
  buildTaskPrompt,
2470
2597
  createAdapter,
@@ -2478,10 +2605,13 @@ export {
2478
2605
  createProgressSink,
2479
2606
  createRuntime,
2480
2607
  createRuntimeBinding,
2608
+ deriveToolchainsForAgents,
2481
2609
  emitSessionClose,
2482
2610
  emitSessionOpen,
2483
2611
  emitSubagentClose,
2484
2612
  emitSubagentOpen,
2613
+ emitToolchainClose,
2614
+ emitToolchainOpen,
2485
2615
  executeTask,
2486
2616
  executeWorkflow,
2487
2617
  extractStructuredResult,