agent-contracts-runtime 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/cli-contract.yaml +2 -2
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/cursor-sdk.d.ts +2 -1
- package/dist/adapters/cursor-sdk.js +3 -1
- package/dist/adapters/cursor-sdk.js.map +1 -1
- package/dist/adapters/gemini-sdk.d.ts +98 -0
- package/dist/adapters/gemini-sdk.js +121 -0
- package/dist/adapters/gemini-sdk.js.map +1 -0
- 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/cli/index.js +6 -2
- package/dist/cli/index.js.map +1 -1
- package/package.json +13 -1
package/README.md
CHANGED
|
@@ -593,6 +593,7 @@ The CLI specification is managed contract-first via [`cli-contracts`](https://ww
|
|
|
593
593
|
|---------|-----|--------|
|
|
594
594
|
| `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
|
|
595
595
|
| `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Implemented |
|
|
596
|
+
| `gemini` | Google Gemini (`@google/genai`) | Implemented |
|
|
596
597
|
| `openai` | OpenAI Agents SDK (`@openai/agents`) | Implemented |
|
|
597
598
|
| `mock` | Simulated responses for testing/demo | Implemented |
|
|
598
599
|
|
|
@@ -715,6 +716,33 @@ Internally the adapter creates a fresh `Agent` for each `send()` call with the c
|
|
|
715
716
|
|
|
716
717
|
> **Note:** `@openai/agents` requires `zod@^4.0.0` as a peer dependency. This runtime uses `zod@^4.0.0` natively.
|
|
717
718
|
|
|
719
|
+
### Google Gemini adapter
|
|
720
|
+
|
|
721
|
+
The Gemini adapter wraps `@google/genai`, Google's TypeScript SDK for Gemini models.
|
|
722
|
+
|
|
723
|
+
```typescript
|
|
724
|
+
import { GeminiSdkAdapter } from "agent-contracts-runtime/adapters/gemini-sdk";
|
|
725
|
+
|
|
726
|
+
const adapter = new GeminiSdkAdapter({
|
|
727
|
+
model: "gemini-2.5-flash", // optional, defaults to gemini-2.5-flash
|
|
728
|
+
apiKey: process.env.GEMINI_API_KEY, // optional, falls back to env var
|
|
729
|
+
temperature: 0.7, // optional
|
|
730
|
+
maxOutputTokens: 8192, // optional
|
|
731
|
+
guardrailHooks, // optional guardrail enforcement
|
|
732
|
+
});
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
Internally the adapter creates a chat session via `ai.chats.create()` for each `send()` call, then calls `chat.sendMessage()`. This maintains conversation state for `followUp()` within the same chat session.
|
|
736
|
+
|
|
737
|
+
| Config option | Description | Default |
|
|
738
|
+
|---------------|-------------|---------|
|
|
739
|
+
| `apiKey` | Gemini API key (or set `GEMINI_API_KEY` env var) | Env var |
|
|
740
|
+
| `model` | Model identifier (e.g. `"gemini-2.5-flash"`, `"gemini-2.5-pro"`) | `"gemini-2.5-flash"` |
|
|
741
|
+
| `systemInstruction` | System instruction prepended to conversations | None |
|
|
742
|
+
| `temperature` | Temperature for generation (0.0–2.0) | SDK default |
|
|
743
|
+
| `maxOutputTokens` | Maximum output tokens | SDK default |
|
|
744
|
+
| `guardrailHooks` | Runtime guardrail hooks (evaluated locally on responses) | None |
|
|
745
|
+
|
|
718
746
|
## Handoff validation
|
|
719
747
|
|
|
720
748
|
The runtime validates both input and output handoffs against generated Zod schemas.
|
|
@@ -915,6 +943,7 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
|
|
|
915
943
|
| `agent-contracts-runtime/generator` | Generator API (`generate`, `checkFreshness`, `buildContractContext`) |
|
|
916
944
|
| `agent-contracts-runtime/adapters/cursor-sdk` | Cursor SDK adapter |
|
|
917
945
|
| `agent-contracts-runtime/adapters/claude-agent-sdk` | Claude Agent SDK adapter |
|
|
946
|
+
| `agent-contracts-runtime/adapters/gemini-sdk` | Google Gemini adapter |
|
|
918
947
|
| `agent-contracts-runtime/adapters/openai-agents-sdk` | OpenAI Agents SDK adapter |
|
|
919
948
|
| `agent-contracts-runtime/adapters/mock` | Mock adapter for testing |
|
|
920
949
|
|
|
@@ -925,6 +954,7 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
|
|
|
925
954
|
- `agent-contracts` (optional peer dependency for DSL resolution)
|
|
926
955
|
- `@anthropic-ai/claude-agent-sdk` (optional, for Claude adapter — requires zod ^4.0.0)
|
|
927
956
|
- `@cursor/sdk` (optional, for Cursor adapter)
|
|
957
|
+
- `@google/genai` (optional, for Gemini adapter)
|
|
928
958
|
- `@openai/agents` (optional, for OpenAI adapter — requires zod ^4.0.0)
|
|
929
959
|
|
|
930
960
|
## License
|
package/cli-contract.yaml
CHANGED
|
@@ -55,7 +55,7 @@ commandSets:
|
|
|
55
55
|
description: Default SDK adapter to configure.
|
|
56
56
|
schema:
|
|
57
57
|
type: string
|
|
58
|
-
enum: [cursor, claude, openai, mock]
|
|
58
|
+
enum: [cursor, claude, gemini, openai, mock]
|
|
59
59
|
default: mock
|
|
60
60
|
|
|
61
61
|
- name: output
|
|
@@ -188,7 +188,7 @@ commandSets:
|
|
|
188
188
|
description: SDK adapter to use. Overrides config.
|
|
189
189
|
schema:
|
|
190
190
|
type: string
|
|
191
|
-
enum: [cursor, claude, openai, mock]
|
|
191
|
+
enum: [cursor, claude, gemini, openai, mock]
|
|
192
192
|
|
|
193
193
|
- name: max-retries
|
|
194
194
|
aliases: [r]
|
|
@@ -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,eAAe,QAAQ;AAChC,qBAAO;AAAA,gBACL,eAAe;AAAA,gBACf,oBAAoB;AAAA,gBACpB,0BAA0B,OAAO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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,gBAAM,aAAa,WAAW,WAAW;AAAA,YACvC,WAAW;AAAA,YACX,YAAY,EAAE,WAAW,SAAS;AAAA,UACpC,C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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":[]}
|
|
@@ -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,YA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,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":[]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-D8b31ZL_.js';
|
|
2
|
+
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Google Gemini SDK Adapter — implements SdkAdapter for @google/genai
|
|
7
|
+
*
|
|
8
|
+
* Uses the GoogleGenAI client from @google/genai to run prompts on
|
|
9
|
+
* Gemini models (gemini-2.5-flash, gemini-2.5-pro, etc.).
|
|
10
|
+
*
|
|
11
|
+
* Supports:
|
|
12
|
+
* - send() — start a new chat session and return the result text
|
|
13
|
+
* - followUp() — continue the same chat session for output-format corrections
|
|
14
|
+
* - sendExecution() — rich path using full contract context
|
|
15
|
+
*
|
|
16
|
+
* The adapter uses the chat API (ai.chats.create + chat.sendMessage) to
|
|
17
|
+
* maintain conversation state for followUp. Each send() starts a fresh chat.
|
|
18
|
+
*
|
|
19
|
+
* GuardrailHooks are evaluated locally before returning results
|
|
20
|
+
* (Gemini does not expose a pre-tool-use hook like Claude/OpenAI).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
type GenerateContentResponse = {
|
|
24
|
+
text?: string;
|
|
25
|
+
candidates?: Array<{
|
|
26
|
+
content?: {
|
|
27
|
+
parts?: Array<{
|
|
28
|
+
text?: string;
|
|
29
|
+
}>;
|
|
30
|
+
};
|
|
31
|
+
finishReason?: string;
|
|
32
|
+
safetyRatings?: Array<{
|
|
33
|
+
category: string;
|
|
34
|
+
probability: string;
|
|
35
|
+
}>;
|
|
36
|
+
}>;
|
|
37
|
+
};
|
|
38
|
+
type ChatSendMessageResult = GenerateContentResponse;
|
|
39
|
+
type Chat = {
|
|
40
|
+
sendMessage(params: {
|
|
41
|
+
message: string;
|
|
42
|
+
}): Promise<ChatSendMessageResult>;
|
|
43
|
+
};
|
|
44
|
+
type ChatsCreateParams = {
|
|
45
|
+
model: string;
|
|
46
|
+
config?: Record<string, unknown>;
|
|
47
|
+
};
|
|
48
|
+
type GoogleGenAIClient = {
|
|
49
|
+
models: {
|
|
50
|
+
generateContent(params: {
|
|
51
|
+
model: string;
|
|
52
|
+
contents: string;
|
|
53
|
+
config?: Record<string, unknown>;
|
|
54
|
+
}): Promise<GenerateContentResponse>;
|
|
55
|
+
};
|
|
56
|
+
chats: {
|
|
57
|
+
create(params: ChatsCreateParams): Chat;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
interface GeminiSdkAdapterConfig {
|
|
61
|
+
/** API key for Gemini Developer API. Falls back to GEMINI_API_KEY env var. */
|
|
62
|
+
apiKey?: string;
|
|
63
|
+
/** Model identifier (e.g. "gemini-2.5-flash", "gemini-2.5-pro"). */
|
|
64
|
+
model?: string;
|
|
65
|
+
/** System instruction prepended to all conversations. */
|
|
66
|
+
systemInstruction?: string;
|
|
67
|
+
/** Temperature for generation (0.0–2.0). */
|
|
68
|
+
temperature?: number;
|
|
69
|
+
/** Maximum output tokens. */
|
|
70
|
+
maxOutputTokens?: number;
|
|
71
|
+
/** Runtime guardrail hooks evaluated locally on responses. */
|
|
72
|
+
guardrailHooks?: GuardrailHooks;
|
|
73
|
+
}
|
|
74
|
+
declare class GeminiSdkAdapter implements SdkAdapter {
|
|
75
|
+
private apiKey;
|
|
76
|
+
private model;
|
|
77
|
+
private systemInstruction;
|
|
78
|
+
private temperature;
|
|
79
|
+
private maxOutputTokens;
|
|
80
|
+
private guardrailHooks;
|
|
81
|
+
private lastChat;
|
|
82
|
+
private client;
|
|
83
|
+
private ClientClass;
|
|
84
|
+
constructor(config?: GeminiSdkAdapterConfig);
|
|
85
|
+
private resolveClient;
|
|
86
|
+
private buildGenerationConfig;
|
|
87
|
+
private createChat;
|
|
88
|
+
send(prompt: string, _options: AdapterSendOptions): Promise<string>;
|
|
89
|
+
followUp(message: string): Promise<string>;
|
|
90
|
+
sendExecution(request: AgentExecutionRequest): Promise<string>;
|
|
91
|
+
/**
|
|
92
|
+
* Inject a custom GoogleGenAI client for testing.
|
|
93
|
+
* Bypasses the dynamic import of @google/genai and API key requirement.
|
|
94
|
+
*/
|
|
95
|
+
static withClient(client: GoogleGenAIClient, config?: GeminiSdkAdapterConfig): GeminiSdkAdapter;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export { GeminiSdkAdapter, type GeminiSdkAdapterConfig };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// src/adapters/gemini-sdk.ts
|
|
2
|
+
function extractText(response) {
|
|
3
|
+
if (response.text) return response.text;
|
|
4
|
+
if (response.candidates?.length) {
|
|
5
|
+
const parts = response.candidates[0].content?.parts;
|
|
6
|
+
if (parts?.length) {
|
|
7
|
+
return parts.map((p) => p.text ?? "").join("");
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
return "";
|
|
11
|
+
}
|
|
12
|
+
function checkSafetyBlock(response) {
|
|
13
|
+
const candidate = response.candidates?.[0];
|
|
14
|
+
if (candidate?.finishReason === "SAFETY") {
|
|
15
|
+
const blocked = candidate.safetyRatings?.filter((r) => r.probability === "HIGH").map((r) => r.category).join(", ");
|
|
16
|
+
throw new Error(
|
|
17
|
+
`Gemini response blocked by safety filters: ${blocked || "unknown category"}`
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
var GeminiSdkAdapter = class _GeminiSdkAdapter {
|
|
22
|
+
apiKey;
|
|
23
|
+
model;
|
|
24
|
+
systemInstruction;
|
|
25
|
+
temperature;
|
|
26
|
+
maxOutputTokens;
|
|
27
|
+
guardrailHooks;
|
|
28
|
+
lastChat = null;
|
|
29
|
+
client = null;
|
|
30
|
+
ClientClass = null;
|
|
31
|
+
constructor(config = {}) {
|
|
32
|
+
this.apiKey = config.apiKey;
|
|
33
|
+
this.model = config.model ?? "gemini-2.5-flash";
|
|
34
|
+
this.systemInstruction = config.systemInstruction;
|
|
35
|
+
this.temperature = config.temperature;
|
|
36
|
+
this.maxOutputTokens = config.maxOutputTokens;
|
|
37
|
+
this.guardrailHooks = config.guardrailHooks;
|
|
38
|
+
}
|
|
39
|
+
// -------------------------------------------------------------------------
|
|
40
|
+
// Internal helpers
|
|
41
|
+
// -------------------------------------------------------------------------
|
|
42
|
+
async resolveClient() {
|
|
43
|
+
if (this.client) return this.client;
|
|
44
|
+
if (!this.ClientClass) {
|
|
45
|
+
const sdk = await import("@google/genai");
|
|
46
|
+
this.ClientClass = sdk.GoogleGenAI;
|
|
47
|
+
}
|
|
48
|
+
const apiKey = this.apiKey ?? process.env.GEMINI_API_KEY;
|
|
49
|
+
if (!apiKey) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
"GEMINI_API_KEY environment variable or apiKey config is required for the Gemini adapter"
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
this.client = new this.ClientClass({ apiKey });
|
|
55
|
+
return this.client;
|
|
56
|
+
}
|
|
57
|
+
buildGenerationConfig() {
|
|
58
|
+
const config = {};
|
|
59
|
+
if (this.systemInstruction) {
|
|
60
|
+
config.systemInstruction = this.systemInstruction;
|
|
61
|
+
}
|
|
62
|
+
if (this.temperature !== void 0) {
|
|
63
|
+
config.temperature = this.temperature;
|
|
64
|
+
}
|
|
65
|
+
if (this.maxOutputTokens !== void 0) {
|
|
66
|
+
config.maxOutputTokens = this.maxOutputTokens;
|
|
67
|
+
}
|
|
68
|
+
return config;
|
|
69
|
+
}
|
|
70
|
+
createChat(client) {
|
|
71
|
+
return client.chats.create({
|
|
72
|
+
model: this.model,
|
|
73
|
+
config: this.buildGenerationConfig()
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
// -------------------------------------------------------------------------
|
|
77
|
+
// SdkAdapter interface
|
|
78
|
+
// -------------------------------------------------------------------------
|
|
79
|
+
async send(prompt, _options) {
|
|
80
|
+
this.lastChat = null;
|
|
81
|
+
const client = await this.resolveClient();
|
|
82
|
+
const chat = this.createChat(client);
|
|
83
|
+
const response = await chat.sendMessage({ message: prompt });
|
|
84
|
+
checkSafetyBlock(response);
|
|
85
|
+
this.lastChat = chat;
|
|
86
|
+
return extractText(response);
|
|
87
|
+
}
|
|
88
|
+
async followUp(message) {
|
|
89
|
+
if (!this.lastChat) {
|
|
90
|
+
throw new Error("followUp() called before send() \u2014 no active session");
|
|
91
|
+
}
|
|
92
|
+
const response = await this.lastChat.sendMessage({ message });
|
|
93
|
+
checkSafetyBlock(response);
|
|
94
|
+
return extractText(response);
|
|
95
|
+
}
|
|
96
|
+
async sendExecution(request) {
|
|
97
|
+
this.lastChat = null;
|
|
98
|
+
const client = await this.resolveClient();
|
|
99
|
+
const chat = this.createChat(client);
|
|
100
|
+
const response = await chat.sendMessage({ message: request.prompt });
|
|
101
|
+
checkSafetyBlock(response);
|
|
102
|
+
this.lastChat = chat;
|
|
103
|
+
return extractText(response);
|
|
104
|
+
}
|
|
105
|
+
// -------------------------------------------------------------------------
|
|
106
|
+
// Test support
|
|
107
|
+
// -------------------------------------------------------------------------
|
|
108
|
+
/**
|
|
109
|
+
* Inject a custom GoogleGenAI client for testing.
|
|
110
|
+
* Bypasses the dynamic import of @google/genai and API key requirement.
|
|
111
|
+
*/
|
|
112
|
+
static withClient(client, config) {
|
|
113
|
+
const adapter = new _GeminiSdkAdapter(config);
|
|
114
|
+
adapter.client = client;
|
|
115
|
+
return adapter;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
export {
|
|
119
|
+
GeminiSdkAdapter
|
|
120
|
+
};
|
|
121
|
+
//# sourceMappingURL=gemini-sdk.js.map
|
|
@@ -0,0 +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 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,QAAQ,OAAO,SAAS;AAC7B,SAAK,oBAAoB,OAAO;AAChC,SAAK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AU;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":[]}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-D8b31ZL_.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,QACA,KAAK,UAAU,KAAK;AAExB,cAAM,UAAU,WAAW,UAAU,EAAE,SAAS,SAAS,CAAC;AAC1D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OAAO,QAAQ,OAAO;AAE/C,SAAK,iBAAiB,OAAO,kBAAkB;AAC/C,SAAK,YAAY;AAEjB,WAAO,KAAK,cAAc,MAAM;AAAA,EAClC;AAAA,EAEA,MAAM,SAAS,SAAkC;AAC/C,QAAI,CAAC,KAAK,gBAAgB;AACxB,YAAM,IAAI,MAAM,0DAAqD;AAAA,IACvE;AAEA,UAAM,EAAE,IAAI,IAAI,MAAM,KAAK,WAAW;AACtC,UAAM,QAAQ,KAAK;AACnB,UAAM,UAAU,KAAK,gBAAgB,KAAK,cAAc;AAExD,UAAM,SAAS,MAAM,IAAI,OAAO,SAAS,OAAO;AAEhD,SAAK,iBAAiB,OAAO,kBAAkB,KAAK;AAEpD,WAAO,KAAK,cAAc,MAAM;AAAA,EAClC;AAAA,EAEA,MAAM,cAAc,SAAiD;AACnE,SAAK,iBAAiB;AACtB,SAAK,YAAY;AAEjB,UAAM,EAAE,OAAO,IAAI,IAAI,MAAM,KAAK,WAAW;AAC7C,UAAM,QAAQ,KAAK,YAAY,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ;AAC9E,UAAM,UAAU,KAAK,gBAAgB;AAErC,UAAM,SAAS,MAAM,IAAI,OAAO,QAAQ,QAAQ,OAAO;AAEvD,SAAK,iBAAiB,OAAO,kBAAkB;AAC/C,SAAK,YAAY;AAEjB,WAAO,KAAK,cAAc,MAAM;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,UACL,YACA,OACA,QACwB;AACxB,UAAM,UAAU,IAAI,wBAAuB,MAAM;AACjD,YAAQ,aAAa;AACrB,YAAQ,QAAQ;AAChB,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/cli/index.js
CHANGED
|
@@ -365,7 +365,7 @@ async function runInit(options) {
|
|
|
365
365
|
|
|
366
366
|
// src/cli/index.ts
|
|
367
367
|
import YAML3 from "yaml";
|
|
368
|
-
var VERSION = "0.
|
|
368
|
+
var VERSION = "0.11.0";
|
|
369
369
|
async function loadGeneratedContracts(configPath) {
|
|
370
370
|
const config = await loadConfig(configPath);
|
|
371
371
|
const basePath = `${config.generatedDir}/index`;
|
|
@@ -410,6 +410,10 @@ async function createAdapter(adapterName, guardrailHooks) {
|
|
|
410
410
|
const { ClaudeAgentSdkAdapter } = await import("../adapters/claude-agent-sdk.js");
|
|
411
411
|
return new ClaudeAgentSdkAdapter({ guardrailHooks });
|
|
412
412
|
}
|
|
413
|
+
case "gemini": {
|
|
414
|
+
const { GeminiSdkAdapter } = await import("../adapters/gemini-sdk.js");
|
|
415
|
+
return new GeminiSdkAdapter({ guardrailHooks });
|
|
416
|
+
}
|
|
413
417
|
case "cursor": {
|
|
414
418
|
const { CursorSdkAdapter } = await import("../adapters/cursor-sdk.js");
|
|
415
419
|
const apiKey = process.env.CURSOR_API_KEY;
|
|
@@ -419,7 +423,7 @@ async function createAdapter(adapterName, guardrailHooks) {
|
|
|
419
423
|
return CursorSdkAdapter.create({ apiKey, guardrailHooks });
|
|
420
424
|
}
|
|
421
425
|
default:
|
|
422
|
-
throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, cursor`);
|
|
426
|
+
throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, cursor`);
|
|
423
427
|
}
|
|
424
428
|
}
|
|
425
429
|
function formatTable(headers, rows) {
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.ts","../../src/lib/doctor.ts","../../src/lib/init.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\nimport { generate, loadConfig, checkFreshness } from \"../generator/index.js\";\nimport {\n buildTaskPrompt,\n pluginRegistry,\n runWorkflow,\n type AgentContractLike,\n type TaskContractLike,\n type SdkAdapter,\n type WorkflowContractLike,\n type WorkflowInvocation,\n type GuardrailHooks,\n} from \"../index.js\";\nimport { loadPlugins } from \"../lib/plugin-loader.js\";\nimport { runDoctor } from \"../lib/doctor.js\";\nimport { runInit } from \"../lib/init.js\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst VERSION = \"0.10.0\";\n\n/**\n * Dynamically import the generated contracts from the configured generated_dir.\n * Handles both .ts (via tsx/ts-node) and .js (compiled) files,\n * and both flat exports and namespace exports.\n */\nasync function loadGeneratedContracts(configPath: string): Promise<{\n agentRegistry: Record<string, AgentContractLike>;\n taskRegistry: Record<string, TaskContractLike>;\n handoffSchemas: Record<string, z.ZodType>;\n workflowRegistry: Record<string, WorkflowContractLike>;\n guardrailHooks?: GuardrailHooks;\n}> {\n const config = await loadConfig(configPath);\n const basePath = `${config.generatedDir}/index`;\n\n let indexPath: string;\n if (existsSync(`${basePath}.js`)) {\n indexPath = `${basePath}.js`;\n } else if (existsSync(`${basePath}.ts`)) {\n indexPath = `${basePath}.ts`;\n } else {\n throw new Error(\n `Generated index file not found at ${basePath}.{js,ts}. Run \\`agent-runtime generate\\` first.`,\n );\n }\n\n const mod = await import(new URL(`file://${indexPath}`).href);\n\n let guardrailHooks: GuardrailHooks | undefined;\n const hooksBasePath = `${config.generatedDir}/hooks/index`;\n const hooksPath = existsSync(`${hooksBasePath}.js`)\n ? `${hooksBasePath}.js`\n : existsSync(`${hooksBasePath}.ts`)\n ? `${hooksBasePath}.ts`\n : null;\n if (hooksPath) {\n try {\n const hooksMod = await import(new URL(`file://${hooksPath}`).href);\n if (hooksMod.guardrailHooks) {\n guardrailHooks = hooksMod.guardrailHooks;\n }\n } catch {\n // Guardrail hooks not available — continue without them\n }\n }\n\n return {\n agentRegistry: mod.agentRegistry ?? mod.agents?.agentRegistry ?? {},\n taskRegistry: mod.taskRegistry ?? mod.tasks?.taskRegistry ?? {},\n handoffSchemas: mod.handoffSchemas ?? mod.handoffs?.handoffSchemas ?? {},\n workflowRegistry: mod.workflowRegistry ?? mod.workflows?.workflowRegistry ?? {},\n guardrailHooks,\n };\n}\n\nasync function createAdapter(adapterName: string, guardrailHooks?: GuardrailHooks): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({ guardrailHooks });\n }\n case \"cursor\": {\n const { CursorSdkAdapter } = await import(\"../adapters/cursor-sdk.js\");\n const apiKey = process.env.CURSOR_API_KEY;\n if (!apiKey) {\n throw new Error(\"CURSOR_API_KEY environment variable is required for the cursor adapter\");\n }\n return CursorSdkAdapter.create({ apiKey, guardrailHooks });\n }\n default:\n throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, cursor`);\n }\n}\n\nfunction formatTable(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n const sep = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const pad = (s: string, w: number) => s.padEnd(w);\n const headerLine = headers.map((h, i) => pad(h, widths[i])).join(\" \");\n const dataLines = rows.map((r) =>\n r.map((c, i) => pad(c ?? \"\", widths[i])).join(\" \"),\n );\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n try {\n const outputDir = resolve(options.output ?? \".\");\n const result = await runInit({\n adapter: options.adapter ?? \"mock\",\n outputDir,\n force: options.force ?? false,\n });\n console.log(JSON.stringify(result, null, 2));\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n },\n\n async generate(options, globalOpts) {\n try {\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n const result = await generate({\n clean: options.clean,\n check: options.check,\n templates: options.templates,\n configPath,\n });\n\n if (result.checkMode) {\n if (result.hasDifferences) {\n console.error(\"Generated files are out of date. Run `agent-runtime generate` to update.\");\n process.exit(1);\n }\n console.log(JSON.stringify({ ...result, status: \"up-to-date\" }, null, 2));\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n } catch (err) {\n console.error(\"Generate failed:\", (err as Error).message);\n process.exit(1);\n }\n },\n\n async run(workflowId, userRequest, options, globalOpts) {\n // --- Resolve input: --file takes precedence over positional args ---\n let resolvedWorkflowId = workflowId;\n let resolvedUserRequest = userRequest;\n let fileInvocation: WorkflowInvocation | undefined;\n\n if (options.file) {\n try {\n const raw = readFileSync(options.file, \"utf8\");\n const parsed = YAML.parse(raw) as Record<string, unknown>;\n resolvedWorkflowId = parsed.workflow as string;\n if (!resolvedWorkflowId) {\n console.error(`Error: invocation file \"${options.file}\" must contain a \"workflow\" field.`);\n process.exit(1);\n }\n fileInvocation = {\n workflow: resolvedWorkflowId,\n user_request: parsed.user_request as string | undefined,\n handoff: parsed.handoff as WorkflowInvocation[\"handoff\"],\n runtime: parsed.runtime as WorkflowInvocation[\"runtime\"],\n };\n resolvedUserRequest = fileInvocation.user_request ?? \"\";\n } catch (err) {\n console.error(`Failed to read invocation file: ${(err as Error).message}`);\n process.exit(1);\n }\n }\n\n if (!resolvedWorkflowId) {\n console.error(\"Error: workflow-id is required (provide as argument or via --file)\");\n process.exit(1);\n }\n if (!fileInvocation && !resolvedUserRequest) {\n console.error(\"Error: user-request is required (provide as argument or via --file)\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n const fresh = await checkFreshness(configPath);\n if (!fresh) {\n console.error(\"Generated files are stale or missing. Run `agent-runtime generate` first.\");\n process.exit(3);\n }\n\n const config = await loadConfig(configPath);\n\n const pluginResult = await loadPlugins({\n pluginPaths: config.pluginPaths.length > 0 ? config.pluginPaths : undefined,\n projectDir: config.configDir,\n });\n if (pluginResult.loaded > 0 && !(globalOpts.quiet as boolean)) {\n console.error(`Loaded ${pluginResult.loaded} plugin(s) from ${pluginResult.files.length} file(s)`);\n }\n for (const err of pluginResult.errors) {\n console.error(`Plugin load error (${err.file}): ${err.error}`);\n }\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n process.exit(1);\n return;\n }\n\n if (!contracts.workflowRegistry[resolvedWorkflowId]) {\n console.error(`Unknown workflow: ${resolvedWorkflowId}`);\n console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const adapterName = (options.adapter as string) ?? \"mock\";\n let adapter: SdkAdapter;\n try {\n adapter = await createAdapter(adapterName, contracts.guardrailHooks);\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n return;\n }\n\n const recovery = config.recovery;\n const maxRetries = options.maxRetries\n ? parseInt(options.maxRetries, 10)\n : undefined;\n const maxFollowUps = options.maxFollowUps\n ? parseInt(options.maxFollowUps, 10)\n : undefined;\n\n const registries = {\n workflowRegistry: contracts.workflowRegistry,\n taskRegistry: contracts.taskRegistry,\n agentRegistry: contracts.agentRegistry,\n handoffSchemas: contracts.handoffSchemas,\n };\n\n const onGate = options.autoApproveGates\n ? async () => true\n : async (gateKind: string, description: string) => {\n console.error(`Gate \"${gateKind}\": ${description}`);\n console.error(\"Use --auto-approve-gates to auto-approve. Rejecting by default.\");\n return false;\n };\n\n let result;\n if (fileInvocation) {\n const invocation: WorkflowInvocation = {\n ...fileInvocation,\n runtime: {\n ...fileInvocation.runtime,\n maxFollowUps: maxFollowUps ?? fileInvocation.runtime?.maxFollowUps ?? recovery.max_follow_ups,\n maxRetries: maxRetries ?? fileInvocation.runtime?.maxRetries ?? recovery.max_retries,\n },\n hooks: { onGate },\n };\n result = await runWorkflow(adapter, invocation, registries);\n } else {\n result = await runWorkflow(adapter, resolvedWorkflowId, {\n user_request: resolvedUserRequest!,\n maxRetries: maxRetries ?? recovery.max_retries,\n maxFollowUps: maxFollowUps ?? recovery.max_follow_ups,\n onGate,\n }, registries);\n }\n\n console.log(JSON.stringify(result, null, 2));\n\n if (result.status !== \"completed\") {\n process.exit(1);\n }\n },\n\n async list(resource, options, globalOpts) {\n if (!resource) {\n console.error(\"Error: resource is required (workflows, tasks, agents)\");\n process.exit(1);\n }\n\n const validResources = [\"workflows\", \"tasks\", \"agents\"];\n if (!validResources.includes(resource)) {\n console.error(`Unknown resource: ${resource}`);\n console.error(`Available resources: ${validResources.join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const format = options.format ?? \"table\";\n\n if (resource === \"agents\") {\n const agents = Object.values(contracts.agentRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n if (agents.length === 0) {\n console.log(\"No agents defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Role\", \"Mode\", \"Purpose\"],\n agents.map((a) => [a.id, a.role_name, a.mode, a.purpose]),\n ));\n }\n } else if (resource === \"tasks\") {\n const tasks = Object.values(contracts.taskRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(tasks, null, 2));\n } else {\n if (tasks.length === 0) {\n console.log(\"No tasks defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Agent\", \"Description\"],\n tasks.map((t) => [t.id, t.target_agent, t.description]),\n ));\n }\n } else {\n const workflows = Object.values(contracts.workflowRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n if (workflows.length === 0) {\n console.log(\"No workflows defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Steps\", \"Description\"],\n workflows.map((w) => [w.id, String(w.steps.length), w.description]),\n ));\n }\n }\n },\n\n async showPrompt(taskId, options, globalOpts) {\n if (!taskId) {\n console.error(\"Error: task-id is required\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const task = contracts.taskRegistry[taskId];\n if (!task) {\n console.error(`Unknown task: ${taskId}`);\n console.error(`Available tasks: ${Object.keys(contracts.taskRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const agent = contracts.agentRegistry[task.target_agent];\n if (!agent) {\n console.error(`Unknown agent: ${task.target_agent} (referenced by task ${taskId})`);\n process.exit(1);\n return;\n }\n\n const pluginsApplied = options.withPlugins ?? false;\n if (pluginsApplied) {\n const showPromptConfig = await loadConfig(configPath);\n await loadPlugins({\n pluginPaths: showPromptConfig.pluginPaths.length > 0 ? showPromptConfig.pluginPaths : undefined,\n projectDir: showPromptConfig.configDir,\n });\n }\n\n const userRequest = options.userRequest ?? \"(preview)\";\n let prompt = buildTaskPrompt(agent, task, { user_request: userRequest }, {\n handoffSchemas: contracts.handoffSchemas,\n });\n\n if (pluginsApplied) {\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, { user_request: userRequest });\n }\n\n const format = options.format ?? \"markdown\";\n if (format === \"json\") {\n console.log(JSON.stringify({\n task_id: taskId,\n agent_id: task.target_agent,\n prompt,\n handoff_schema: task.result_handoff,\n plugins_applied: pluginsApplied,\n }, null, 2));\n } else {\n console.log(prompt);\n }\n },\n\n async doctor(globalOpts) {\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n const result = await runDoctor(configPath);\n\n const statusIcon = (s: string) =>\n s === \"pass\" ? \"✓\" : s === \"warn\" ? \"!\" : \"✗\";\n\n for (const check of result.checks) {\n const icon = statusIcon(check.status);\n const msg = check.message ? ` ${check.message}` : \"\";\n console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg}`);\n }\n\n console.log(\"\");\n if (result.allPassed) {\n console.log(\"All checks passed.\");\n } else {\n console.log(\"Some checks failed.\");\n }\n\n console.log(JSON.stringify(result));\n\n if (!result.allPassed) {\n process.exitCode = 1;\n }\n },\n\n};\n\nconst program = createProgram(handlers, VERSION);\nawait program.parseAsync();\n","// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean; templates?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; maxFollowUps?: string; dryRun?: boolean; autoApproveGates?: boolean; file?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n showPrompt: (taskId: string | undefined, options: { userRequest?: string; format?: string; withPlugins?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .option(\"-t, --templates <value>\", \"Custom templates directory. Overrides built-in templates.\")\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"[workflow-id]\", \"ID of the workflow to execute. Required unless --file is used.\")\n .argument(\"[user-request]\", \"Natural language description of what to do. Required unless --file is used.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-f, --max-follow-ups <value>\", \"Override default max follow-ups per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .option(\"--file <value>\", \"Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n\")\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"show-prompt\")\n .description(\"Display the generated prompt for a task.\")\n .argument(\"<task-id>\", \"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\")\n .option(\"-u, --user-request <value>\", \"User request text to include in the prompt preview.\", \"(preview)\")\n .option(\"--format <value>\", \"Output format.\", \"markdown\")\n .option(\"--with-plugins\", \"Apply registered plugin prompt enhancers to the output.\", false)\n .action(async (taskId, opts, cmd) => {\n await handlers.showPrompt(taskId, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","/**\n * Doctor — diagnostic checks for agent-contracts-runtime configuration health\n *\n * Each check returns a DoctorCheck with pass/fail/warn status.\n * The runner collects all checks and determines overall health.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { loadConfig, RuntimeConfigSchema, type ResolvedConfig } from \"../generator/config.js\";\nimport { checkFreshness } from \"../generator/index.js\";\n\nexport interface DoctorCheck {\n name: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n allPassed: boolean;\n}\n\nconst ADAPTER_ENV_VARS: Record<string, string> = {\n cursor: \"CURSOR_API_KEY\",\n claude: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n};\n\nasync function checkConfigExists(configPath: string): Promise<{ check: DoctorCheck; config?: ResolvedConfig }> {\n try {\n const config = await loadConfig(configPath);\n return {\n check: { name: \"config_exists\", status: \"pass\", message: `Loaded ${configPath}` },\n config,\n };\n } catch (err) {\n const absPath = resolve(configPath);\n if (!existsSync(absPath)) {\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config file not found: ${absPath}` },\n };\n }\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config parse error: ${(err as Error).message}` },\n };\n }\n}\n\nasync function checkDslExists(config: ResolvedConfig): Promise<DoctorCheck> {\n if (!existsSync(config.dslPath)) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL file not found: ${config.dslPath}` };\n }\n\n try {\n const raw = await readFile(config.dslPath, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return { name: \"dsl_exists\", status: \"fail\", message: \"DSL file is empty or not a valid YAML object\" };\n }\n const agentCount = Object.keys(parsed.agents ?? {}).length;\n const taskCount = Object.keys(parsed.tasks ?? {}).length;\n const workflowCount = Object.keys(parsed.workflow ?? {}).length;\n return {\n name: \"dsl_exists\",\n status: \"pass\",\n message: `Parsed OK — ${agentCount} agent(s), ${taskCount} task(s), ${workflowCount} workflow(s)`,\n };\n } catch (err) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL parse error: ${(err as Error).message}` };\n }\n}\n\nasync function checkManifestFresh(configPath: string, config: ResolvedConfig): Promise<DoctorCheck> {\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n if (!existsSync(manifestPath)) {\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated manifest not found. Run `agent-runtime generate` first.\",\n };\n }\n\n try {\n const fresh = await checkFreshness(configPath);\n if (fresh) {\n return { name: \"manifest_fresh\", status: \"pass\", message: \"Generated files are up to date\" };\n }\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated files are stale. Run `agent-runtime generate` to update.\",\n };\n } catch (err) {\n return { name: \"manifest_fresh\", status: \"fail\", message: `Freshness check error: ${(err as Error).message}` };\n }\n}\n\nfunction checkAdapterConfigured(): DoctorCheck {\n const configured: string[] = [];\n const missing: string[] = [];\n\n for (const [adapter, envVar] of Object.entries(ADAPTER_ENV_VARS)) {\n if (process.env[envVar]) {\n configured.push(adapter);\n } else {\n missing.push(`${adapter} (${envVar})`);\n }\n }\n\n if (configured.length > 0) {\n return {\n name: \"adapter_configured\",\n status: \"pass\",\n message: `Configured: ${configured.join(\", \")}${missing.length > 0 ? ` | Not set: ${missing.join(\", \")}` : \"\"}`,\n };\n }\n\n return {\n name: \"adapter_configured\",\n status: \"warn\",\n message: `No SDK adapter API keys found. Set one of: ${Object.entries(ADAPTER_ENV_VARS).map(([a, e]) => `${e} (${a})`).join(\", \")}`,\n };\n}\n\nfunction checkPluginEntrypoints(config: ResolvedConfig): DoctorCheck {\n if (config.pluginPaths.length === 0) {\n return { name: \"plugin_entrypoint\", status: \"pass\", message: \"No plugins configured\" };\n }\n\n const missing: string[] = [];\n for (const p of config.pluginPaths) {\n const absPath = resolve(config.configDir, p);\n if (!existsSync(absPath)) {\n missing.push(p);\n }\n }\n\n if (missing.length === 0) {\n return {\n name: \"plugin_entrypoint\",\n status: \"pass\",\n message: `All ${config.pluginPaths.length} plugin file(s) found`,\n };\n }\n\n return {\n name: \"plugin_entrypoint\",\n status: \"fail\",\n message: `Missing plugin file(s): ${missing.join(\", \")}`,\n };\n}\n\nasync function checkBindingsValid(config: ResolvedConfig): Promise<DoctorCheck> {\n if (config.bindingPaths.length === 0) {\n return { name: \"bindings_valid\", status: \"pass\", message: \"No bindings configured\" };\n }\n\n const errors: string[] = [];\n for (const bp of config.bindingPaths) {\n if (!existsSync(bp)) {\n errors.push(`Not found: ${bp}`);\n continue;\n }\n try {\n const raw = await readFile(bp, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n errors.push(`Invalid YAML object: ${bp}`);\n }\n } catch (err) {\n errors.push(`Parse error in ${bp}: ${(err as Error).message}`);\n }\n }\n\n if (errors.length === 0) {\n return {\n name: \"bindings_valid\",\n status: \"pass\",\n message: `All ${config.bindingPaths.length} binding file(s) valid`,\n };\n }\n\n return {\n name: \"bindings_valid\",\n status: \"fail\",\n message: errors.join(\"; \"),\n };\n}\n\nexport async function runDoctor(configPath: string): Promise<DoctorResult> {\n const checks: DoctorCheck[] = [];\n\n // 1. Config exists and parses\n const configResult = await checkConfigExists(configPath);\n checks.push(configResult.check);\n\n if (!configResult.config) {\n return { checks, allPassed: false };\n }\n\n const config = configResult.config;\n\n // 2–6 can run concurrently since they only read state\n const [dslCheck, manifestCheck, pluginCheck, bindingsCheck] = await Promise.all([\n checkDslExists(config),\n checkManifestFresh(configPath, config),\n Promise.resolve(checkPluginEntrypoints(config)),\n checkBindingsValid(config),\n ]);\n\n checks.push(dslCheck);\n checks.push(manifestCheck);\n checks.push(checkAdapterConfigured());\n checks.push(pluginCheck);\n checks.push(bindingsCheck);\n\n const allPassed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, allPassed };\n}\n","/**\n * init — scaffold a new agent-contracts-runtime project\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile, readFile, appendFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport YAML from \"yaml\";\n\nexport interface InitOptions {\n adapter: string;\n outputDir: string;\n force: boolean;\n}\n\nexport interface InitResult {\n filesCreated: string[];\n}\n\ninterface FileEntry {\n relativePath: string;\n content: string;\n}\n\nfunction buildConfigYaml(adapter: string): string {\n return YAML.stringify(\n {\n dsl: \"./agent-contracts.yaml\",\n generated_dir: \"./agent/generated\",\n plugins: [\"./agent/src/plugins/example-plugin.ts\"],\n recovery: {\n max_follow_ups: 2,\n max_retries: 0,\n },\n },\n { lineWidth: 0 },\n );\n}\n\nconst EXAMPLE_PLUGIN_TS = `\\\nimport type { AgentPlugin } from \"agent-contracts-runtime\";\n\n/**\n * Example plugin — extend agent-contracts-runtime with custom hooks.\n *\n * Register lifecycle hooks for tasks and workflows:\n * beforeTask / afterTask — pre/post-process task execution\n * contextEnhancer — augment task context before prompt generation\n * promptEnhancer — post-process generated prompts\n * customGuardrails — add project-specific guardrail checks\n * beforeWorkflow / afterWorkflow — workflow lifecycle hooks\n *\n * See https://github.com/foo-ogawa/agent-contracts-runtime#plugins\n */\nexport const examplePlugin: AgentPlugin = {\n id: \"example-plugin\",\n\n // Uncomment hooks as needed:\n\n // async beforeTask(taskId, context) {\n // console.log(\\`[example-plugin] beforeTask: \\${taskId}\\`);\n // return context;\n // },\n\n // async afterTask(taskId, outcome) {\n // console.log(\\`[example-plugin] afterTask: \\${taskId} — \\${outcome.status}\\`);\n // return outcome;\n // },\n\n // promptEnhancer(taskId, prompt, _context) {\n // return prompt + \"\\\\n\\\\n<!-- enhanced by example-plugin -->\";\n // },\n};\n\nexport default examplePlugin;\n`;\n\nconst CUSTOM_GUARDRAILS_TS = `\\\nimport type { AgentPlugin, GuardrailResult } from \"agent-contracts-runtime\";\n\n/**\n * Custom guardrails — project-specific safety checks.\n *\n * Implement evaluateCommand, evaluateFilePath, or evaluateFileContent\n * to enforce project rules beyond the built-in guardrails.\n *\n * See https://github.com/foo-ogawa/agent-contracts-runtime#guardrails\n */\nexport const customGuardrailsPlugin: AgentPlugin = {\n id: \"custom-guardrails\",\n\n customGuardrails: {\n // evaluateCommand(command: string): GuardrailResult[] {\n // const results: GuardrailResult[] = [];\n // // Example: block dangerous patterns\n // if (command.includes(\"DROP TABLE\")) {\n // results.push({\n // matched: true,\n // guardrail_id: \"no-drop-table\",\n // severity: \"critical\",\n // action: \"block\",\n // message: \"DROP TABLE is forbidden\",\n // });\n // }\n // return results;\n // },\n },\n};\n\nexport default customGuardrailsPlugin;\n`;\n\nconst GITIGNORE_ENTRIES = [\n \"\",\n \"# agent-contracts-runtime generated files\",\n \"agent/generated/\",\n];\n\nfunction buildScaffoldFiles(adapter: string): FileEntry[] {\n return [\n {\n relativePath: \"agent-runtime.config.yaml\",\n content: buildConfigYaml(adapter),\n },\n {\n relativePath: \"agent/src/plugins/example-plugin.ts\",\n content: EXAMPLE_PLUGIN_TS,\n },\n {\n relativePath: \"agent/src/guardrails/custom-guardrails.ts\",\n content: CUSTOM_GUARDRAILS_TS,\n },\n ];\n}\n\nexport async function runInit(options: InitOptions): Promise<InitResult> {\n const { adapter, outputDir, force } = options;\n const filesCreated: string[] = [];\n\n const entries = buildScaffoldFiles(adapter);\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n if (!force && existsSync(absPath)) {\n throw new Error(\n `File already exists: ${entry.relativePath}. Use --force to overwrite.`,\n );\n }\n }\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n const dir = join(absPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(absPath, entry.content, \"utf8\");\n filesCreated.push(entry.relativePath);\n }\n\n const gitignorePath = join(outputDir, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const existing = await readFile(gitignorePath, \"utf8\");\n if (!existing.includes(\"agent/generated/\")) {\n await appendFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\") + \"\\n\", \"utf8\");\n filesCreated.push(\".gitignore\");\n }\n } else {\n await writeFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\").trimStart() + \"\\n\", \"utf8\");\n filesCreated.push(\".gitignore\");\n }\n\n return { filesCreated };\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,WAAAC,gBAAe;;;ACRxB,SAAS,eAAe;AAWjB,SAAS,cACdC,WACA,SACS;AACT,QAAMC,WAAU,IAAI,QAAQ;AAC5B,EAAAA,SACG,KAAK,eAAe,EACpB,QAAQ,SAAS,eAAe,EAChC,YAAY,mFAA8E;AAE7F,EAAAA,SAAQ,OAAO,wBAAwB,sCAAsC,6BAA6B;AAC1G,EAAAA,SAAQ,OAAO,iBAAiB,0BAA0B,KAAK;AAC/D,EAAAA,SAAQ,OAAO,eAAe,8BAA8B,KAAK;AAEjE,EAAAA,SACG,QAAQ,MAAM,EACd,YAAY,+CAA+C,EAC3D,OAAO,yBAAyB,qCAAqC,MAAM,EAC3E,OAAO,wBAAwB,+CAA+C,GAAG,EACjF,OAAO,eAAe,+CAA+C,KAAK,EAC1E,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,KAAK,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACjD,CAAC;AAEH,EAAAC,SACG,QAAQ,UAAU,EAClB,YAAY,gDAAgD,EAC5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AQ,IAAI,EAAE;AACd,QAAI,OAAO,WAAW;AACpB,cAAQ,IAAI,oBAAoB;AAAA,IAClC,OAAO;AACL,cAAQ,IAAI,qBAAqB;AAAA,IACnC;AAEA,YAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;AAElC,QAAI,CAAC,OAAO,WAAW;AACrB,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AAEF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,MAAM,QAAQ,WAAW;","names":["existsSync","resolve","handlers","program","existsSync","readFile","join","YAML","YAML","existsSync","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.ts","../../src/lib/doctor.ts","../../src/lib/init.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\nimport { generate, loadConfig, checkFreshness } from \"../generator/index.js\";\nimport {\n buildTaskPrompt,\n pluginRegistry,\n runWorkflow,\n type AgentContractLike,\n type TaskContractLike,\n type SdkAdapter,\n type WorkflowContractLike,\n type WorkflowInvocation,\n type GuardrailHooks,\n} from \"../index.js\";\nimport { loadPlugins } from \"../lib/plugin-loader.js\";\nimport { runDoctor } from \"../lib/doctor.js\";\nimport { runInit } from \"../lib/init.js\";\nimport type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst VERSION = \"0.11.0\";\n\n/**\n * Dynamically import the generated contracts from the configured generated_dir.\n * Handles both .ts (via tsx/ts-node) and .js (compiled) files,\n * and both flat exports and namespace exports.\n */\nasync function loadGeneratedContracts(configPath: string): Promise<{\n agentRegistry: Record<string, AgentContractLike>;\n taskRegistry: Record<string, TaskContractLike>;\n handoffSchemas: Record<string, z.ZodType>;\n workflowRegistry: Record<string, WorkflowContractLike>;\n guardrailHooks?: GuardrailHooks;\n}> {\n const config = await loadConfig(configPath);\n const basePath = `${config.generatedDir}/index`;\n\n let indexPath: string;\n if (existsSync(`${basePath}.js`)) {\n indexPath = `${basePath}.js`;\n } else if (existsSync(`${basePath}.ts`)) {\n indexPath = `${basePath}.ts`;\n } else {\n throw new Error(\n `Generated index file not found at ${basePath}.{js,ts}. Run \\`agent-runtime generate\\` first.`,\n );\n }\n\n const mod = await import(new URL(`file://${indexPath}`).href);\n\n let guardrailHooks: GuardrailHooks | undefined;\n const hooksBasePath = `${config.generatedDir}/hooks/index`;\n const hooksPath = existsSync(`${hooksBasePath}.js`)\n ? `${hooksBasePath}.js`\n : existsSync(`${hooksBasePath}.ts`)\n ? `${hooksBasePath}.ts`\n : null;\n if (hooksPath) {\n try {\n const hooksMod = await import(new URL(`file://${hooksPath}`).href);\n if (hooksMod.guardrailHooks) {\n guardrailHooks = hooksMod.guardrailHooks;\n }\n } catch {\n // Guardrail hooks not available — continue without them\n }\n }\n\n return {\n agentRegistry: mod.agentRegistry ?? mod.agents?.agentRegistry ?? {},\n taskRegistry: mod.taskRegistry ?? mod.tasks?.taskRegistry ?? {},\n handoffSchemas: mod.handoffSchemas ?? mod.handoffs?.handoffSchemas ?? {},\n workflowRegistry: mod.workflowRegistry ?? mod.workflows?.workflowRegistry ?? {},\n guardrailHooks,\n };\n}\n\nasync function createAdapter(adapterName: string, guardrailHooks?: GuardrailHooks): Promise<SdkAdapter> {\n switch (adapterName) {\n case \"mock\": {\n const { MockAdapter } = await import(\"../adapters/mock.js\");\n return new MockAdapter();\n }\n case \"claude\": {\n const { ClaudeAgentSdkAdapter } = await import(\"../adapters/claude-agent-sdk.js\");\n return new ClaudeAgentSdkAdapter({ guardrailHooks });\n }\n case \"gemini\": {\n const { GeminiSdkAdapter } = await import(\"../adapters/gemini-sdk.js\");\n return new GeminiSdkAdapter({ guardrailHooks });\n }\n case \"cursor\": {\n const { CursorSdkAdapter } = await import(\"../adapters/cursor-sdk.js\");\n const apiKey = process.env.CURSOR_API_KEY;\n if (!apiKey) {\n throw new Error(\"CURSOR_API_KEY environment variable is required for the cursor adapter\");\n }\n return CursorSdkAdapter.create({ apiKey, guardrailHooks });\n }\n default:\n throw new Error(`Unknown adapter: ${adapterName}. Available: mock, claude, gemini, cursor`);\n }\n}\n\nfunction formatTable(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n const sep = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const pad = (s: string, w: number) => s.padEnd(w);\n const headerLine = headers.map((h, i) => pad(h, widths[i])).join(\" \");\n const dataLines = rows.map((r) =>\n r.map((c, i) => pad(c ?? \"\", widths[i])).join(\" \"),\n );\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n try {\n const outputDir = resolve(options.output ?? \".\");\n const result = await runInit({\n adapter: options.adapter ?? \"mock\",\n outputDir,\n force: options.force ?? false,\n });\n console.log(JSON.stringify(result, null, 2));\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n },\n\n async generate(options, globalOpts) {\n try {\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n const result = await generate({\n clean: options.clean,\n check: options.check,\n templates: options.templates,\n configPath,\n });\n\n if (result.checkMode) {\n if (result.hasDifferences) {\n console.error(\"Generated files are out of date. Run `agent-runtime generate` to update.\");\n process.exit(1);\n }\n console.log(JSON.stringify({ ...result, status: \"up-to-date\" }, null, 2));\n } else {\n console.log(JSON.stringify(result, null, 2));\n }\n } catch (err) {\n console.error(\"Generate failed:\", (err as Error).message);\n process.exit(1);\n }\n },\n\n async run(workflowId, userRequest, options, globalOpts) {\n // --- Resolve input: --file takes precedence over positional args ---\n let resolvedWorkflowId = workflowId;\n let resolvedUserRequest = userRequest;\n let fileInvocation: WorkflowInvocation | undefined;\n\n if (options.file) {\n try {\n const raw = readFileSync(options.file, \"utf8\");\n const parsed = YAML.parse(raw) as Record<string, unknown>;\n resolvedWorkflowId = parsed.workflow as string;\n if (!resolvedWorkflowId) {\n console.error(`Error: invocation file \"${options.file}\" must contain a \"workflow\" field.`);\n process.exit(1);\n }\n fileInvocation = {\n workflow: resolvedWorkflowId,\n user_request: parsed.user_request as string | undefined,\n handoff: parsed.handoff as WorkflowInvocation[\"handoff\"],\n runtime: parsed.runtime as WorkflowInvocation[\"runtime\"],\n };\n resolvedUserRequest = fileInvocation.user_request ?? \"\";\n } catch (err) {\n console.error(`Failed to read invocation file: ${(err as Error).message}`);\n process.exit(1);\n }\n }\n\n if (!resolvedWorkflowId) {\n console.error(\"Error: workflow-id is required (provide as argument or via --file)\");\n process.exit(1);\n }\n if (!fileInvocation && !resolvedUserRequest) {\n console.error(\"Error: user-request is required (provide as argument or via --file)\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n const fresh = await checkFreshness(configPath);\n if (!fresh) {\n console.error(\"Generated files are stale or missing. Run `agent-runtime generate` first.\");\n process.exit(3);\n }\n\n const config = await loadConfig(configPath);\n\n const pluginResult = await loadPlugins({\n pluginPaths: config.pluginPaths.length > 0 ? config.pluginPaths : undefined,\n projectDir: config.configDir,\n });\n if (pluginResult.loaded > 0 && !(globalOpts.quiet as boolean)) {\n console.error(`Loaded ${pluginResult.loaded} plugin(s) from ${pluginResult.files.length} file(s)`);\n }\n for (const err of pluginResult.errors) {\n console.error(`Plugin load error (${err.file}): ${err.error}`);\n }\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n process.exit(1);\n return;\n }\n\n if (!contracts.workflowRegistry[resolvedWorkflowId]) {\n console.error(`Unknown workflow: ${resolvedWorkflowId}`);\n console.error(`Available workflows: ${Object.keys(contracts.workflowRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const adapterName = (options.adapter as string) ?? \"mock\";\n let adapter: SdkAdapter;\n try {\n adapter = await createAdapter(adapterName, contracts.guardrailHooks);\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n return;\n }\n\n const recovery = config.recovery;\n const maxRetries = options.maxRetries\n ? parseInt(options.maxRetries, 10)\n : undefined;\n const maxFollowUps = options.maxFollowUps\n ? parseInt(options.maxFollowUps, 10)\n : undefined;\n\n const registries = {\n workflowRegistry: contracts.workflowRegistry,\n taskRegistry: contracts.taskRegistry,\n agentRegistry: contracts.agentRegistry,\n handoffSchemas: contracts.handoffSchemas,\n };\n\n const onGate = options.autoApproveGates\n ? async () => true\n : async (gateKind: string, description: string) => {\n console.error(`Gate \"${gateKind}\": ${description}`);\n console.error(\"Use --auto-approve-gates to auto-approve. Rejecting by default.\");\n return false;\n };\n\n let result;\n if (fileInvocation) {\n const invocation: WorkflowInvocation = {\n ...fileInvocation,\n runtime: {\n ...fileInvocation.runtime,\n maxFollowUps: maxFollowUps ?? fileInvocation.runtime?.maxFollowUps ?? recovery.max_follow_ups,\n maxRetries: maxRetries ?? fileInvocation.runtime?.maxRetries ?? recovery.max_retries,\n },\n hooks: { onGate },\n };\n result = await runWorkflow(adapter, invocation, registries);\n } else {\n result = await runWorkflow(adapter, resolvedWorkflowId, {\n user_request: resolvedUserRequest!,\n maxRetries: maxRetries ?? recovery.max_retries,\n maxFollowUps: maxFollowUps ?? recovery.max_follow_ups,\n onGate,\n }, registries);\n }\n\n console.log(JSON.stringify(result, null, 2));\n\n if (result.status !== \"completed\") {\n process.exit(1);\n }\n },\n\n async list(resource, options, globalOpts) {\n if (!resource) {\n console.error(\"Error: resource is required (workflows, tasks, agents)\");\n process.exit(1);\n }\n\n const validResources = [\"workflows\", \"tasks\", \"agents\"];\n if (!validResources.includes(resource)) {\n console.error(`Unknown resource: ${resource}`);\n console.error(`Available resources: ${validResources.join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const format = options.format ?? \"table\";\n\n if (resource === \"agents\") {\n const agents = Object.values(contracts.agentRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(agents, null, 2));\n } else {\n if (agents.length === 0) {\n console.log(\"No agents defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Role\", \"Mode\", \"Purpose\"],\n agents.map((a) => [a.id, a.role_name, a.mode, a.purpose]),\n ));\n }\n } else if (resource === \"tasks\") {\n const tasks = Object.values(contracts.taskRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(tasks, null, 2));\n } else {\n if (tasks.length === 0) {\n console.log(\"No tasks defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Agent\", \"Description\"],\n tasks.map((t) => [t.id, t.target_agent, t.description]),\n ));\n }\n } else {\n const workflows = Object.values(contracts.workflowRegistry);\n if (format === \"json\") {\n console.log(JSON.stringify(workflows, null, 2));\n } else {\n if (workflows.length === 0) {\n console.log(\"No workflows defined.\");\n return;\n }\n console.log(formatTable(\n [\"ID\", \"Steps\", \"Description\"],\n workflows.map((w) => [w.id, String(w.steps.length), w.description]),\n ));\n }\n }\n },\n\n async showPrompt(taskId, options, globalOpts) {\n if (!taskId) {\n console.error(\"Error: task-id is required\");\n process.exit(1);\n }\n\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n\n let contracts: Awaited<ReturnType<typeof loadGeneratedContracts>>;\n try {\n contracts = await loadGeneratedContracts(configPath);\n } catch (err) {\n console.error(`Failed to load generated contracts: ${(err as Error).message}`);\n console.error(\"Run `agent-runtime generate` first.\");\n process.exit(1);\n return;\n }\n\n const task = contracts.taskRegistry[taskId];\n if (!task) {\n console.error(`Unknown task: ${taskId}`);\n console.error(`Available tasks: ${Object.keys(contracts.taskRegistry).join(\", \")}`);\n process.exit(1);\n return;\n }\n\n const agent = contracts.agentRegistry[task.target_agent];\n if (!agent) {\n console.error(`Unknown agent: ${task.target_agent} (referenced by task ${taskId})`);\n process.exit(1);\n return;\n }\n\n const pluginsApplied = options.withPlugins ?? false;\n if (pluginsApplied) {\n const showPromptConfig = await loadConfig(configPath);\n await loadPlugins({\n pluginPaths: showPromptConfig.pluginPaths.length > 0 ? showPromptConfig.pluginPaths : undefined,\n projectDir: showPromptConfig.configDir,\n });\n }\n\n const userRequest = options.userRequest ?? \"(preview)\";\n let prompt = buildTaskPrompt(agent, task, { user_request: userRequest }, {\n handoffSchemas: contracts.handoffSchemas,\n });\n\n if (pluginsApplied) {\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, { user_request: userRequest });\n }\n\n const format = options.format ?? \"markdown\";\n if (format === \"json\") {\n console.log(JSON.stringify({\n task_id: taskId,\n agent_id: task.target_agent,\n prompt,\n handoff_schema: task.result_handoff,\n plugins_applied: pluginsApplied,\n }, null, 2));\n } else {\n console.log(prompt);\n }\n },\n\n async doctor(globalOpts) {\n const configPath = (globalOpts.config as string) ?? \"./agent-runtime.config.yaml\";\n const result = await runDoctor(configPath);\n\n const statusIcon = (s: string) =>\n s === \"pass\" ? \"✓\" : s === \"warn\" ? \"!\" : \"✗\";\n\n for (const check of result.checks) {\n const icon = statusIcon(check.status);\n const msg = check.message ? ` ${check.message}` : \"\";\n console.log(` ${icon} ${check.name.padEnd(20)} ${check.status.toUpperCase()}${msg}`);\n }\n\n console.log(\"\");\n if (result.allPassed) {\n console.log(\"All checks passed.\");\n } else {\n console.log(\"Some checks failed.\");\n }\n\n console.log(JSON.stringify(result));\n\n if (!result.allPassed) {\n process.exitCode = 1;\n }\n },\n\n};\n\nconst program = createProgram(handlers, VERSION);\nawait program.parseAsync();\n","// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean; templates?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; maxFollowUps?: string; dryRun?: boolean; autoApproveGates?: boolean; file?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n showPrompt: (taskId: string | undefined, options: { userRequest?: string; format?: string; withPlugins?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .option(\"-t, --templates <value>\", \"Custom templates directory. Overrides built-in templates.\")\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"[workflow-id]\", \"ID of the workflow to execute. Required unless --file is used.\")\n .argument(\"[user-request]\", \"Natural language description of what to do. Required unless --file is used.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-f, --max-follow-ups <value>\", \"Override default max follow-ups per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .option(\"--file <value>\", \"Path to a YAML invocation file. When provided, workflow-id and\\nuser-request arguments are read from the file instead of CLI args.\\n\")\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"show-prompt\")\n .description(\"Display the generated prompt for a task.\")\n .argument(\"<task-id>\", \"ID of the task to show the prompt for (e.g. plan-and-implement, audit-tests).\")\n .option(\"-u, --user-request <value>\", \"User request text to include in the prompt preview.\", \"(preview)\")\n .option(\"--format <value>\", \"Output format.\", \"markdown\")\n .option(\"--with-plugins\", \"Apply registered plugin prompt enhancers to the output.\", false)\n .action(async (taskId, opts, cmd) => {\n await handlers.showPrompt(taskId, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","/**\n * Doctor — diagnostic checks for agent-contracts-runtime configuration health\n *\n * Each check returns a DoctorCheck with pass/fail/warn status.\n * The runner collects all checks and determines overall health.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { loadConfig, RuntimeConfigSchema, type ResolvedConfig } from \"../generator/config.js\";\nimport { checkFreshness } from \"../generator/index.js\";\n\nexport interface DoctorCheck {\n name: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n}\n\nexport interface DoctorResult {\n checks: DoctorCheck[];\n allPassed: boolean;\n}\n\nconst ADAPTER_ENV_VARS: Record<string, string> = {\n cursor: \"CURSOR_API_KEY\",\n claude: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n};\n\nasync function checkConfigExists(configPath: string): Promise<{ check: DoctorCheck; config?: ResolvedConfig }> {\n try {\n const config = await loadConfig(configPath);\n return {\n check: { name: \"config_exists\", status: \"pass\", message: `Loaded ${configPath}` },\n config,\n };\n } catch (err) {\n const absPath = resolve(configPath);\n if (!existsSync(absPath)) {\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config file not found: ${absPath}` },\n };\n }\n return {\n check: { name: \"config_exists\", status: \"fail\", message: `Config parse error: ${(err as Error).message}` },\n };\n }\n}\n\nasync function checkDslExists(config: ResolvedConfig): Promise<DoctorCheck> {\n if (!existsSync(config.dslPath)) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL file not found: ${config.dslPath}` };\n }\n\n try {\n const raw = await readFile(config.dslPath, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return { name: \"dsl_exists\", status: \"fail\", message: \"DSL file is empty or not a valid YAML object\" };\n }\n const agentCount = Object.keys(parsed.agents ?? {}).length;\n const taskCount = Object.keys(parsed.tasks ?? {}).length;\n const workflowCount = Object.keys(parsed.workflow ?? {}).length;\n return {\n name: \"dsl_exists\",\n status: \"pass\",\n message: `Parsed OK — ${agentCount} agent(s), ${taskCount} task(s), ${workflowCount} workflow(s)`,\n };\n } catch (err) {\n return { name: \"dsl_exists\", status: \"fail\", message: `DSL parse error: ${(err as Error).message}` };\n }\n}\n\nasync function checkManifestFresh(configPath: string, config: ResolvedConfig): Promise<DoctorCheck> {\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n if (!existsSync(manifestPath)) {\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated manifest not found. Run `agent-runtime generate` first.\",\n };\n }\n\n try {\n const fresh = await checkFreshness(configPath);\n if (fresh) {\n return { name: \"manifest_fresh\", status: \"pass\", message: \"Generated files are up to date\" };\n }\n return {\n name: \"manifest_fresh\",\n status: \"fail\",\n message: \"Generated files are stale. Run `agent-runtime generate` to update.\",\n };\n } catch (err) {\n return { name: \"manifest_fresh\", status: \"fail\", message: `Freshness check error: ${(err as Error).message}` };\n }\n}\n\nfunction checkAdapterConfigured(): DoctorCheck {\n const configured: string[] = [];\n const missing: string[] = [];\n\n for (const [adapter, envVar] of Object.entries(ADAPTER_ENV_VARS)) {\n if (process.env[envVar]) {\n configured.push(adapter);\n } else {\n missing.push(`${adapter} (${envVar})`);\n }\n }\n\n if (configured.length > 0) {\n return {\n name: \"adapter_configured\",\n status: \"pass\",\n message: `Configured: ${configured.join(\", \")}${missing.length > 0 ? ` | Not set: ${missing.join(\", \")}` : \"\"}`,\n };\n }\n\n return {\n name: \"adapter_configured\",\n status: \"warn\",\n message: `No SDK adapter API keys found. Set one of: ${Object.entries(ADAPTER_ENV_VARS).map(([a, e]) => `${e} (${a})`).join(\", \")}`,\n };\n}\n\nfunction checkPluginEntrypoints(config: ResolvedConfig): DoctorCheck {\n if (config.pluginPaths.length === 0) {\n return { name: \"plugin_entrypoint\", status: \"pass\", message: \"No plugins configured\" };\n }\n\n const missing: string[] = [];\n for (const p of config.pluginPaths) {\n const absPath = resolve(config.configDir, p);\n if (!existsSync(absPath)) {\n missing.push(p);\n }\n }\n\n if (missing.length === 0) {\n return {\n name: \"plugin_entrypoint\",\n status: \"pass\",\n message: `All ${config.pluginPaths.length} plugin file(s) found`,\n };\n }\n\n return {\n name: \"plugin_entrypoint\",\n status: \"fail\",\n message: `Missing plugin file(s): ${missing.join(\", \")}`,\n };\n}\n\nasync function checkBindingsValid(config: ResolvedConfig): Promise<DoctorCheck> {\n if (config.bindingPaths.length === 0) {\n return { name: \"bindings_valid\", status: \"pass\", message: \"No bindings configured\" };\n }\n\n const errors: string[] = [];\n for (const bp of config.bindingPaths) {\n if (!existsSync(bp)) {\n errors.push(`Not found: ${bp}`);\n continue;\n }\n try {\n const raw = await readFile(bp, \"utf8\");\n const parsed = YAML.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n errors.push(`Invalid YAML object: ${bp}`);\n }\n } catch (err) {\n errors.push(`Parse error in ${bp}: ${(err as Error).message}`);\n }\n }\n\n if (errors.length === 0) {\n return {\n name: \"bindings_valid\",\n status: \"pass\",\n message: `All ${config.bindingPaths.length} binding file(s) valid`,\n };\n }\n\n return {\n name: \"bindings_valid\",\n status: \"fail\",\n message: errors.join(\"; \"),\n };\n}\n\nexport async function runDoctor(configPath: string): Promise<DoctorResult> {\n const checks: DoctorCheck[] = [];\n\n // 1. Config exists and parses\n const configResult = await checkConfigExists(configPath);\n checks.push(configResult.check);\n\n if (!configResult.config) {\n return { checks, allPassed: false };\n }\n\n const config = configResult.config;\n\n // 2–6 can run concurrently since they only read state\n const [dslCheck, manifestCheck, pluginCheck, bindingsCheck] = await Promise.all([\n checkDslExists(config),\n checkManifestFresh(configPath, config),\n Promise.resolve(checkPluginEntrypoints(config)),\n checkBindingsValid(config),\n ]);\n\n checks.push(dslCheck);\n checks.push(manifestCheck);\n checks.push(checkAdapterConfigured());\n checks.push(pluginCheck);\n checks.push(bindingsCheck);\n\n const allPassed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, allPassed };\n}\n","/**\n * init — scaffold a new agent-contracts-runtime project\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile, readFile, appendFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport YAML from \"yaml\";\n\nexport interface InitOptions {\n adapter: string;\n outputDir: string;\n force: boolean;\n}\n\nexport interface InitResult {\n filesCreated: string[];\n}\n\ninterface FileEntry {\n relativePath: string;\n content: string;\n}\n\nfunction buildConfigYaml(adapter: string): string {\n return YAML.stringify(\n {\n dsl: \"./agent-contracts.yaml\",\n generated_dir: \"./agent/generated\",\n plugins: [\"./agent/src/plugins/example-plugin.ts\"],\n recovery: {\n max_follow_ups: 2,\n max_retries: 0,\n },\n },\n { lineWidth: 0 },\n );\n}\n\nconst EXAMPLE_PLUGIN_TS = `\\\nimport type { AgentPlugin } from \"agent-contracts-runtime\";\n\n/**\n * Example plugin — extend agent-contracts-runtime with custom hooks.\n *\n * Register lifecycle hooks for tasks and workflows:\n * beforeTask / afterTask — pre/post-process task execution\n * contextEnhancer — augment task context before prompt generation\n * promptEnhancer — post-process generated prompts\n * customGuardrails — add project-specific guardrail checks\n * beforeWorkflow / afterWorkflow — workflow lifecycle hooks\n *\n * See https://github.com/foo-ogawa/agent-contracts-runtime#plugins\n */\nexport const examplePlugin: AgentPlugin = {\n id: \"example-plugin\",\n\n // Uncomment hooks as needed:\n\n // async beforeTask(taskId, context) {\n // console.log(\\`[example-plugin] beforeTask: \\${taskId}\\`);\n // return context;\n // },\n\n // async afterTask(taskId, outcome) {\n // console.log(\\`[example-plugin] afterTask: \\${taskId} — \\${outcome.status}\\`);\n // return outcome;\n // },\n\n // promptEnhancer(taskId, prompt, _context) {\n // return prompt + \"\\\\n\\\\n<!-- enhanced by example-plugin -->\";\n // },\n};\n\nexport default examplePlugin;\n`;\n\nconst CUSTOM_GUARDRAILS_TS = `\\\nimport type { AgentPlugin, GuardrailResult } from \"agent-contracts-runtime\";\n\n/**\n * Custom guardrails — project-specific safety checks.\n *\n * Implement evaluateCommand, evaluateFilePath, or evaluateFileContent\n * to enforce project rules beyond the built-in guardrails.\n *\n * See https://github.com/foo-ogawa/agent-contracts-runtime#guardrails\n */\nexport const customGuardrailsPlugin: AgentPlugin = {\n id: \"custom-guardrails\",\n\n customGuardrails: {\n // evaluateCommand(command: string): GuardrailResult[] {\n // const results: GuardrailResult[] = [];\n // // Example: block dangerous patterns\n // if (command.includes(\"DROP TABLE\")) {\n // results.push({\n // matched: true,\n // guardrail_id: \"no-drop-table\",\n // severity: \"critical\",\n // action: \"block\",\n // message: \"DROP TABLE is forbidden\",\n // });\n // }\n // return results;\n // },\n },\n};\n\nexport default customGuardrailsPlugin;\n`;\n\nconst GITIGNORE_ENTRIES = [\n \"\",\n \"# agent-contracts-runtime generated files\",\n \"agent/generated/\",\n];\n\nfunction buildScaffoldFiles(adapter: string): FileEntry[] {\n return [\n {\n relativePath: \"agent-runtime.config.yaml\",\n content: buildConfigYaml(adapter),\n },\n {\n relativePath: \"agent/src/plugins/example-plugin.ts\",\n content: EXAMPLE_PLUGIN_TS,\n },\n {\n relativePath: \"agent/src/guardrails/custom-guardrails.ts\",\n content: CUSTOM_GUARDRAILS_TS,\n },\n ];\n}\n\nexport async function runInit(options: InitOptions): Promise<InitResult> {\n const { adapter, outputDir, force } = options;\n const filesCreated: string[] = [];\n\n const entries = buildScaffoldFiles(adapter);\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n if (!force && existsSync(absPath)) {\n throw new Error(\n `File already exists: ${entry.relativePath}. Use --force to overwrite.`,\n );\n }\n }\n\n for (const entry of entries) {\n const absPath = join(outputDir, entry.relativePath);\n const dir = join(absPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(absPath, entry.content, \"utf8\");\n filesCreated.push(entry.relativePath);\n }\n\n const gitignorePath = join(outputDir, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const existing = await readFile(gitignorePath, \"utf8\");\n if (!existing.includes(\"agent/generated/\")) {\n await appendFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\") + \"\\n\", \"utf8\");\n filesCreated.push(\".gitignore\");\n }\n } else {\n await writeFile(gitign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C/C,MAAM,QAAQ,WAAW;","names":["existsSync","resolve","handlers","program","existsSync","readFile","join","YAML","YAML","existsSync","resolve"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-contracts-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -25,6 +25,10 @@
|
|
|
25
25
|
"types": "./dist/adapters/openai-agents-sdk.d.ts",
|
|
26
26
|
"import": "./dist/adapters/openai-agents-sdk.js"
|
|
27
27
|
},
|
|
28
|
+
"./adapters/gemini-sdk": {
|
|
29
|
+
"types": "./dist/adapters/gemini-sdk.d.ts",
|
|
30
|
+
"import": "./dist/adapters/gemini-sdk.js"
|
|
31
|
+
},
|
|
28
32
|
"./adapters/mock": {
|
|
29
33
|
"types": "./dist/adapters/mock.d.ts",
|
|
30
34
|
"import": "./dist/adapters/mock.js"
|
|
@@ -89,6 +93,10 @@
|
|
|
89
93
|
"zod": "^4.0.0"
|
|
90
94
|
},
|
|
91
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",
|
|
92
100
|
"@types/node": "^25.6.0",
|
|
93
101
|
"cli-contracts": "^0.2.1",
|
|
94
102
|
"tsup": "^8.5.0",
|
|
@@ -99,10 +107,14 @@
|
|
|
99
107
|
"peerDependencies": {
|
|
100
108
|
"@anthropic-ai/claude-agent-sdk": ">=0.2.0",
|
|
101
109
|
"@cursor/sdk": ">=1.0.0",
|
|
110
|
+
"@google/genai": ">=2.0.0",
|
|
102
111
|
"@openai/agents": ">=0.10.0",
|
|
103
112
|
"agent-contracts": "^0.17.0"
|
|
104
113
|
},
|
|
105
114
|
"peerDependenciesMeta": {
|
|
115
|
+
"@google/genai": {
|
|
116
|
+
"optional": true
|
|
117
|
+
},
|
|
106
118
|
"agent-contracts": {
|
|
107
119
|
"optional": true
|
|
108
120
|
},
|