agent-contracts-runtime 0.11.0 → 0.12.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/adapters/claude-agent-sdk.d.ts +1 -1
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/cursor-sdk.d.ts +3 -2
- package/dist/adapters/cursor-sdk.js +3 -1
- package/dist/adapters/cursor-sdk.js.map +1 -1
- package/dist/adapters/gemini-sdk.d.ts +1 -1
- package/dist/adapters/gemini-sdk.js.map +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/adapters/openai-agents-sdk.d.ts +97 -0
- package/dist/adapters/openai-agents-sdk.js +151 -0
- package/dist/adapters/openai-agents-sdk.js.map +1 -0
- package/dist/{chunk-3NE3OA6F.js → chunk-COHQ2PB5.js} +85 -21
- package/dist/chunk-COHQ2PB5.js.map +1 -0
- package/dist/cli/index.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{task-runner-D8b31ZL_.d.ts → task-runner-CPLSadjY.d.ts} +4 -2
- package/package.json +5 -1
- package/dist/chunk-3NE3OA6F.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-CPLSadjY.js';
|
|
2
2
|
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk\n *\n * Uses the `query()` function from the Claude Agent SDK to run Claude as a\n * stateful coding agent with tool execution (Read, Edit, Bash, etc.).\n *\n * Supports:\n * - send() — start a new query session and return the result text\n * - followUp() — resume the same session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates\n * the stream, extracts the final result text from the SDKResultSuccess message,\n * and captures the session_id for followUp via `resume`.\n *\n * GuardrailHooks are mapped to the SDK's PreToolUse hook system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on zod v4)\n// ---------------------------------------------------------------------------\n\ntype SDKResultSuccess = {\n type: \"result\";\n subtype: \"success\";\n result: string;\n session_id: string;\n};\n\ntype SDKResultError = {\n type: \"result\";\n subtype: \"error\";\n error: string;\n session_id: string;\n};\n\ntype SDKMessage = {\n type: string;\n subtype?: string;\n result?: string;\n error?: string;\n session_id?: string;\n};\n\ntype HookCallbackInput = {\n hook_event_name: string;\n tool_name: string;\n tool_input: unknown;\n [key: string]: unknown;\n};\n\ntype HookCallbackOutput = {\n hookEventName: string;\n permissionDecision?: \"allow\" | \"deny\" | \"ask\";\n permissionDecisionReason?: string;\n additionalContext?: string;\n};\n\ntype HookCallbackMatcher = {\n tool_name?: string;\n hooks: Array<(input: HookCallbackInput) => HookCallbackOutput | Promise<HookCallbackOutput>>;\n};\n\ntype QueryOptions = Record<string, unknown>;\n\ntype QueryFn = (params: {\n prompt: string;\n options?: QueryOptions;\n}) => AsyncGenerator<SDKMessage, void>;\n\n// ---------------------------------------------------------------------------\n// Guardrail hook bridge\n// ---------------------------------------------------------------------------\n\nfunction buildClaudeHooks(\n guardrails: GuardrailHooks,\n): Partial<Record<string, HookCallbackMatcher[]>> {\n const preToolUseHook: HookCallbackMatcher = {\n hooks: [\n (input: HookCallbackInput): HookCallbackOutput => {\n const toolInput = input.tool_input as Record<string, unknown> | undefined;\n const toolName = input.tool_name;\n\n if (toolName === \"Bash\" || toolName === \"Shell\") {\n const command = (toolInput?.command ?? toolInput?.input) as string | undefined;\n if (command) {\n const result = guardrails.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: result.user_message ?? result.agent_message,\n };\n }\n if (result.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: result.additionalContext };\n }\n }\n }\n\n const filePath = (toolInput?.file_path ?? toolInput?.path) as string | undefined;\n if (filePath) {\n const pathResult = guardrails.preToolUse({\n tool_name: toolName,\n tool_input: { file_path: filePath },\n });\n if (pathResult.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: pathResult.user_message ?? pathResult.agent_message,\n };\n }\n if (pathResult.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: pathResult.additionalContext };\n }\n }\n\n return { hookEventName: \"PreToolUse\" };\n },\n ],\n };\n\n return { PreToolUse: [preToolUseHook] };\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeAgentSdkAdapterConfig {\n /** Working directory for the agent. Defaults to process.cwd(). */\n cwd?: string;\n /** Model identifier (e.g. \"claude-sonnet-4-20250514\"). Uses SDK default if omitted. */\n model?: string;\n /**\n * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.\n * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.\n */\n tools?: string[] | { type: \"preset\"; preset: \"claude_code\" };\n /** Permission mode. Defaults to \"bypassPermissions\" for automated workflows. */\n permissionMode?: \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n /** Max turns before stopping. */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */\n guardrailHooks?: GuardrailHooks;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private cwd: string;\n private model: string | undefined;\n private tools: string[] | { type: \"preset\"; preset: \"claude_code\" } | undefined;\n private permissionMode: string;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private lastSessionId: string | null = null;\n private queryFn: QueryFn | null = null;\n\n constructor(config: ClaudeAgentSdkAdapterConfig = {}) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model;\n this.tools = config.tools;\n this.permissionMode = config.permissionMode ?? \"bypassPermissions\";\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveQueryFn(): Promise<QueryFn> {\n if (this.queryFn) return this.queryFn;\n\n // @ts-expect-error — @anthropic-ai/claude-agent-sdk is an optional peer dependency\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as {\n query: QueryFn;\n };\n this.queryFn = sdk.query;\n return this.queryFn;\n }\n\n private buildOptions(readonly: boolean, resume?: string): QueryOptions {\n const opts: QueryOptions = {\n cwd: this.cwd,\n permissionMode: this.permissionMode,\n allowDangerouslySkipPermissions: this.permissionMode === \"bypassPermissions\",\n };\n\n if (this.model) opts.model = this.model;\n if (this.maxTurns) opts.maxTurns = this.maxTurns;\n\n if (this.tools) {\n opts.tools = this.tools;\n } else {\n opts.tools = readonly\n ? [\"Read\", \"Glob\", \"Grep\"]\n : [\"Read\", \"Glob\", \"Grep\", \"Edit\", \"Write\", \"Bash\"];\n }\n\n if (resume) opts.resume = resume;\n\n if (this.guardrailHooks) {\n opts.hooks = buildClaudeHooks(this.guardrailHooks);\n }\n\n return opts;\n }\n\n private async runQuery(\n prompt: string,\n options: QueryOptions,\n ): Promise<{ text: string; sessionId: string }> {\n const queryFn = await this.resolveQueryFn();\n const stream = queryFn({ prompt, options });\n\n let resultText = \"\";\n let sessionId = \"\";\n\n for await (const message of stream) {\n if (message.type === \"result\") {\n sessionId = message.session_id ?? sessionId;\n if (message.subtype === \"success\") {\n resultText = (message as SDKResultSuccess).result;\n } else if (message.subtype === \"error\") {\n throw new Error(`Claude Agent SDK error: ${(message as SDKResultError).error}`);\n }\n }\n }\n\n return { text: resultText, sessionId };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(options.readonly);\n const { text, sessionId } = await this.runQuery(prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastSessionId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const opts = this.buildOptions(false, this.lastSessionId);\n const { text, sessionId } = await this.runQuery(message, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(request.options.readonly);\n const { text, sessionId } = await this.runQuery(request.prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom query function for testing.\n * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.\n */\n static withQueryFn(\n queryFn: QueryFn,\n config?: ClaudeAgentSdkAdapterConfig,\n ): ClaudeAgentSdkAdapter {\n const adapter = new ClaudeAgentSdkAdapter(config);\n adapter.queryFn = queryFn;\n return adapter;\n }\n}\n"],"mappings":";AAiFA,SAAS,iBACP,YACgD;AAChD,QAAM,iBAAsC;AAAA,IAC1C,OAAO;AAAA,MACL,CAAC,UAAiD;AAChD,cAAM,YAAY,MAAM;AACxB,cAAM,WAAW,MAAM;AAEvB,YAAI,aAAa,UAAU,aAAa,SAAS;AAC/C,gBAAM,UAAW,WAAW,WAAW,WAAW;AAClD,cAAI,SAAS;AACX,kBAAM,SAAS,WAAW,qBAAqB,EAAE,QAAQ,CAAC;AAC1D,gBAAI,OAAO,eAA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AAE,MAAM,UAAU,IAAI,MAAM,KAAK,SAAS,QAAQ,IAAI;AAC5D,SAAK,gBAAgB;AACrB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,SAAS,SAAkC;AAC/C,QAAI,CAAC,KAAK,eAAe;AACvB,YAAM,IAAI,MAAM,0DAAqD;AAAA,IACvE;AACA,UAAM,OAAO,KAAK,aAAa,OAAO,KAAK,aAAa;AACxD,UAAM,EAAE,MAAM,UAAU,IAAI,MAAM,KAAK,SAAS,SAAS,IAAI;AAC7D,SAAK,gBAAgB;AACrB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,cAAc,SAAiD;AACnE,SAAK,gBAAgB;AACrB,UAAM,OAAO,KAAK,aAAa,QAAQ,QAAQ,QAAQ;AACvD,UAAM,EAAE,MAAM,UAAU,IAAI,MAAM,KAAK,SAAS,QAAQ,QAAQ,IAAI;AACpE,SAAK,gBAAgB;AACrB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,YACL,SACA,QACuB;AACvB,UAAM,UAAU,IAAI,uBAAsB,MAAM;AAChD,YAAQ,UAAU;AAClB,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk\n *\n * Uses the `query()` function from the Claude Agent SDK to run Claude as a\n * stateful coding agent with tool execution (Read, Edit, Bash, etc.).\n *\n * Supports:\n * - send() — start a new query session and return the result text\n * - followUp() — resume the same session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates\n * the stream, extracts the final result text from the SDKResultSuccess message,\n * and captures the session_id for followUp via `resume`.\n *\n * GuardrailHooks are mapped to the SDK's PreToolUse hook system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on zod v4)\n// ---------------------------------------------------------------------------\n\ntype SDKResultSuccess = {\n type: \"result\";\n subtype: \"success\";\n result: string;\n session_id: string;\n};\n\ntype SDKResultError = {\n type: \"result\";\n subtype: \"error\";\n error: string;\n session_id: string;\n};\n\ntype SDKMessage = {\n type: string;\n subtype?: string;\n result?: string;\n error?: string;\n session_id?: string;\n};\n\ntype HookCallbackInput = {\n hook_event_name: string;\n tool_name: string;\n tool_input: unknown;\n [key: string]: unknown;\n};\n\ntype HookCallbackOutput = {\n hookEventName: string;\n permissionDecision?: \"allow\" | \"deny\" | \"ask\";\n permissionDecisionReason?: string;\n additionalContext?: string;\n};\n\ntype HookCallbackMatcher = {\n tool_name?: string;\n hooks: Array<(input: HookCallbackInput) => HookCallbackOutput | Promise<HookCallbackOutput>>;\n};\n\ntype QueryOptions = Record<string, unknown>;\n\ntype QueryFn = (params: {\n prompt: string;\n options?: QueryOptions;\n}) => AsyncGenerator<SDKMessage, void>;\n\n// ---------------------------------------------------------------------------\n// Guardrail hook bridge\n// ---------------------------------------------------------------------------\n\nfunction buildClaudeHooks(\n guardrails: GuardrailHooks,\n): Partial<Record<string, HookCallbackMatcher[]>> {\n const preToolUseHook: HookCallbackMatcher = {\n hooks: [\n (input: HookCallbackInput): HookCallbackOutput => {\n const toolInput = input.tool_input as Record<string, unknown> | undefined;\n const toolName = input.tool_name;\n\n if (toolName === \"Bash\" || toolName === \"Shell\") {\n const command = (toolInput?.command ?? toolInput?.input) as string | undefined;\n if (command) {\n const result = guardrails.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: result.user_message ?? result.agent_message,\n };\n }\n if (result.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: result.additionalContext };\n }\n }\n }\n\n const filePath = (toolInput?.file_path ?? toolInput?.path) as string | undefined;\n if (filePath) {\n const pathResult = guardrails.preToolUse({\n tool_name: toolName,\n tool_input: { file_path: filePath },\n });\n if (pathResult.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: pathResult.user_message ?? pathResult.agent_message,\n };\n }\n if (pathResult.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: pathResult.additionalContext };\n }\n }\n\n return { hookEventName: \"PreToolUse\" };\n },\n ],\n };\n\n return { PreToolUse: [preToolUseHook] };\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeAgentSdkAdapterConfig {\n /** Working directory for the agent. Defaults to process.cwd(). */\n cwd?: string;\n /** Model identifier (e.g. \"claude-sonnet-4-20250514\"). Uses SDK default if omitted. */\n model?: string;\n /**\n * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.\n * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.\n */\n tools?: string[] | { type: \"preset\"; preset: \"claude_code\" };\n /** Permission mode. Defaults to \"bypassPermissions\" for automated workflows. */\n permissionMode?: \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n /** Max turns before stopping. */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */\n guardrailHooks?: GuardrailHooks;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private cwd: string;\n private model: string | undefined;\n private tools: string[] | { type: \"preset\"; preset: \"claude_code\" } | undefined;\n private permissionMode: string;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private lastSessionId: string | null = null;\n private queryFn: QueryFn | null = null;\n\n constructor(config: ClaudeAgentSdkAdapterConfig = {}) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model;\n this.tools = config.tools;\n this.permissionMode = config.permissionMode ?? \"bypassPermissions\";\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveQueryFn(): Promise<QueryFn> {\n if (this.queryFn) return this.queryFn;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as {\n query: QueryFn;\n };\n this.queryFn = sdk.query;\n return this.queryFn;\n }\n\n private buildOptions(readonly: boolean, resume?: string): QueryOptions {\n const opts: QueryOptions = {\n cwd: this.cwd,\n permissionMode: this.permissionMode,\n allowDangerouslySkipPermissions: this.permissionMode === \"bypassPermissions\",\n };\n\n if (this.model) opts.model = this.model;\n if (this.maxTurns) opts.maxTurns = this.maxTurns;\n\n if (this.tools) {\n opts.tools = this.tools;\n } else {\n opts.tools = readonly\n ? [\"Read\", \"Glob\", \"Grep\"]\n : [\"Read\", \"Glob\", \"Grep\", \"Edit\", \"Write\", \"Bash\"];\n }\n\n if (resume) opts.resume = resume;\n\n if (this.guardrailHooks) {\n opts.hooks = buildClaudeHooks(this.guardrailHooks);\n }\n\n return opts;\n }\n\n private async runQuery(\n prompt: string,\n options: QueryOptions,\n ): Promise<{ text: string; sessionId: string }> {\n const queryFn = await this.resolveQueryFn();\n const stream = queryFn({ prompt, options });\n\n let resultText = \"\";\n let sessionId = \"\";\n\n for await (const message of stream) {\n if (message.type === \"result\") {\n sessionId = message.session_id ?? sessionId;\n if (message.subtype === \"success\") {\n resultText = (message as SDKResultSuccess).result;\n } else if (message.subtype === \"error\") {\n throw new Error(`Claude Agent SDK error: ${(message as SDKResultError).error}`);\n }\n }\n }\n\n return { text: resultText, sessionId };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(options.readonly);\n const { text, sessionId } = await this.runQuery(prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastSessionId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const opts = this.buildOptions(false, this.lastSessionId);\n const { text, sessionId } = await this.runQuery(message, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastSessionId = null;\n const opts = this.buildOptions(request.options.readonly);\n const { text, sessionId } = await this.runQuery(request.prompt, opts);\n this.lastSessionId = sessionId;\n return text;\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom query function for testing.\n * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.\n */\n static withQueryFn(\n queryFn: QueryFn,\n config?: ClaudeAgentSdkAdapterConfig,\n ): ClaudeAgentSdkAdapter {\n const adapter = new ClaudeAgentSdkAdapter(config);\n adapter.queryFn = queryFn;\n return adapter;\n }\n}\n"],"mappings":";AAiFA,SAAS,iBACP,YACgD;AAChD,QAAM,iBAAsC;AAAA,IAC1C,OAAO;AAAA,MACL,CAAC,UAAiD;AAChD,cAAM,YAAY,MAAM;AACxB,cAAM,WAAW,MAAM;AAEvB,YAAI,aAAa,UAAU,aAAa,SAAS;AAC/C,gBAAM,UAAW,WAAW,WAAW,WAAW;AAClD,cAAI,SAAS;AACX,kBAAM,SAAS,WAAW,qBAAqB,EAAE,QAAQ,CAAC;AAC1D,gBAAI,OAAO,eAAe,QAAQ;AAChC,qBAAO;AAAA,gBACL,eAAe;AAAA,gBACf,oBAAoB;AAAA,gBACpB,0BAA0B,OAAO,gBAAgB,OAAO;AAAA,cAC1D;AAAA,YACF;AACA,gBAAI,OAAO,mBAAmB;AAC5B,qBAAO,EAAE,eAAe,cAAc,mBAAmB,OAAO,kBAAkB;AAAA,YACpF;AAAA,UACF;AAAA,QACF;AAEA,cAAM,WAAY,WAAW,aAAa,WAAW;AACrD,YAAI,UAAU;AACZ,gBA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SAAS,IAAI;AAC7D,SAAK,gBAAgB;AACrB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,cAAc,SAAiD;AACnE,SAAK,gBAAgB;AACrB,UAAM,OAAO,KAAK,aAAa,QAAQ,QAAQ,QAAQ;AACvD,UAAM,EAAE,MAAM,UAAU,IAAI,MAAM,KAAK,SAAS,QAAQ,QAAQ,IAAI;AACpE,SAAK,gBAAgB;AACrB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,YACL,SACA,QACuB;AACvB,UAAM,UAAU,IAAI,uBAAsB,MAAM;AAChD,YAAQ,UAAU;AAClB,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SdkAdapter, A as AdapterSendOptions } from '../task-runner-
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions } from '../task-runner-CPLSadjY.js';
|
|
2
2
|
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
@@ -17,7 +17,8 @@ type CursorAgentInstance = {
|
|
|
17
17
|
send(prompt: string): Promise<CursorAgentRun>;
|
|
18
18
|
};
|
|
19
19
|
interface CursorSdkAdapterConfig {
|
|
20
|
-
|
|
20
|
+
/** API key. When omitted, the SDK uses the local Cursor IDE instance. */
|
|
21
|
+
apiKey?: string;
|
|
21
22
|
model?: string;
|
|
22
23
|
cwd?: string;
|
|
23
24
|
guardrailHooks?: GuardrailHooks;
|
|
@@ -57,10 +57,12 @@ var CursorSdkAdapter = class _CursorSdkAdapter {
|
|
|
57
57
|
static async create(config) {
|
|
58
58
|
const { Agent } = await import("@cursor/sdk");
|
|
59
59
|
const agentOpts = {
|
|
60
|
-
apiKey: config.apiKey,
|
|
61
60
|
model: { id: config.model ?? "composer-2" },
|
|
62
61
|
local: { cwd: config.cwd ?? process.cwd() }
|
|
63
62
|
};
|
|
63
|
+
if (config.apiKey) {
|
|
64
|
+
agentOpts.apiKey = config.apiKey;
|
|
65
|
+
}
|
|
64
66
|
if (config.guardrailHooks) {
|
|
65
67
|
Object.assign(agentOpts, buildSdkHooks(config.guardrailHooks));
|
|
66
68
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/cursor-sdk.ts"],"sourcesContent":["/**\n * Cursor SDK Adapter — implements SdkAdapter for Cursor Cloud Agents API\n *\n * Supports both send() (new session) and followUp() (same session continuation)\n * for lightweight output-format corrections without re-executing the entire task.\n *\n * When guardrailHooks are provided, registers beforeShellExecution / preToolUse /\n * afterFileEdit hooks with the SDK agent so guardrail violations are enforced\n * during LLM sessions.\n */\n\nimport type { SdkAdapter } from \"../lib/task-runner.js\";\nimport type { GuardrailHooks, HookResponse } from \"../lib/guardrail-hooks.js\";\n\ntype CursorAgentRun = {\n stream(): AsyncIterable<{\n type: string;\n message?: { content?: Array<{ type: string; text?: string }> };\n }>;\n};\n\ntype CursorAgentInstance = {\n send(prompt: string): Promise<CursorAgentRun>;\n};\n\nexport interface CursorSdkAdapterConfig {\n apiKey
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/cursor-sdk.ts"],"sourcesContent":["/**\n * Cursor SDK Adapter — implements SdkAdapter for Cursor Cloud Agents API\n *\n * Supports both send() (new session) and followUp() (same session continuation)\n * for lightweight output-format corrections without re-executing the entire task.\n *\n * When guardrailHooks are provided, registers beforeShellExecution / preToolUse /\n * afterFileEdit hooks with the SDK agent so guardrail violations are enforced\n * during LLM sessions.\n */\n\nimport type { SdkAdapter } from \"../lib/task-runner.js\";\nimport type { GuardrailHooks, HookResponse } from \"../lib/guardrail-hooks.js\";\n\ntype CursorAgentRun = {\n stream(): AsyncIterable<{\n type: string;\n message?: { content?: Array<{ type: string; text?: string }> };\n }>;\n};\n\ntype CursorAgentInstance = {\n send(prompt: string): Promise<CursorAgentRun>;\n};\n\nexport interface CursorSdkAdapterConfig {\n /** API key. When omitted, the SDK uses the local Cursor IDE instance. */\n apiKey?: string;\n model?: string;\n cwd?: string;\n guardrailHooks?: GuardrailHooks;\n}\n\n/**\n * Convert runtime GuardrailHooks into the shape the Cursor SDK expects.\n * The SDK uses `permissionDecision: \"deny\"` to block actions.\n */\nfunction buildSdkHooks(hooks: GuardrailHooks): Record<string, unknown> {\n return {\n beforeShellExecution: (input: { command?: string }) => {\n const result = hooks.beforeShellExecution(input);\n return hookResponseToSdkDecision(result);\n },\n preToolUse: (input: { tool_name?: string; tool_input?: { file_path?: string; path?: string } }) => {\n const result = hooks.preToolUse(input);\n return hookResponseToSdkDecision(result);\n },\n afterFileEdit: (input: { file_path?: string; content?: string }) => {\n const result = hooks.afterFileEdit(input);\n return hookResponseToSdkDecision(result);\n },\n };\n}\n\nfunction hookResponseToSdkDecision(response: HookResponse): Record<string, unknown> {\n if (response.permission === \"deny\") {\n return {\n permissionDecision: \"deny\",\n userMessage: response.user_message,\n agentMessage: response.agent_message,\n };\n }\n if (response.additionalContext) {\n return { additionalContext: response.additionalContext };\n }\n return {};\n}\n\nexport class CursorSdkAdapter implements SdkAdapter {\n private agent: CursorAgentInstance;\n\n constructor(agent: CursorAgentInstance) {\n this.agent = agent;\n }\n\n private async collectStream(run: CursorAgentRun): Promise<string> {\n let fullOutput = \"\";\n for await (const event of run.stream()) {\n if (event.type === \"assistant\" && event.message?.content) {\n for (const part of event.message.content) {\n if (part.type === \"text\" && part.text) {\n fullOutput += part.text;\n }\n }\n }\n }\n return fullOutput;\n }\n\n async send(prompt: string, _options: import(\"../lib/task-runner.js\").AdapterSendOptions): Promise<string> {\n const run = await this.agent.send(prompt);\n return this.collectStream(run);\n }\n\n async followUp(message: string): Promise<string> {\n const run = await this.agent.send(message);\n return this.collectStream(run);\n }\n\n static async create(config: CursorSdkAdapterConfig): Promise<CursorSdkAdapter> {\n const { Agent } = await import(\"@cursor/sdk\") as { Agent: { create(opts: Record<string, unknown>): Promise<CursorAgentInstance> } };\n\n const agentOpts: Record<string, unknown> = {\n model: { id: config.model ?? \"composer-2\" },\n local: { cwd: config.cwd ?? process.cwd() },\n };\n if (config.apiKey) {\n agentOpts.apiKey = config.apiKey;\n }\n\n if (config.guardrailHooks) {\n Object.assign(agentOpts, buildSdkHooks(config.guardrailHooks));\n }\n\n const agent = await Agent.create(agentOpts);\n return new CursorSdkAdapter(agent);\n }\n}\n"],"mappings":";AAqCA,SAAS,cAAc,OAAgD;AACrE,SAAO;AAAA,IACL,sBAAsB,CAAC,UAAgC;AACrD,YAAM,SAAS,MAAM,qBAAqB,KAAK;AAC/C,aAAO,0BAA0B,MAAM;AAAA,IACzC;AAAA,IACA,YAAY,CAAC,UAAsF;AACjG,YAAM,SAAS,MAAM,WAAW,KAAK;AACrC,aAAO,0BAA0B,MAAM;AAAA,IACzC;AAAA,IACA,eAAe,CAAC,UAAoD;AAClE,YAAM,SAAS,MAAM,cAAc,KAAK;AACxC,aAAO,0BAA0B,MAAM;AAAA,IACzC;AAAA,EACF;AACF;AAEA,SAAS,0BAA0B,UAAiD;AAClF,MAAI,SAAS,eAAe,QAAQ;AAClC,WAAO;AAAA,MACL,oBAAoB;AAAA,MACpB,aAAa,SAAS;AAAA,MACtB,cAAc,SAAS;AAAA,IACzB;AAAA,EACF;AACA,MAAI,SAAS,mBAAmB;AAC9B,WAAO,EAAE,mBAAmB,SAAS,kBAAkB;AAAA,EACzD;AACA,SAAO,CAAC;AACV;AAEO,IAAM,mBAAN,MAAM,kBAAuC;AAAA,EAC1C;AAAA,EAER,YAAY,OAA4B;AACtC,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAc,cAAc,KAAsC;AAChE,QAAI,aAAa;AACjB,qBAAiB,SAAS,IAAI,OAAO,GAAG;AACtC,UAAI,MAAM,SAAS,eAAe,MAAM,SAAS,SAAS;AACxD,mBAAW,QAAQ,MAAM,QAAQ,SAAS;AACxC,cAAI,KAAK,SAAS,UAAU,KAAK,MAAM;AACrC,0BAAc,KAAK;AAAA,UACrB;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,KAAK,QAAgB,UAA+E;AACxG,UAAM,MAAM,MAAM,KAAK,MAAM,KAAK,MAAM;AACxC,WAAO,KAAK,cAAc,GAAG;AAAA,EAC/B;AAAA,EAEA,MAAM,SAAS,SAAkC;AAC/C,UAAM,MAAM,MAAM,KAAK,MAAM,KAAK,OAAO;AACzC,WAAO,KAAK,cAAc,GAAG;AAAA,EAC/B;AAAA,EAEA,aAAa,OAAO,QAA2D;AAC7E,UAAM,EAAE,MAAM,IAAI,MAAM,OAAO,aAAa;AAE5C,UAAM,YAAqC;AAAA,MACzC,OAAO,EAAE,IAAI,OAAO,SAAS,aAAa;AAAA,MAC1C,OAAO,EAAE,KAAK,OAAO,OAAO,QAAQ,IAAI,EAAE;AAAA,IAC5C;AACA,QAAI,OAAO,QAAQ;AACjB,gBAAU,SAAS,OAAO;AAAA,IAC5B;AAEA,QAAI,OAAO,gBAAgB;AACzB,aAAO,OAAO,WAAW,cAAc,OAAO,cAAc,CAAC;AAAA,IAC/D;AAEA,UAAM,QAAQ,MAAM,MAAM,OAAO,SAAS;AAC1C,WAAO,IAAI,kBAAiB,KAAK;AAAA,EACnC;AACF;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-CPLSadjY.js';
|
|
2
2
|
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/gemini-sdk.ts"],"sourcesContent":["/**\n * Google Gemini SDK Adapter — implements SdkAdapter for @google/genai\n *\n * Uses the GoogleGenAI client from @google/genai to run prompts on\n * Gemini models (gemini-2.5-flash, gemini-2.5-pro, etc.).\n *\n * Supports:\n * - send() — start a new chat session and return the result text\n * - followUp() — continue the same chat session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The adapter uses the chat API (ai.chats.create + chat.sendMessage) to\n * maintain conversation state for followUp. Each send() starts a fresh chat.\n *\n * GuardrailHooks are evaluated locally before returning results\n * (Gemini does not expose a pre-tool-use hook like Claude/OpenAI).\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on @google/genai)\n// ---------------------------------------------------------------------------\n\ntype GenerateContentResponse = {\n text?: string;\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n finishReason?: string;\n safetyRatings?: Array<{ category: string; probability: string }>;\n }>;\n};\n\ntype ChatSendMessageResult = GenerateContentResponse;\n\ntype Chat = {\n sendMessage(params: { message: string }): Promise<ChatSendMessageResult>;\n};\n\ntype GoogleGenAIOptions = {\n apiKey?: string;\n enterprise?: boolean;\n project?: string;\n location?: string;\n [key: string]: unknown;\n};\n\ntype ChatsCreateParams = {\n model: string;\n config?: Record<string, unknown>;\n};\n\ntype GoogleGenAIClient = {\n models: {\n generateContent(params: {\n model: string;\n contents: string;\n config?: Record<string, unknown>;\n }): Promise<GenerateContentResponse>;\n };\n chats: {\n create(params: ChatsCreateParams): Chat;\n };\n};\n\ntype GoogleGenAIConstructor = new (options: GoogleGenAIOptions) => GoogleGenAIClient;\n\n// ---------------------------------------------------------------------------\n// Response text extraction\n// ---------------------------------------------------------------------------\n\nfunction extractText(response: GenerateContentResponse): string {\n if (response.text) return response.text;\n\n if (response.candidates?.length) {\n const parts = response.candidates[0].content?.parts;\n if (parts?.length) {\n return parts.map((p) => p.text ?? \"\").join(\"\");\n }\n }\n\n return \"\";\n}\n\nfunction checkSafetyBlock(response: GenerateContentResponse): void {\n const candidate = response.candidates?.[0];\n if (candidate?.finishReason === \"SAFETY\") {\n const blocked = candidate.safetyRatings\n ?.filter((r) => r.probability === \"HIGH\")\n .map((r) => r.category)\n .join(\", \");\n throw new Error(\n `Gemini response blocked by safety filters: ${blocked || \"unknown category\"}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface GeminiSdkAdapterConfig {\n /** API key for Gemini Developer API. Falls back to GEMINI_API_KEY env var. */\n apiKey?: string;\n /** Model identifier (e.g. \"gemini-2.5-flash\", \"gemini-2.5-pro\"). */\n model?: string;\n /** System instruction prepended to all conversations. */\n systemInstruction?: string;\n /** Temperature for generation (0.0–2.0). */\n temperature?: number;\n /** Maximum output tokens. */\n maxOutputTokens?: number;\n /** Runtime guardrail hooks evaluated locally on responses. */\n guardrailHooks?: GuardrailHooks;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class GeminiSdkAdapter implements SdkAdapter {\n private apiKey: string | undefined;\n private model: string;\n private systemInstruction: string | undefined;\n private temperature: number | undefined;\n private maxOutputTokens: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private lastChat: Chat | null = null;\n\n private client: GoogleGenAIClient | null = null;\n private ClientClass: GoogleGenAIConstructor | null = null;\n\n constructor(config: GeminiSdkAdapterConfig = {}) {\n this.apiKey = config.apiKey;\n this.model = config.model ?? \"gemini-2.5-flash\";\n this.systemInstruction = config.systemInstruction;\n this.temperature = config.temperature;\n this.maxOutputTokens = config.maxOutputTokens;\n this.guardrailHooks = config.guardrailHooks;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveClient(): Promise<GoogleGenAIClient> {\n if (this.client) return this.client;\n\n if (!this.ClientClass) {\n // @ts-expect-error — @google/genai is an optional peer dependency\n const sdk = (await import(\"@google/genai\")) as {\n GoogleGenAI: GoogleGenAIConstructor;\n };\n this.ClientClass = sdk.GoogleGenAI;\n }\n\n const apiKey = this.apiKey ?? process.env.GEMINI_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"GEMINI_API_KEY environment variable or apiKey config is required for the Gemini adapter\",\n );\n }\n\n this.client = new this.ClientClass({ apiKey });\n return this.client;\n }\n\n private buildGenerationConfig(): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n if (this.systemInstruction) {\n config.systemInstruction = this.systemInstruction;\n }\n if (this.temperature !== undefined) {\n config.temperature = this.temperature;\n }\n if (this.maxOutputTokens !== undefined) {\n config.maxOutputTokens = this.maxOutputTokens;\n }\n return config;\n }\n\n private createChat(client: GoogleGenAIClient): Chat {\n return client.chats.create({\n model: this.model,\n config: this.buildGenerationConfig(),\n });\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n _options: AdapterSendOptions,\n ): Promise<string> {\n this.lastChat = null;\n\n const client = await this.resolveClient();\n const chat = this.createChat(client);\n const response = await chat.sendMessage({ message: prompt });\n\n checkSafetyBlock(response);\n this.lastChat = chat;\n\n return extractText(response);\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastChat) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n\n const response = await this.lastChat.sendMessage({ message });\n checkSafetyBlock(response);\n\n return extractText(response);\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastChat = null;\n\n const client = await this.resolveClient();\n const chat = this.createChat(client);\n const response = await chat.sendMessage({ message: request.prompt });\n\n checkSafetyBlock(response);\n this.lastChat = chat;\n\n return extractText(response);\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom GoogleGenAI client for testing.\n * Bypasses the dynamic import of @google/genai and API key requirement.\n */\n static withClient(\n client: GoogleGenAIClient,\n config?: GeminiSdkAdapterConfig,\n ): GeminiSdkAdapter {\n const adapter = new GeminiSdkAdapter(config);\n adapter.client = client;\n return adapter;\n }\n}\n"],"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Q,OAAO,CAAC;AAEnE,qBAAiB,QAAQ;AACzB,SAAK,WAAW;AAEhB,WAAO,YAAY,QAAQ;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,WACL,QACA,QACkB;AAClB,UAAM,UAAU,IAAI,kBAAiB,MAAM;AAC3C,YAAQ,SAAS;AACjB,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/gemini-sdk.ts"],"sourcesContent":["/**\n * Google Gemini SDK Adapter — implements SdkAdapter for @google/genai\n *\n * Uses the GoogleGenAI client from @google/genai to run prompts on\n * Gemini models (gemini-2.5-flash, gemini-2.5-pro, etc.).\n *\n * Supports:\n * - send() — start a new chat session and return the result text\n * - followUp() — continue the same chat session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The adapter uses the chat API (ai.chats.create + chat.sendMessage) to\n * maintain conversation state for followUp. Each send() starts a fresh chat.\n *\n * GuardrailHooks are evaluated locally before returning results\n * (Gemini does not expose a pre-tool-use hook like Claude/OpenAI).\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on @google/genai)\n// ---------------------------------------------------------------------------\n\ntype GenerateContentResponse = {\n text?: string;\n candidates?: Array<{\n content?: { parts?: Array<{ text?: string }> };\n finishReason?: string;\n safetyRatings?: Array<{ category: string; probability: string }>;\n }>;\n};\n\ntype ChatSendMessageResult = GenerateContentResponse;\n\ntype Chat = {\n sendMessage(params: { message: string }): Promise<ChatSendMessageResult>;\n};\n\ntype GoogleGenAIOptions = {\n apiKey?: string;\n enterprise?: boolean;\n project?: string;\n location?: string;\n [key: string]: unknown;\n};\n\ntype ChatsCreateParams = {\n model: string;\n config?: Record<string, unknown>;\n};\n\ntype GoogleGenAIClient = {\n models: {\n generateContent(params: {\n model: string;\n contents: string;\n config?: Record<string, unknown>;\n }): Promise<GenerateContentResponse>;\n };\n chats: {\n create(params: ChatsCreateParams): Chat;\n };\n};\n\ntype GoogleGenAIConstructor = new (options: GoogleGenAIOptions) => GoogleGenAIClient;\n\n// ---------------------------------------------------------------------------\n// Response text extraction\n// ---------------------------------------------------------------------------\n\nfunction extractText(response: GenerateContentResponse): string {\n if (response.text) return response.text;\n\n if (response.candidates?.length) {\n const parts = response.candidates[0].content?.parts;\n if (parts?.length) {\n return parts.map((p) => p.text ?? \"\").join(\"\");\n }\n }\n\n return \"\";\n}\n\nfunction checkSafetyBlock(response: GenerateContentResponse): void {\n const candidate = response.candidates?.[0];\n if (candidate?.finishReason === \"SAFETY\") {\n const blocked = candidate.safetyRatings\n ?.filter((r) => r.probability === \"HIGH\")\n .map((r) => r.category)\n .join(\", \");\n throw new Error(\n `Gemini response blocked by safety filters: ${blocked || \"unknown category\"}`,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface GeminiSdkAdapterConfig {\n /** API key for Gemini Developer API. Falls back to GEMINI_API_KEY env var. */\n apiKey?: string;\n /** Model identifier (e.g. \"gemini-2.5-flash\", \"gemini-2.5-pro\"). */\n model?: string;\n /** System instruction prepended to all conversations. */\n systemInstruction?: string;\n /** Temperature for generation (0.0–2.0). */\n temperature?: number;\n /** Maximum output tokens. */\n maxOutputTokens?: number;\n /** Runtime guardrail hooks evaluated locally on responses. */\n guardrailHooks?: GuardrailHooks;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class GeminiSdkAdapter implements SdkAdapter {\n private apiKey: string | undefined;\n private model: string;\n private systemInstruction: string | undefined;\n private temperature: number | undefined;\n private maxOutputTokens: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private lastChat: Chat | null = null;\n\n private client: GoogleGenAIClient | null = null;\n private ClientClass: GoogleGenAIConstructor | null = null;\n\n constructor(config: GeminiSdkAdapterConfig = {}) {\n this.apiKey = config.apiKey;\n this.model = config.model ?? \"gemini-2.5-flash\";\n this.systemInstruction = config.systemInstruction;\n this.temperature = config.temperature;\n this.maxOutputTokens = config.maxOutputTokens;\n this.guardrailHooks = config.guardrailHooks;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveClient(): Promise<GoogleGenAIClient> {\n if (this.client) return this.client;\n\n if (!this.ClientClass) {\n const sdk = (await import(\"@google/genai\")) as {\n GoogleGenAI: GoogleGenAIConstructor;\n };\n this.ClientClass = sdk.GoogleGenAI;\n }\n\n const apiKey = this.apiKey ?? process.env.GEMINI_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"GEMINI_API_KEY environment variable or apiKey config is required for the Gemini adapter\",\n );\n }\n\n this.client = new this.ClientClass({ apiKey });\n return this.client;\n }\n\n private buildGenerationConfig(): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n if (this.systemInstruction) {\n config.systemInstruction = this.systemInstruction;\n }\n if (this.temperature !== undefined) {\n config.temperature = this.temperature;\n }\n if (this.maxOutputTokens !== undefined) {\n config.maxOutputTokens = this.maxOutputTokens;\n }\n return config;\n }\n\n private createChat(client: GoogleGenAIClient): Chat {\n return client.chats.create({\n model: this.model,\n config: this.buildGenerationConfig(),\n });\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n _options: AdapterSendOptions,\n ): Promise<string> {\n this.lastChat = null;\n\n const client = await this.resolveClient();\n const chat = this.createChat(client);\n const response = await chat.sendMessage({ message: prompt });\n\n checkSafetyBlock(response);\n this.lastChat = chat;\n\n return extractText(response);\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastChat) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n\n const response = await this.lastChat.sendMessage({ message });\n checkSafetyBlock(response);\n\n return extractText(response);\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastChat = null;\n\n const client = await this.resolveClient();\n const chat = this.createChat(client);\n const response = await chat.sendMessage({ message: request.prompt });\n\n checkSafetyBlock(response);\n this.lastChat = chat;\n\n return extractText(response);\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom GoogleGenAI client for testing.\n * Bypasses the dynamic import of @google/genai and API key requirement.\n */\n static withClient(\n client: GoogleGenAIClient,\n config?: GeminiSdkAdapterConfig,\n ): GeminiSdkAdapter {\n const adapter = new GeminiSdkAdapter(config);\n adapter.client = client;\n return adapter;\n }\n}\n"],"mappings":";AA4EA,SAAS,YAAY,UAA2C;AAC9D,MAAI,SAAS,KAAM,QAAO,SAAS;AAEnC,MAAI,SAAS,YAAY,QAAQ;AAC/B,UAAM,QAAQ,SAAS,WAAW,CAAC,EAAE,SAAS;AAC9C,QAAI,OAAO,QAAQ;AACjB,aAAO,MAAM,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,iBAAiB,UAAyC;AACjE,QAAM,YAAY,SAAS,aAAa,CAAC;AACzC,MAAI,WAAW,iBAAiB,UAAU;AACxC,UAAM,UAAU,UAAU,eACtB,OAAO,CAAC,MAAM,EAAE,gBAAgB,MAAM,EACvC,IAAI,CAAC,MAAM,EAAE,QAAQ,EACrB,KAAK,IAAI;AACZ,UAAM,IAAI;AAAA,MACR,8CAA8C,WAAW,kBAAkB;AAAA,IAC7E;AAAA,EACF;AACF;AAyBO,IAAM,mBAAN,MAAM,kBAAuC;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAwB;AAAA,EAExB,SAAmC;AAAA,EACnC,cAA6C;AAAA,EAErD,YAAY,SAAiC,CAAC,GAAG;AAC/C,SAAK,SAAS,OAAO;AACrB,SAAK,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AAA,EAEA,MAAM,SAAS,SAAkC;AAC/C,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,0DAAqD;AAAA,IACvE;AAEA,UAAM,WAAW,MAAM,KAAK,SAAS,YAAY,EAAE,QAAQ,CAAC;AAC5D,qBAAiB,QAAQ;AAEzB,WAAO,YAAY,QAAQ;AAAA,EAC7B;AAAA,EAEA,MAAM,cAAc,SAAiD;AACnE,SAAK,WAAW;AAEhB,UAAM,SAAS,MAAM,KAAK,cAAc;AACxC,UAAM,OAAO,KAAK,WAAW,MAAM;AACnC,UAAM,WAAW,MAAM,KAAK,YAAY,EAAE,SAAS,QAAQ,OAAO,CAAC;AAEnE,qBAAiB,QAAQ;AACzB,SAAK,WAAW;AAEhB,WAAO,YAAY,QAAQ;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,WACL,QACA,QACkB;AAClB,UAAM,UAAU,IAAI,kBAAiB,MAAM;AAC3C,YAAQ,SAAS;AACjB,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/adapters/mock.d.ts
CHANGED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-CPLSadjY.js';
|
|
2
|
+
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* OpenAI Agents SDK Adapter — implements SdkAdapter for @openai/agents
|
|
7
|
+
*
|
|
8
|
+
* Uses the `run()` function (or `Runner`) from the OpenAI Agents SDK to execute
|
|
9
|
+
* an Agent with instructions derived from the contract prompt.
|
|
10
|
+
*
|
|
11
|
+
* Supports:
|
|
12
|
+
* - send() — create a fresh Agent + run() and return finalOutput
|
|
13
|
+
* - followUp() — resume the same conversation via previousResponseId
|
|
14
|
+
* - sendExecution() — rich path using full contract context
|
|
15
|
+
*
|
|
16
|
+
* The SDK's `run()` returns a RunResult with `finalOutput` (the model's final
|
|
17
|
+
* text output) and `lastResponseId` for continuation.
|
|
18
|
+
*
|
|
19
|
+
* GuardrailHooks are mapped to the SDK's InputGuardrail system.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
type RunResult = {
|
|
23
|
+
finalOutput?: string | unknown;
|
|
24
|
+
lastResponseId?: string;
|
|
25
|
+
newItems?: Array<{
|
|
26
|
+
type: string;
|
|
27
|
+
rawItem?: {
|
|
28
|
+
type?: string;
|
|
29
|
+
content?: unknown;
|
|
30
|
+
};
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}>;
|
|
33
|
+
state?: unknown;
|
|
34
|
+
};
|
|
35
|
+
type AgentOptions = {
|
|
36
|
+
name: string;
|
|
37
|
+
model?: string;
|
|
38
|
+
instructions: string | ((ctx: unknown) => string);
|
|
39
|
+
tools?: unknown[];
|
|
40
|
+
inputGuardrails?: unknown[];
|
|
41
|
+
outputType?: unknown;
|
|
42
|
+
[key: string]: unknown;
|
|
43
|
+
};
|
|
44
|
+
type AgentInstance = AgentOptions & {
|
|
45
|
+
[key: string]: unknown;
|
|
46
|
+
};
|
|
47
|
+
type RunOptions = {
|
|
48
|
+
maxTurns?: number | null;
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
previousResponseId?: string;
|
|
51
|
+
stream?: boolean;
|
|
52
|
+
context?: unknown;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
};
|
|
55
|
+
type AgentConstructor = new (options: AgentOptions) => AgentInstance;
|
|
56
|
+
type RunFn = (agent: AgentInstance, input: string | unknown[], options?: RunOptions) => Promise<RunResult>;
|
|
57
|
+
interface OpenAIAgentsSdkAdapterConfig {
|
|
58
|
+
/** Model identifier (e.g. "gpt-4.1", "gpt-5.5"). Uses SDK default if omitted. */
|
|
59
|
+
model?: string;
|
|
60
|
+
/** Maximum conversation turns per run. Defaults to 10 (SDK default). */
|
|
61
|
+
maxTurns?: number;
|
|
62
|
+
/** Runtime guardrail hooks enforced via InputGuardrail. */
|
|
63
|
+
guardrailHooks?: GuardrailHooks;
|
|
64
|
+
/** Additional tools to pass to the Agent. */
|
|
65
|
+
tools?: unknown[];
|
|
66
|
+
/** Agent name prefix. Defaults to "contract-agent". */
|
|
67
|
+
agentName?: string;
|
|
68
|
+
/** AbortSignal for cancellation. */
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}
|
|
71
|
+
declare class OpenAIAgentsSdkAdapter implements SdkAdapter {
|
|
72
|
+
private model;
|
|
73
|
+
private maxTurns;
|
|
74
|
+
private guardrailHooks;
|
|
75
|
+
private tools;
|
|
76
|
+
private agentName;
|
|
77
|
+
private signal;
|
|
78
|
+
private lastResponseId;
|
|
79
|
+
private lastAgent;
|
|
80
|
+
private AgentClass;
|
|
81
|
+
private runFn;
|
|
82
|
+
constructor(config?: OpenAIAgentsSdkAdapterConfig);
|
|
83
|
+
private resolveSdk;
|
|
84
|
+
private createAgent;
|
|
85
|
+
private buildRunOptions;
|
|
86
|
+
private extractOutput;
|
|
87
|
+
send(prompt: string, options: AdapterSendOptions): Promise<string>;
|
|
88
|
+
followUp(message: string): Promise<string>;
|
|
89
|
+
sendExecution(request: AgentExecutionRequest): Promise<string>;
|
|
90
|
+
/**
|
|
91
|
+
* Inject custom Agent constructor and run function for testing.
|
|
92
|
+
* Bypasses the dynamic import of @openai/agents.
|
|
93
|
+
*/
|
|
94
|
+
static withRunFn(AgentClass: AgentConstructor, runFn: RunFn, config?: OpenAIAgentsSdkAdapterConfig): OpenAIAgentsSdkAdapter;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { OpenAIAgentsSdkAdapter, type OpenAIAgentsSdkAdapterConfig };
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// src/adapters/openai-agents-sdk.ts
|
|
2
|
+
function buildInputGuardrails(guardrails) {
|
|
3
|
+
return [
|
|
4
|
+
{
|
|
5
|
+
name: "contract-runtime-guardrail",
|
|
6
|
+
execute: async ({ input }) => {
|
|
7
|
+
const inputStr = typeof input === "string" ? input : JSON.stringify(input);
|
|
8
|
+
const results = guardrails.runChecks({ command: inputStr });
|
|
9
|
+
const blocking = results.filter((r) => !r.passed && r.action === "block");
|
|
10
|
+
return {
|
|
11
|
+
outputInfo: { results },
|
|
12
|
+
tripwireTriggered: blocking.length > 0
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
var OpenAIAgentsSdkAdapter = class _OpenAIAgentsSdkAdapter {
|
|
19
|
+
model;
|
|
20
|
+
maxTurns;
|
|
21
|
+
guardrailHooks;
|
|
22
|
+
tools;
|
|
23
|
+
agentName;
|
|
24
|
+
signal;
|
|
25
|
+
lastResponseId = null;
|
|
26
|
+
lastAgent = null;
|
|
27
|
+
AgentClass = null;
|
|
28
|
+
runFn = null;
|
|
29
|
+
constructor(config = {}) {
|
|
30
|
+
this.model = config.model;
|
|
31
|
+
this.maxTurns = config.maxTurns;
|
|
32
|
+
this.guardrailHooks = config.guardrailHooks;
|
|
33
|
+
this.tools = config.tools;
|
|
34
|
+
this.agentName = config.agentName ?? "contract-agent";
|
|
35
|
+
this.signal = config.signal;
|
|
36
|
+
}
|
|
37
|
+
// -------------------------------------------------------------------------
|
|
38
|
+
// Internal helpers
|
|
39
|
+
// -------------------------------------------------------------------------
|
|
40
|
+
async resolveSdk() {
|
|
41
|
+
if (this.AgentClass && this.runFn) {
|
|
42
|
+
return { Agent: this.AgentClass, run: this.runFn };
|
|
43
|
+
}
|
|
44
|
+
const sdk = await import("@openai/agents");
|
|
45
|
+
this.AgentClass = sdk.Agent;
|
|
46
|
+
this.runFn = sdk.run;
|
|
47
|
+
return { Agent: this.AgentClass, run: this.runFn };
|
|
48
|
+
}
|
|
49
|
+
createAgent(Agent, instructions, _readonly) {
|
|
50
|
+
const opts = {
|
|
51
|
+
name: this.agentName,
|
|
52
|
+
instructions
|
|
53
|
+
};
|
|
54
|
+
if (this.model) opts.model = this.model;
|
|
55
|
+
if (this.tools) opts.tools = this.tools;
|
|
56
|
+
if (this.guardrailHooks) {
|
|
57
|
+
opts.inputGuardrails = buildInputGuardrails(this.guardrailHooks);
|
|
58
|
+
}
|
|
59
|
+
return new Agent(opts);
|
|
60
|
+
}
|
|
61
|
+
buildRunOptions(previousResponseId) {
|
|
62
|
+
const opts = {};
|
|
63
|
+
if (this.maxTurns !== void 0) opts.maxTurns = this.maxTurns;
|
|
64
|
+
if (this.signal) opts.signal = this.signal;
|
|
65
|
+
if (previousResponseId) opts.previousResponseId = previousResponseId;
|
|
66
|
+
return opts;
|
|
67
|
+
}
|
|
68
|
+
extractOutput(result) {
|
|
69
|
+
if (typeof result.finalOutput === "string") {
|
|
70
|
+
return result.finalOutput;
|
|
71
|
+
}
|
|
72
|
+
if (result.finalOutput !== void 0 && result.finalOutput !== null) {
|
|
73
|
+
return JSON.stringify(result.finalOutput, null, 2);
|
|
74
|
+
}
|
|
75
|
+
if (result.newItems) {
|
|
76
|
+
const textParts = [];
|
|
77
|
+
for (const item of result.newItems) {
|
|
78
|
+
if (item.type === "message_output_item" || item.type === "text") {
|
|
79
|
+
const rawItem = item.rawItem;
|
|
80
|
+
if (rawItem?.content) {
|
|
81
|
+
const content = rawItem.content;
|
|
82
|
+
if (Array.isArray(content)) {
|
|
83
|
+
for (const part of content) {
|
|
84
|
+
if (typeof part === "object" && part !== null && "text" in part) {
|
|
85
|
+
textParts.push(part.text);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} else if (typeof content === "string") {
|
|
89
|
+
textParts.push(content);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (textParts.length > 0) return textParts.join("\n");
|
|
95
|
+
}
|
|
96
|
+
return "";
|
|
97
|
+
}
|
|
98
|
+
// -------------------------------------------------------------------------
|
|
99
|
+
// SdkAdapter interface
|
|
100
|
+
// -------------------------------------------------------------------------
|
|
101
|
+
async send(prompt, options) {
|
|
102
|
+
this.lastResponseId = null;
|
|
103
|
+
this.lastAgent = null;
|
|
104
|
+
const { Agent, run } = await this.resolveSdk();
|
|
105
|
+
const agent = this.createAgent(Agent, prompt, options.readonly);
|
|
106
|
+
const runOpts = this.buildRunOptions();
|
|
107
|
+
const result = await run(agent, prompt, runOpts);
|
|
108
|
+
this.lastResponseId = result.lastResponseId ?? null;
|
|
109
|
+
this.lastAgent = agent;
|
|
110
|
+
return this.extractOutput(result);
|
|
111
|
+
}
|
|
112
|
+
async followUp(message) {
|
|
113
|
+
if (!this.lastResponseId) {
|
|
114
|
+
throw new Error("followUp() called before send() \u2014 no active session");
|
|
115
|
+
}
|
|
116
|
+
const { run } = await this.resolveSdk();
|
|
117
|
+
const agent = this.lastAgent;
|
|
118
|
+
const runOpts = this.buildRunOptions(this.lastResponseId);
|
|
119
|
+
const result = await run(agent, message, runOpts);
|
|
120
|
+
this.lastResponseId = result.lastResponseId ?? this.lastResponseId;
|
|
121
|
+
return this.extractOutput(result);
|
|
122
|
+
}
|
|
123
|
+
async sendExecution(request) {
|
|
124
|
+
this.lastResponseId = null;
|
|
125
|
+
this.lastAgent = null;
|
|
126
|
+
const { Agent, run } = await this.resolveSdk();
|
|
127
|
+
const agent = this.createAgent(Agent, request.prompt, request.options.readonly);
|
|
128
|
+
const runOpts = this.buildRunOptions();
|
|
129
|
+
const result = await run(agent, request.prompt, runOpts);
|
|
130
|
+
this.lastResponseId = result.lastResponseId ?? null;
|
|
131
|
+
this.lastAgent = agent;
|
|
132
|
+
return this.extractOutput(result);
|
|
133
|
+
}
|
|
134
|
+
// -------------------------------------------------------------------------
|
|
135
|
+
// Test support
|
|
136
|
+
// -------------------------------------------------------------------------
|
|
137
|
+
/**
|
|
138
|
+
* Inject custom Agent constructor and run function for testing.
|
|
139
|
+
* Bypasses the dynamic import of @openai/agents.
|
|
140
|
+
*/
|
|
141
|
+
static withRunFn(AgentClass, runFn, config) {
|
|
142
|
+
const adapter = new _OpenAIAgentsSdkAdapter(config);
|
|
143
|
+
adapter.AgentClass = AgentClass;
|
|
144
|
+
adapter.runFn = runFn;
|
|
145
|
+
return adapter;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
export {
|
|
149
|
+
OpenAIAgentsSdkAdapter
|
|
150
|
+
};
|
|
151
|
+
//# sourceMappingURL=openai-agents-sdk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/openai-agents-sdk.ts"],"sourcesContent":["/**\n * OpenAI Agents SDK Adapter — implements SdkAdapter for @openai/agents\n *\n * Uses the `run()` function (or `Runner`) from the OpenAI Agents SDK to execute\n * an Agent with instructions derived from the contract prompt.\n *\n * Supports:\n * - send() — create a fresh Agent + run() and return finalOutput\n * - followUp() — resume the same conversation via previousResponseId\n * - sendExecution() — rich path using full contract context\n *\n * The SDK's `run()` returns a RunResult with `finalOutput` (the model's final\n * text output) and `lastResponseId` for continuation.\n *\n * GuardrailHooks are mapped to the SDK's InputGuardrail system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n} from \"../lib/task-runner.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on @openai/agents)\n// ---------------------------------------------------------------------------\n\ntype RunResult = {\n finalOutput?: string | unknown;\n lastResponseId?: string;\n newItems?: Array<{\n type: string;\n rawItem?: { type?: string; content?: unknown };\n [key: string]: unknown;\n }>;\n state?: unknown;\n};\n\ntype AgentOptions = {\n name: string;\n model?: string;\n instructions: string | ((ctx: unknown) => string);\n tools?: unknown[];\n inputGuardrails?: unknown[];\n outputType?: unknown;\n [key: string]: unknown;\n};\n\ntype AgentInstance = AgentOptions & { [key: string]: unknown };\n\ntype RunOptions = {\n maxTurns?: number | null;\n signal?: AbortSignal;\n previousResponseId?: string;\n stream?: boolean;\n context?: unknown;\n [key: string]: unknown;\n};\n\ntype AgentConstructor = new (options: AgentOptions) => AgentInstance;\n\ntype RunFn = (\n agent: AgentInstance,\n input: string | unknown[],\n options?: RunOptions,\n) => Promise<RunResult>;\n\n// ---------------------------------------------------------------------------\n// Guardrail bridge\n// ---------------------------------------------------------------------------\n\nfunction buildInputGuardrails(\n guardrails: GuardrailHooks,\n): unknown[] {\n return [\n {\n name: \"contract-runtime-guardrail\",\n execute: async ({ input }: { input: unknown }) => {\n const inputStr = typeof input === \"string\"\n ? input\n : JSON.stringify(input);\n\n const results = guardrails.runChecks({ command: inputStr });\n const blocking = results.filter((r) => !r.passed && r.action === \"block\");\n\n return {\n outputInfo: { results },\n tripwireTriggered: blocking.length > 0,\n };\n },\n },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface OpenAIAgentsSdkAdapterConfig {\n /** Model identifier (e.g. \"gpt-4.1\", \"gpt-5.5\"). Uses SDK default if omitted. */\n model?: string;\n /** Maximum conversation turns per run. Defaults to 10 (SDK default). */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via InputGuardrail. */\n guardrailHooks?: GuardrailHooks;\n /** Additional tools to pass to the Agent. */\n tools?: unknown[];\n /** Agent name prefix. Defaults to \"contract-agent\". */\n agentName?: string;\n /** AbortSignal for cancellation. */\n signal?: AbortSignal;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class OpenAIAgentsSdkAdapter implements SdkAdapter {\n private model: string | undefined;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private tools: unknown[] | undefined;\n private agentName: string;\n private signal: AbortSignal | undefined;\n private lastResponseId: string | null = null;\n private lastAgent: AgentInstance | null = null;\n\n private AgentClass: AgentConstructor | null = null;\n private runFn: RunFn | null = null;\n\n constructor(config: OpenAIAgentsSdkAdapterConfig = {}) {\n this.model = config.model;\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n this.tools = config.tools;\n this.agentName = config.agentName ?? \"contract-agent\";\n this.signal = config.signal;\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveSdk(): Promise<{ Agent: AgentConstructor; run: RunFn }> {\n if (this.AgentClass && this.runFn) {\n return { Agent: this.AgentClass, run: this.runFn };\n }\n\n const sdk = (await import(\"@openai/agents\")) as unknown as {\n Agent: AgentConstructor;\n run: RunFn;\n };\n this.AgentClass = sdk.Agent;\n this.runFn = sdk.run;\n return { Agent: this.AgentClass, run: this.runFn };\n }\n\n private createAgent(\n Agent: AgentConstructor,\n instructions: string,\n _readonly: boolean,\n ): AgentInstance {\n const opts: AgentOptions = {\n name: this.agentName,\n instructions,\n };\n\n if (this.model) opts.model = this.model;\n if (this.tools) opts.tools = this.tools;\n\n if (this.guardrailHooks) {\n opts.inputGuardrails = buildInputGuardrails(this.guardrailHooks);\n }\n\n return new Agent(opts);\n }\n\n private buildRunOptions(previousResponseId?: string): RunOptions {\n const opts: RunOptions = {};\n\n if (this.maxTurns !== undefined) opts.maxTurns = this.maxTurns;\n if (this.signal) opts.signal = this.signal;\n if (previousResponseId) opts.previousResponseId = previousResponseId;\n\n return opts;\n }\n\n private extractOutput(result: RunResult): string {\n if (typeof result.finalOutput === \"string\") {\n return result.finalOutput;\n }\n\n if (result.finalOutput !== undefined && result.finalOutput !== null) {\n return JSON.stringify(result.finalOutput, null, 2);\n }\n\n if (result.newItems) {\n const textParts: string[] = [];\n for (const item of result.newItems) {\n if (item.type === \"message_output_item\" || item.type === \"text\") {\n const rawItem = item.rawItem as Record<string, unknown> | undefined;\n if (rawItem?.content) {\n const content = rawItem.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (typeof part === \"object\" && part !== null && \"text\" in part) {\n textParts.push((part as { text: string }).text);\n }\n }\n } else if (typeof content === \"string\") {\n textParts.push(content);\n }\n }\n }\n }\n if (textParts.length > 0) return textParts.join(\"\\n\");\n }\n\n return \"\";\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastResponseId = null;\n this.lastAgent = null;\n\n const { Agent, run } = await this.resolveSdk();\n const agent = this.createAgent(Agent, prompt, options.readonly);\n const runOpts = this.buildRunOptions();\n\n const result = await run(agent, prompt, runOpts);\n\n this.lastResponseId = result.lastResponseId ?? null;\n this.lastAgent = agent;\n\n return this.extractOutput(result);\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastResponseId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n\n const { run } = await this.resolveSdk();\n const agent = this.lastAgent!;\n const runOpts = this.buildRunOptions(this.lastResponseId);\n\n const result = await run(agent, message, runOpts);\n\n this.lastResponseId = result.lastResponseId ?? this.lastResponseId;\n\n return this.extractOutput(result);\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastResponseId = null;\n this.lastAgent = null;\n\n const { Agent, run } = await this.resolveSdk();\n const agent = this.createAgent(Agent, request.prompt, request.options.readonly);\n const runOpts = this.buildRunOptions();\n\n const result = await run(agent, request.prompt, runOpts);\n\n this.lastResponseId = result.lastResponseId ?? null;\n this.lastAgent = agent;\n\n return this.extractOutput(result);\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject custom Agent constructor and run function for testing.\n * Bypasses the dynamic import of @openai/agents.\n */\n static withRunFn(\n AgentClass: AgentConstructor,\n runFn: RunFn,\n config?: OpenAIAgentsSdkAdapterConfig,\n ): OpenAIAgentsSdkAdapter {\n const adapter = new OpenAIAgentsSdkAdapter(config);\n adapter.AgentClass = AgentClass;\n adapter.runFn = runFn;\n return adapter;\n }\n}\n"],"mappings":";AAwEA,SAAS,qBACP,YACW;AACX,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,SAAS,OAAO,EAAE,MAAM,MAA0B;AAChD,cAAM,WAAW,OAAO,UAAU,WAC9B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.options.join(", ")})`;
|
|
106
106
|
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
|
|
107
107
|
if (schema instanceof z.ZodArray) {
|
|
108
|
-
const
|
|
108
|
+
const element = schema._def.element;
|
|
109
|
+
const inner = zodTypeToString(element);
|
|
109
110
|
return `${inner}[]`;
|
|
110
111
|
}
|
|
111
112
|
if (schema instanceof z.ZodObject) return "object";
|
|
@@ -115,6 +116,19 @@ function zodTypeToString(schema) {
|
|
|
115
116
|
if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
|
|
116
117
|
return "unknown";
|
|
117
118
|
}
|
|
119
|
+
function unwrapOptional(schema) {
|
|
120
|
+
if (schema instanceof z.ZodOptional) {
|
|
121
|
+
return schema._def.innerType;
|
|
122
|
+
}
|
|
123
|
+
return schema;
|
|
124
|
+
}
|
|
125
|
+
function getArrayElement(schema) {
|
|
126
|
+
const inner = unwrapOptional(schema);
|
|
127
|
+
if (inner instanceof z.ZodArray) {
|
|
128
|
+
return inner._def.element;
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
118
132
|
function extractFieldDescriptors(schema) {
|
|
119
133
|
let shape = null;
|
|
120
134
|
if (schema instanceof z.ZodObject) {
|
|
@@ -134,43 +148,93 @@ function extractFieldDescriptors(schema) {
|
|
|
134
148
|
});
|
|
135
149
|
}
|
|
136
150
|
function zodSchemaToPromptDescription(schema) {
|
|
151
|
+
const tables = [];
|
|
152
|
+
collectFieldTables(schema, "", tables);
|
|
153
|
+
return tables.join("\n\n");
|
|
154
|
+
}
|
|
155
|
+
function collectFieldTables(schema, pathPrefix, tables) {
|
|
137
156
|
const fields = extractFieldDescriptors(schema);
|
|
138
|
-
if (!fields || fields.length === 0) return
|
|
157
|
+
if (!fields || fields.length === 0) return;
|
|
158
|
+
const title = pathPrefix ? `**${pathPrefix}**
|
|
159
|
+
|
|
160
|
+
` : "";
|
|
139
161
|
const header = "| Field | Type | Required | Description |";
|
|
140
162
|
const sep = "|-------|------|----------|-------------|";
|
|
141
163
|
const rows = fields.map(
|
|
142
164
|
(f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.description ?? ""} |`
|
|
143
165
|
);
|
|
144
|
-
|
|
166
|
+
tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
|
|
167
|
+
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
168
|
+
if (!shape) return;
|
|
169
|
+
for (const f of fields) {
|
|
170
|
+
const rawField = shape[f.name];
|
|
171
|
+
const inner = unwrapOptional(rawField);
|
|
172
|
+
if (inner instanceof z.ZodObject) {
|
|
173
|
+
collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
|
|
174
|
+
} else if (inner instanceof z.ZodArray) {
|
|
175
|
+
const element = inner._def.element;
|
|
176
|
+
if (element instanceof z.ZodObject) {
|
|
177
|
+
collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
145
181
|
}
|
|
146
|
-
function zodSchemaToYamlExample(schema) {
|
|
182
|
+
function zodSchemaToYamlExample(schema, maxDepth = 3) {
|
|
183
|
+
return renderYamlObject(schema, 0, maxDepth);
|
|
184
|
+
}
|
|
185
|
+
function renderYamlObject(schema, indent, maxDepth) {
|
|
147
186
|
const fields = extractFieldDescriptors(schema);
|
|
148
187
|
if (!fields || fields.length === 0) return "";
|
|
188
|
+
const prefix = " ".repeat(indent);
|
|
149
189
|
const lines = [];
|
|
150
190
|
for (const f of fields) {
|
|
191
|
+
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
192
|
+
const rawField = shape?.[f.name];
|
|
151
193
|
if (f.type.endsWith("[]")) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
194
|
+
lines.push(`${prefix}${f.name}:`);
|
|
195
|
+
const element = rawField ? getArrayElement(rawField) : null;
|
|
196
|
+
if (element && element instanceof z.ZodObject && indent < maxDepth) {
|
|
197
|
+
const nested = renderYamlObject(element, indent + 2, maxDepth);
|
|
198
|
+
if (nested) {
|
|
199
|
+
const basePrefix = " ".repeat(indent + 2);
|
|
200
|
+
const nestedLines = nested.split("\n");
|
|
201
|
+
lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
|
|
202
|
+
for (let i = 1; i < nestedLines.length; i++) {
|
|
203
|
+
lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
lines.push(`${prefix} - key: "value"`);
|
|
207
|
+
}
|
|
208
|
+
} else if (f.type === "string[]") {
|
|
209
|
+
lines.push(`${prefix} - "example"`);
|
|
210
|
+
} else {
|
|
211
|
+
lines.push(`${prefix} - key: "value"`);
|
|
212
|
+
}
|
|
213
|
+
} else if (f.type === "object" && indent < maxDepth) {
|
|
214
|
+
const inner = rawField ? unwrapOptional(rawField) : null;
|
|
215
|
+
if (inner && inner instanceof z.ZodObject) {
|
|
216
|
+
lines.push(`${prefix}${f.name}:`);
|
|
217
|
+
const nested = renderYamlObject(inner, indent + 1, maxDepth);
|
|
218
|
+
if (nested) {
|
|
219
|
+
lines.push(nested);
|
|
220
|
+
} else {
|
|
221
|
+
lines.push(`${prefix} key: "value"`);
|
|
222
|
+
}
|
|
159
223
|
} else {
|
|
160
|
-
lines.push(`${f.name}:`);
|
|
161
|
-
lines.push(
|
|
224
|
+
lines.push(`${prefix}${f.name}:`);
|
|
225
|
+
lines.push(`${prefix} key: "value"`);
|
|
162
226
|
}
|
|
163
227
|
} else if (f.type === "string") {
|
|
164
|
-
lines.push(`${f.name}: "..."`);
|
|
228
|
+
lines.push(`${prefix}${f.name}: "..."`);
|
|
165
229
|
} else if (f.type === "number") {
|
|
166
|
-
lines.push(`${f.name}: 0`);
|
|
230
|
+
lines.push(`${prefix}${f.name}: 0`);
|
|
167
231
|
} else if (f.type === "boolean") {
|
|
168
|
-
lines.push(`${f.name}: false`);
|
|
169
|
-
} else if (f.type
|
|
170
|
-
|
|
171
|
-
lines.push(
|
|
232
|
+
lines.push(`${prefix}${f.name}: false`);
|
|
233
|
+
} else if (f.type.startsWith("enum(")) {
|
|
234
|
+
const enumVals = f.type.slice(5, -1).split(", ");
|
|
235
|
+
lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
|
|
172
236
|
} else {
|
|
173
|
-
lines.push(`${f.name}: "..."`);
|
|
237
|
+
lines.push(`${prefix}${f.name}: "..."`);
|
|
174
238
|
}
|
|
175
239
|
}
|
|
176
240
|
return lines.join("\n");
|
|
@@ -928,4 +992,4 @@ export {
|
|
|
928
992
|
loadPluginsFromDirectory,
|
|
929
993
|
loadPlugins
|
|
930
994
|
};
|
|
931
|
-
//# sourceMappingURL=chunk-
|
|
995
|
+
//# sourceMappingURL=chunk-COHQ2PB5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/workflow-runner.ts","../src/lib/guardrail-hooks.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts"],"sourcesContent":["/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const element = (schema as z.ZodArray<z.ZodType>)._def.element;\n const inner = zodTypeToString(element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\n/** Unwrap ZodOptional to get the inner type. */\nfunction unwrapOptional(schema: z.ZodType): z.ZodType {\n if (schema instanceof z.ZodOptional) {\n return (schema as z.ZodOptional<z.ZodType>)._def.innerType;\n }\n return schema;\n}\n\n/** Get the element schema from an array type. */\nfunction getArrayElement(schema: z.ZodType): z.ZodType | null {\n const inner = unwrapOptional(schema);\n if (inner instanceof z.ZodArray) {\n return (inner as z.ZodArray<z.ZodType>)._def.element;\n }\n return null;\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n * Recursively generates sub-tables for nested objects and array elements.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const tables: string[] = [];\n collectFieldTables(schema, \"\", tables);\n return tables.join(\"\\n\\n\");\n}\n\nfunction collectFieldTables(\n schema: z.ZodType,\n pathPrefix: string,\n tables: string[],\n): void {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return;\n\n const title = pathPrefix ? `**${pathPrefix}**\\n\\n` : \"\";\n const header = \"| Field | Type | Required | Description |\";\n const sep = \"|-------|------|----------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.description ?? \"\"} |`,\n );\n tables.push(`${title}${[header, sep, ...rows].join(\"\\n\")}`);\n\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n if (!shape) return;\n\n for (const f of fields) {\n const rawField = shape[f.name];\n const inner = unwrapOptional(rawField);\n\n if (inner instanceof z.ZodObject) {\n collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);\n } else if (inner instanceof z.ZodArray) {\n const element = (inner as z.ZodArray<z.ZodType>)._def.element;\n if (element instanceof z.ZodObject) {\n collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);\n }\n }\n }\n}\n\n/**\n * Generate a YAML example from a Zod schema shape, recursively expanding\n * nested objects and arrays up to a configurable depth.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType, maxDepth = 3): string {\n return renderYamlObject(schema, 0, maxDepth);\n}\n\nfunction renderYamlObject(schema: z.ZodType, indent: number, maxDepth: number): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const prefix = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const f of fields) {\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n const rawField = shape?.[f.name];\n\n if (f.type.endsWith(\"[]\")) {\n lines.push(`${prefix}${f.name}:`);\n const element = rawField ? getArrayElement(rawField) : null;\n if (element && element instanceof z.ZodObject && indent < maxDepth) {\n const nested = renderYamlObject(element, indent + 2, maxDepth);\n if (nested) {\n const basePrefix = \" \".repeat(indent + 2);\n const nestedLines = nested.split(\"\\n\");\n lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);\n for (let i = 1; i < nestedLines.length; i++) {\n lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);\n }\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"string[]\") {\n lines.push(`${prefix} - \"example\"`);\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"object\" && indent < maxDepth) {\n const inner = rawField ? unwrapOptional(rawField) : null;\n if (inner && inner instanceof z.ZodObject) {\n lines.push(`${prefix}${f.name}:`);\n const nested = renderYamlObject(inner, indent + 1, maxDepth);\n if (nested) {\n lines.push(nested);\n } else {\n lines.push(`${prefix} key: \"value\"`);\n }\n } else {\n lines.push(`${prefix}${f.name}:`);\n lines.push(`${prefix} key: \"value\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${prefix}${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${prefix}${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${prefix}${f.name}: false`);\n } else if (f.type.startsWith(\"enum(\")) {\n const enumVals = f.type.slice(5, -1).split(\", \");\n lines.push(`${prefix}${f.name}: \"${enumVals[0]}\"`);\n } else {\n lines.push(`${prefix}${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n sections.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n sections.push(`## User Request\\n\\n${context.user_request}`);\n sections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n } else {\n sections.push(`## User Request\\n\\n${context.user_request}`);\n }\n\n if (context.prior_context) {\n sections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n sections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n sections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n sections.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n sections.push(recoverySection);\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const promptOpts: PromptBuilderOptions = { handoffSchemas: schemas, retry: options?.retry };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n let prompt = pluginRegistry.applyPromptBuilder(builderArgs)\n ?? buildTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n\n const isReadonly = agentContract.mode === \"read-only\";\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n options: { readonly: isReadonly, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\n }\n } catch (err) {\n return { outcome: { status: \"error\", message: `SDK error: ${(err as Error).message}` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (cursorSessionId,\n * openaiThreadId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapter: SdkAdapter,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n const stepResults: StepResult[] = [];\n const workflowStart = Date.now();\n let accumulatedContext = \"\";\n\n for (let i = 0; i < workflow.steps.length; i++) {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n const result = await handleGateStep(step, stepResults, options, i);\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"gate_rejected\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n continue;\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: accumulatedContext };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: accumulatedContext,\n ...(invocationHandoff ? { handoff_input: invocationHandoff } : {}),\n };\n const taskResult: TaskRunResult = await runTask(adapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n });\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Accumulate context from successful steps\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n // Escalation — stop workflow\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n // Unrecoverable failure after all recovery attempts\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (!options.onGate) {\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: DelegateStep | GateStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * The generated hooks/index.ts calls createGuardrailHooks() with the\n * DSL-generated check functions. All logic lives here in the lib.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by Cursor / Claude SDKs,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — auto-discovers and registers user plugin files\n *\n * Discovery strategies (in priority order):\n * 1. Config-based: `plugins` array in agent-runtime.config.yaml\n * 2. Convention-based: scan `src/plugins/` for files exporting AgentPlugin\n *\n * Each discovered module is dynamically import()'d. Exports that satisfy the\n * AgentPlugin interface (have an `id` string property) are registered with\n * the pluginRegistry singleton.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nconst PLUGIN_EXTENSIONS = [\".ts\", \".js\", \".mts\", \".mjs\"];\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Scan a directory for files that may export plugins.\n * Returns absolute paths of candidate files.\n */\nasync function scanDirectory(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n\n const entries = await readdir(dir, { withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) &&\n !e.name.startsWith(\"_\") &&\n !e.name.endsWith(\".d.ts\") &&\n !e.name.endsWith(\".test.ts\") &&\n !e.name.endsWith(\".spec.ts\"),\n )\n .map((e) => resolve(dir, e.name));\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n loaded: number;\n files: string[];\n errors: Array<{ file: string; error: string }>;\n}\n\n/**\n * Load plugins from explicit paths (config-based discovery).\n */\nexport async function loadPluginsFromPaths(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n result.errors.push({ file: p, error: `File not found: ${absPath}` });\n continue;\n }\n\n try {\n const count = await loadPluginModule(absPath);\n result.loaded += count;\n result.files.push(absPath);\n } catch (err) {\n result.errors.push({\n file: p,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Load plugins using convention-based directory scanning.\n * Scans `<projectDir>/src/plugins/` by default.\n */\nexport async function loadPluginsFromDirectory(\n dir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n const candidates = await scanDirectory(dir);\n\n for (const filePath of candidates) {\n try {\n const count = await loadPluginModule(filePath);\n result.loaded += count;\n result.files.push(filePath);\n } catch (err) {\n result.errors.push({\n file: filePath,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Auto-discover and load plugins. Uses config-based paths if provided,\n * otherwise falls back to convention-based scanning of src/plugins/.\n */\nexport async function loadPlugins(options: {\n pluginPaths?: string[];\n projectDir: string;\n}): Promise<PluginLoadResult> {\n if (options.pluginPaths && options.pluginPaths.length > 0) {\n return loadPluginsFromPaths(options.pluginPaths, options.projectDir);\n }\n\n const conventionDir = join(options.projectDir, \"src\", \"plugins\");\n return loadPluginsFromDirectory(conventionDir);\n}\n"],"mappings":";AAiBA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACmCf,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,sB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.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, S as SdkAdapter, P as PromptBuilderOptions } from './task-runner-
|
|
2
|
-
export { A as AdapterSendOptions, a as AgentExecutionRequest, R as RetryDecision, e as TaskRunOptions, f as TaskRunResult, g as buildRetryFollowUp, h as buildTaskPrompt, i as extractStructuredResult, r as runTask, z as zodSchemaToPromptDescription, j as zodSchemaToYamlExample } from './task-runner-
|
|
1
|
+
import { T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, S as SdkAdapter, P as PromptBuilderOptions } from './task-runner-CPLSadjY.js';
|
|
2
|
+
export { A as AdapterSendOptions, a as AgentExecutionRequest, R as RetryDecision, e as TaskRunOptions, f as TaskRunResult, g as buildRetryFollowUp, h as buildTaskPrompt, i as extractStructuredResult, r as runTask, z as zodSchemaToPromptDescription, j as zodSchemaToYamlExample } from './task-runner-CPLSadjY.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
export { a as GuardrailCheckFunctions, b as GuardrailCheckResult, G as GuardrailHooks, H as HookContext, c as HookResponse, d as createGuardrailHooks, g as getBlockingViolations, e as getWarnings, h as hasBlockingViolation } from './guardrail-hooks-5MSNWxnl.js';
|
|
5
5
|
|
package/dist/index.js
CHANGED
|
@@ -140,12 +140,14 @@ interface TaskRunResult {
|
|
|
140
140
|
}
|
|
141
141
|
/**
|
|
142
142
|
* Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.
|
|
143
|
+
* Recursively generates sub-tables for nested objects and array elements.
|
|
143
144
|
*/
|
|
144
145
|
declare function zodSchemaToPromptDescription(schema: z.ZodType): string;
|
|
145
146
|
/**
|
|
146
|
-
* Generate a
|
|
147
|
+
* Generate a YAML example from a Zod schema shape, recursively expanding
|
|
148
|
+
* nested objects and arrays up to a configurable depth.
|
|
147
149
|
*/
|
|
148
|
-
declare function zodSchemaToYamlExample(schema: z.ZodType): string;
|
|
150
|
+
declare function zodSchemaToYamlExample(schema: z.ZodType, maxDepth?: number): string;
|
|
149
151
|
interface PromptBuilderOptions {
|
|
150
152
|
handoffSchemas?: Record<string, z.ZodType>;
|
|
151
153
|
retry?: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-contracts-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -93,6 +93,10 @@
|
|
|
93
93
|
"zod": "^4.0.0"
|
|
94
94
|
},
|
|
95
95
|
"devDependencies": {
|
|
96
|
+
"@anthropic-ai/claude-agent-sdk": "^0.2.138",
|
|
97
|
+
"@cursor/sdk": "^1.0.12",
|
|
98
|
+
"@google/genai": "^2.0.1",
|
|
99
|
+
"@openai/agents": "^0.11.1",
|
|
96
100
|
"@types/node": "^25.6.0",
|
|
97
101
|
"cli-contracts": "^0.2.1",
|
|
98
102
|
"tsup": "^8.5.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/workflow-runner.ts","../src/lib/guardrail-hooks.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts"],"sourcesContent":["/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const inner = zodTypeToString((schema as z.ZodArray<z.ZodType>)._def.element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const header = \"| Field | Type | Required | Description |\";\n const sep = \"|-------|------|----------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.description ?? \"\"} |`,\n );\n return [header, sep, ...rows].join(\"\\n\");\n}\n\n/**\n * Generate a minimal YAML example from a Zod schema shape.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const lines: string[] = [];\n for (const f of fields) {\n if (f.type.endsWith(\"[]\")) {\n const innerType = f.type.slice(0, -2);\n if (innerType === \"string\") {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n } else if (innerType === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` - key: \"value\"`);\n } else {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${f.name}: false`);\n } else if (f.type === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` key: \"value\"`);\n } else {\n lines.push(`${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n sections.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n sections.push(`## User Request\\n\\n${context.user_request}`);\n sections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n } else {\n sections.push(`## User Request\\n\\n${context.user_request}`);\n }\n\n if (context.prior_context) {\n sections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n sections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n sections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n sections.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n sections.push(recoverySection);\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const promptOpts: PromptBuilderOptions = { handoffSchemas: schemas, retry: options?.retry };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n let prompt = pluginRegistry.applyPromptBuilder(builderArgs)\n ?? buildTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n\n const isReadonly = agentContract.mode === \"read-only\";\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n options: { readonly: isReadonly, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\n }\n } catch (err) {\n return { outcome: { status: \"error\", message: `SDK error: ${(err as Error).message}` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (cursorSessionId,\n * openaiThreadId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapter: SdkAdapter,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n const stepResults: StepResult[] = [];\n const workflowStart = Date.now();\n let accumulatedContext = \"\";\n\n for (let i = 0; i < workflow.steps.length; i++) {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n const result = await handleGateStep(step, stepResults, options, i);\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"gate_rejected\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n continue;\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: accumulatedContext };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: accumulatedContext,\n ...(invocationHandoff ? { handoff_input: invocationHandoff } : {}),\n };\n const taskResult: TaskRunResult = await runTask(adapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n });\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Accumulate context from successful steps\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n // Escalation — stop workflow\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n // Unrecoverable failure after all recovery attempts\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (!options.onGate) {\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: DelegateStep | GateStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * The generated hooks/index.ts calls createGuardrailHooks() with the\n * DSL-generated check functions. All logic lives here in the lib.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by Cursor / Claude SDKs,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — auto-discovers and registers user plugin files\n *\n * Discovery strategies (in priority order):\n * 1. Config-based: `plugins` array in agent-runtime.config.yaml\n * 2. Convention-based: scan `src/plugins/` for files exporting AgentPlugin\n *\n * Each discovered module is dynamically import()'d. Exports that satisfy the\n * AgentPlugin interface (have an `id` string property) are registered with\n * the pluginRegistry singleton.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nconst PLUGIN_EXTENSIONS = [\".ts\", \".js\", \".mts\", \".mjs\"];\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Scan a directory for files that may export plugins.\n * Returns absolute paths of candidate files.\n */\nasync function scanDirectory(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n\n const entries = await readdir(dir, { withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) &&\n !e.name.startsWith(\"_\") &&\n !e.name.endsWith(\".d.ts\") &&\n !e.name.endsWith(\".test.ts\") &&\n !e.name.endsWith(\".spec.ts\"),\n )\n .map((e) => resolve(dir, e.name));\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n loaded: number;\n files: string[];\n errors: Array<{ file: string; error: string }>;\n}\n\n/**\n * Load plugins from explicit paths (config-based discovery).\n */\nexport async function loadPluginsFromPaths(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n result.errors.push({ file: p, error: `File not found: ${absPath}` });\n continue;\n }\n\n try {\n const count = await loadPluginModule(absPath);\n result.loaded += count;\n result.files.push(absPath);\n } catch (err) {\n result.errors.push({\n file: p,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Load plugins using convention-based directory scanning.\n * Scans `<projectDir>/src/plugins/` by default.\n */\nexport async function loadPluginsFromDirectory(\n dir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n const candidates = await scanDirectory(dir);\n\n for (const filePath of candidates) {\n try {\n const count = await loadPluginModule(filePath);\n result.loaded += count;\n result.files.push(filePath);\n } catch (err) {\n result.errors.push({\n file: filePath,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Auto-discover and load plugins. Uses config-based paths if provided,\n * otherwise falls back to convention-based scanning of src/plugins/.\n */\nexport async function loadPlugins(options: {\n pluginPaths?: string[];\n projectDir: string;\n}): Promise<PluginLoadResult> {\n if (options.pluginPaths && options.pluginPaths.length > 0) {\n return loadPluginsFromPaths(options.pluginPaths, options.projectDir);\n }\n\n const conventionDir = join(options.projectDir, \"src\", \"plugins\");\n return loadPluginsFromDirectory(conventionDir);\n}\n"],"mappings":";AAiBA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACmCf,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,sBAAsB,QAAgB,SAAmC;AACvE,QAAI,MAAM;AACV,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,gBAAiB;AAC7B,YAAM,OAAO,gBAAgB,QAAQ,GAAG;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,mBAAmB,MAAwC;AACzD,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAe;AAC3B,YAAM,SAAS,OAAO,cAAc,IAAI;AACxC,UAAI,WAAW,KAAM,Q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