agent-contracts-runtime 0.30.0 → 0.30.2

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 CHANGED
@@ -951,6 +951,7 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
951
951
 
952
952
  - Node.js 20+
953
953
  - TypeScript 5.x (ESM, strict mode)
954
+ - `tsx` (bundled as a dependency — used by the CLI to load generated `.ts` contracts and plugins at runtime)
954
955
  - `agent-contracts` (optional peer dependency for DSL resolution)
955
956
  - `@anthropic-ai/claude-agent-sdk` (optional, for Claude adapter — requires zod ^4.0.0)
956
957
  - `@cursor/sdk` (optional, for Cursor adapter)
package/dist/cli/index.js CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  // src/cli/index.ts
15
15
  import { existsSync as existsSync3, readFileSync } from "fs";
16
16
  import { resolve as resolve2 } from "path";
17
+ import { register } from "tsx/esm/api";
17
18
 
18
19
  // src/generated/cli/program.ts
19
20
  import { Command } from "commander";
@@ -141,6 +142,18 @@ function checkAdapterConfigured() {
141
142
  message: `No SDK adapter API keys found. Set one of: ${Object.entries(ADAPTER_ENV_VARS).map(([a, e]) => `${e} (${a})`).join(", ")}`
142
143
  };
143
144
  }
145
+ async function checkTsxAvailable() {
146
+ try {
147
+ await import("tsx/esm");
148
+ return { name: "tsx_available", status: "pass", message: "tsx is installed" };
149
+ } catch {
150
+ return {
151
+ name: "tsx_available",
152
+ status: "fail",
153
+ message: "tsx is not installed. Required for loading generated .ts files. Run: npm install tsx"
154
+ };
155
+ }
156
+ }
144
157
  function checkPluginEntrypoints(config) {
145
158
  if (config.pluginPaths.length === 0) {
146
159
  return { name: "plugin_entrypoint", status: "pass", message: "No plugins configured" };
@@ -206,17 +219,19 @@ async function runDoctor(configPath) {
206
219
  return { checks, all_passed: false };
207
220
  }
208
221
  const config = configResult.config;
209
- const [dslCheck, manifestCheck, pluginCheck, bindingsCheck] = await Promise.all([
222
+ const [dslCheck, manifestCheck, pluginCheck, bindingsCheck, tsxCheck] = await Promise.all([
210
223
  checkDslExists(config),
211
224
  checkManifestFresh(configPath, config),
212
225
  Promise.resolve(checkPluginEntrypoints(config)),
213
- checkBindingsValid(config)
226
+ checkBindingsValid(config),
227
+ checkTsxAvailable()
214
228
  ]);
215
229
  checks.push(dslCheck);
216
230
  checks.push(manifestCheck);
217
231
  checks.push(checkAdapterConfigured());
218
232
  checks.push(pluginCheck);
219
233
  checks.push(bindingsCheck);
234
+ checks.push(tsxCheck);
220
235
  const all_passed = checks.every((c) => c.status !== "fail");
221
236
  return { checks, all_passed };
222
237
  }
@@ -365,6 +380,7 @@ async function runInit(options) {
365
380
 
366
381
  // src/cli/index.ts
367
382
  import YAML3 from "yaml";
383
+ register();
368
384
  var VERSION = "0.11.0";
369
385
  async function loadGeneratedContracts(configPath) {
370
386
  const config = await loadConfig(configPath);
@@ -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.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.check_mode) {\n if (result.has_differences) {\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.all_passed) {\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.all_passed) {\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: (options: Record<string, never>, 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 all_passed: 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, all_passed: 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 all_passed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, all_passed };\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 files_created: 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 files_created: 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 files_created.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 files_created.push(\".gitignore\");\n }\n } else {\n await writeFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\").trimStart() + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n\n return { files_created };\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,EAC5D,OAAO,WAAW,+GAA+G,KAAK,EACtI,OAAO,WAAW,oKAAoK,KAAK,EAC3L,OAAO,2BAA2B,2DAA2D,EAC7F,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,SAAS,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACrD,CAAC;AAEH,EAAAC,SACG,QAAQ,KAAK,EACb,YAAY,qBAAqB,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;AAAA,IACnC;AAEA,YAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;AAElC,QAAI,CAAC,OAAO,YAAY;AACtB,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 { register } from \"tsx/esm/api\";\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\nregister();\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.check_mode) {\n if (result.has_differences) {\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.all_passed) {\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.all_passed) {\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: (options: Record<string, never>, 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 all_passed: 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\nasync function checkTsxAvailable(): Promise<DoctorCheck> {\n try {\n await import(\"tsx/esm\");\n return { name: \"tsx_available\", status: \"pass\", message: \"tsx is installed\" };\n } catch {\n return {\n name: \"tsx_available\",\n status: \"fail\",\n message: \"tsx is not installed. Required for loading generated .ts files. Run: npm install tsx\",\n };\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, all_passed: false };\n }\n\n const config = configResult.config;\n\n // 2–7 can run concurrently since they only read state\n const [dslCheck, manifestCheck, pluginCheck, bindingsCheck, tsxCheck] = await Promise.all([\n checkDslExists(config),\n checkManifestFresh(configPath, config),\n Promise.resolve(checkPluginEntrypoints(config)),\n checkBindingsValid(config),\n checkTsxAvailable(),\n ]);\n\n checks.push(dslCheck);\n checks.push(manifestCheck);\n checks.push(checkAdapterConfigured());\n checks.push(pluginCheck);\n checks.push(bindingsCheck);\n checks.push(tsxCheck);\n\n const all_passed = checks.every((c) => c.status !== \"fail\");\n\n return { checks, all_passed };\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 files_created: 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 files_created: 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 files_created.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 files_created.push(\".gitignore\");\n }\n } else {\n await writeFile(gitignorePath, GITIGNORE_ENTRIES.join(\"\\n\").trimStart() + \"\\n\", \"utf8\");\n files_created.push(\".gitignore\");\n }\n\n return { files_created };\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,WAAAC,gBAAe;AACxB,SAAS,gBAAgB;;;ACTzB,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,EAC5D,OAAO,WAAW,+GAA+G,KAAK,EACtI,OAAO,WAAW,oKAAoK,KAAK,EAC3L,OAAO,2BAA2B,2DAA2D,EAC7F,OAAO,OAAO,MAAM,QAAQ;AAC3B,UAAMD,UAAS,SAAS,MAAM,IAAI,gBAAgB,CAAC;AAAA,EACrD,CAAC;AAEH,EAAAC,SACG,QAAQ,KAAK,EACb,YAAY,qBAAqB,E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