agent-contracts-runtime 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -2
- package/dist/adapters/claude-agent-sdk.d.ts +1 -1
- package/dist/adapters/cursor-sdk.d.ts +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/{chunk-74HEBMGQ.js → chunk-3NE3OA6F.js} +4 -4
- package/dist/chunk-3NE3OA6F.js.map +1 -0
- package/dist/{chunk-TSVIMZ5N.js → chunk-V52RRB44.js} +9 -5
- package/dist/chunk-V52RRB44.js.map +1 -0
- package/dist/cli/index.js +3 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/generator/index.d.ts +4 -32
- package/dist/generator/index.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{task-runner-Bt2XiEUU.d.ts → task-runner-D8b31ZL_.d.ts} +4 -4
- package/package.json +6 -2
- package/dist/chunk-74HEBMGQ.js.map +0 -1
- package/dist/chunk-TSVIMZ5N.js.map +0 -1
package/README.md
CHANGED
|
@@ -334,6 +334,23 @@ const result = await runWorkflow(adapter, "feature-implement", {
|
|
|
334
334
|
});
|
|
335
335
|
```
|
|
336
336
|
|
|
337
|
+
Or with the OpenAI Agents SDK adapter:
|
|
338
|
+
|
|
339
|
+
```typescript
|
|
340
|
+
import { runWorkflow } from "agent-contracts-runtime";
|
|
341
|
+
import { OpenAIAgentsSdkAdapter } from "agent-contracts-runtime/adapters/openai-agents-sdk";
|
|
342
|
+
|
|
343
|
+
const adapter = new OpenAIAgentsSdkAdapter({
|
|
344
|
+
model: "gpt-4.1",
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
const result = await runWorkflow(adapter, "feature-implement", {
|
|
348
|
+
user_request: "Add login endpoint with JWT",
|
|
349
|
+
maxFollowUps: 3,
|
|
350
|
+
maxRetries: 1,
|
|
351
|
+
});
|
|
352
|
+
```
|
|
353
|
+
|
|
337
354
|
For production integration, prefer the Structured API or Builder API so that input handoffs are validated before execution.
|
|
338
355
|
|
|
339
356
|
### Structured API
|
|
@@ -523,7 +540,7 @@ The CLI specification is managed contract-first via [`cli-contracts`](https://ww
|
|
|
523
540
|
|---------|-----|--------|
|
|
524
541
|
| `cursor` | Cursor Cloud Agents (`@cursor/sdk`) | Implemented |
|
|
525
542
|
| `claude` | Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) | Implemented |
|
|
526
|
-
| `openai` | OpenAI Agents SDK |
|
|
543
|
+
| `openai` | OpenAI Agents SDK (`@openai/agents`) | Implemented |
|
|
527
544
|
| `mock` | Simulated responses for testing/demo | Implemented |
|
|
528
545
|
|
|
529
546
|
### Adapter interface
|
|
@@ -576,6 +593,13 @@ const claudeAdapter = new ClaudeAgentSdkAdapter({
|
|
|
576
593
|
cwd: process.cwd(),
|
|
577
594
|
guardrailHooks,
|
|
578
595
|
});
|
|
596
|
+
|
|
597
|
+
// OpenAI Agents SDK
|
|
598
|
+
const openaiAdapter = new OpenAIAgentsSdkAdapter({
|
|
599
|
+
model: "gpt-4.1",
|
|
600
|
+
maxTurns: 20,
|
|
601
|
+
guardrailHooks,
|
|
602
|
+
});
|
|
579
603
|
```
|
|
580
604
|
|
|
581
605
|
### Claude Agent SDK adapter
|
|
@@ -607,7 +631,36 @@ Internally the adapter calls the SDK's `query()` function, which returns an Asyn
|
|
|
607
631
|
| `maxTurns` | Maximum conversation turns | No limit |
|
|
608
632
|
| `guardrailHooks` | Runtime guardrail hooks (mapped to SDK `PreToolUse` hooks) | None |
|
|
609
633
|
|
|
610
|
-
> **Note:** `@anthropic-ai/claude-agent-sdk` requires `zod@^4.0.0` as a peer dependency.
|
|
634
|
+
> **Note:** `@anthropic-ai/claude-agent-sdk` requires `zod@^4.0.0` as a peer dependency. This runtime uses `zod@^4.0.0` natively.
|
|
635
|
+
|
|
636
|
+
### OpenAI Agents SDK adapter
|
|
637
|
+
|
|
638
|
+
The OpenAI adapter wraps `@openai/agents`, which provides a lightweight agent framework with built-in tool execution, guardrails, handoffs, and tracing.
|
|
639
|
+
|
|
640
|
+
```typescript
|
|
641
|
+
import { OpenAIAgentsSdkAdapter } from "agent-contracts-runtime/adapters/openai-agents-sdk";
|
|
642
|
+
|
|
643
|
+
const adapter = new OpenAIAgentsSdkAdapter({
|
|
644
|
+
model: "gpt-4.1", // optional, uses SDK default
|
|
645
|
+
maxTurns: 20, // optional turn limit (default: 10)
|
|
646
|
+
guardrailHooks, // optional guardrail enforcement
|
|
647
|
+
});
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
Internally the adapter creates a fresh `Agent` for each `send()` call with the contract prompt as `instructions`, then calls the SDK's `run()` function and extracts `finalOutput` as the result text.
|
|
651
|
+
|
|
652
|
+
`followUp()` resumes the same conversation via the SDK's `previousResponseId` option, so the model retains full context when correcting output format.
|
|
653
|
+
|
|
654
|
+
| Config option | Description | Default |
|
|
655
|
+
|---------------|-------------|---------|
|
|
656
|
+
| `model` | Model identifier (e.g. `"gpt-4.1"`, `"gpt-5.5"`) | SDK default |
|
|
657
|
+
| `maxTurns` | Maximum agent loop turns | `10` (SDK default) |
|
|
658
|
+
| `tools` | Additional tools to pass to the Agent | None |
|
|
659
|
+
| `agentName` | Name for the Agent instance | `"contract-agent"` |
|
|
660
|
+
| `guardrailHooks` | Runtime guardrail hooks (mapped to SDK `InputGuardrail`) | None |
|
|
661
|
+
| `signal` | `AbortSignal` for cancellation | None |
|
|
662
|
+
|
|
663
|
+
> **Note:** `@openai/agents` requires `zod@^4.0.0` as a peer dependency. This runtime uses `zod@^4.0.0` natively.
|
|
611
664
|
|
|
612
665
|
## Handoff validation
|
|
613
666
|
|
|
@@ -809,6 +862,7 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
|
|
|
809
862
|
| `agent-contracts-runtime/generator` | Generator API (`generate`, `checkFreshness`, `buildContractContext`) |
|
|
810
863
|
| `agent-contracts-runtime/adapters/cursor-sdk` | Cursor SDK adapter |
|
|
811
864
|
| `agent-contracts-runtime/adapters/claude-agent-sdk` | Claude Agent SDK adapter |
|
|
865
|
+
| `agent-contracts-runtime/adapters/openai-agents-sdk` | OpenAI Agents SDK adapter |
|
|
812
866
|
| `agent-contracts-runtime/adapters/mock` | Mock adapter for testing |
|
|
813
867
|
|
|
814
868
|
## Requirements
|
|
@@ -818,6 +872,7 @@ templates_dir: ./custom-templates # optional, overrides built-in templa
|
|
|
818
872
|
- `agent-contracts` (optional peer dependency for DSL resolution)
|
|
819
873
|
- `@anthropic-ai/claude-agent-sdk` (optional, for Claude adapter — requires zod ^4.0.0)
|
|
820
874
|
- `@cursor/sdk` (optional, for Cursor adapter)
|
|
875
|
+
- `@openai/agents` (optional, for OpenAI adapter — requires zod ^4.0.0)
|
|
821
876
|
|
|
822
877
|
## License
|
|
823
878
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-
|
|
1
|
+
import { S as SdkAdapter, A as AdapterSendOptions, a as AgentExecutionRequest } from '../task-runner-D8b31ZL_.js';
|
|
2
2
|
import { G as GuardrailHooks } from '../guardrail-hooks-5MSNWxnl.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
package/dist/adapters/mock.d.ts
CHANGED
|
@@ -103,9 +103,9 @@ function zodTypeToString(schema) {
|
|
|
103
103
|
if (schema instanceof z.ZodNumber) return "number";
|
|
104
104
|
if (schema instanceof z.ZodBoolean) return "boolean";
|
|
105
105
|
if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
|
|
106
|
-
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.
|
|
106
|
+
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
|
|
107
107
|
if (schema instanceof z.ZodArray) {
|
|
108
|
-
const inner = zodTypeToString(schema._def.
|
|
108
|
+
const inner = zodTypeToString(schema._def.element);
|
|
109
109
|
return `${inner}[]`;
|
|
110
110
|
}
|
|
111
111
|
if (schema instanceof z.ZodObject) return "object";
|
|
@@ -124,7 +124,7 @@ function extractFieldDescriptors(schema) {
|
|
|
124
124
|
return Object.entries(shape).map(([name, field]) => {
|
|
125
125
|
const isOptional = field instanceof z.ZodOptional;
|
|
126
126
|
const innerField = isOptional ? field._def.innerType : field;
|
|
127
|
-
const description = innerField.
|
|
127
|
+
const description = innerField.description ?? field.description;
|
|
128
128
|
return {
|
|
129
129
|
name,
|
|
130
130
|
type: zodTypeToString(field),
|
|
@@ -928,4 +928,4 @@ export {
|
|
|
928
928
|
loadPluginsFromDirectory,
|
|
929
929
|
loadPlugins
|
|
930
930
|
};
|
|
931
|
-
//# sourceMappingURL=chunk-
|
|
931
|
+
//# sourceMappingURL=chunk-3NE3OA6F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/workflow-runner.ts","../src/lib/guardrail-hooks.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts"],"sourcesContent":["/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const inner = zodTypeToString((schema as z.ZodArray<z.ZodType>)._def.element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const header = \"| Field | Type | Required | Description |\";\n const sep = \"|-------|------|----------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.description ?? \"\"} |`,\n );\n return [header, sep, ...rows].join(\"\\n\");\n}\n\n/**\n * Generate a minimal YAML example from a Zod schema shape.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const lines: string[] = [];\n for (const f of fields) {\n if (f.type.endsWith(\"[]\")) {\n const innerType = f.type.slice(0, -2);\n if (innerType === \"string\") {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n } else if (innerType === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` - key: \"value\"`);\n } else {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${f.name}: false`);\n } else if (f.type === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` key: \"value\"`);\n } else {\n lines.push(`${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n sections.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n sections.push(`## User Request\\n\\n${context.user_request}`);\n sections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n } else {\n sections.push(`## User Request\\n\\n${context.user_request}`);\n }\n\n if (context.prior_context) {\n sections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n sections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n sections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n sections.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n sections.push(recoverySection);\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodType>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const promptOpts: PromptBuilderOptions = { handoffSchemas: schemas, retry: options?.retry };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n let prompt = pluginRegistry.applyPromptBuilder(builderArgs)\n ?? buildTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n\n const isReadonly = agentContract.mode === \"read-only\";\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n options: { readonly: isReadonly, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\n }\n } catch (err) {\n return { outcome: { status: \"error\", message: `SDK error: ${(err as Error).message}` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (cursorSessionId,\n * openaiThreadId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodType>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapter: SdkAdapter,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n const stepResults: StepResult[] = [];\n const workflowStart = Date.now();\n let accumulatedContext = \"\";\n\n for (let i = 0; i < workflow.steps.length; i++) {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n const result = await handleGateStep(step, stepResults, options, i);\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"gate_rejected\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n continue;\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: accumulatedContext };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: accumulatedContext,\n ...(invocationHandoff ? { handoff_input: invocationHandoff } : {}),\n };\n const taskResult: TaskRunResult = await runTask(adapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n });\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Accumulate context from successful steps\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n // Escalation — stop workflow\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n // Unrecoverable failure after all recovery attempts\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (!options.onGate) {\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: DelegateStep | GateStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * The generated hooks/index.ts calls createGuardrailHooks() with the\n * DSL-generated check functions. All logic lives here in the lib.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by Cursor / Claude SDKs,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — auto-discovers and registers user plugin files\n *\n * Discovery strategies (in priority order):\n * 1. Config-based: `plugins` array in agent-runtime.config.yaml\n * 2. Convention-based: scan `src/plugins/` for files exporting AgentPlugin\n *\n * Each discovered module is dynamically import()'d. Exports that satisfy the\n * AgentPlugin interface (have an `id` string property) are registered with\n * the pluginRegistry singleton.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nconst PLUGIN_EXTENSIONS = [\".ts\", \".js\", \".mts\", \".mjs\"];\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Scan a directory for files that may export plugins.\n * Returns absolute paths of candidate files.\n */\nasync function scanDirectory(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n\n const entries = await readdir(dir, { withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) &&\n !e.name.startsWith(\"_\") &&\n !e.name.endsWith(\".d.ts\") &&\n !e.name.endsWith(\".test.ts\") &&\n !e.name.endsWith(\".spec.ts\"),\n )\n .map((e) => resolve(dir, e.name));\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n loaded: number;\n files: string[];\n errors: Array<{ file: string; error: string }>;\n}\n\n/**\n * Load plugins from explicit paths (config-based discovery).\n */\nexport async function loadPluginsFromPaths(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n result.errors.push({ file: p, error: `File not found: ${absPath}` });\n continue;\n }\n\n try {\n const count = await loadPluginModule(absPath);\n result.loaded += count;\n result.files.push(absPath);\n } catch (err) {\n result.errors.push({\n file: p,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Load plugins using convention-based directory scanning.\n * Scans `<projectDir>/src/plugins/` by default.\n */\nexport async function loadPluginsFromDirectory(\n dir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n const candidates = await scanDirectory(dir);\n\n for (const filePath of candidates) {\n try {\n const count = await loadPluginModule(filePath);\n result.loaded += count;\n result.files.push(filePath);\n } catch (err) {\n result.errors.push({\n file: filePath,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Auto-discover and load plugins. Uses config-based paths if provided,\n * otherwise falls back to convention-based scanning of src/plugins/.\n */\nexport async function loadPlugins(options: {\n pluginPaths?: string[];\n projectDir: string;\n}): Promise<PluginLoadResult> {\n if (options.pluginPaths && options.pluginPaths.length > 0) {\n return loadPluginsFromPaths(options.pluginPaths, options.projectDir);\n }\n\n const conventionDir = join(options.projectDir, \"src\", \"plugins\");\n return loadPluginsFromDirectory(conventionDir);\n}\n"],"mappings":";AAiBA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACmCf,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SA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,UAAU;AACjB,aAAO,MAAM,KAAK,OAAO;AAAA,IAC3B,SAAS,KAAK;AACZ,aAAO,OAAO,KAAK;AAAA,QACjB,MAAM;AAAA,QACN,OAAQ,IAAc;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;AAMA,eAAsB,yBACpB,KAC2B;AAC3B,QAAM,SAA2B,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,QAAQ,CAAC,EAAE;AACpE,QAAM,aAAa,MAAM,cAAc,GAAG;AAE1C,aAAW,YAAY,YAAY;AACjC,QAAI;AACF,YAAM,QAAQ,MAAM,iBAAiB,QAAQ;AAC7C,aAAO,UAAU;AACjB,aAAO,MAAM,KAAK,QAAQ;AAAA,IAC5B,SAAS,KAAK;AACZ,aAAO,OAAO,KAAK;AAAA,QACjB,MAAM;AAAA,QACN,OAAQ,IAAc;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;AAMA,eAAsB,YAAY,SAGJ;AAC5B,MAAI,QAAQ,eAAe,QAAQ,YAAY,SAAS,GAAG;AACzD,WAAO,qBAAqB,QAAQ,aAAa,QAAQ,UAAU;AAAA,EACrE;AAEA,QAAM,gBAAgB,KAAK,QAAQ,YAAY,OAAO,SAAS;AAC/D,SAAO,yBAAyB,aAAa;AAC/C;","names":["result","wfResult"]}
|
|
@@ -12,7 +12,7 @@ import YAML from "yaml";
|
|
|
12
12
|
var RecoverySchema = z.object({
|
|
13
13
|
max_follow_ups: z.number().int().min(0).default(2),
|
|
14
14
|
max_retries: z.number().int().min(0).default(0)
|
|
15
|
-
}).default({});
|
|
15
|
+
}).default(() => ({ max_follow_ups: 2, max_retries: 0 }));
|
|
16
16
|
var RuntimeConfigSchema = z.object({
|
|
17
17
|
dsl: z.string().default("./agent-contracts.yaml"),
|
|
18
18
|
generated_dir: z.string().default("./agent/generated"),
|
|
@@ -117,7 +117,7 @@ ${fields}
|
|
|
117
117
|
if (schema.allOf) {
|
|
118
118
|
const parts = schema.allOf.map(zodType);
|
|
119
119
|
if (parts.length === 1) return parts[0];
|
|
120
|
-
return parts.
|
|
120
|
+
return parts.reduce((acc, part) => `${acc}.extend(${part}.shape)`);
|
|
121
121
|
}
|
|
122
122
|
return "z.unknown()";
|
|
123
123
|
});
|
|
@@ -198,7 +198,7 @@ function buildContractContext(dsl) {
|
|
|
198
198
|
if (step.type === "delegate") {
|
|
199
199
|
entry.task = step.task;
|
|
200
200
|
entry.from_agent = step.from_agent;
|
|
201
|
-
entry.description = step.description;
|
|
201
|
+
entry.description = step.description ?? "";
|
|
202
202
|
const wfStep = step;
|
|
203
203
|
entry.optional = isTaskOptional(
|
|
204
204
|
step.task,
|
|
@@ -216,7 +216,7 @@ function buildContractContext(dsl) {
|
|
|
216
216
|
}
|
|
217
217
|
} else if (step.type === "gate") {
|
|
218
218
|
entry.gate_kind = step.gate_kind;
|
|
219
|
-
entry.description = step.description;
|
|
219
|
+
entry.description = step.description ?? "";
|
|
220
220
|
}
|
|
221
221
|
return entry;
|
|
222
222
|
});
|
|
@@ -312,6 +312,10 @@ async function loadDsl(dslPath) {
|
|
|
312
312
|
/* webpackIgnore: true */
|
|
313
313
|
modName
|
|
314
314
|
);
|
|
315
|
+
if (mod.resolve) {
|
|
316
|
+
const result = await mod.resolve(dslPath);
|
|
317
|
+
return result.data;
|
|
318
|
+
}
|
|
315
319
|
if (mod.loadDsl) {
|
|
316
320
|
const result = await mod.loadDsl(dslPath);
|
|
317
321
|
return result.data;
|
|
@@ -446,4 +450,4 @@ export {
|
|
|
446
450
|
generate,
|
|
447
451
|
checkFreshness
|
|
448
452
|
};
|
|
449
|
-
//# sourceMappingURL=chunk-
|
|
453
|
+
//# sourceMappingURL=chunk-V52RRB44.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/generator/index.ts","../src/generator/config.ts","../src/generator/template-engine.ts","../src/generator/context.ts"],"sourcesContent":["/**\n * Generator — orchestrates DSL-to-TypeScript code generation\n */\n\nimport { readFile, writeFile, mkdir, rm, stat } from \"node:fs/promises\";\nimport { resolve, join, relative } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport YAML from \"yaml\";\nimport { loadConfig, type ResolvedConfig } from \"./config.js\";\nimport { renderTemplate } from \"./template-engine.js\";\nimport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n\nexport interface GenerateOptions {\n clean?: boolean;\n check?: boolean;\n templates?: string;\n configPath?: string;\n}\n\nexport interface GenerateResult {\n filesGenerated: string[];\n dslHash: string;\n generationInputHash: string;\n cleaned: boolean;\n checkMode: boolean;\n hasDifferences: boolean;\n}\n\nconst DO_NOT_EDIT_HEADER = `/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\n`;\n\nasync function loadYaml(filePath: string): Promise<unknown> {\n const raw = await readFile(filePath, \"utf8\");\n return YAML.parse(raw);\n}\n\nfunction computeHash(data: string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Load DSL — tries agent-contracts resolve() (which handles extends + merge\n * operators like $replace/$append) if available, then loadDsl() as fallback,\n * and finally raw YAML.\n */\nasync function loadDsl(dslPath: string): Promise<Record<string, unknown>> {\n try {\n const modName = \"agent-contracts\";\n const mod = await import(/* webpackIgnore: true */ modName);\n if (mod.resolve) {\n const result = await mod.resolve(dslPath);\n return (result as { data: Record<string, unknown> }).data;\n }\n if (mod.loadDsl) {\n const result = await mod.loadDsl(dslPath);\n return (result as { data: Record<string, unknown> }).data;\n }\n } catch {\n // agent-contracts not available — use raw YAML\n }\n return (await loadYaml(dslPath)) as Record<string, unknown>;\n}\n\nconst CONTRACT_TEMPLATES = [\n { template: \"agents.ts.hbs\", output: \"agents.ts\" },\n { template: \"tasks.ts.hbs\", output: \"tasks.ts\" },\n { template: \"workflows.ts.hbs\", output: \"workflows.ts\" },\n { template: \"handoffs.ts.hbs\", output: \"handoffs.ts\" },\n { template: \"contracts-index.ts.hbs\", output: \"index.ts\" },\n];\n\nconst GUARDRAIL_TEMPLATES = [\n { template: \"guardrails.ts.hbs\", output: \"hooks/guardrails.ts\" },\n { template: \"hooks-index.ts.hbs\", output: \"hooks/index.ts\" },\n];\n\nexport async function generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const configPath = options.configPath ?? \"./agent-runtime.config.yaml\";\n const config = await loadConfig(configPath);\n\n const templatesDir = options.templates ?? config.templatesDir;\n const checkMode = options.check ?? false;\n const cleaned = options.clean ?? false;\n\n if (cleaned && !checkMode) {\n try {\n await rm(config.generatedDir, { recursive: true, force: true });\n } catch {\n // directory may not exist\n }\n }\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const dslHash = computeHash(dslCanonical);\n\n const contractCtx = buildContractContext(dsl);\n\n const filesGenerated: string[] = [];\n const generatedContents: Map<string, string> = new Map();\n\n // Phase 1: Contract files\n for (const { template, output } of CONTRACT_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx as unknown as Record<string, unknown>, templatesDir);\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n\n // Phase 2: Guardrail hooks (only if bindings are configured)\n if (config.bindingPaths.length > 0) {\n for (const bindingPath of config.bindingPaths) {\n const binding = await loadYaml(bindingPath);\n const guardrailCtx = buildGuardrailContext(\n dsl,\n binding,\n config.active_guardrail_policy,\n );\n\n if (guardrailCtx.hasGuardrails) {\n for (const { template, output } of GUARDRAIL_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(\n template,\n guardrailCtx as unknown as Record<string, unknown>,\n templatesDir,\n );\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n }\n }\n }\n\n // Compute generation input hash (DSL + binding + generator version)\n const generationInputParts = [dslCanonical];\n for (const bp of config.bindingPaths) {\n try {\n generationInputParts.push(await readFile(bp, \"utf8\"));\n } catch {\n // binding may not exist\n }\n }\n const generationInputHash = computeHash(generationInputParts.join(\"\\n---\\n\"));\n\n // Check mode — compare without writing\n let hasDifferences = false;\n if (checkMode) {\n for (const [outPath, content] of generatedContents) {\n try {\n const existing = await readFile(outPath, \"utf8\");\n if (existing !== content) {\n hasDifferences = true;\n break;\n }\n } catch {\n hasDifferences = true;\n break;\n }\n }\n } else {\n // Write files\n for (const [outPath, content] of generatedContents) {\n const dir = resolve(outPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(outPath, content, \"utf8\");\n }\n\n // Write manifest\n const manifest = {\n generatedAt: new Date().toISOString(),\n dslHash,\n generationInputHash,\n files: filesGenerated,\n };\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n await mkdir(resolve(manifestPath, \"..\"), { recursive: true });\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\");\n }\n\n return {\n filesGenerated,\n dslHash,\n generationInputHash,\n cleaned,\n checkMode,\n hasDifferences,\n };\n}\n\nexport async function checkFreshness(configPath?: string): Promise<boolean> {\n const config = await loadConfig(configPath ?? \"./agent-runtime.config.yaml\");\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n try {\n const raw = await readFile(manifestPath, \"utf8\");\n const manifest = JSON.parse(raw) as { dslHash: string };\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const currentHash = computeHash(dslCanonical);\n\n return manifest.dslHash === currentHash;\n } catch {\n return false;\n }\n}\n\nexport { loadConfig, type ResolvedConfig } from \"./config.js\";\nexport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n","/**\n * Generator configuration — loads and validates agent-runtime.config.yaml\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, dirname } from \"node:path\";\nimport { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst RecoverySchema = z.object({\n max_follow_ups: z.number().int().min(0).default(2),\n max_retries: z.number().int().min(0).default(0),\n}).default(() => ({ max_follow_ups: 2, max_retries: 0 }));\n\nexport const RuntimeConfigSchema = z.object({\n dsl: z.string().default(\"./agent-contracts.yaml\"),\n generated_dir: z.string().default(\"./agent/generated\"),\n bindings: z.array(z.string()).default([]),\n active_guardrail_policy: z.string().optional(),\n templates_dir: z.string().optional(),\n plugins: z.array(z.string()).default([]),\n recovery: RecoverySchema,\n});\n\nexport type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;\n\nexport interface ResolvedConfig extends RuntimeConfig {\n configDir: string;\n dslPath: string;\n generatedDir: string;\n bindingPaths: string[];\n templatesDir: string | undefined;\n pluginPaths: string[];\n}\n\nexport async function loadConfig(configPath: string): Promise<ResolvedConfig> {\n const absPath = resolve(configPath);\n const raw = await readFile(absPath, \"utf8\");\n const parsed = YAML.parse(raw);\n const config = RuntimeConfigSchema.parse(parsed);\n const configDir = dirname(absPath);\n\n return {\n ...config,\n configDir,\n dslPath: resolve(configDir, config.dsl),\n generatedDir: resolve(configDir, config.generated_dir),\n bindingPaths: config.bindings.map((b) => resolve(configDir, b)),\n templatesDir: config.templates_dir\n ? resolve(configDir, config.templates_dir)\n : undefined,\n pluginPaths: config.plugins,\n };\n}\n","/**\n * Handlebars template engine with custom helpers for TypeScript code generation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport Handlebars from \"handlebars\";\n\nimport { existsSync } from \"node:fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\nfunction findPackageRoot(): string {\n let dir = __dirname;\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n dir = resolve(dir, \"..\");\n }\n return resolve(__dirname, \"..\");\n}\n\nconst BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), \"templates\");\n\nfunction toCamelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction toPascalCase(str: string): string {\n const camel = toCamelCase(str);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nconst hbs = Handlebars.create();\n\nhbs.registerHelper(\"camelCase\", (str: string) => toCamelCase(str));\nhbs.registerHelper(\"PascalCase\", (str: string) => toPascalCase(str));\n\nhbs.registerHelper(\"eq\", (a: unknown, b: unknown) => a === b);\nhbs.registerHelper(\"notEmpty\", (arr: unknown) =>\n Array.isArray(arr) ? arr.length > 0 : !!arr,\n);\n\nhbs.registerHelper(\"json\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value, null, 2)),\n);\n\nhbs.registerHelper(\"jsonInline\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value)),\n);\n\nhbs.registerHelper(\"indent\", (text: string, spaces: number) => {\n if (typeof text !== \"string\") return text;\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map((line, i) => (i === 0 ? line : pad + line))\n .join(\"\\n\");\n});\n\nhbs.registerHelper(\"zodType\", function zodType(schema: Record<string, unknown>): string {\n if (!schema || typeof schema !== \"object\") return \"z.unknown()\";\n\n if (schema.enum) {\n const vals = (schema.enum as string[]).map((v) => `\"${v}\"`).join(\", \");\n return `z.enum([${vals}])`;\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})`;\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return \"z.string()\";\n if (type === \"number\" || type === \"integer\") return \"z.number()\";\n if (type === \"boolean\") return \"z.boolean()\";\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? zodType(items) : \"z.unknown()\";\n return `z.array(${inner})`;\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return \"z.record(z.string(), z.unknown())\";\n\n const required = (schema.required as string[]) ?? [];\n const fields = Object.entries(props)\n .map(([key, val]) => {\n const base = zodType(val);\n const opt = required.includes(key) ? \"\" : \".optional()\";\n return ` ${key}: ${base}${opt},`;\n })\n .join(\"\\n\");\n return `z.object({\\n${fields}\\n})`;\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(zodType);\n if (parts.length === 1) return parts[0];\n return parts.reduce((acc, part) => `${acc}.extend(${part}.shape)`);\n }\n\n return \"z.unknown()\";\n});\n\nhbs.registerHelper(\"regexEscape\", (str: string) => {\n if (typeof str !== \"string\") return str;\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n});\n\nhbs.registerHelper(\"stringArray\", (arr: unknown) => {\n if (!Array.isArray(arr)) return \"[]\";\n return \"[\" + arr.map((s) => `\"${s}\"`).join(\", \") + \"]\";\n});\n\n/**\n * Load a template by name, with custom dir override fallback to built-in.\n */\nasync function loadTemplate(\n name: string,\n customDir?: string,\n): Promise<string> {\n if (customDir) {\n try {\n return await readFile(join(customDir, name), \"utf8\");\n } catch {\n // fallback to built-in\n }\n }\n return readFile(join(BUILTIN_TEMPLATES_DIR, name), \"utf8\");\n}\n\nexport async function renderTemplate(\n name: string,\n context: Record<string, unknown>,\n customDir?: string,\n): Promise<string> {\n const source = await loadTemplate(name, customDir);\n const compiled = hbs.compile(source, { noEscape: true });\n return compiled(context);\n}\n\nexport { hbs, toCamelCase, toPascalCase };\n","/**\n * Build template contexts from resolved DSL data\n */\n\nimport { toCamelCase, toPascalCase } from \"./template-engine.js\";\n\nexport interface AgentEntry {\n id: string;\n varName: string;\n role_name: string;\n purpose: string;\n mode: string;\n dispatch_only: boolean;\n can_read_artifacts: string[];\n can_write_artifacts: string[];\n can_execute_tools: string[];\n can_invoke_agents: string[];\n can_return_handoffs: string[];\n responsibilities: string[];\n constraints: string[];\n rules: Array<{ id: string; description: string; severity: string }>;\n escalation_criteria: Array<{ condition: string; action: string }>;\n}\n\nexport interface TaskEntry {\n id: string;\n varName: string;\n description: string;\n target_agent: string;\n allowed_from_agents: string[];\n workflow: string;\n invocation_handoff: string;\n result_handoff: string;\n input_artifacts: string[];\n responsibilities: string[];\n completion_criteria: string[];\n optional: boolean;\n}\n\nexport interface WorkflowStepEntry {\n type: string;\n task?: string;\n from_agent?: string;\n description?: string;\n optional?: boolean;\n max_retries?: number;\n max_follow_ups?: number;\n gate_kind?: string;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n}\n\nexport interface WorkflowEntry {\n id: string;\n varName: string;\n description: string;\n trigger: string;\n entry_conditions: string[];\n steps: WorkflowStepEntry[];\n}\n\nexport interface HandoffEntry {\n id: string;\n varName: string;\n pascalName: string;\n schemaName: string;\n description: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ContractContext {\n agentEntries: AgentEntry[];\n taskEntries: TaskEntry[];\n workflowEntries: WorkflowEntry[];\n handoffEntries: HandoffEntry[];\n}\n\n/**\n * Determine if a task is optional by checking if any workflow step referencing it is optional.\n */\nfunction isTaskOptional(\n taskId: string,\n workflows: Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n): boolean {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId && step.optional) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Compute max_retries from workflow step or fallback to 0.\n */\nfunction getMaxRetries(\n taskId: string,\n workflows: Record<string, { steps: Array<Record<string, unknown>> }>,\n): number {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId) {\n const retry = step.retry as { condition: string } | undefined;\n return retry ? 1 : 0;\n }\n }\n }\n return 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function buildContractContext(dsl: any): ContractContext {\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const tasks = (dsl.tasks ?? {}) as Record<string, Record<string, unknown>>;\n const workflows = (dsl.workflow ?? {}) as Record<string, Record<string, unknown>>;\n const handoffTypes = (dsl.handoff_types ?? {}) as Record<string, Record<string, unknown>>;\n\n const agentEntries: AgentEntry[] = Object.entries(agents).map(([id, agent]) => ({\n id,\n varName: toCamelCase(id),\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode: (agent.mode as string) ?? \"read-write\",\n dispatch_only: (agent.dispatch_only as boolean) ?? false,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_execute_tools: (agent.can_execute_tools as string[]) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as AgentEntry[\"rules\"]) ?? [],\n escalation_criteria: (agent.escalation_criteria as AgentEntry[\"escalation_criteria\"]) ?? [],\n }));\n\n const taskEntries: TaskEntry[] = Object.entries(tasks).map(([id, task]) => ({\n id,\n varName: toCamelCase(id),\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n allowed_from_agents: (task.allowed_from_agents as string[]) ?? [],\n workflow: (task.workflow as string) ?? \"\",\n invocation_handoff: (task.invocation_handoff as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n input_artifacts: (task.input_artifacts as string[]) ?? [],\n responsibilities: (task.responsibilities as string[]) ?? [],\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n optional: isTaskOptional(id, workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>),\n }));\n\n const workflowEntries: WorkflowEntry[] = Object.entries(workflows).map(\n ([id, wf]) => {\n const steps = ((wf.steps as Array<Record<string, unknown>>) ?? []).map((step) => {\n const entry: WorkflowStepEntry = { type: step.type as string };\n if (step.type === \"delegate\") {\n entry.task = step.task as string;\n entry.from_agent = step.from_agent as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n const wfStep = step as Record<string, unknown>;\n entry.optional = isTaskOptional(\n step.task as string,\n workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n );\n entry.max_retries = (wfStep.max_retries as number | undefined) ?? (wfStep.retry ? 1 : 0);\n entry.max_follow_ups = wfStep.max_follow_ups as number | undefined;\n if (wfStep.retry) {\n const r = wfStep.retry as Record<string, unknown>;\n entry.retry = {\n condition: r.condition as string,\n fix_task: r.fix_task as string,\n revalidate_task: r.revalidate_task as string | undefined,\n };\n }\n } else if (step.type === \"gate\") {\n entry.gate_kind = step.gate_kind as string;\n entry.description = (step.description as string | undefined) ?? \"\";\n }\n return entry;\n });\n\n return {\n id,\n varName: toCamelCase(id),\n description: (wf.description as string) ?? \"\",\n trigger: (wf.trigger as string) ?? \"\",\n entry_conditions: (wf.entry_conditions as string[]) ?? [],\n steps,\n };\n },\n );\n\n const handoffEntries: HandoffEntry[] = Object.entries(handoffTypes).map(\n ([id, ht]) => ({\n id,\n varName: toCamelCase(id),\n pascalName: toPascalCase(id),\n schemaName: toPascalCase(id) + \"Schema\",\n description: (ht.description as string) ?? \"\",\n schema: (ht.schema as Record<string, unknown>) ?? {},\n }),\n );\n\n return { agentEntries, taskEntries, workflowEntries, handoffEntries };\n}\n\nexport interface GuardrailCheckEntry {\n guardrail_id: string;\n description: string;\n severity: string;\n action: string;\n matcher_type: string;\n pattern: string;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailContext {\n commandChecks: GuardrailCheckEntry[];\n fileChecks: GuardrailCheckEntry[];\n contentChecks: GuardrailCheckEntry[];\n allChecks: GuardrailCheckEntry[];\n hasGuardrails: boolean;\n}\n\n/**\n * Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.\n * Mirrors the agent-contracts resolveChecks pattern.\n */\nexport function buildGuardrailContext(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dsl: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n binding: any,\n policyName?: string,\n): GuardrailContext {\n const empty: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (!binding?.guardrail_impl) return empty;\n\n const guardrails = dsl.guardrails ?? {};\n const policies = dsl.guardrail_policies ?? {};\n const policy = policyName ? policies[policyName] : undefined;\n\n const allChecks: GuardrailCheckEntry[] = [];\n\n for (const [guardrailId, impl] of Object.entries(\n binding.guardrail_impl as Record<string, { checks: Array<Record<string, unknown>> }>,\n )) {\n const guardrail = guardrails[guardrailId] as Record<string, unknown> | undefined;\n const description = (guardrail?.description as string) ?? guardrailId;\n\n const policyRule = policy?.rules?.find(\n (r: Record<string, unknown>) => r.guardrail === guardrailId,\n );\n const severity = (policyRule?.severity as string) ?? \"warning\";\n const action = (policyRule?.action as string) ?? \"warn\";\n\n for (const check of impl.checks) {\n const matcher = check.matcher as Record<string, unknown> | undefined;\n if (!matcher) continue;\n\n allChecks.push({\n guardrail_id: guardrailId,\n description,\n severity,\n action,\n matcher_type: matcher.type as string,\n pattern: matcher.pattern as string,\n message: (check.message as string) ?? description,\n file_glob: matcher.file_glob as string | undefined,\n exclude_glob: matcher.exclude_glob as string | undefined,\n });\n }\n }\n\n return {\n commandChecks: allChecks.filter((c) => c.matcher_type === \"command_regex\"),\n fileChecks: allChecks.filter((c) => c.matcher_type === \"file_glob\"),\n contentChecks: allChecks.filter((c) => c.matcher_type === \"content_regex\"),\n allChecks,\n hasGuardrails: allChecks.length > 0,\n };\n}\n"],"mappings":";AAIA,SAAS,YAAAA,WAAU,WAAW,OAAO,UAAgB;AACrD,SAAS,WAAAC,UAAS,QAAAC,OAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,OAAOC,WAAU;;;ACHjB,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AACjC,SAAS,SAAS;AAClB,OAAO,UAAU;AAEjB,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QA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;AAAA,EAC9B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["readFile","resolve","join","YAML","readFile","resolve","readFile","YAML","join","resolve"]}
|
package/dist/cli/index.js
CHANGED
|
@@ -4,12 +4,12 @@ import {
|
|
|
4
4
|
loadPlugins,
|
|
5
5
|
pluginRegistry,
|
|
6
6
|
runWorkflow
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-3NE3OA6F.js";
|
|
8
8
|
import {
|
|
9
9
|
checkFreshness,
|
|
10
10
|
generate,
|
|
11
11
|
loadConfig
|
|
12
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-V52RRB44.js";
|
|
13
13
|
|
|
14
14
|
// src/cli/index.ts
|
|
15
15
|
import { existsSync, readFileSync } from "fs";
|
|
@@ -48,7 +48,7 @@ function createProgram(handlers2, version) {
|
|
|
48
48
|
|
|
49
49
|
// src/cli/index.ts
|
|
50
50
|
import YAML from "yaml";
|
|
51
|
-
var VERSION = "0.
|
|
51
|
+
var VERSION = "0.8.1";
|
|
52
52
|
async function loadGeneratedContracts(configPath) {
|
|
53
53
|
const config = await loadConfig(configPath);
|
|
54
54
|
const basePath = `${config.generatedDir}/index`;
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.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 { 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 type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst VERSION = \"0.6.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.ZodTypeAny>;\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 console.log(\"agent-runtime init — not yet implemented\");\n console.log(\"Options:\", JSON.stringify(options));\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 console.log(\"agent-runtime doctor — not yet implemented\");\n },\n\n async replay(runDir, options, _globalOpts) {\n console.log(\"agent-runtime replay — not yet implemented\");\n console.log(`Run dir: ${runDir}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n};\n\nconst program = createProgram(handlers, VERSION);\nprogram.parse();\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 replay: (runDir: string | undefined, options: { validateOnly?: boolean }, 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 program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) =>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,KAAK,CAAC;AACd;AAAA,IACF;AAEA,UAAM,iBAAiB,QAAQ,eAAe;AAC9C,QAAI,gBAAgB;AAClB,YAAM,mBAAmB,MAAM,WAAW,UAAU;AACpD,YAAM,YAAY;AAAA,QAChB,aAAa,iBAAiB,YAAY,SAAS,IAAI,iBAAiB,cAAc;AAAA,QACtF,YAAY,iBAAiB;AAAA,MAC/B,CAAC;AAAA,IACH;AAEA,UAAM,cAAc,QAAQ,eAAe;AAC3C,QAAI,SAAS,gBAAgB,OAAO,MAAM,EAAE,cAAc,YAAY,GAAG;AAAA,MACvE,gBAAgB,UAAU;AAAA,IAC5B,CAAC;AAED,QAAI,gBAAgB;AAClB,eAAS,eAAe,qBAAqB,QAAQ,QAAQ,EAAE,cAAc,YAAY,CAAC;AAAA,IAC5F;AAEA,UAAM,SAAS,QAAQ,UAAU;AACjC,QAAI,WAAW,QAAQ;AACrB,cAAQ,IAAI,KAAK,UAAU;AAAA,QACzB,SAAS;AAAA,QACT,UAAU,KAAK;AAAA,QACf;AAAA,QACA,gBAAgB,KAAK;AAAA,QACrB,iBAAiB;AAAA,MACnB,GAAG,MAAM,CAAC,CAAC;AAAA,IACb,OAAO;AACL,cAAQ,IAAI,MAAM;AAAA,IACpB;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,aAAa;AACxB,YAAQ,IAAI,iDAA4C;AAAA,EAC1D;AAAA,EAEA,MAAM,OAAO,QAAQ,SAAS,aAAa;AACzC,YAAQ,IAAI,iDAA4C;AACxD,YAAQ,IAAI,YAAY,MAAM,EAAE;AAChC,YAAQ,IAAI,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,EACjD;AACF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,QAAQ,MAAM;","names":["handlers","program"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/index.ts","../../src/generated/cli/program.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 { 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 type { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst VERSION = \"0.8.1\";\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 console.log(\"agent-runtime init — not yet implemented\");\n console.log(\"Options:\", JSON.stringify(options));\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 console.log(\"agent-runtime doctor — not yet implemented\");\n },\n\n async replay(runDir, options, _globalOpts) {\n console.log(\"agent-runtime replay — not yet implemented\");\n console.log(`Run dir: ${runDir}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n};\n\nconst program = createProgram(handlers, VERSION);\nprogram.parse();\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 replay: (runDir: string | undefined, options: { validateOnly?: boolean }, 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 program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) => {\n await handlers.replay(runDir, opts, cmd.optsWithGlobals());\n });\n\n return program;\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,SAAS,YAAY,oBAAoB;;;ACPzC,SAAS,eAAe;AAYjB,SAAS,cACdA,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,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AACxD,YAAQ,IAAI,YAAY,MAAM,EAAE;AAChC,YAAQ,IAAI,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,EACjD;AACF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,QAAQ,MAAM;","names":["handlers","program"]}
|
|
@@ -7,43 +7,15 @@ import { z } from 'zod';
|
|
|
7
7
|
declare const RuntimeConfigSchema: z.ZodObject<{
|
|
8
8
|
dsl: z.ZodDefault<z.ZodString>;
|
|
9
9
|
generated_dir: z.ZodDefault<z.ZodString>;
|
|
10
|
-
bindings: z.ZodDefault<z.ZodArray<z.ZodString
|
|
10
|
+
bindings: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
11
11
|
active_guardrail_policy: z.ZodOptional<z.ZodString>;
|
|
12
12
|
templates_dir: z.ZodOptional<z.ZodString>;
|
|
13
|
-
plugins: z.ZodDefault<z.ZodArray<z.ZodString
|
|
13
|
+
plugins: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
14
14
|
recovery: z.ZodDefault<z.ZodObject<{
|
|
15
15
|
max_follow_ups: z.ZodDefault<z.ZodNumber>;
|
|
16
16
|
max_retries: z.ZodDefault<z.ZodNumber>;
|
|
17
|
-
},
|
|
18
|
-
|
|
19
|
-
max_retries: number;
|
|
20
|
-
}, {
|
|
21
|
-
max_follow_ups?: number | undefined;
|
|
22
|
-
max_retries?: number | undefined;
|
|
23
|
-
}>>;
|
|
24
|
-
}, "strip", z.ZodTypeAny, {
|
|
25
|
-
dsl: string;
|
|
26
|
-
generated_dir: string;
|
|
27
|
-
bindings: string[];
|
|
28
|
-
plugins: string[];
|
|
29
|
-
recovery: {
|
|
30
|
-
max_follow_ups: number;
|
|
31
|
-
max_retries: number;
|
|
32
|
-
};
|
|
33
|
-
active_guardrail_policy?: string | undefined;
|
|
34
|
-
templates_dir?: string | undefined;
|
|
35
|
-
}, {
|
|
36
|
-
dsl?: string | undefined;
|
|
37
|
-
generated_dir?: string | undefined;
|
|
38
|
-
bindings?: string[] | undefined;
|
|
39
|
-
active_guardrail_policy?: string | undefined;
|
|
40
|
-
templates_dir?: string | undefined;
|
|
41
|
-
plugins?: string[] | undefined;
|
|
42
|
-
recovery?: {
|
|
43
|
-
max_follow_ups?: number | undefined;
|
|
44
|
-
max_retries?: number | undefined;
|
|
45
|
-
} | undefined;
|
|
46
|
-
}>;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
}, z.core.$strip>;
|
|
47
19
|
type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;
|
|
48
20
|
interface ResolvedConfig extends RuntimeConfig {
|
|
49
21
|
configDir: string;
|
package/dist/generator/index.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, S as SdkAdapter, P as PromptBuilderOptions } from './task-runner-
|
|
2
|
-
export { A as AdapterSendOptions, a as AgentExecutionRequest, R as RetryDecision, e as TaskRunOptions, f as TaskRunResult, g as buildRetryFollowUp, h as buildTaskPrompt, i as extractStructuredResult, r as runTask, z as zodSchemaToPromptDescription, j as zodSchemaToYamlExample } from './task-runner-
|
|
1
|
+
import { T as TaskOutcome, b as TaskContractLike, c as AgentContractLike, d as TaskContext, S as SdkAdapter, P as PromptBuilderOptions } from './task-runner-D8b31ZL_.js';
|
|
2
|
+
export { A as AdapterSendOptions, a as AgentExecutionRequest, R as RetryDecision, e as TaskRunOptions, f as TaskRunResult, g as buildRetryFollowUp, h as buildTaskPrompt, i as extractStructuredResult, r as runTask, z as zodSchemaToPromptDescription, j as zodSchemaToYamlExample } from './task-runner-D8b31ZL_.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
export { a as GuardrailCheckFunctions, b as GuardrailCheckResult, G as GuardrailHooks, H as HookContext, c as HookResponse, d as createGuardrailHooks, g as getBlockingViolations, e as getWarnings, h as hasBlockingViolation } from './guardrail-hooks-5MSNWxnl.js';
|
|
5
5
|
|
|
@@ -126,7 +126,7 @@ interface WorkflowRegistries {
|
|
|
126
126
|
workflowRegistry?: Record<string, WorkflowContractLike>;
|
|
127
127
|
taskRegistry?: Record<string, TaskContractLike>;
|
|
128
128
|
agentRegistry?: Record<string, AgentContractLike>;
|
|
129
|
-
handoffSchemas?: Record<string, z.
|
|
129
|
+
handoffSchemas?: Record<string, z.ZodType>;
|
|
130
130
|
}
|
|
131
131
|
/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */
|
|
132
132
|
declare function runWorkflow(adapter: SdkAdapter, workflowId: string, options: WorkflowRunOptions, registries?: WorkflowRegistries): Promise<WorkflowResult>;
|
package/dist/index.js
CHANGED
|
@@ -141,13 +141,13 @@ interface TaskRunResult {
|
|
|
141
141
|
/**
|
|
142
142
|
* Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.
|
|
143
143
|
*/
|
|
144
|
-
declare function zodSchemaToPromptDescription(schema: z.
|
|
144
|
+
declare function zodSchemaToPromptDescription(schema: z.ZodType): string;
|
|
145
145
|
/**
|
|
146
146
|
* Generate a minimal YAML example from a Zod schema shape.
|
|
147
147
|
*/
|
|
148
|
-
declare function zodSchemaToYamlExample(schema: z.
|
|
148
|
+
declare function zodSchemaToYamlExample(schema: z.ZodType): string;
|
|
149
149
|
interface PromptBuilderOptions {
|
|
150
|
-
handoffSchemas?: Record<string, z.
|
|
150
|
+
handoffSchemas?: Record<string, z.ZodType>;
|
|
151
151
|
retry?: {
|
|
152
152
|
condition: string;
|
|
153
153
|
fix_task: string;
|
|
@@ -160,7 +160,7 @@ declare function buildRetryFollowUp(task: TaskContractLike, lastOutcome: TaskOut
|
|
|
160
160
|
declare function runTask(adapter: SdkAdapter, taskId: string, context: TaskContext, options?: TaskRunOptions & {
|
|
161
161
|
agentRegistry?: Record<string, AgentContractLike>;
|
|
162
162
|
taskRegistry?: Record<string, TaskContractLike>;
|
|
163
|
-
handoffSchemas?: Record<string, z.
|
|
163
|
+
handoffSchemas?: Record<string, z.ZodType>;
|
|
164
164
|
retry?: {
|
|
165
165
|
condition: string;
|
|
166
166
|
fix_task: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-contracts-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Runtime bridge for executing agent-contracts workflows on Agent SDKs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"dotenv": "^17.4.2",
|
|
87
87
|
"handlebars": "^4.7.9",
|
|
88
88
|
"yaml": "^2.8.3",
|
|
89
|
-
"zod": "^
|
|
89
|
+
"zod": "^4.0.0"
|
|
90
90
|
},
|
|
91
91
|
"devDependencies": {
|
|
92
92
|
"@types/node": "^25.6.0",
|
|
@@ -99,6 +99,7 @@
|
|
|
99
99
|
"peerDependencies": {
|
|
100
100
|
"@anthropic-ai/claude-agent-sdk": ">=0.2.0",
|
|
101
101
|
"@cursor/sdk": ">=1.0.0",
|
|
102
|
+
"@openai/agents": ">=0.10.0",
|
|
102
103
|
"agent-contracts": "^0.17.0"
|
|
103
104
|
},
|
|
104
105
|
"peerDependenciesMeta": {
|
|
@@ -110,6 +111,9 @@
|
|
|
110
111
|
},
|
|
111
112
|
"@anthropic-ai/claude-agent-sdk": {
|
|
112
113
|
"optional": true
|
|
114
|
+
},
|
|
115
|
+
"@openai/agents": {
|
|
116
|
+
"optional": true
|
|
113
117
|
}
|
|
114
118
|
}
|
|
115
119
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/workflow-runner.ts","../src/lib/guardrail-hooks.ts","../src/lib/builder.ts","../src/lib/plugin-loader.ts"],"sourcesContent":["/**\n * Task Runner — runs a single DSL task via an SDK agent\n *\n * Responsibilities:\n * 1. Resolve task contract → target agent contract\n * 2. Build the agent prompt from contract + context\n * 3. Apply plugin prompt enhancers and beforeTask hooks\n * 4. Send to SDK agent (via abstract SdkAdapter) and stream result\n * 5. Parse + validate result against handoff schema\n * 6. Apply plugin afterTask hooks\n * 7. Return typed result or escalation signal\n *\n * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\n/**\n * Base options for SdkAdapter.send(). SDK-specific options (model, cwd,\n * sessionMode, etc.) belong on the adapter constructor / factory — not here.\n */\nexport interface AdapterSendOptions {\n readonly: boolean;\n}\n\n/**\n * Rich execution request for adapters that need more than a prompt string.\n * Adapters can implement sendExecution() to receive full contract context.\n */\nexport interface AgentExecutionRequest {\n agentId: string;\n taskId: string;\n prompt: string;\n\n handoff?: {\n type: string;\n payload: unknown;\n };\n\n schema?: {\n handoffType: string;\n zodSchema: unknown;\n promptDescription: string;\n };\n\n context: TaskContext;\n\n options: AdapterSendOptions & {\n maxFollowUps: number;\n attempt: number;\n };\n}\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: AdapterSendOptions): Promise<string>;\n\n /**\n * Send a follow-up message within the same agent session.\n * Used for output-format corrections without re-executing the task.\n * Falls back to send() if not implemented (stateless adapters like mock).\n */\n followUp?(message: string): Promise<string>;\n\n /**\n * Rich execution path. When implemented, the runtime prefers this over\n * send() and passes the full contract context. Adapters that only need\n * a prompt string can ignore this — the runtime falls back to send().\n */\n sendExecution?(request: AgentExecutionRequest): Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TaskContext {\n user_request: string;\n prior_context?: string;\n relevant_paths?: string[];\n acceptance_criteria?: string[];\n\n /**\n * Structured handoff input (primary data). When present, prompt builders\n * should derive the prompt from this rather than user_request alone.\n */\n handoff_input?: {\n type: string;\n version?: number;\n payload: unknown;\n };\n\n /** Arbitrary structured variables plugins or workflow context may inject. */\n variables?: Record<string, unknown>;\n}\n\nexport type TaskOutcome =\n | { status: \"success\"; data: unknown; raw: string }\n | { status: \"validation_error\"; errors: z.ZodError; raw: string }\n | { status: \"escalation\"; reason: string; raw: string }\n | { status: \"error\"; message: string };\n\n/**\n * Retry strategy decision.\n *\n * - \"follow_up\": lightweight — same session, fix output format only\n * - \"retry\": heavyweight — new send(), re-execute the entire task\n * - \"abort\": stop retrying, return the current outcome\n */\nexport type RetryDecision = \"follow_up\" | \"retry\" | \"abort\";\n\nexport interface TaskRunOptions {\n /** Max follow-up attempts (output format correction, same session). Default: 2 */\n maxFollowUps?: number;\n /** Max full retry attempts (re-execute entire task via send). Default: 0 */\n maxRetries?: number;\n /**\n * Called on each failure to decide which recovery strategy to use.\n * Default: validation_error → follow_up, empty output → retry, else abort.\n */\n decideRetryStrategy?: (\n outcome: TaskOutcome,\n counts: { followUps: number; retries: number },\n ) => Promise<RetryDecision> | RetryDecision;\n}\n\nexport interface TaskRunResult {\n outcome: TaskOutcome;\n follow_ups_used: number;\n retries_used: number;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-to-prompt description utility\n// ---------------------------------------------------------------------------\n\ninterface FieldDescriptor {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n}\n\nfunction zodTypeToString(schema: z.ZodTypeAny): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema as z.ZodEnum<[string, ...string[]]>).options.join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema as z.ZodLiteral<unknown>)._def.value)}\"`;\n if (schema instanceof z.ZodArray) {\n const inner = zodTypeToString((schema as z.ZodArray<z.ZodTypeAny>)._def.type);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodTypeAny>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\nfunction extractFieldDescriptors(schema: z.ZodTypeAny): FieldDescriptor[] | null {\n let shape: z.ZodRawShape | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<z.ZodRawShape>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodTypeAny>)._def.innerType : field;\n const description = innerField._def.description ?? field._def.description;\n return {\n name,\n type: zodTypeToString(field as z.ZodTypeAny),\n required: !isOptional,\n description,\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodTypeAny): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const header = \"| Field | Type | Required | Description |\";\n const sep = \"|-------|------|----------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.description ?? \"\"} |`,\n );\n return [header, sep, ...rows].join(\"\\n\");\n}\n\n/**\n * Generate a minimal YAML example from a Zod schema shape.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodTypeAny): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const lines: string[] = [];\n for (const f of fields) {\n if (f.type.endsWith(\"[]\")) {\n const innerType = f.type.slice(0, -2);\n if (innerType === \"string\") {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n } else if (innerType === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` - key: \"value\"`);\n } else {\n lines.push(`${f.name}:`);\n lines.push(` - \"example\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${f.name}: false`);\n } else if (f.type === \"object\") {\n lines.push(`${f.name}:`);\n lines.push(` key: \"value\"`);\n } else {\n lines.push(`${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n sections.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (context.handoff_input) {\n const hi = context.handoff_input;\n const payloadStr = typeof hi.payload === \"string\"\n ? hi.payload\n : yaml.stringify(hi.payload);\n sections.push(`## User Request\\n\\n${context.user_request}`);\n sections.push(`## Handoff Input (${hi.type})\\n\\n\\`\\`\\`yaml\\n${payloadStr}\\`\\`\\``);\n } else {\n sections.push(`## User Request\\n\\n${context.user_request}`);\n }\n\n if (context.prior_context) {\n sections.push(`## Prior Context\\n\\n${context.prior_context}`);\n }\n\n if (context.relevant_paths && context.relevant_paths.length > 0) {\n sections.push(\n `## Relevant Files\\n\\n${context.relevant_paths.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n }\n\n if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {\n sections.push(\n `## Acceptance Criteria\\n\\n${context.acceptance_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let outputSection = `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n outputSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n outputSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n outputSection += ` Include all required fields.`;\n }\n\n sections.push(outputSection);\n\n if (options?.retry) {\n const r = options.retry;\n let recoverySection = `## Recovery Instructions\\n\\nIf the task fails due to: \"${r.condition}\"\\n→ Apply the recovery approach from task \"${r.fix_task}\"`;\n if (r.revalidate_task) {\n recoverySection += `\\n→ Then revalidate using task \"${r.revalidate_task}\"`;\n }\n sections.push(recoverySection);\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Result parser\n// ---------------------------------------------------------------------------\n\nexport function extractStructuredResult(raw: string): unknown | null {\n const yamlMatch = raw.match(/```ya?ml\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n try { return yaml.parse(yamlMatch[1]); } catch { /* fall through */ }\n }\n\n const jsonMatch = raw.match(/```json\\n([\\s\\S]*?)```/);\n if (jsonMatch) {\n try { return JSON.parse(jsonMatch[1]); } catch { /* fall through */ }\n }\n\n try { return JSON.parse(raw); } catch { /* not JSON */ }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodTypeAny>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n sections.push(\n \"Your previous response could not be validated. \" +\n \"The task work itself is fine — please re-output only the structured result block in the correct format.\",\n );\n\n if (lastOutcome.status === \"validation_error\") {\n sections.push(`Validation errors:\\n${lastOutcome.errors.message}`);\n } else if (lastOutcome.status === \"error\") {\n sections.push(`Error: ${lastOutcome.message}`);\n }\n\n const handoffId = task.result_handoff;\n const schema = options?.handoffSchemas?.[handoffId];\n let formatSection = `Required format: Return your result as a YAML block matching the \"${handoffId}\" schema.`;\n\n if (schema) {\n const fieldTable = zodSchemaToPromptDescription(schema);\n if (fieldTable) {\n formatSection += `\\n\\n${fieldTable}`;\n }\n\n const yamlExample = zodSchemaToYamlExample(schema);\n if (yamlExample) {\n formatSection += `\\n\\nExample:\\n\\n\\`\\`\\`yaml\\n${yamlExample}\\n\\`\\`\\``;\n }\n } else {\n formatSection += ` Include all required fields.`;\n }\n\n sections.push(formatSection);\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n },\n): Promise<TaskRunResult> {\n const taskReg = options?.taskRegistry ?? {};\n const agentReg = options?.agentRegistry ?? {};\n const schemas = options?.handoffSchemas ?? {};\n\n const task = taskReg[taskId];\n if (!task) return { outcome: { status: \"error\", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { outcome: { status: \"error\", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { outcome: { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);\n\n const promptOpts: PromptBuilderOptions = { handoffSchemas: schemas, retry: options?.retry };\n const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };\n let prompt = pluginRegistry.applyPromptBuilder(builderArgs)\n ?? buildTaskPrompt(agentContract, task, enrichedContext, promptOpts);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);\n\n const isReadonly = agentContract.mode === \"read-only\";\n const maxFollowUps = options?.maxFollowUps ?? 2;\n const maxRetries = options?.maxRetries ?? 0;\n const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;\n\n let followUpsUsed = 0;\n let retriesUsed = 0;\n\n // --- Initial send (prefer sendExecution if available) ---\n let fullOutput: string;\n try {\n if (adapter.sendExecution) {\n fullOutput = await adapter.sendExecution({\n agentId: agentContract.id,\n taskId,\n prompt,\n handoff: schemas[task.result_handoff]\n ? { type: task.result_handoff, payload: undefined }\n : undefined,\n schema: schemas[task.result_handoff]\n ? {\n handoffType: task.result_handoff,\n zodSchema: schemas[task.result_handoff],\n promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff]),\n }\n : undefined,\n context: enrichedContext,\n options: { readonly: isReadonly, maxFollowUps, attempt: 0 },\n });\n } else {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\n }\n } catch (err) {\n return { outcome: { status: \"error\", message: `SDK error: ${(err as Error).message}` }, follow_ups_used: 0, retries_used: 0 };\n }\n\n let outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n\n // --- Recovery loop ---\n while (outcome.status === \"validation_error\" || outcome.status === \"error\") {\n const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });\n\n if (decision === \"abort\") break;\n\n // If requested strategy is exhausted, escalate to the other\n let effectiveDecision = decision;\n if (effectiveDecision === \"follow_up\" && followUpsUsed >= maxFollowUps) {\n effectiveDecision = \"retry\";\n }\n if (effectiveDecision === \"retry\" && retriesUsed >= maxRetries) {\n break;\n }\n\n if (effectiveDecision === \"follow_up\") {\n followUpsUsed++;\n\n const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);\n try {\n if (adapter.followUp) {\n fullOutput = await adapter.followUp(followUpPrompt);\n } else {\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- FollowUp ${followUpsUsed} ---\\n${followUpPrompt}`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n }\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on followUp ${followUpsUsed}: ${(err as Error).message}` };\n continue;\n }\n } else {\n // effectiveDecision === \"retry\" — full re-execution\n retriesUsed++;\n\n const retryContext: TaskContext = {\n ...modifiedContext,\n prior_context: (modifiedContext.prior_context ?? \"\") +\n `\\n\\n--- Full Retry ${retriesUsed} ---\\nPrevious attempt failed: ` +\n (outcome.status === \"validation_error\"\n ? `Validation errors: ${outcome.errors.message}`\n : outcome.status === \"error\" ? outcome.message : \"unknown\") +\n `\\nPlease re-execute the entire task.`,\n };\n let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);\n retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);\n\n try {\n fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });\n } catch (err) {\n outcome = { status: \"error\", message: `SDK error on retry ${retriesUsed}: ${(err as Error).message}` };\n continue;\n }\n }\n\n outcome = validateOutput(fullOutput, task, schemas);\n outcome = await pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome, AgentContractLike, TaskContractLike, PromptBuilderOptions } from \"./task-runner.js\";\nimport type { WorkflowResult } from \"./workflow-runner.js\";\n\nexport interface GuardrailResult {\n matched: boolean;\n guardrail_id: string;\n severity: \"critical\" | \"mandatory\" | \"warning\" | \"info\";\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface PromptBuilderArgs {\n agent: AgentContractLike;\n task: TaskContractLike;\n context: TaskContext;\n options?: PromptBuilderOptions;\n}\n\nexport interface AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n /**\n * Enrich the structured TaskContext before prompt generation.\n * Unlike beforeTask (which can skip a task by returning null),\n * this hook is purely for context augmentation.\n */\n contextEnhancer?(taskId: string, context: TaskContext): TaskContext;\n /**\n * Lightweight prompt post-processor. Applied after the prompt is built.\n * Use for appending instructions or modifying sections.\n */\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\n /**\n * Full prompt builder override. If provided and returns a non-null string,\n * replaces the default buildTaskPrompt output entirely.\n * Receives the agent/task contracts and context so the plugin can build\n * a completely custom prompt.\n */\n promptBuilder?(args: PromptBuilderArgs): string | null;\n customGuardrails?: {\n evaluateCommand?(command: string): GuardrailResult[];\n evaluateFilePath?(filePath: string): GuardrailResult[];\n evaluateFileContent?(filePath: string, content: string): GuardrailResult[];\n };\n beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;\n afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;\n}\n\nexport class PluginRegistry {\n private plugins: AgentPlugin[] = [];\n\n register(plugin: AgentPlugin): void {\n if (this.plugins.some((p) => p.id === plugin.id)) {\n throw new Error(`Plugin \"${plugin.id}\" is already registered`);\n }\n this.plugins.push(plugin);\n }\n\n getAll(): readonly AgentPlugin[] {\n return this.plugins;\n }\n\n async runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null> {\n let ctx: TaskContext | null = context;\n for (const plugin of this.plugins) {\n if (!plugin.beforeTask || ctx === null) continue;\n ctx = await plugin.beforeTask(taskId, ctx);\n }\n return ctx;\n }\n\n async runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome> {\n let result = outcome;\n for (const plugin of this.plugins) {\n if (!plugin.afterTask) continue;\n result = await plugin.afterTask(taskId, result);\n }\n return result;\n }\n\n applyContextEnhancers(taskId: string, context: TaskContext): TaskContext {\n let ctx = context;\n for (const plugin of this.plugins) {\n if (!plugin.contextEnhancer) continue;\n ctx = plugin.contextEnhancer(taskId, ctx);\n }\n return ctx;\n }\n\n /**\n * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,\n * or null to use the default buildTaskPrompt.\n */\n applyPromptBuilder(args: PromptBuilderArgs): string | null {\n for (const plugin of this.plugins) {\n if (!plugin.promptBuilder) continue;\n const result = plugin.promptBuilder(args);\n if (result !== null) return result;\n }\n return null;\n }\n\n applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string {\n let enhanced = prompt;\n for (const plugin of this.plugins) {\n if (!plugin.promptEnhancer) continue;\n enhanced = plugin.promptEnhancer(taskId, enhanced, context);\n }\n return enhanced;\n }\n\n evaluateCommandGuardrails(command: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateCommand) continue;\n results.push(...plugin.customGuardrails.evaluateCommand(command));\n }\n return results;\n }\n\n evaluateFilePathGuardrails(filePath: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFilePath) continue;\n results.push(...plugin.customGuardrails.evaluateFilePath(filePath));\n }\n return results;\n }\n\n evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[] {\n const results: GuardrailResult[] = [];\n for (const plugin of this.plugins) {\n if (!plugin.customGuardrails?.evaluateFileContent) continue;\n results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));\n }\n return results;\n }\n\n async runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.beforeWorkflow) continue;\n await plugin.beforeWorkflow(workflowId, userRequest);\n }\n }\n\n async runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void> {\n for (const plugin of this.plugins) {\n if (!plugin.afterWorkflow) continue;\n await plugin.afterWorkflow(workflowId, result);\n }\n }\n}\n\nexport const pluginRegistry = new PluginRegistry();\n","/**\n * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions\n *\n * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n readonly max_follow_ups?: number;\n readonly retry?: {\n readonly condition: string;\n readonly fix_task: string;\n readonly revalidate_task?: string;\n };\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n /** Override max follow-up attempts per step (lightweight output-format correction). Default: 2 */\n maxFollowUps?: number;\n /** Override max full retry attempts per step. Default: from DSL step.max_retries */\n maxRetries?: number;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowInvocation — SDK-independent structured envelope (G3 / G1)\n// ---------------------------------------------------------------------------\n\n/** Typed handoff envelope for workflow input. */\nexport interface HandoffInput<\n TType extends string = string,\n TPayload = unknown,\n> {\n readonly type: TType;\n readonly version?: number;\n readonly payload: TPayload;\n}\n\n/**\n * Standard runtime invocation envelope. SDK-specific options (cursorSessionId,\n * openaiThreadId, etc.) belong on the adapter constructor — not here.\n */\nexport interface WorkflowInvocation<\n THandoffType extends string = string,\n TPayload = unknown,\n> {\n workflow: string;\n\n /** Structured typed handoff input. Takes precedence over user_request if both are set. */\n handoff?: HandoffInput<THandoffType, TPayload>;\n\n /** Simple string input (convenience shorthand). */\n user_request?: string;\n\n runtime?: {\n maxFollowUps?: number;\n maxRetries?: number;\n timeoutMs?: number;\n readonly?: boolean;\n dryRun?: boolean;\n };\n\n hooks?: {\n onStepComplete?: (event: StepCompleteEvent) => void;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\n };\n\n context?: {\n cwd?: string;\n environment?: \"local\" | \"ci\" | \"remote\";\n artifacts?: Record<string, string>;\n variables?: Record<string, unknown>;\n };\n}\n\nexport interface StepResult {\n step_index: number;\n task_id?: string;\n gate_kind?: string;\n outcome: TaskOutcome | { status: \"gate_approved\" } | { status: \"gate_rejected\" } | { status: \"skipped\" };\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface StepCompleteEvent {\n workflow_id: string;\n step_index: number;\n step_type: \"delegate\" | \"gate\";\n task_id?: string;\n gate_kind?: string;\n outcome_status: string;\n follow_ups_used: number;\n retries_used: number;\n elapsed_ms: number;\n}\n\nexport interface WorkflowResult {\n workflow_id: string;\n status: \"completed\" | \"escalated\" | \"gate_rejected\" | \"error\";\n steps: StepResult[];\n total_elapsed_ms: number;\n escalation_reason?: string;\n error_message?: string;\n}\n\nexport interface WorkflowRegistries {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a WorkflowInvocation into the legacy (workflowId, WorkflowRunOptions) pair.\n * If a typed handoff is provided, serialise its payload as the user_request\n * context and attach a structured handoff_context prefix so the prompt builder\n * can reference it.\n */\nfunction resolveInvocation(invocation: WorkflowInvocation): {\n workflowId: string;\n options: WorkflowRunOptions;\n} {\n let userRequest: string;\n if (invocation.handoff) {\n const h = invocation.handoff;\n userRequest = invocation.user_request\n ? invocation.user_request\n : typeof h.payload === \"string\"\n ? h.payload\n : JSON.stringify(h.payload, null, 2);\n } else {\n userRequest = invocation.user_request ?? \"\";\n }\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n onGate: invocation.hooks?.onGate,\n onStepComplete: invocation.hooks?.onStepComplete,\n onOptionalStep: invocation.hooks?.onOptionalStep,\n },\n };\n}\n\n/** @deprecated Use the WorkflowInvocation overload for typed handoff input. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\n/** Structured invocation with typed handoff envelope. */\nexport function runWorkflow(\n adapter: SdkAdapter,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapter: SdkAdapter,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n let workflowId: string;\n let options: WorkflowRunOptions;\n let registries: WorkflowRegistries | undefined;\n let invocationHandoff: HandoffInput | undefined;\n\n if (typeof workflowIdOrInvocation === \"string\") {\n workflowId = workflowIdOrInvocation;\n options = optionsOrRegistries as WorkflowRunOptions;\n registries = maybeRegistries;\n } else {\n const resolved = resolveInvocation(workflowIdOrInvocation);\n workflowId = resolved.workflowId;\n options = resolved.options;\n registries = optionsOrRegistries as WorkflowRegistries | undefined;\n invocationHandoff = workflowIdOrInvocation.handoff;\n }\n\n // --- G9: Validate input handoff against schema if available ---\n if (invocationHandoff && registries?.handoffSchemas) {\n const inputSchema = registries.handoffSchemas[invocationHandoff.type];\n if (inputSchema) {\n const validation = inputSchema.safeParse(invocationHandoff.payload);\n if (!validation.success) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Input handoff validation failed for \"${invocationHandoff.type}\": ${validation.error.message}`,\n };\n }\n }\n }\n\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n const stepResults: StepResult[] = [];\n const workflowStart = Date.now();\n let accumulatedContext = \"\";\n\n for (let i = 0; i < workflow.steps.length; i++) {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n const result = await handleGateStep(step, stepResults, options, i);\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"gate_rejected\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n continue;\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: accumulatedContext };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: accumulatedContext,\n ...(invocationHandoff ? { handoff_input: invocationHandoff } : {}),\n };\n const taskResult: TaskRunResult = await runTask(adapter, step.task, context, {\n maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,\n maxRetries: options.maxRetries ?? step.max_retries ?? 0,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n retry: step.retry,\n });\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Accumulate context from successful steps\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n // Escalation — stop workflow\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n // Unrecoverable failure after all recovery attempts\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (!options.onGate) {\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: DelegateStep | GateStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n","/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions\n * + plugin guardrails to SDK-compatible hook responses.\n *\n * The generated hooks/index.ts calls createGuardrailHooks() with the\n * DSL-generated check functions. All logic lives here in the lib.\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: \"block\" | \"warn\" | \"shadow\" | \"info\";\n message: string;\n}\n\nexport interface HookResponse {\n permission?: \"deny\";\n user_message?: string;\n agent_message?: string;\n additionalContext?: string;\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\nexport interface GuardrailHooks {\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }) => HookResponse;\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"block\");\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return results.some((r) => !r.passed && r.action === \"block\");\n}\n\nfunction pluginResultToCheckResult(r: {\n matched: boolean;\n guardrail_id: string;\n action: string;\n message: string;\n}): GuardrailCheckResult {\n return {\n guardrail_id: r.guardrail_id,\n passed: !r.matched,\n action: r.action as GuardrailCheckResult[\"action\"],\n message: r.matched ? r.message : \"\",\n };\n}\n\n/**\n * Create SDK hook functions from generated guardrail check functions.\n *\n * Merges DSL-generated checks with plugin-registered guardrails and\n * returns hook functions in the format expected by Cursor / Claude SDKs,\n * plus a generic runChecks() for programmatic use.\n */\nexport function createGuardrailHooks(checks: GuardrailCheckFunctions): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n results.push(...checks.checkCommand(ctx.command));\n results.push(\n ...pluginRegistry.evaluateCommandGuardrails(ctx.command).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath) {\n results.push(...checks.checkFilePath(ctx.filePath));\n results.push(\n ...pluginRegistry.evaluateFilePathGuardrails(ctx.filePath).map(pluginResultToCheckResult),\n );\n }\n\n if (ctx.filePath && ctx.content) {\n results.push(...checks.checkContent(ctx.filePath, ctx.content));\n results.push(\n ...pluginRegistry\n .evaluateFileContentGuardrails(ctx.filePath, ctx.content)\n .map(pluginResultToCheckResult),\n );\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n if (warns.length > 0) {\n return {\n additionalContext: warns.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\"),\n };\n }\n\n return {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: { file_path?: string; path?: string };\n }): HookResponse {\n const filePath = input.tool_input?.file_path ?? input.tool_input?.path ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n const filePath = input.file_path ?? \"\";\n const content = input.content ?? \"\";\n if (!filePath) return {};\n\n const results = runChecks({ filePath, content });\n const blocks = getBlockingViolations(results);\n\n if (blocks.length > 0) {\n const msg = blocks.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n return { permission: \"deny\", user_message: msg, agent_message: msg };\n }\n\n return {};\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n","/**\n * Fluent Builder API for workflow invocation.\n *\n * Usage:\n * const runtime = createRuntime({ adapter, registries });\n * const result = await runtime\n * .workflow(\"feature-implement\")\n * .handoff(handoffs.featureImplementationRequest({ ... }))\n * .maxFollowUps(3)\n * .onGate(async () => true)\n * .run();\n */\n\nimport {\n runWorkflow,\n type HandoffInput,\n type WorkflowInvocation,\n type WorkflowRegistries,\n type WorkflowResult,\n type StepCompleteEvent,\n type StepResult,\n type DelegateStep,\n} from \"./workflow-runner.js\";\nimport type { SdkAdapter, TaskContext } from \"./task-runner.js\";\n\n// ---------------------------------------------------------------------------\n// Runtime factory\n// ---------------------------------------------------------------------------\n\nexport interface RuntimeConfig {\n adapter: SdkAdapter;\n registries?: WorkflowRegistries;\n}\n\nexport interface Runtime {\n workflow(workflowId: string): WorkflowBuilder;\n}\n\nexport function createRuntime(config: RuntimeConfig): Runtime {\n return {\n workflow(workflowId: string): WorkflowBuilder {\n return new WorkflowBuilder(config.adapter, workflowId, config.registries);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// WorkflowBuilder\n// ---------------------------------------------------------------------------\n\nexport class WorkflowBuilder {\n private adapter: SdkAdapter;\n private invocation: WorkflowInvocation;\n private registries: WorkflowRegistries | undefined;\n\n constructor(\n adapter: SdkAdapter,\n workflowId: string,\n registries?: WorkflowRegistries,\n ) {\n this.adapter = adapter;\n this.invocation = { workflow: workflowId };\n this.registries = registries;\n }\n\n /** Set a typed handoff envelope as input. */\n handoff<T extends string>(input: HandoffInput<T>): this {\n this.invocation = { ...this.invocation, handoff: input };\n return this;\n }\n\n /** Set a simple string request (convenience shorthand). */\n request(userRequest: string): this {\n this.invocation = { ...this.invocation, user_request: userRequest };\n return this;\n }\n\n maxFollowUps(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxFollowUps: n },\n };\n return this;\n }\n\n maxRetries(n: number): this {\n this.invocation = {\n ...this.invocation,\n runtime: { ...this.invocation.runtime, maxRetries: n },\n };\n return this;\n }\n\n onStepComplete(\n cb: (event: StepCompleteEvent) => void,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onStepComplete: cb },\n };\n return this;\n }\n\n onGate(\n cb: (\n gateKind: string,\n description: string,\n stepResults: StepResult[],\n ) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onGate: cb },\n };\n return this;\n }\n\n onOptionalStep(\n cb: (step: DelegateStep, context: TaskContext) => Promise<boolean>,\n ): this {\n this.invocation = {\n ...this.invocation,\n hooks: { ...this.invocation.hooks, onOptionalStep: cb },\n };\n return this;\n }\n\n async run(): Promise<WorkflowResult> {\n return runWorkflow(this.adapter, this.invocation, this.registries);\n }\n}\n","/**\n * Plugin Loader — auto-discovers and registers user plugin files\n *\n * Discovery strategies (in priority order):\n * 1. Config-based: `plugins` array in agent-runtime.config.yaml\n * 2. Convention-based: scan `src/plugins/` for files exporting AgentPlugin\n *\n * Each discovered module is dynamically import()'d. Exports that satisfy the\n * AgentPlugin interface (have an `id` string property) are registered with\n * the pluginRegistry singleton.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { pluginRegistry, type AgentPlugin } from \"./plugin.js\";\n\nconst PLUGIN_EXTENSIONS = [\".ts\", \".js\", \".mts\", \".mjs\"];\n\nfunction isPluginLike(obj: unknown): obj is AgentPlugin {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n typeof (obj as Record<string, unknown>).id === \"string\"\n );\n}\n\n/**\n * Scan a directory for files that may export plugins.\n * Returns absolute paths of candidate files.\n */\nasync function scanDirectory(dir: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n\n const entries = await readdir(dir, { withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) &&\n !e.name.startsWith(\"_\") &&\n !e.name.endsWith(\".d.ts\") &&\n !e.name.endsWith(\".test.ts\") &&\n !e.name.endsWith(\".spec.ts\"),\n )\n .map((e) => resolve(dir, e.name));\n}\n\n/**\n * Import a single module and register any AgentPlugin exports.\n * Returns the number of plugins registered from this module.\n */\nasync function loadPluginModule(modulePath: string): Promise<number> {\n const mod = await import(new URL(`file://${modulePath}`).href);\n let count = 0;\n\n for (const exportValue of Object.values(mod)) {\n if (isPluginLike(exportValue)) {\n try {\n pluginRegistry.register(exportValue);\n count++;\n } catch {\n // Already registered — skip duplicate\n }\n }\n }\n\n return count;\n}\n\nexport interface PluginLoadResult {\n loaded: number;\n files: string[];\n errors: Array<{ file: string; error: string }>;\n}\n\n/**\n * Load plugins from explicit paths (config-based discovery).\n */\nexport async function loadPluginsFromPaths(\n paths: string[],\n baseDir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n\n for (const p of paths) {\n const absPath = resolve(baseDir, p);\n if (!existsSync(absPath)) {\n result.errors.push({ file: p, error: `File not found: ${absPath}` });\n continue;\n }\n\n try {\n const count = await loadPluginModule(absPath);\n result.loaded += count;\n result.files.push(absPath);\n } catch (err) {\n result.errors.push({\n file: p,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Load plugins using convention-based directory scanning.\n * Scans `<projectDir>/src/plugins/` by default.\n */\nexport async function loadPluginsFromDirectory(\n dir: string,\n): Promise<PluginLoadResult> {\n const result: PluginLoadResult = { loaded: 0, files: [], errors: [] };\n const candidates = await scanDirectory(dir);\n\n for (const filePath of candidates) {\n try {\n const count = await loadPluginModule(filePath);\n result.loaded += count;\n result.files.push(filePath);\n } catch (err) {\n result.errors.push({\n file: filePath,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Auto-discover and load plugins. Uses config-based paths if provided,\n * otherwise falls back to convention-based scanning of src/plugins/.\n */\nexport async function loadPlugins(options: {\n pluginPaths?: string[];\n projectDir: string;\n}): Promise<PluginLoadResult> {\n if (options.pluginPaths && options.pluginPaths.length > 0) {\n return loadPluginsFromPaths(options.pluginPaths, options.projectDir);\n }\n\n const conventionDir = join(options.projectDir, \"src\", \"plugins\");\n return loadPluginsFromDirectory(conventionDir);\n}\n"],"mappings":";AAiBA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACmCf,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,sBAAsB,QAAgB,SAAmC;AACvE,QAAI,MAAM;AACV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AAQ,aAAa,QAAQ,UAAU;AAAA,EACrE;AAEA,QAAM,gBAAgB,KAAK,QAAQ,YAAY,OAAO,SAAS;AAC/D,SAAO,yBAAyB,aAAa;AAC/C;","names":["result","wfResult"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generator/index.ts","../src/generator/config.ts","../src/generator/template-engine.ts","../src/generator/context.ts"],"sourcesContent":["/**\n * Generator — orchestrates DSL-to-TypeScript code generation\n */\n\nimport { readFile, writeFile, mkdir, rm, stat } from \"node:fs/promises\";\nimport { resolve, join, relative } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport YAML from \"yaml\";\nimport { loadConfig, type ResolvedConfig } from \"./config.js\";\nimport { renderTemplate } from \"./template-engine.js\";\nimport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n\nexport interface GenerateOptions {\n clean?: boolean;\n check?: boolean;\n templates?: string;\n configPath?: string;\n}\n\nexport interface GenerateResult {\n filesGenerated: string[];\n dslHash: string;\n generationInputHash: string;\n cleaned: boolean;\n checkMode: boolean;\n hasDifferences: boolean;\n}\n\nconst DO_NOT_EDIT_HEADER = `/**\n * AUTO-GENERATED by agent-contracts-runtime. DO NOT EDIT.\n *\n * Regenerate via: npx agent-runtime generate\n */\n\n`;\n\nasync function loadYaml(filePath: string): Promise<unknown> {\n const raw = await readFile(filePath, \"utf8\");\n return YAML.parse(raw);\n}\n\nfunction computeHash(data: string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Load DSL — tries agent-contracts resolve if available, falls back to raw YAML.\n */\nasync function loadDsl(dslPath: string): Promise<Record<string, unknown>> {\n try {\n const modName = \"agent-contracts\";\n const mod = await import(/* webpackIgnore: true */ modName);\n if (mod.loadDsl) {\n const result = await mod.loadDsl(dslPath);\n return (result as { data: Record<string, unknown> }).data;\n }\n } catch {\n // agent-contracts not available — use raw YAML\n }\n return (await loadYaml(dslPath)) as Record<string, unknown>;\n}\n\nconst CONTRACT_TEMPLATES = [\n { template: \"agents.ts.hbs\", output: \"agents.ts\" },\n { template: \"tasks.ts.hbs\", output: \"tasks.ts\" },\n { template: \"workflows.ts.hbs\", output: \"workflows.ts\" },\n { template: \"handoffs.ts.hbs\", output: \"handoffs.ts\" },\n { template: \"contracts-index.ts.hbs\", output: \"index.ts\" },\n];\n\nconst GUARDRAIL_TEMPLATES = [\n { template: \"guardrails.ts.hbs\", output: \"hooks/guardrails.ts\" },\n { template: \"hooks-index.ts.hbs\", output: \"hooks/index.ts\" },\n];\n\nexport async function generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const configPath = options.configPath ?? \"./agent-runtime.config.yaml\";\n const config = await loadConfig(configPath);\n\n const templatesDir = options.templates ?? config.templatesDir;\n const checkMode = options.check ?? false;\n const cleaned = options.clean ?? false;\n\n if (cleaned && !checkMode) {\n try {\n await rm(config.generatedDir, { recursive: true, force: true });\n } catch {\n // directory may not exist\n }\n }\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const dslHash = computeHash(dslCanonical);\n\n const contractCtx = buildContractContext(dsl);\n\n const filesGenerated: string[] = [];\n const generatedContents: Map<string, string> = new Map();\n\n // Phase 1: Contract files\n for (const { template, output } of CONTRACT_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(template, contractCtx as unknown as Record<string, unknown>, templatesDir);\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n\n // Phase 2: Guardrail hooks (only if bindings are configured)\n if (config.bindingPaths.length > 0) {\n for (const bindingPath of config.bindingPaths) {\n const binding = await loadYaml(bindingPath);\n const guardrailCtx = buildGuardrailContext(\n dsl,\n binding,\n config.active_guardrail_policy,\n );\n\n if (guardrailCtx.hasGuardrails) {\n for (const { template, output } of GUARDRAIL_TEMPLATES) {\n const rendered = DO_NOT_EDIT_HEADER + await renderTemplate(\n template,\n guardrailCtx as unknown as Record<string, unknown>,\n templatesDir,\n );\n const outPath = join(config.generatedDir, output);\n filesGenerated.push(relative(config.configDir, outPath));\n generatedContents.set(outPath, rendered);\n }\n }\n }\n }\n\n // Compute generation input hash (DSL + binding + generator version)\n const generationInputParts = [dslCanonical];\n for (const bp of config.bindingPaths) {\n try {\n generationInputParts.push(await readFile(bp, \"utf8\"));\n } catch {\n // binding may not exist\n }\n }\n const generationInputHash = computeHash(generationInputParts.join(\"\\n---\\n\"));\n\n // Check mode — compare without writing\n let hasDifferences = false;\n if (checkMode) {\n for (const [outPath, content] of generatedContents) {\n try {\n const existing = await readFile(outPath, \"utf8\");\n if (existing !== content) {\n hasDifferences = true;\n break;\n }\n } catch {\n hasDifferences = true;\n break;\n }\n }\n } else {\n // Write files\n for (const [outPath, content] of generatedContents) {\n const dir = resolve(outPath, \"..\");\n await mkdir(dir, { recursive: true });\n await writeFile(outPath, content, \"utf8\");\n }\n\n // Write manifest\n const manifest = {\n generatedAt: new Date().toISOString(),\n dslHash,\n generationInputHash,\n files: filesGenerated,\n };\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n await mkdir(resolve(manifestPath, \"..\"), { recursive: true });\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + \"\\n\", \"utf8\");\n }\n\n return {\n filesGenerated,\n dslHash,\n generationInputHash,\n cleaned,\n checkMode,\n hasDifferences,\n };\n}\n\nexport async function checkFreshness(configPath?: string): Promise<boolean> {\n const config = await loadConfig(configPath ?? \"./agent-runtime.config.yaml\");\n const manifestPath = join(config.generatedDir, \".manifest.json\");\n\n try {\n const raw = await readFile(manifestPath, \"utf8\");\n const manifest = JSON.parse(raw) as { dslHash: string };\n\n const dsl = await loadDsl(config.dslPath);\n const dslCanonical = JSON.stringify(dsl, Object.keys(dsl).sort(), 0);\n const currentHash = computeHash(dslCanonical);\n\n return manifest.dslHash === currentHash;\n } catch {\n return false;\n }\n}\n\nexport { loadConfig, type ResolvedConfig } from \"./config.js\";\nexport { buildContractContext, buildGuardrailContext } from \"./context.js\";\n","/**\n * Generator configuration — loads and validates agent-runtime.config.yaml\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, dirname } from \"node:path\";\nimport { z } from \"zod\";\nimport YAML from \"yaml\";\n\nconst RecoverySchema = z.object({\n max_follow_ups: z.number().int().min(0).default(2),\n max_retries: z.number().int().min(0).default(0),\n}).default({});\n\nexport const RuntimeConfigSchema = z.object({\n dsl: z.string().default(\"./agent-contracts.yaml\"),\n generated_dir: z.string().default(\"./agent/generated\"),\n bindings: z.array(z.string()).default([]),\n active_guardrail_policy: z.string().optional(),\n templates_dir: z.string().optional(),\n plugins: z.array(z.string()).default([]),\n recovery: RecoverySchema,\n});\n\nexport type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;\n\nexport interface ResolvedConfig extends RuntimeConfig {\n configDir: string;\n dslPath: string;\n generatedDir: string;\n bindingPaths: string[];\n templatesDir: string | undefined;\n pluginPaths: string[];\n}\n\nexport async function loadConfig(configPath: string): Promise<ResolvedConfig> {\n const absPath = resolve(configPath);\n const raw = await readFile(absPath, \"utf8\");\n const parsed = YAML.parse(raw);\n const config = RuntimeConfigSchema.parse(parsed);\n const configDir = dirname(absPath);\n\n return {\n ...config,\n configDir,\n dslPath: resolve(configDir, config.dsl),\n generatedDir: resolve(configDir, config.generated_dir),\n bindingPaths: config.bindings.map((b) => resolve(configDir, b)),\n templatesDir: config.templates_dir\n ? resolve(configDir, config.templates_dir)\n : undefined,\n pluginPaths: config.plugins,\n };\n}\n","/**\n * Handlebars template engine with custom helpers for TypeScript code generation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport Handlebars from \"handlebars\";\n\nimport { existsSync } from \"node:fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\nfunction findPackageRoot(): string {\n let dir = __dirname;\n for (let i = 0; i < 5; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n dir = resolve(dir, \"..\");\n }\n return resolve(__dirname, \"..\");\n}\n\nconst BUILTIN_TEMPLATES_DIR = join(findPackageRoot(), \"templates\");\n\nfunction toCamelCase(str: string): string {\n return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\nfunction toPascalCase(str: string): string {\n const camel = toCamelCase(str);\n return camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n\nconst hbs = Handlebars.create();\n\nhbs.registerHelper(\"camelCase\", (str: string) => toCamelCase(str));\nhbs.registerHelper(\"PascalCase\", (str: string) => toPascalCase(str));\n\nhbs.registerHelper(\"eq\", (a: unknown, b: unknown) => a === b);\nhbs.registerHelper(\"notEmpty\", (arr: unknown) =>\n Array.isArray(arr) ? arr.length > 0 : !!arr,\n);\n\nhbs.registerHelper(\"json\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value, null, 2)),\n);\n\nhbs.registerHelper(\"jsonInline\", (value: unknown) =>\n new Handlebars.SafeString(JSON.stringify(value)),\n);\n\nhbs.registerHelper(\"indent\", (text: string, spaces: number) => {\n if (typeof text !== \"string\") return text;\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map((line, i) => (i === 0 ? line : pad + line))\n .join(\"\\n\");\n});\n\nhbs.registerHelper(\"zodType\", function zodType(schema: Record<string, unknown>): string {\n if (!schema || typeof schema !== \"object\") return \"z.unknown()\";\n\n if (schema.enum) {\n const vals = (schema.enum as string[]).map((v) => `\"${v}\"`).join(\", \");\n return `z.enum([${vals}])`;\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})`;\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return \"z.string()\";\n if (type === \"number\" || type === \"integer\") return \"z.number()\";\n if (type === \"boolean\") return \"z.boolean()\";\n\n if (type === \"array\") {\n const items = schema.items as Record<string, unknown> | undefined;\n const inner = items ? zodType(items) : \"z.unknown()\";\n return `z.array(${inner})`;\n }\n\n if (type === \"object\") {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return \"z.record(z.string(), z.unknown())\";\n\n const required = (schema.required as string[]) ?? [];\n const fields = Object.entries(props)\n .map(([key, val]) => {\n const base = zodType(val);\n const opt = required.includes(key) ? \"\" : \".optional()\";\n return ` ${key}: ${base}${opt},`;\n })\n .join(\"\\n\");\n return `z.object({\\n${fields}\\n})`;\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(zodType);\n if (parts.length === 1) return parts[0];\n return parts.join(\".merge(\") + \")\".repeat(parts.length - 1);\n }\n\n return \"z.unknown()\";\n});\n\nhbs.registerHelper(\"regexEscape\", (str: string) => {\n if (typeof str !== \"string\") return str;\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n});\n\nhbs.registerHelper(\"stringArray\", (arr: unknown) => {\n if (!Array.isArray(arr)) return \"[]\";\n return \"[\" + arr.map((s) => `\"${s}\"`).join(\", \") + \"]\";\n});\n\n/**\n * Load a template by name, with custom dir override fallback to built-in.\n */\nasync function loadTemplate(\n name: string,\n customDir?: string,\n): Promise<string> {\n if (customDir) {\n try {\n return await readFile(join(customDir, name), \"utf8\");\n } catch {\n // fallback to built-in\n }\n }\n return readFile(join(BUILTIN_TEMPLATES_DIR, name), \"utf8\");\n}\n\nexport async function renderTemplate(\n name: string,\n context: Record<string, unknown>,\n customDir?: string,\n): Promise<string> {\n const source = await loadTemplate(name, customDir);\n const compiled = hbs.compile(source, { noEscape: true });\n return compiled(context);\n}\n\nexport { hbs, toCamelCase, toPascalCase };\n","/**\n * Build template contexts from resolved DSL data\n */\n\nimport { toCamelCase, toPascalCase } from \"./template-engine.js\";\n\nexport interface AgentEntry {\n id: string;\n varName: string;\n role_name: string;\n purpose: string;\n mode: string;\n dispatch_only: boolean;\n can_read_artifacts: string[];\n can_write_artifacts: string[];\n can_execute_tools: string[];\n can_invoke_agents: string[];\n can_return_handoffs: string[];\n responsibilities: string[];\n constraints: string[];\n rules: Array<{ id: string; description: string; severity: string }>;\n escalation_criteria: Array<{ condition: string; action: string }>;\n}\n\nexport interface TaskEntry {\n id: string;\n varName: string;\n description: string;\n target_agent: string;\n allowed_from_agents: string[];\n workflow: string;\n invocation_handoff: string;\n result_handoff: string;\n input_artifacts: string[];\n responsibilities: string[];\n completion_criteria: string[];\n optional: boolean;\n}\n\nexport interface WorkflowStepEntry {\n type: string;\n task?: string;\n from_agent?: string;\n description?: string;\n optional?: boolean;\n max_retries?: number;\n max_follow_ups?: number;\n gate_kind?: string;\n retry?: { condition: string; fix_task: string; revalidate_task?: string };\n}\n\nexport interface WorkflowEntry {\n id: string;\n varName: string;\n description: string;\n trigger: string;\n entry_conditions: string[];\n steps: WorkflowStepEntry[];\n}\n\nexport interface HandoffEntry {\n id: string;\n varName: string;\n pascalName: string;\n schemaName: string;\n description: string;\n schema: Record<string, unknown>;\n}\n\nexport interface ContractContext {\n agentEntries: AgentEntry[];\n taskEntries: TaskEntry[];\n workflowEntries: WorkflowEntry[];\n handoffEntries: HandoffEntry[];\n}\n\n/**\n * Determine if a task is optional by checking if any workflow step referencing it is optional.\n */\nfunction isTaskOptional(\n taskId: string,\n workflows: Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n): boolean {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId && step.optional) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Compute max_retries from workflow step or fallback to 0.\n */\nfunction getMaxRetries(\n taskId: string,\n workflows: Record<string, { steps: Array<Record<string, unknown>> }>,\n): number {\n for (const wf of Object.values(workflows)) {\n for (const step of wf.steps) {\n if (step.type === \"delegate\" && step.task === taskId) {\n const retry = step.retry as { condition: string } | undefined;\n return retry ? 1 : 0;\n }\n }\n }\n return 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function buildContractContext(dsl: any): ContractContext {\n const agents = (dsl.agents ?? {}) as Record<string, Record<string, unknown>>;\n const tasks = (dsl.tasks ?? {}) as Record<string, Record<string, unknown>>;\n const workflows = (dsl.workflow ?? {}) as Record<string, Record<string, unknown>>;\n const handoffTypes = (dsl.handoff_types ?? {}) as Record<string, Record<string, unknown>>;\n\n const agentEntries: AgentEntry[] = Object.entries(agents).map(([id, agent]) => ({\n id,\n varName: toCamelCase(id),\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode: (agent.mode as string) ?? \"read-write\",\n dispatch_only: (agent.dispatch_only as boolean) ?? false,\n can_read_artifacts: (agent.can_read_artifacts as string[]) ?? [],\n can_write_artifacts: (agent.can_write_artifacts as string[]) ?? [],\n can_execute_tools: (agent.can_execute_tools as string[]) ?? [],\n can_invoke_agents: (agent.can_invoke_agents as string[]) ?? [],\n can_return_handoffs: (agent.can_return_handoffs as string[]) ?? [],\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as AgentEntry[\"rules\"]) ?? [],\n escalation_criteria: (agent.escalation_criteria as AgentEntry[\"escalation_criteria\"]) ?? [],\n }));\n\n const taskEntries: TaskEntry[] = Object.entries(tasks).map(([id, task]) => ({\n id,\n varName: toCamelCase(id),\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n allowed_from_agents: (task.allowed_from_agents as string[]) ?? [],\n workflow: (task.workflow as string) ?? \"\",\n invocation_handoff: (task.invocation_handoff as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n input_artifacts: (task.input_artifacts as string[]) ?? [],\n responsibilities: (task.responsibilities as string[]) ?? [],\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n optional: isTaskOptional(id, workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>),\n }));\n\n const workflowEntries: WorkflowEntry[] = Object.entries(workflows).map(\n ([id, wf]) => {\n const steps = ((wf.steps as Array<Record<string, unknown>>) ?? []).map((step) => {\n const entry: WorkflowStepEntry = { type: step.type as string };\n if (step.type === \"delegate\") {\n entry.task = step.task as string;\n entry.from_agent = step.from_agent as string;\n entry.description = step.description as string;\n const wfStep = step as Record<string, unknown>;\n entry.optional = isTaskOptional(\n step.task as string,\n workflows as Record<string, { steps: Array<{ type: string; task?: string; optional?: boolean }> }>,\n );\n entry.max_retries = (wfStep.max_retries as number | undefined) ?? (wfStep.retry ? 1 : 0);\n entry.max_follow_ups = wfStep.max_follow_ups as number | undefined;\n if (wfStep.retry) {\n const r = wfStep.retry as Record<string, unknown>;\n entry.retry = {\n condition: r.condition as string,\n fix_task: r.fix_task as string,\n revalidate_task: r.revalidate_task as string | undefined,\n };\n }\n } else if (step.type === \"gate\") {\n entry.gate_kind = step.gate_kind as string;\n entry.description = step.description as string;\n }\n return entry;\n });\n\n return {\n id,\n varName: toCamelCase(id),\n description: (wf.description as string) ?? \"\",\n trigger: (wf.trigger as string) ?? \"\",\n entry_conditions: (wf.entry_conditions as string[]) ?? [],\n steps,\n };\n },\n );\n\n const handoffEntries: HandoffEntry[] = Object.entries(handoffTypes).map(\n ([id, ht]) => ({\n id,\n varName: toCamelCase(id),\n pascalName: toPascalCase(id),\n schemaName: toPascalCase(id) + \"Schema\",\n description: (ht.description as string) ?? \"\",\n schema: (ht.schema as Record<string, unknown>) ?? {},\n }),\n );\n\n return { agentEntries, taskEntries, workflowEntries, handoffEntries };\n}\n\nexport interface GuardrailCheckEntry {\n guardrail_id: string;\n description: string;\n severity: string;\n action: string;\n matcher_type: string;\n pattern: string;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailContext {\n commandChecks: GuardrailCheckEntry[];\n fileChecks: GuardrailCheckEntry[];\n contentChecks: GuardrailCheckEntry[];\n allChecks: GuardrailCheckEntry[];\n hasGuardrails: boolean;\n}\n\n/**\n * Build guardrail context from DSL guardrails, binding guardrail_impl, and active policy.\n * Mirrors the agent-contracts resolveChecks pattern.\n */\nexport function buildGuardrailContext(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dsl: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n binding: any,\n policyName?: string,\n): GuardrailContext {\n const empty: GuardrailContext = {\n commandChecks: [],\n fileChecks: [],\n contentChecks: [],\n allChecks: [],\n hasGuardrails: false,\n };\n\n if (!binding?.guardrail_impl) return empty;\n\n const guardrails = dsl.guardrails ?? {};\n const policies = dsl.guardrail_policies ?? {};\n const policy = policyName ? policies[policyName] : undefined;\n\n const allChecks: GuardrailCheckEntry[] = [];\n\n for (const [guardrailId, impl] of Object.entries(\n binding.guardrail_impl as Record<string, { checks: Array<Record<string, unknown>> }>,\n )) {\n const guardrail = guardrails[guardrailId] as Record<string, unknown> | undefined;\n const description = (guardrail?.description as string) ?? guardrailId;\n\n const policyRule = policy?.rules?.find(\n (r: Record<string, unknown>) => r.guardrail === guardrailId,\n );\n const severity = (policyRule?.severity as string) ?? \"warning\";\n const action = (policyRule?.action as string) ?? \"warn\";\n\n for (const check of impl.checks) {\n const matcher = check.matcher as Record<string, unknown> | undefined;\n if (!matcher) continue;\n\n allChecks.push({\n guardrail_id: guardrailId,\n description,\n severity,\n action,\n matcher_type: matcher.type as string,\n pattern: matcher.pattern as string,\n message: (check.message as string) ?? description,\n file_glob: matcher.file_glob as string | undefined,\n exclude_glob: matcher.exclude_glob as string | undefined,\n });\n }\n }\n\n return {\n commandChecks: allChecks.filter((c) => c.matcher_type === \"command_regex\"),\n fileChecks: allChecks.filter((c) => c.matcher_type === \"file_glob\"),\n contentChecks: allChecks.filter((c) => c.matcher_type === \"content_regex\"),\n allChecks,\n hasGuardrails: allChecks.length > 0,\n };\n}\n"],"mappings":";AAIA,SAAS,YAAAA,WAAU,WAAW,OAAO,UAAgB;AACrD,SAAS,WAAAC,UAAS,QAAAC,OAAM,gBAAgB;AACxC,SAAS,kBAAkB;AAC3B,OAAOC,WAAU;;;ACHjB,SAAS,gBAAgB;AACzB,SAAS,SAAS,eAAe;AACjC,SAAS,SAAS;AAClB,OA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