agent-contracts-runtime 0.33.1 → 0.33.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-runtime.bundle.mjs +234 -219
- package/dist/agent-runtime.bundle.mjs.map +3 -3
- package/dist/{chunk-TR4RR7M3.js → chunk-XM22OOCZ.js} +8 -1
- package/dist/chunk-XM22OOCZ.js.map +1 -0
- package/dist/{chunk-GVJYNAEQ.js → chunk-YTPEKBSI.js} +240 -2
- package/dist/chunk-YTPEKBSI.js.map +1 -0
- package/dist/cli/index.js +33 -21
- package/dist/cli/index.js.map +1 -1
- package/dist/generator/index.js +1 -1
- package/dist/index.d.ts +73 -1
- package/dist/index.js +9 -1
- package/package.json +1 -1
- package/templates/contracts-index.ts.hbs +1 -0
- package/dist/chunk-GVJYNAEQ.js.map +0 -1
- package/dist/chunk-TR4RR7M3.js.map +0 -1
|
@@ -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","../src/lib/schema-converter.ts","../src/lib/dsl-context.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 readonly rules?: readonly { readonly id: string; readonly description: string; readonly severity: 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 readonly model_class?: \"fast\" | \"standard\" | \"thinking\";\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 constraints?: string;\n}\n\ntype ZodCheckEntry = {\n kind?: string;\n value?: number;\n regex?: RegExp;\n isInt?: boolean;\n _zod?: { def?: Record<string, unknown> };\n};\n\nfunction getZodChecks(schema: z.ZodType): ZodCheckEntry[] {\n const def = (schema as z.ZodType & { _def?: { checks?: ZodCheckEntry[] } })._def;\n return def?.checks ?? [];\n}\n\n/** Extract validation constraints from Zod's internal checks for prompt display. */\nfunction extractZodConstraints(schema: z.ZodType): string | undefined {\n const inner = unwrapOptional(schema);\n const parts: string[] = [];\n\n if (inner instanceof z.ZodString) {\n const str = inner as z.ZodString & {\n minLength?: number | null;\n maxLength?: number | null;\n };\n if (str.minLength != null) parts.push(`min: ${str.minLength}`);\n if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.kind === \"regex\" && check.regex) parts.push(`regex: ${check.regex}`);\n const def = check._zod?.def;\n if (def?.format === \"regex\" && def.pattern instanceof RegExp) {\n parts.push(`regex: ${def.pattern}`);\n }\n }\n } else if (inner instanceof z.ZodNumber) {\n let hasInt = false;\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"int\") hasInt = true;\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n if (check.isInt) hasInt = true;\n const def = check._zod?.def;\n if (def?.check === \"number_format\" && def.format === \"safeint\") hasInt = true;\n if (def?.check === \"greater_than\") parts.push(`min: ${def.value}`);\n if (def?.check === \"less_than\") parts.push(`max: ${def.value}`);\n }\n if (hasInt) parts.unshift(\"int\");\n } else if (inner instanceof z.ZodArray) {\n for (const check of getZodChecks(inner)) {\n if (check.kind === \"min\") parts.push(`min: ${check.value}`);\n if (check.kind === \"max\") parts.push(`max: ${check.value}`);\n const def = check._zod?.def;\n if (def?.check === \"min_length\") parts.push(`min: ${def.minimum}`);\n if (def?.check === \"max_length\") parts.push(`max: ${def.maximum}`);\n }\n }\n\n return parts.length > 0 ? parts.join(\", \") : undefined;\n}\n\nfunction zodTypeToString(schema: z.ZodType): string {\n if (schema instanceof z.ZodString) return \"string\";\n if (schema instanceof z.ZodNumber) return \"number\";\n if (schema instanceof z.ZodBoolean) return \"boolean\";\n if (schema instanceof z.ZodEnum) return `enum(${(schema.options as string[]).join(\", \")})`;\n if (schema instanceof z.ZodLiteral) return `\"${String((schema._def as { values: unknown[] }).values[0])}\"`;\n\n if (schema instanceof z.ZodArray) {\n const element = (schema as z.ZodArray<z.ZodType>)._def.element;\n const inner = zodTypeToString(element);\n return `${inner}[]`;\n }\n if (schema instanceof z.ZodObject) return \"object\";\n if (schema instanceof z.ZodOptional) {\n return zodTypeToString((schema as z.ZodOptional<z.ZodType>)._def.innerType);\n }\n if (schema instanceof z.ZodRecord) return \"Record<string, unknown>\";\n return \"unknown\";\n}\n\n/** Unwrap ZodOptional to get the inner type. */\nfunction unwrapOptional(schema: z.ZodType): z.ZodType {\n if (schema instanceof z.ZodOptional) {\n return (schema as z.ZodOptional<z.ZodType>)._def.innerType;\n }\n return schema;\n}\n\n/** Get the element schema from an array type. */\nfunction getArrayElement(schema: z.ZodType): z.ZodType | null {\n const inner = unwrapOptional(schema);\n if (inner instanceof z.ZodArray) {\n return (inner as z.ZodArray<z.ZodType>)._def.element;\n }\n return null;\n}\n\nfunction extractFieldDescriptors(schema: z.ZodType): FieldDescriptor[] | null {\n let shape: Record<string, z.ZodType> | null = null;\n\n if (schema instanceof z.ZodObject) {\n shape = (schema as z.ZodObject<Record<string, z.ZodType>>).shape;\n }\n\n if (!shape) return null;\n\n return Object.entries(shape).map(([name, field]) => {\n const isOptional = field instanceof z.ZodOptional;\n const innerField = isOptional ? (field as z.ZodOptional<z.ZodType>)._def.innerType : field;\n const description = (innerField as z.ZodType & { description?: string }).description\n ?? (field as z.ZodType & { description?: string }).description;\n return {\n name,\n type: zodTypeToString(field as z.ZodType),\n required: !isOptional,\n description,\n constraints: extractZodConstraints(innerField as z.ZodType),\n };\n });\n}\n\n/**\n * Convert a Zod schema into a human-readable field table for inclusion in LLM prompts.\n * Recursively generates sub-tables for nested objects and array elements.\n */\nexport function zodSchemaToPromptDescription(schema: z.ZodType): string {\n const tables: string[] = [];\n collectFieldTables(schema, \"\", tables);\n return tables.join(\"\\n\\n\");\n}\n\nfunction collectFieldTables(\n schema: z.ZodType,\n pathPrefix: string,\n tables: string[],\n): void {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return;\n\n const title = pathPrefix ? `**${pathPrefix}**\\n\\n` : \"\";\n const header = \"| Field | Type | Required | Constraints | Description |\";\n const sep = \"|-------|------|----------|-------------|-------------|\";\n const rows = fields.map((f) =>\n `| ${f.name} | ${f.type} | ${f.required ? \"Yes\" : \"No\"} | ${f.constraints ?? \"\"} | ${f.description ?? \"\"} |`,\n );\n tables.push(`${title}${[header, sep, ...rows].join(\"\\n\")}`);\n\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n if (!shape) return;\n\n for (const f of fields) {\n const rawField = shape[f.name];\n const inner = unwrapOptional(rawField);\n\n if (inner instanceof z.ZodObject) {\n collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);\n } else if (inner instanceof z.ZodArray) {\n const element = (inner as z.ZodArray<z.ZodType>)._def.element;\n if (element instanceof z.ZodObject) {\n collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);\n }\n }\n }\n}\n\n/**\n * Generate a YAML example from a Zod schema shape, recursively expanding\n * nested objects and arrays up to a configurable depth.\n */\nexport function zodSchemaToYamlExample(schema: z.ZodType, maxDepth = 3): string {\n return renderYamlObject(schema, 0, maxDepth);\n}\n\nfunction renderYamlObject(schema: z.ZodType, indent: number, maxDepth: number): string {\n const fields = extractFieldDescriptors(schema);\n if (!fields || fields.length === 0) return \"\";\n\n const prefix = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const f of fields) {\n const shape = (schema instanceof z.ZodObject)\n ? (schema as z.ZodObject<Record<string, z.ZodType>>).shape\n : null;\n const rawField = shape?.[f.name];\n\n if (f.type.endsWith(\"[]\")) {\n lines.push(`${prefix}${f.name}:`);\n const element = rawField ? getArrayElement(rawField) : null;\n if (element && element instanceof z.ZodObject && indent < maxDepth) {\n const nested = renderYamlObject(element, indent + 2, maxDepth);\n if (nested) {\n const basePrefix = \" \".repeat(indent + 2);\n const nestedLines = nested.split(\"\\n\");\n lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);\n for (let i = 1; i < nestedLines.length; i++) {\n lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);\n }\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"string[]\") {\n lines.push(`${prefix} - \"example\"`);\n } else {\n lines.push(`${prefix} - key: \"value\"`);\n }\n } else if (f.type === \"object\" && indent < maxDepth) {\n const inner = rawField ? unwrapOptional(rawField) : null;\n if (inner && inner instanceof z.ZodObject) {\n lines.push(`${prefix}${f.name}:`);\n const nested = renderYamlObject(inner, indent + 1, maxDepth);\n if (nested) {\n lines.push(nested);\n } else {\n lines.push(`${prefix} key: \"value\"`);\n }\n } else {\n lines.push(`${prefix}${f.name}:`);\n lines.push(`${prefix} key: \"value\"`);\n }\n } else if (f.type === \"string\") {\n lines.push(`${prefix}${f.name}: \"...\"`);\n } else if (f.type === \"number\") {\n lines.push(`${prefix}${f.name}: 0`);\n } else if (f.type === \"boolean\") {\n lines.push(`${prefix}${f.name}: false`);\n } else if (f.type.startsWith(\"enum(\")) {\n const enumVals = f.type.slice(5, -1).split(\", \");\n lines.push(`${prefix}${f.name}: \"${enumVals[0]}\"`);\n } else {\n lines.push(`${prefix}${f.name}: \"...\"`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport interface PromptBuilderOptions {\n handoffSchemas?: Record<string, z.ZodType>;\n retry?: {\n condition: string;\n fix_task: string;\n revalidate_task?: string;\n };\n}\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n options?: PromptBuilderOptions,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.rules && agent.rules.length > 0) {\n const ruleLines = agent.rules.map(\n (r) => `- **${r.id}** [${r.severity}]: ${r.description}`,\n );\n sections.push(`## Rules\\n\\n${ruleLines.join(\"\\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 { ModelClass } from \"./model-resolver.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Adapter factory — enables true parallelism with stateful adapters\n// ---------------------------------------------------------------------------\n\n/**\n * A factory that creates independent SdkAdapter instances.\n * Used by runWorkflow to allocate one adapter per parallel step,\n * avoiding session-level serialization in stateful SDK adapters.\n */\nexport type SdkAdapterFactory = () => SdkAdapter;\n\n/**\n * Model-aware adapter factory. Accepts a model_class and returns an adapter\n * configured for that capability level (possibly a different provider/model).\n */\nexport type ModelAwareSdkAdapterFactory = (modelClass?: ModelClass) => SdkAdapter | Promise<SdkAdapter>;\n\n/** Accepts either a single adapter (serial/shared) or a factory (parallel-safe). */\nexport type AdapterOrFactory = SdkAdapter | SdkAdapterFactory | ModelAwareSdkAdapterFactory;\n\nfunction isAdapterFactory(v: AdapterOrFactory): v is SdkAdapterFactory | ModelAwareSdkAdapterFactory {\n return typeof v === \"function\" && !(\"send\" in v);\n}\n\nfunction resolveAdapter(adapterOrFactory: AdapterOrFactory): { adapter: SdkAdapter; factory: (SdkAdapterFactory | ModelAwareSdkAdapterFactory) | undefined } {\n if (isAdapterFactory(adapterOrFactory)) {\n const result = adapterOrFactory();\n if (result && typeof (result as Promise<SdkAdapter>).then === \"function\") {\n throw new Error(\"ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.\");\n }\n return { adapter: result as SdkAdapter, factory: adapterOrFactory };\n }\n return { adapter: adapterOrFactory, factory: undefined };\n}\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 depends_on?: readonly string[];\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 readonly depends_on?: readonly 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 /** Variables propagated to every TaskContext in the workflow (from WorkflowInvocation.context). */\n variables?: Record<string, unknown>;\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 const ctx = invocation.context;\n const variables: Record<string, unknown> = { ...ctx?.variables };\n if (ctx?.cwd) variables.cwd = ctx.cwd;\n if (ctx?.environment) variables.environment = ctx.environment;\n if (ctx?.artifacts) variables.artifacts = ctx.artifacts;\n\n return {\n workflowId: invocation.workflow,\n options: {\n user_request: userRequest,\n maxFollowUps: invocation.runtime?.maxFollowUps,\n maxRetries: invocation.runtime?.maxRetries,\n variables: Object.keys(variables).length > 0 ? variables : undefined,\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: AdapterOrFactory,\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: AdapterOrFactory,\n invocation: WorkflowInvocation,\n registries?: WorkflowRegistries,\n): Promise<WorkflowResult>;\n\nexport async function runWorkflow(\n adapterOrFactory: AdapterOrFactory,\n workflowIdOrInvocation: string | WorkflowInvocation,\n optionsOrRegistries?: WorkflowRunOptions | WorkflowRegistries,\n maybeRegistries?: WorkflowRegistries,\n): Promise<WorkflowResult> {\n const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(adapterOrFactory);\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 workflowStart = Date.now();\n\n // Build step identity map: step index → task ID (delegate) or gate_kind (gate)\n const stepId = (i: number): string => {\n const s = workflow.steps[i];\n return s.type === \"delegate\" ? s.task : `gate:${s.gate_kind}`;\n };\n\n // Resolve depends_on: if specified (even as empty array) use it, otherwise depend on all preceding steps\n const depsByIndex: number[][] = workflow.steps.map((step, i) => {\n if (step.depends_on !== undefined) {\n return step.depends_on.map((dep) => {\n const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);\n if (idx === -1) {\n throw new Error(`depends_on \"${dep}\" in step ${i} (${stepId(i)}) not found among preceding steps`);\n }\n return idx;\n });\n }\n // Default: depend on all preceding steps (preserves sequential behaviour)\n return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);\n });\n\n // DAG scheduler state\n const completed = new Set<number>();\n const stepResults: StepResult[] = new Array(workflow.steps.length);\n const stepContexts: string[] = new Array(workflow.steps.length).fill(\"\");\n let abortResult: WorkflowResult | undefined;\n\n /** Build accumulated context for a step from its dependency chain. */\n function contextFor(stepIndex: number): string {\n const deps = depsByIndex[stepIndex];\n if (deps.length === 0) return \"\";\n return deps\n .filter((d) => completed.has(d))\n .map((d) => stepContexts[d])\n .filter(Boolean)\n .join(\"\");\n }\n\n /** Execute a single step (delegate or gate). */\n async function executeStep(i: number, stepAdapter: SdkAdapter): Promise<StepResult> {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: contextFor(i), variables: options.variables };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n return {\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 }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: contextFor(i),\n variables: options.variables,\n ...(invocationHandoff ? { handoff_input: invocationHandoff } : {}),\n };\n const taskResult: TaskRunResult = await runTask(stepAdapter, 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 return {\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 }\n\n // DAG execution loop: on each iteration, find all steps whose deps are satisfied\n // and run them concurrently.\n while (completed.size < workflow.steps.length) {\n const ready: number[] = [];\n for (let i = 0; i < workflow.steps.length; i++) {\n if (completed.has(i)) continue;\n if (depsByIndex[i].every((d) => completed.has(d))) {\n ready.push(i);\n }\n }\n\n if (ready.length === 0) {\n // Should not happen with valid DAG; safeguard against cycles\n abortResult = {\n workflow_id: workflow.id,\n status: \"error\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n error_message: \"Dependency cycle detected: no steps are ready to execute\",\n };\n break;\n }\n\n const batchResults = await Promise.all(ready.map(async (i) => {\n const step = workflow.steps[i];\n const modelClass = step.type === \"delegate\"\n ? (registries?.taskRegistry?.[step.task]?.model_class as ModelClass | undefined)\n : undefined;\n\n let stepAdapter: SdkAdapter;\n if (ready.length > 1 && adapterFactory) {\n const result = adapterFactory(modelClass);\n stepAdapter = (result && typeof (result as Promise<SdkAdapter>).then === \"function\")\n ? await (result as Promise<SdkAdapter>)\n : result as SdkAdapter;\n } else if (modelClass && adapterFactory) {\n const result = adapterFactory(modelClass);\n stepAdapter = (result && typeof (result as Promise<SdkAdapter>).then === \"function\")\n ? await (result as Promise<SdkAdapter>)\n : result as SdkAdapter;\n } else {\n stepAdapter = primaryAdapter;\n }\n return executeStep(i, stepAdapter);\n }));\n\n for (let b = 0; b < ready.length; b++) {\n const i = ready[b];\n const result = batchResults[b];\n const step = workflow.steps[i];\n\n stepResults[i] = result;\n completed.add(i);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Store context fragment for dependants\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n stepContexts[i] = `\\n\\n--- Step ${i + 1}: ${stepId(i)} ---\\n` +\n (typeof data === \"string\" ? data : JSON.stringify(data, null, 2));\n }\n\n // Abort-worthy outcomes\n if (result.outcome.status === \"gate_rejected\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n };\n } else if (result.outcome.status === \"escalation\") {\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n } else if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const taskId = step.type === \"delegate\" ? step.task : step.gate_kind;\n abortResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults.filter(Boolean),\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${taskId}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n }\n }\n\n if (abortResult) break;\n }\n\n const wfResult: WorkflowResult = abortResult ?? {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults.filter(Boolean),\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 adapter?: SdkAdapter,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (options.onGate) {\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\n // LLM-based gate evaluation using the description as the condition\n if (adapter && step.description) {\n const approved = await evaluateGateWithLlm(adapter, step, 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\n // Fallback: no onGate, no adapter or no description — auto-approve with warning\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/**\n * Use the LLM adapter to evaluate a gate condition.\n * Sends a lightweight prompt with the gate description and prior step outcomes,\n * expecting a JSON response with { \"approved\": boolean, \"reason\": string }.\n */\nasync function evaluateGateWithLlm(\n adapter: SdkAdapter,\n step: GateStep,\n priorResults: StepResult[],\n): Promise<boolean> {\n const priorContext = priorResults\n .map((r) => {\n const id = r.task_id ?? r.gate_kind ?? `step_${r.step_index}`;\n const data = \"data\" in r.outcome ? (r.outcome as { data: unknown }).data : undefined;\n return `- ${id}: status=${r.outcome.status}${data ? `, data=${typeof data === \"string\" ? data : JSON.stringify(data)}` : \"\"}`;\n })\n .join(\"\\n\");\n\n const prompt = buildGateEvaluationPrompt(step, priorContext);\n\n try {\n const response = await adapter.send(prompt, { readonly: true });\n return parseGateEvaluationResponse(response);\n } catch {\n // On LLM failure, reject the gate (fail-closed)\n return false;\n }\n}\n\nexport function buildGateEvaluationPrompt(step: GateStep, priorContext: string): string {\n return `You are a gate evaluator in a workflow pipeline. Your job is to decide whether the workflow should proceed based on prior step results.\n\n## Gate\n- kind: ${step.gate_kind}\n- condition: ${step.description}\n\n## Prior Step Results\n${priorContext || \"(no prior results)\"}\n\n## Instructions\nEvaluate whether the gate condition is satisfied based on the prior step results.\nRespond with ONLY a JSON object (no markdown fences, no extra text):\n\n{\"approved\": true, \"reason\": \"brief explanation\"}\n\nor\n\n{\"approved\": false, \"reason\": \"brief explanation\"}`;\n}\n\nexport function parseGateEvaluationResponse(response: string): boolean {\n // Try to extract JSON from the response\n const jsonMatch = response.match(/\\{[\\s\\S]*?\"approved\"\\s*:\\s*(true|false)[\\s\\S]*?\\}/);\n if (jsonMatch) {\n try {\n const parsed = JSON.parse(jsonMatch[0]);\n return parsed.approved === true;\n } catch {\n // fall through\n }\n }\n\n // Heuristic fallback: look for explicit approval/rejection keywords\n const lower = response.toLowerCase();\n if (lower.includes('\"approved\": true') || lower.includes('\"approved\":true')) {\n return true;\n }\n if (lower.includes('\"approved\": false') || lower.includes('\"approved\":false')) {\n return false;\n }\n\n // Fail-closed: if we can't parse, reject\n return false;\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","/**\n * Runtime JSON Schema → Zod converter.\n *\n * Mirrors the compile-time zodType Handlebars helper in\n * generator/template-engine.ts but produces live z.ZodType\n * objects instead of code strings.\n */\n\nimport { z } from \"zod\";\n\nfunction applyStringValidations(schema: z.ZodString, def: Record<string, unknown>): z.ZodType {\n let s: z.ZodString = schema;\n if (typeof def.minLength === \"number\") s = s.min(def.minLength);\n if (typeof def.maxLength === \"number\") s = s.max(def.maxLength);\n if (typeof def.pattern === \"string\") s = s.regex(new RegExp(def.pattern));\n return s;\n}\n\nfunction applyNumberValidations(schema: z.ZodNumber, def: Record<string, unknown>, isInteger: boolean): z.ZodType {\n let n: z.ZodNumber = schema;\n if (isInteger) n = n.int();\n if (typeof def.minimum === \"number\") n = n.min(def.minimum);\n if (typeof def.maximum === \"number\") n = n.max(def.maximum);\n return n;\n}\n\nfunction applyArrayValidations(schema: z.ZodArray<z.ZodType>, def: Record<string, unknown>): z.ZodType {\n let a: z.ZodArray<z.ZodType> = schema;\n if (typeof def.minItems === \"number\") a = a.min(def.minItems);\n if (typeof def.maxItems === \"number\") a = a.max(def.maxItems);\n return a;\n}\n\n/**\n * Convert a JSON Schema definition to a Zod schema object at runtime.\n *\n * Supports the same subset as the compile-time zodType helper:\n * object, array, string, number, integer, boolean, enum, const, allOf.\n */\nexport function jsonSchemaToZod(schema: Record<string, unknown>): z.ZodType {\n if (!schema || typeof schema !== \"object\") return z.unknown();\n\n if (schema.enum) {\n const vals = schema.enum as [string, ...string[]];\n if (vals.length === 0) return z.unknown();\n return z.enum(vals);\n }\n\n if (schema.const !== undefined) {\n const val = schema.const;\n if (typeof val === \"string\" || typeof val === \"number\" || typeof val === \"boolean\") {\n return z.literal(val);\n }\n return z.unknown();\n }\n\n const type = schema.type as string | undefined;\n\n if (type === \"string\") return applyStringValidations(z.string(), schema);\n if (type === \"integer\") return applyNumberValidations(z.number(), schema, true);\n if (type === \"number\") return applyNumberValidations(z.number(), schema, false);\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 ? jsonSchemaToZod(items) : z.unknown();\n return applyArrayValidations(z.array(inner), schema);\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 = new Set((schema.required as string[]) ?? []);\n const shape: Record<string, z.ZodType> = {};\n for (const [key, val] of Object.entries(props)) {\n const fieldSchema = jsonSchemaToZod(val);\n shape[key] = required.has(key) ? fieldSchema : fieldSchema.optional();\n }\n return z.object(shape).passthrough();\n }\n\n if (schema.allOf) {\n const parts = (schema.allOf as Record<string, unknown>[]).map(jsonSchemaToZod);\n if (parts.length === 0) return z.unknown();\n if (parts.length === 1) return parts[0];\n let merged = parts[0];\n for (let i = 1; i < parts.length; i++) {\n const part = parts[i];\n if (merged instanceof z.ZodObject && part instanceof z.ZodObject) {\n merged = merged.merge(part);\n }\n }\n return merged;\n }\n\n return z.unknown();\n}\n","/**\n * Runtime DSL Context — builds WorkflowRegistries from embedded DSL data,\n * optionally merging with project-level DSL extensions.\n *\n * Default flow:\n * CLI binary embeds resolved DSL data (from code generation) →\n * loadDslContext() builds registries from it.\n *\n * Extended flow:\n * Project provides a DSL that extends/overrides the embedded base →\n * loadDslContext() merges via agent-contracts' mergeDsl() →\n * builds registries from the merged result.\n */\n\nimport type { z } from \"zod\";\nimport type { WorkflowRegistries, WorkflowContractLike, WorkflowStep } from \"./workflow-runner.js\";\nimport type { AgentContractLike, TaskContractLike } from \"./task-runner.js\";\nimport { jsonSchemaToZod } from \"./schema-converter.js\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface LoadDslOptions {\n /**\n * Pre-resolved DSL data embedded in the CLI binary.\n * Produced by the code generator alongside TypeScript contracts.\n * This is the default DSL — used as-is when no project extension exists.\n */\n embeddedDsl: Record<string, unknown>;\n\n /**\n * Path to a project-level DSL file that extends/overrides the embedded DSL.\n * When provided, the project DSL is resolved (including its own extends chain)\n * and merged with embeddedDsl via mergeDsl().\n */\n projectDslPath?: string;\n\n /** Entities the CLI depends on — validated after merge. */\n requiredEntities?: RequiredEntities;\n}\n\nexport interface RequiredEntities {\n workflows?: string[];\n tasks?: string[];\n}\n\nexport interface DslContext {\n readonly registries: WorkflowRegistries;\n readonly dsl: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class DslValidationError extends Error {\n readonly missing: string[];\n constructor(missing: string[]) {\n super(\n \"Required entities missing after DSL merge:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\"),\n );\n this.name = \"DslValidationError\";\n this.missing = missing;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build registries from resolved DSL\n// ---------------------------------------------------------------------------\n\nfunction buildAgentRegistry(\n agents: Record<string, Record<string, unknown>>,\n): Record<string, AgentContractLike> {\n const registry: Record<string, AgentContractLike> = {};\n for (const [id, agent] of Object.entries(agents)) {\n const rawMode = (agent.mode as string) ?? \"read-only\";\n const mode: \"read-write\" | \"read-only\" = rawMode === \"read-write\" ? \"read-write\" : \"read-only\";\n registry[id] = {\n id,\n role_name: (agent.role_name as string) ?? id,\n purpose: (agent.purpose as string) ?? \"\",\n mode,\n responsibilities: (agent.responsibilities as string[]) ?? [],\n constraints: (agent.constraints as string[]) ?? [],\n rules: (agent.rules as Array<{ id: string; description: string; severity: string }>) ?? [],\n };\n }\n return registry;\n}\n\nfunction buildTaskRegistry(\n tasks: Record<string, Record<string, unknown>>,\n): Record<string, TaskContractLike> {\n const registry: Record<string, TaskContractLike> = {};\n for (const [id, task] of Object.entries(tasks)) {\n registry[id] = {\n id,\n description: (task.description as string) ?? \"\",\n target_agent: (task.target_agent as string) ?? \"\",\n result_handoff: (task.result_handoff as string) ?? \"\",\n completion_criteria: (task.completion_criteria as string[]) ?? [],\n model_class: task.model_class as \"fast\" | \"standard\" | \"thinking\" | undefined,\n };\n }\n return registry;\n}\n\nfunction buildWorkflowStep(step: Record<string, unknown>): WorkflowStep {\n if (step.type === \"gate\") {\n return {\n type: \"gate\" as const,\n gate_kind: (step.gate_kind as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n depends_on: step.depends_on as readonly string[] | undefined,\n };\n }\n return {\n type: \"delegate\" as const,\n task: (step.task as string) ?? \"\",\n from_agent: (step.from_agent as string) ?? \"\",\n description: (step.description as string) ?? \"\",\n optional: (step.optional as boolean) ?? false,\n max_retries: (step.max_retries as number) ?? 0,\n max_follow_ups: step.max_follow_ups as number | undefined,\n depends_on: step.depends_on as readonly string[] | undefined,\n retry: step.retry as { condition: string; fix_task: string; revalidate_task?: string } | undefined,\n };\n}\n\nfunction buildWorkflowRegistry(\n workflows: Record<string, Record<string, unknown>>,\n): Record<string, WorkflowContractLike> {\n const registry: Record<string, WorkflowContractLike> = {};\n for (const [id, wf] of Object.entries(workflows)) {\n const steps = ((wf.steps as Record<string, unknown>[]) ?? []).map(buildWorkflowStep);\n registry[id] = { id, description: (wf.description as string) ?? \"\", steps };\n }\n return registry;\n}\n\nfunction buildHandoffSchemas(\n handoffTypes: Record<string, Record<string, unknown>>,\n): Record<string, z.ZodType> {\n const schemas: Record<string, z.ZodType> = {};\n for (const [id, ht] of Object.entries(handoffTypes)) {\n const schema = ht.schema as Record<string, unknown> | undefined;\n if (schema) {\n schemas[id] = jsonSchemaToZod(schema);\n }\n }\n return schemas;\n}\n\n// ---------------------------------------------------------------------------\n// Build registries from a resolved DSL object\n// ---------------------------------------------------------------------------\n\nexport function buildRegistriesFromDsl(\n dsl: Record<string, unknown>,\n): WorkflowRegistries {\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 return {\n agentRegistry: buildAgentRegistry(agents),\n taskRegistry: buildTaskRegistry(tasks),\n workflowRegistry: buildWorkflowRegistry(workflows),\n handoffSchemas: buildHandoffSchemas(handoffTypes),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nfunction validateRequiredEntities(\n dsl: Record<string, unknown>,\n required: RequiredEntities,\n): void {\n const missing: string[] = [];\n\n const workflows = (dsl.workflow as Record<string, unknown>) ?? {};\n const tasks = (dsl.tasks as Record<string, unknown>) ?? {};\n const handoffTypes = (dsl.handoff_types as Record<string, unknown>) ?? {};\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) {\n missing.push(`workflow \"${wfId}\" is required by the CLI but not found in the resolved DSL`);\n }\n }\n }\n\n if (required.tasks) {\n for (const taskId of required.tasks) {\n if (!(taskId in tasks)) {\n missing.push(`task \"${taskId}\" is required by the CLI but not found in the resolved DSL`);\n continue;\n }\n const task = tasks[taskId] as Record<string, unknown>;\n const invHandoff = task.invocation_handoff as string | undefined;\n const resHandoff = task.result_handoff as string | undefined;\n if (invHandoff && !(invHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${invHandoff}\" (invocation_handoff of task \"${taskId}\") not found`);\n }\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result_handoff of task \"${taskId}\") not found`);\n }\n }\n }\n\n if (required.workflows) {\n for (const wfId of required.workflows) {\n if (!(wfId in workflows)) continue;\n const wf = workflows[wfId] as Record<string, unknown>;\n const steps = (wf.steps as Array<Record<string, unknown>>) ?? [];\n for (const step of steps) {\n if (step.type !== \"delegate\") continue;\n const taskId = step.task as string;\n if (taskId && taskId in tasks) {\n const task = tasks[taskId] as Record<string, unknown>;\n const resHandoff = task.result_handoff as string | undefined;\n if (resHandoff && !(resHandoff in handoffTypes)) {\n missing.push(`handoff_type \"${resHandoff}\" (result of task \"${taskId}\" in workflow \"${wfId}\") not found`);\n }\n }\n }\n }\n }\n\n if (missing.length > 0) {\n throw new DslValidationError(missing);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main API\n// ---------------------------------------------------------------------------\n\n/**\n * Build a DslContext from embedded DSL data, optionally merging with\n * a project-level DSL extension.\n *\n * Default (no projectDslPath):\n * Builds registries directly from embeddedDsl — no filesystem access.\n *\n * Extended (with projectDslPath):\n * Resolves the project DSL from filesystem, merges it over embeddedDsl\n * via agent-contracts' mergeDsl(), then builds registries from the result.\n */\nexport async function loadDslContext(\n options: LoadDslOptions,\n): Promise<DslContext> {\n let dsl: Record<string, unknown>;\n\n if (options.projectDslPath) {\n const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import(\"agent-contracts\");\n const projectResult = await resolveDsl(options.projectDslPath);\n const merged = mergeDsl(options.embeddedDsl, projectResult.data);\n dsl = expandDefaults(merged);\n } else {\n dsl = options.embeddedDsl;\n }\n\n if (options.requiredEntities) {\n validateRequiredEntities(dsl, options.requiredEntities);\n }\n\n const registries = buildRegistriesFromDsl(dsl);\n\n return { registries, dsl };\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;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k-AWBHN3LI.js";
|
|
9
9
|
import {
|
|
10
10
|
checkFreshness,
|
|
11
11
|
generate,
|
|
12
12
|
loadConfig
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-XM22OOCZ.js";
|
|
14
14
|
|
|
15
15
|
// src/cli/index.ts
|
|
16
16
|
import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
@@ -490,7 +490,7 @@ import { fileURLToPath } from "url";
|
|
|
490
490
|
var implementationAuditor = {
|
|
491
491
|
id: "implementation-auditor",
|
|
492
492
|
role_name: "Implementation Auditor",
|
|
493
|
-
purpose: "Audits an existing LLM command integration to verify it correctly\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\nstack conventions. Detects architectural violations, missing patterns,\nincorrect API usage, and deviations from the canonical\nintegrate-llm-commands pattern.\n\nThis agent is read-only \u2014 it analyzes code but does not modify it.\nIt produces structured findings (AgentAuditResult) that identify\nexactly what is wrong and how to fix it.\n\n## What This Agent Checks\n\n### Layer 1: agent-contracts DSL\n- DSL entry has version:1 and system block with id/name\n- Agents defined with all required fields (role_name, purpose, mode,\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\n- Handoff type schemas conform to AgentAuditResult base shape\n- Workflows define steps with correct task/agent cross-references\n- Guardrails and guardrail_policies are defined\n- agent-runtime.config.yaml exists with dsl and generated_dir\n\n### Layer 2: agent-contracts-runtime Integration\n- orchestrator.ts uses
|
|
493
|
+
purpose: "Audits an existing LLM command integration to verify it correctly\nfollows the agent-contracts + agent-contracts-runtime + cli-contracts\nstack conventions. Detects architectural violations, missing patterns,\nincorrect API usage, and deviations from the canonical\nintegrate-llm-commands pattern.\n\nThis agent is read-only \u2014 it analyzes code but does not modify it.\nIt produces structured findings (AgentAuditResult) that identify\nexactly what is wrong and how to fix it.\n\n## What This Agent Checks\n\n### Layer 1: agent-contracts DSL\n- DSL entry has version:1 and system block with id/name\n- Agents defined with all required fields (role_name, purpose, mode,\n can_read_artifacts, can_write_artifacts, responsibilities, constraints)\n- Tasks have target_agent, workflow, result_handoff, completion_criteria\n- Handoff type schemas conform to AgentAuditResult base shape\n- Workflows define steps with correct task/agent cross-references\n- Guardrails and guardrail_policies are defined\n- agent-runtime.config.yaml exists with dsl and generated_dir\n\n### Layer 2: agent-contracts-runtime Integration\n- orchestrator.ts uses runWorkflow(), NOT runTask() or adapter.send()\n- runTask() is a low-level internal API \u2014 consumer projects must\n use runWorkflow() which handles workflow DAG, plugin hooks, gates\n- Adapters imported from agent-contracts-runtime/adapters/*, not custom\n- Dynamic import pattern for graceful degradation (exit 11/12)\n- Generated registries imported from src/generated/dsl/index.js\n- Registries (including workflowRegistry) passed to runWorkflow\n- Plugin hooks not bypassed\n- No hand-rolled prompt building (use buildTaskPrompt or let runWorkflow do it)\n\n### Layer 3: cli-contracts Compliance\n- cli-contract.yaml has LLM commands with all standard options:\n --adapter, --model, --dry-run, --fail-on, --output, --report-format\n- x-agent metadata present (riskLevel, safeDryRunOption, expectedDurationMs)\n- Exit codes follow convention (0, 1, 3, 10, 11, 12)\n- components/schemas includes AgentAuditResult and related types\n- --report-format used (not --format) for LLM commands\n\n### Architecture & Patterns\n- src/agents/ module structure (orchestrator, context-builder, formatter, types)\n- Context builder caps input at 16KB\n- Formatter implements computeExitCode with correct threshold logic\n- --dry-run returns prompt without LLM call\n- No direct LLM API calls anywhere in the codebase\n\n### Semantic Design Coherence\n- Context-builder must contain only domain DATA (file contents,\n config, scan results) \u2014 never agent INSTRUCTIONS (evaluation\n criteria, rules, anti-patterns, output format specifications).\n These belong in the DSL agent definition and are injected by\n buildTaskPrompt / runWorkflow. Hardcoding instructions in\n context-builder defeats the purpose of using DSL.\n- Agent mode must match purpose: read-only agents must not have\n write-oriented purposes, read-write agents must propagate cwd\n to their adapter so file tools operate in the project directory.\n- CLI must use cli-contracts' generated CommandHandlers interface\n and createProgram() \u2014 not manually wired Commander commands.\n",
|
|
494
494
|
mode: "read-only",
|
|
495
495
|
dispatch_only: false,
|
|
496
496
|
can_read_artifacts: [],
|
|
@@ -507,8 +507,8 @@ var implementationAuditor = {
|
|
|
507
507
|
"Validate task definitions: target_agent matches a defined agent, workflow matches a defined workflow, result_handoff matches a defined handoff type, completion_criteria are specific and testable.",
|
|
508
508
|
"Verify handoff type schemas conform to AgentAuditResult shape when applicable (summary, riskLevel, findings[], recommendedActions[], metadata). Check $ref usage and SSoT comments for inlined schemas.",
|
|
509
509
|
"Check that guardrails and guardrail_policies are defined, and that output-schema-conformance is included.",
|
|
510
|
-
"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of
|
|
511
|
-
"Verify no file in the project calls adapter.send(), adapter.followUp(),
|
|
510
|
+
"Scan src/agents/orchestrator.ts for: (1) imports from agent-contracts-runtime (not custom SDK wrappers), (2) usage of runWorkflow() \u2014 NOT runTask() which is a low-level internal API that bypasses workflow orchestration, plugin hooks, and gate steps, (3) dynamic import pattern with exit code 11 for missing runtime and exit code 12 for adapter errors, (4) generated registries (including workflowRegistry) imported and passed to runWorkflow.",
|
|
511
|
+
"Verify no file in the project calls adapter.send(), adapter.followUp(), adapter.sendExecution(), or runTask() directly \u2014 all LLM invocations must go through runWorkflow().",
|
|
512
512
|
"Check that src/generated/dsl/ exists and contains the expected files (agents.ts, tasks.ts, workflows.ts, handoffs.ts, index.ts). Verify the .manifest.json exists and is not stale.",
|
|
513
513
|
"Verify adapter creation uses the correct constructors: CursorSdkAdapter.create() (async static), ClaudeAgentSdkAdapter constructor, OpenAIAgentsSdkAdapter constructor, etc.",
|
|
514
514
|
"Check cli-contract.yaml for each LLM command: all six standard options present (--adapter, --model, --dry-run, --fail-on, --output, --report-format). Verify --report-format is used (not --format).",
|
|
@@ -544,7 +544,7 @@ var implementationAuditor = {
|
|
|
544
544
|
},
|
|
545
545
|
{
|
|
546
546
|
"id": "R-AUDIT-003",
|
|
547
|
-
"description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing
|
|
547
|
+
"description": "Critical findings must be surfaced for: (1) direct adapter.send() calls bypassing runWorkflow, (2) runTask() used instead of runWorkflow() \u2014 runTask is a low-level internal API that bypasses workflow orchestration, (3) custom adapter classes not from agent-contracts-runtime, (4) missing generated registries in runWorkflow calls.",
|
|
548
548
|
"severity": "mandatory"
|
|
549
549
|
},
|
|
550
550
|
{
|
|
@@ -554,7 +554,12 @@ var implementationAuditor = {
|
|
|
554
554
|
},
|
|
555
555
|
{
|
|
556
556
|
"id": "R-AUDIT-005",
|
|
557
|
-
"description": "Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt /
|
|
557
|
+
"description": "Context-builder must be audited for SSoT violations. Any hardcoded agent instructions (evaluation criteria, rules, anti-patterns, output format specs) in context-builder is a critical finding \u2014 these belong in the DSL agent definition and are injected by buildTaskPrompt / runWorkflow. Context-builder may only contain domain-specific data (file contents, configuration, scan results, project metadata).",
|
|
558
|
+
"severity": "mandatory"
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
"id": "R-AUDIT-007",
|
|
562
|
+
"description": "runTask() usage in consumer projects is a CRITICAL finding. Consumer projects integrating with cli-contracts must use runWorkflow() exclusively. runTask() is a low-level internal API that bypasses workflow DAG orchestration, workflow-level plugin hooks (beforeWorkflow/afterWorkflow), gate steps, and step dependencies. Any occurrence of runTask import or call in orchestrator, command handler, or CLI entry point code must be reported as severity: critical.",
|
|
558
563
|
"severity": "mandatory"
|
|
559
564
|
},
|
|
560
565
|
{
|
|
@@ -598,17 +603,17 @@ var llmFeatureImplementer = {
|
|
|
598
603
|
"Define guardrails (output-schema-conformance, domain-specific safety) and guardrail_policies grouping them with severity and action.",
|
|
599
604
|
"Create agent-runtime.config.yaml: dsl points to main DSL file, generated_dir points to src/generated/dsl.",
|
|
600
605
|
"Implement src/agents/types.ts: TaskId union type, AgentConfig interface (adapter, model, temperature), AgentOptions interface (dryRun, failOn), AgentRunResult interface (taskId, data, raw, prompt, dryRun, status, errorMessage, followUpsUsed, retriesUsed).",
|
|
601
|
-
"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*,
|
|
606
|
+
"Implement src/agents/orchestrator.ts: createAdapter() with dynamic imports from agent-contracts-runtime/adapters/*, runAgentWorkflow() that imports runWorkflow from agent-contracts-runtime, loads generated registries (including workflowRegistry) from src/generated/dsl/index.js, and calls runWorkflow with registries. NEVER use runTask \u2014 it is a low-level internal API that bypasses workflow orchestration.",
|
|
602
607
|
"Implement src/agents/context-builder.ts: build{Command}Context() functions that transform CLI inputs into structured markdown prompts. Cap context at 16KB. Structure: # Request, ## Configuration, ## Target, ## Instructions.",
|
|
603
608
|
"Implement src/agents/formatter.ts: computeExitCode() mapping findings to exit codes via --fail-on threshold, formatResultText() with severity icons, formatResultJson() for structured output.",
|
|
604
|
-
"Create src/commands/{command}.ts handlers: load config, call context builder, call
|
|
609
|
+
"Create src/commands/{command}.ts handlers: load config, call context builder, call runAgentWorkflow, format output, compute exit code.",
|
|
605
610
|
"Update cli-contract.yaml: add command definitions with standard LLM options (--adapter, --model, --dry-run, --fail-on, --output, --report-format), exit codes (0, 1, 3, 10, 11, 12), x-agent metadata, and register AgentAuditResult/AgentFinding/AgentRecommendedAction in components/schemas.",
|
|
606
611
|
'Add npm scripts: "dsl:generate" running agent-runtime generate --config dsl/agent-runtime.config.yaml. Add agent-contracts and agent-contracts-runtime as devDependencies. Add SDK packages as optional peerDependencies.'
|
|
607
612
|
],
|
|
608
613
|
constraints: [
|
|
609
614
|
"NEVER create custom adapter classes. Import from agent-contracts-runtime: ClaudeAgentSdkAdapter from agent-contracts-runtime/adapters/claude-agent-sdk, CursorSdkAdapter from agent-contracts-runtime/adapters/cursor-sdk, OpenAIAgentsSdkAdapter from agent-contracts-runtime/adapters/openai-agents-sdk, GeminiSdkAdapter from agent-contracts-runtime/adapters/gemini-sdk, MockAdapter from agent-contracts-runtime/adapters/mock.",
|
|
610
|
-
"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through
|
|
611
|
-
'Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = "agent-contracts-runtime"; try { const {
|
|
615
|
+
"NEVER call adapter.send() or adapter.sendExecution() directly. All LLM invocations must go through runWorkflow() imported from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API. runWorkflow() handles prompt building, handoff validation, retry/followUp, workflow DAG, and plugin hooks.",
|
|
616
|
+
'Dynamic-import both agent-contracts-runtime and adapter packages. The tool must work without them installed (graceful degradation). Pattern: const RUNTIME = "agent-contracts-runtime"; try { const { runWorkflow } = await import(RUNTIME); } catch { exit(11); }',
|
|
612
617
|
"LLM commands use --report-format (json|text|yaml) for output format. --format is reserved for deterministic commands. Never mix them.",
|
|
613
618
|
"Exit code convention: 0=success (no findings above threshold), 1=general error, 3=input validation/parse failed, 10=findings detected above --fail-on threshold, 11=agent-contracts-runtime not installed, 12=adapter initialization error (missing API key, etc.).",
|
|
614
619
|
"Standard LLM command options (all must be present): --adapter <name> (mock|cursor|claude|openai|gemini, default varies), --model <name> (optional override), --dry-run (output prompt without LLM call), --fail-on <level> (warning|error|critical, default error), --output/-o <file> (write to file instead of stdout), --report-format <fmt> (json|text|yaml, default json).",
|
|
@@ -618,10 +623,9 @@ var llmFeatureImplementer = {
|
|
|
618
623
|
"Main DSL entry must have version:1 and a system block with id and name. Without these, the generator produces numbered files instead of named ones.",
|
|
619
624
|
"Every task must have a workflow field matching a defined workflow ID. Every workflow step's from_agent must match a defined agent ID. can_read_artifacts and can_write_artifacts must be empty arrays ([]) when no artifact registry is defined.",
|
|
620
625
|
"agent-runtime.config.yaml format: dsl: ./{project}-dsl.yaml generated_dir: ../src/generated/dsl Optional: plugins (array of paths), recovery ({max_follow_ups, max_retries}).",
|
|
621
|
-
"
|
|
622
|
-
"runWorkflow overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured. WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly,dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }.",
|
|
626
|
+
"runWorkflow (the ONLY API consumer projects should use): Overloads: (1) runWorkflow(adapter, workflowId, options, registries?) \u2014 legacy. (2) runWorkflow(adapter, invocation, registries?) \u2014 structured (preferred). WorkflowInvocation: { workflow, handoff?, user_request?, runtime? {maxFollowUps,maxRetries,timeoutMs,readonly, dryRun}, hooks? {onStepComplete,onGate,onOptionalStep}, context? {cwd,environment,artifacts,variables} }. WorkflowResult: { workflow_id, status (completed|escalated|gate_rejected|error), steps[], total_elapsed_ms, escalation_reason?, error_message? }. NEVER use runTask() \u2014 it is a low-level internal API.",
|
|
623
627
|
"Adapter constructors: MockAdapter({responses?, defaultLatencyMs?}), CursorSdkAdapter.create({apiKey, model?, cwd?, guardrailHooks?}) \u2014 async static, ClaudeAgentSdkAdapter({cwd?, model?, tools?, permissionMode?, maxTurns?, guardrailHooks?}), OpenAIAgentsSdkAdapter({model?, maxTurns?, guardrailHooks?, tools?, agentName?, signal?}), GeminiSdkAdapter({apiKey?, model?, systemInstruction?, temperature?, maxOutputTokens?, guardrailHooks?}).",
|
|
624
|
-
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as
|
|
628
|
+
'Generated contract imports: import { agentRegistry, taskRegistry, handoffSchemas, workflowRegistry } from "../generated/dsl/index.js". Pass these as registries to runWorkflow: { workflowRegistry, taskRegistry, agentRegistry, handoffSchemas }.',
|
|
625
629
|
"Plugin interface (AgentPlugin): id (string), beforeTask?(taskId, context), afterTask?(taskId, outcome), contextEnhancer?(taskId, context), promptEnhancer?(taskId, prompt, context), promptBuilder?(args), customGuardrails?, beforeWorkflow?(workflowId, userRequest), afterWorkflow?(workflowId, result).",
|
|
626
630
|
"x-agent fields for LLM commands in cli-contract.yaml: riskLevel (low for read-only analysis), requiresConfirmation (false for read-only), idempotent (true for analysis), sideEffects ([network]), sideEffectNote (describe network call and optional file write), safeDryRunOption (dry-run), expectedDurationMs (120000 typical), retryableExitCodes ([1, 12])."
|
|
627
631
|
],
|
|
@@ -633,7 +637,7 @@ var llmFeatureImplementer = {
|
|
|
633
637
|
},
|
|
634
638
|
{
|
|
635
639
|
"id": "R-IMPL-002",
|
|
636
|
-
"description": "All LLM invocations must use
|
|
640
|
+
"description": "All LLM invocations must use runWorkflow() from agent-contracts-runtime. NEVER use runTask() \u2014 it is a low-level internal API that bypasses workflow orchestration. Never call adapter.send(), adapter.followUp(), or adapter.sendExecution() directly. The runtime handles prompt building, schema validation, retry, followUp, workflow DAG, and plugin hooks.",
|
|
637
641
|
"severity": "mandatory"
|
|
638
642
|
},
|
|
639
643
|
{
|
|
@@ -658,7 +662,7 @@ var llmFeatureImplementer = {
|
|
|
658
662
|
},
|
|
659
663
|
{
|
|
660
664
|
"id": "R-IMPL-007",
|
|
661
|
-
"description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to
|
|
665
|
+
"description": "Generated DSL contracts must be imported from src/generated/dsl/index.js and passed as registries to runWorkflow. Never hard-code agent definitions, task definitions, or handoff schemas in application code.",
|
|
662
666
|
"severity": "mandatory"
|
|
663
667
|
}
|
|
664
668
|
],
|
|
@@ -685,7 +689,7 @@ var agentRegistry = {
|
|
|
685
689
|
// src/builtin-agents/generated/tasks.ts
|
|
686
690
|
var implementLlmFeature = {
|
|
687
691
|
id: "implement-llm-feature",
|
|
688
|
-
description: 'Implement LLM-powered commands in a target CLI tool using the\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n## Implementation Procedure\n\n### Step 1: Project Analysis\n\nRead these files from the target project:\n- cli-contract.yaml \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 understand existing command handler pattern\n\nDetermine:\n- Which LLM commands to add (audit / propose / explain)\n- What domain-specific context each command needs\n- What structured output schema each command returns\n- Whether the project already has agent-contracts integration\n\n### Step 2: Install Dependencies\n\nAdd to package.json devDependencies:\n- agent-contracts: ^0.32.0\n- agent-contracts-runtime: ^0.31.0\n- zod: ^4.0.0\n\nAdd optional peerDependencies for SDK packages:\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\n- @openai/agents: >=0.10.0\n- @google/genai: >=2.0.0\n- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 handoff-types.yaml\n\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\n\n version: 1\n system:\n id: {project}\n name: "{Project} Agent System"\n default_workflow_order:\n - {workflow-ids}\n agents: { $ref: "./agents/" }\n tasks: { $ref: "./tasks.yaml" }\n handoff_types: { $ref: "./handoff-types.yaml" }\n guardrails:\n output-schema-conformance:\n description: ...\n scope: { agents: [...], tasks: [...] }\n rationale: ...\n guardrail_policies:\n {domain}-safety-policy:\n rules:\n - guardrail: output-schema-conformance\n severity: critical\n action: block\n workflow:\n {workflow-id}:\n description: ...\n trigger: cli-command\n entry_conditions: [...]\n steps:\n - type: delegate\n task: {task-id}\n from_agent: {agent-id}\n\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\n\n {agent-name}:\n role_name: "{Role Name}"\n purpose: >-\n Domain-specific purpose describing what the agent knows\n and what it can do that static rules cannot.\n mode: read-only\n can_read_artifacts: []\n can_write_artifacts: []\n can_invoke_agents: []\n can_execute_tools: []\n can_return_handoffs: [{result-handoff-ids}]\n responsibilities: [...]\n constraints: [...]\n rules:\n - id: "R-{PREFIX}-001"\n description: ...\n severity: mandatory\n escalation_criteria:\n - condition: ...\n action: stop_and_report\n\n**Tasks** (`dsl/tasks.yaml`):\n\n {task-id}:\n description: ...\n target_agent: {agent-name}\n allowed_from_agents: [{agent-name}]\n workflow: {workflow-id}\n input_artifacts: []\n invocation_handoff: {request-handoff}\n result_handoff: {result-handoff}\n responsibilities: [...]\n completion_criteria: [...]\n\n**Handoff types** (`dsl/handoff-types.yaml`):\nUse AgentAuditResult shape as the base for result types:\n\n {result-handoff}:\n version: 1\n description: ...\n schema:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary: { type: string }\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n findings:\n type: array\n items:\n type: object\n required: [severity, category, message]\n properties:\n id: { type: string }\n severity:\n type: string\n enum: [info, warning, error, critical]\n category: { type: string }\n target: { type: string }\n location: { type: string }\n message: { type: string }\n recommendation: { type: string }\n confidence: { type: number, minimum: 0, maximum: 1 }\n recommendedActions:\n type: array\n items:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title: { type: string }\n command: { type: string }\n target: { type: string }\n rationale: { type: string }\n metadata:\n type: object\n properties:\n tool: { type: string }\n command: { type: string }\n version: { type: string }\n generatedAt: { type: string }\n adapter: { type: string }\n model: { type: string }\n\nDomain-specific result types add properties alongside the base fields.\n\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\n\n dsl: ./{project}-dsl.yaml\n generated_dir: ../src/generated/dsl\n\n### Step 4: Generate TypeScript Contracts\n\nAdd to package.json scripts:\n\n "dsl:generate": "agent-runtime generate --config dsl/agent-runtime.config.yaml"\n\nRun: npm run dsl:generate\n\nThis produces src/generated/dsl/ containing:\n- agents.ts (AgentContract interface + agentRegistry)\n- tasks.ts (TaskContract interface + taskRegistry)\n- workflows.ts (WorkflowContract + workflowRegistry)\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\n- index.ts (barrel re-exports)\n\n### Step 5: Implement src/agents/ Module\n\n**src/agents/types.ts**:\n\n import type { {ResultType} } from "../generated/dsl/handoffs.js";\n\n export type TaskId = "{task-1}" | "{task-2}" | ...;\n\n export interface AgentConfig {\n adapter?: string;\n model?: string;\n temperature?: number;\n }\n\n export interface AgentOptions {\n dryRun?: boolean;\n failOn?: "warning" | "error" | "critical";\n }\n\n export interface AgentRunResult {\n taskId: TaskId;\n data: {ResultType} | null;\n raw: string;\n prompt: string;\n dryRun: boolean;\n status: "success" | "error" | "escalation" | "validation_error";\n errorMessage?: string;\n followUpsUsed: number;\n retriesUsed: number;\n }\n\n**src/agents/orchestrator.ts**:\n\n export const EXIT_RUNTIME_MISSING = 11;\n export const EXIT_ADAPTER_ERROR = 12;\n\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\n switch (name) {\n case "mock": {\n const m = await import(`${pkg}/adapters/mock`);\n return new m.MockAdapter();\n }\n case "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\n }\n case "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function runAgentTask(\n userRequest: string, taskId: TaskId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { taskId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success", followUpsUsed:0, retriesUsed:0 };\n\n const PKG = "agent-contracts-runtime";\n let runTask;\n try { ({ runTask } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas };\n } catch { registries = { agentRegistry:{}, taskRegistry:{}, handoffSchemas:{} }; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runTask(adapter, taskId, { user_request: userRequest }, { maxFollowUps:3, maxRetries:1, ...registries });\n // map result.outcome to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runTask. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \u2014 no instructions here.\n // Agent instructions come from DSL via buildTaskPrompt.\n // Cap total context at 16KB\n return sections.join("\\n\\n");\n }\n\n**src/agents/formatter.ts**:\n\n export function computeExitCode(result, options): number {\n if (result.dryRun) return 0;\n if (result.status !== "success") return 1;\n const order = ["info","warning","error","critical"];\n const threshold = order.indexOf(options.failOn ?? "error");\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\n }\n\n export function formatResultText(result): string { /* severity icons, structured output */ }\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\n\n### Step 6: Create CLI Command Handlers\n\nFor each LLM command, create src/commands/{command}.ts:\n\n export async function command{Name}(target, opts) {\n const cwd = process.cwd();\n const context = build{Name}Context(target, config);\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\n const result = await runAgentTask(context, "{task-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
692
|
+
description: 'Implement LLM-powered commands in a target CLI tool using the\nagent-contracts + agent-contracts-runtime + cli-contracts stack.\n\n## Implementation Procedure\n\n### Step 1: Project Analysis\n\nRead these files from the target project:\n- cli-contract.yaml \u2014 existing commands, components/schemas, x-agent usage\n- package.json \u2014 dependencies, scripts, bin entries, type:"module" check\n- tsconfig.json \u2014 module resolution, paths, outDir\n- src/ directory structure \u2014 understand existing command handler pattern\n\nDetermine:\n- Which LLM commands to add (audit / propose / explain)\n- What domain-specific context each command needs\n- What structured output schema each command returns\n- Whether the project already has agent-contracts integration\n\n### Step 2: Install Dependencies\n\nAdd to package.json devDependencies:\n- agent-contracts: ^0.32.0\n- agent-contracts-runtime: ^0.31.0\n- zod: ^4.0.0\n\nAdd optional peerDependencies for SDK packages:\n- @anthropic-ai/claude-agent-sdk: >=0.2.0\n- @openai/agents: >=0.10.0\n- @google/genai: >=2.0.0\n- @cursor/sdk (no version constraint)\n\n### Step 3: Create DSL Definitions\n\nCreate directory structure:\n\n dsl/\n \u251C\u2500\u2500 {project}-dsl.yaml\n \u251C\u2500\u2500 agent-runtime.config.yaml\n \u251C\u2500\u2500 agents/\n \u2502 \u2514\u2500\u2500 {agent-name}.yaml\n \u251C\u2500\u2500 tasks.yaml\n \u2514\u2500\u2500 handoff-types.yaml\n\n**Main DSL entry** (`dsl/{project}-dsl.yaml`):\n\n version: 1\n system:\n id: {project}\n name: "{Project} Agent System"\n default_workflow_order:\n - {workflow-ids}\n agents: { $ref: "./agents/" }\n tasks: { $ref: "./tasks.yaml" }\n handoff_types: { $ref: "./handoff-types.yaml" }\n guardrails:\n output-schema-conformance:\n description: ...\n scope: { agents: [...], tasks: [...] }\n rationale: ...\n guardrail_policies:\n {domain}-safety-policy:\n rules:\n - guardrail: output-schema-conformance\n severity: critical\n action: block\n workflow:\n {workflow-id}:\n description: ...\n trigger: cli-command\n entry_conditions: [...]\n steps:\n - type: delegate\n task: {task-id}\n from_agent: {agent-id}\n\n**Agent definition** (`dsl/agents/{agent-name}.yaml`):\n\n {agent-name}:\n role_name: "{Role Name}"\n purpose: >-\n Domain-specific purpose describing what the agent knows\n and what it can do that static rules cannot.\n mode: read-only\n can_read_artifacts: []\n can_write_artifacts: []\n can_invoke_agents: []\n can_execute_tools: []\n can_return_handoffs: [{result-handoff-ids}]\n responsibilities: [...]\n constraints: [...]\n rules:\n - id: "R-{PREFIX}-001"\n description: ...\n severity: mandatory\n escalation_criteria:\n - condition: ...\n action: stop_and_report\n\n**Tasks** (`dsl/tasks.yaml`):\n\n {task-id}:\n description: ...\n target_agent: {agent-name}\n allowed_from_agents: [{agent-name}]\n workflow: {workflow-id}\n input_artifacts: []\n invocation_handoff: {request-handoff}\n result_handoff: {result-handoff}\n responsibilities: [...]\n completion_criteria: [...]\n\n**Handoff types** (`dsl/handoff-types.yaml`):\nUse AgentAuditResult shape as the base for result types:\n\n {result-handoff}:\n version: 1\n description: ...\n schema:\n type: object\n required: [summary, riskLevel, findings]\n properties:\n summary: { type: string }\n riskLevel:\n type: string\n enum: [low, medium, high, critical]\n findings:\n type: array\n items:\n type: object\n required: [severity, category, message]\n properties:\n id: { type: string }\n severity:\n type: string\n enum: [info, warning, error, critical]\n category: { type: string }\n target: { type: string }\n location: { type: string }\n message: { type: string }\n recommendation: { type: string }\n confidence: { type: number, minimum: 0, maximum: 1 }\n recommendedActions:\n type: array\n items:\n type: object\n required: [kind, title]\n properties:\n kind:\n type: string\n enum: [run_command, edit_file, review, confirm, block, ignore]\n title: { type: string }\n command: { type: string }\n target: { type: string }\n rationale: { type: string }\n metadata:\n type: object\n properties:\n tool: { type: string }\n command: { type: string }\n version: { type: string }\n generatedAt: { type: string }\n adapter: { type: string }\n model: { type: string }\n\nDomain-specific result types add properties alongside the base fields.\n\n**Runtime config** (`dsl/agent-runtime.config.yaml`):\n\n dsl: ./{project}-dsl.yaml\n generated_dir: ../src/generated/dsl\n\n### Step 4: Generate TypeScript Contracts\n\nAdd to package.json scripts:\n\n "dsl:generate": "agent-runtime generate --config dsl/agent-runtime.config.yaml"\n\nRun: npm run dsl:generate\n\nThis produces src/generated/dsl/ containing:\n- agents.ts (AgentContract interface + agentRegistry)\n- tasks.ts (TaskContract interface + taskRegistry)\n- workflows.ts (WorkflowContract + workflowRegistry)\n- handoffs.ts (Zod schemas + handoffSchemas + factory functions)\n- index.ts (barrel re-exports)\n\n### Step 5: Implement src/agents/ Module\n\n**src/agents/types.ts**:\n\n import type { {ResultType} } from "../generated/dsl/handoffs.js";\n\n export type TaskId = "{task-1}" | "{task-2}" | ...;\n\n export interface AgentConfig {\n adapter?: string;\n model?: string;\n temperature?: number;\n }\n\n export interface AgentOptions {\n dryRun?: boolean;\n failOn?: "warning" | "error" | "critical";\n }\n\n export interface AgentRunResult {\n taskId: TaskId;\n data: {ResultType} | null;\n raw: string;\n prompt: string;\n dryRun: boolean;\n status: "success" | "error" | "escalation" | "validation_error";\n errorMessage?: string;\n followUpsUsed: number;\n retriesUsed: number;\n }\n\n**src/agents/orchestrator.ts**:\n\n export const EXIT_RUNTIME_MISSING = 11;\n export const EXIT_ADAPTER_ERROR = 12;\n\n async function createAdapter(pkg: string, name: string, config: AgentConfig) {\n switch (name) {\n case "mock": {\n const m = await import(`${pkg}/adapters/mock`);\n return new m.MockAdapter();\n }\n case "cursor": {\n const m = await import(`${pkg}/adapters/cursor-sdk`);\n return m.CursorSdkAdapter.create({ apiKey: process.env.CURSOR_API_KEY, model: config.model });\n }\n case "claude": {\n const m = await import(`${pkg}/adapters/claude-agent-sdk`);\n return new m.ClaudeAgentSdkAdapter({ model: config.model });\n }\n case "openai": {\n const m = await import(`${pkg}/adapters/openai-agents-sdk`);\n return new m.OpenAIAgentsSdkAdapter({ model: config.model });\n }\n case "gemini": {\n const m = await import(`${pkg}/adapters/gemini-sdk`);\n return new m.GeminiSdkAdapter({ apiKey: process.env.GEMINI_API_KEY, model: config.model });\n }\n }\n }\n\n export async function runAgentWorkflow(\n userRequest: string, workflowId: WorkflowId, config: AgentConfig, options: AgentOptions,\n ): Promise<AgentRunResult> {\n if (options.dryRun) return { workflowId, data:null, raw:"", prompt:userRequest, dryRun:true, status:"success" };\n\n const PKG = "agent-contracts-runtime";\n let runWorkflow;\n try { ({ runWorkflow } = await import(PKG)); }\n catch { throw Object.assign(new Error("agent-contracts-runtime not installed"), { exitCode: EXIT_RUNTIME_MISSING }); }\n\n let registries;\n try {\n const dsl = await import("../generated/dsl/index.js");\n registries = { agentRegistry: dsl.agentRegistry, taskRegistry: dsl.taskRegistry, handoffSchemas: dsl.handoffSchemas, workflowRegistry: dsl.workflowRegistry };\n } catch { registries = {}; }\n\n const adapter = await createAdapter(PKG, config.adapter ?? "mock", config);\n const result = await runWorkflow(adapter, { workflow: workflowId, user_request: userRequest, runtime: { maxFollowUps:3, maxRetries:1 } }, registries);\n // map result to AgentRunResult\n }\n\n**src/agents/context-builder.ts**:\n\nCRITICAL: context-builder builds the USER-SIDE prompt only.\nAgent instructions (purpose, responsibilities, constraints, rules,\nevaluation criteria, anti-patterns, output format) are defined in\nthe DSL (dsl/agents/*.yaml) and injected by the runtime via\nbuildTaskPrompt / runWorkflow. NEVER hardcode these in context-builder.\n\nContext-builder SHOULD contain:\n- Domain-specific DATA: file contents, configuration, scan results\n- Project metadata: target paths, dialect, directory structure\n- Deterministic pre-analysis: lint results, schema excerpts\n- Operational context: cwd, timestamps\n- Brief task framing: "# Migration Safety Audit Request"\n\nContext-builder MUST NOT contain:\n- "## Instructions" / "## Required Patterns" sections\n- Output format specifications (handled by handoff schema)\n- Evaluation criteria or checklists\n- Anti-pattern definitions or rule sets\n- API reference material\n- Anything that duplicates DSL agent purpose/responsibilities/rules\n\n export function build{Command}Context(target, config): string {\n const sections = [];\n sections.push("# {Command} Request");\n sections.push(`## Target\\n\\n${target}`);\n // Domain data only \u2014 no instructions here.\n // Agent instructions come from DSL via buildTaskPrompt.\n // Cap total context at 16KB\n return sections.join("\\n\\n");\n }\n\n**src/agents/formatter.ts**:\n\n export function computeExitCode(result, options): number {\n if (result.dryRun) return 0;\n if (result.status !== "success") return 1;\n const order = ["info","warning","error","critical"];\n const threshold = order.indexOf(options.failOn ?? "error");\n return result.data.findings.some(f => order.indexOf(f.severity) >= threshold) ? 10 : 0;\n }\n\n export function formatResultText(result): string { /* severity icons, structured output */ }\n export function formatResultJson(result): string { return JSON.stringify(result.data, null, 2); }\n\n### Step 6: Create CLI Command Handlers\n\nFor each LLM command, create src/commands/{command}.ts:\n\n export async function command{Name}(target, opts) {\n const cwd = process.cwd();\n const context = build{Name}Context(target, config);\n const agentConfig = { adapter: opts.adapter, model: opts.model, cwd };\n const result = await runAgentWorkflow(context, "{workflow-id}", agentConfig, agentOpts);\n if (opts.reportFormat === "json") console.log(formatResultJson(result));\n else console.log(formatResultText(result));\n process.exit(computeExitCode(result, opts));\n }\n\nWire handlers through cli-contracts\' generated program:\n\n import { createProgram, type CommandHandlers } from \'./generated/program.js\';\n\n const handlers: CommandHandlers = {\n {commandName}: async (target, opts) => {\n await command{Name}(target, opts);\n },\n // ... other handlers\n };\n\n createProgram(handlers, version).parse();\n\n### Step 7: Update cli-contract.yaml\n\nAdd each LLM command with standard options and x-agent metadata:\n\n {command-name}:\n summary: "{Command summary}"\n arguments: [...]\n options:\n - name: adapter\n schema: { type: string, enum: [mock, cursor, claude, openai, gemini] }\n - name: model\n schema: { type: string }\n - name: dry-run\n schema: { type: boolean, default: false }\n - name: fail-on\n schema: { type: string, enum: [warning, error, critical], default: error }\n - name: output\n aliases: [o]\n schema: { type: string }\n file: { mode: write }\n - name: report-format\n schema: { type: string, enum: [json, text, yaml], default: json }\n x-agent:\n riskLevel: low\n requiresConfirmation: false\n idempotent: true\n sideEffects: [network]\n sideEffectNote: >-\n Network calls to LLM provider when adapter is not mock.\n Filesystem write only when --output is specified.\n safeDryRunOption: dry-run\n expectedDurationMs: 120000\n retryableExitCodes: [1, 12]\n exits:\n \'0\': { description: "No blocking findings.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'1\': { description: "General error.", stderr: { format: text } }\n \'3\': { description: "Input validation failed.", stderr: { format: json } }\n \'10\': { description: "Blocking findings detected.", stdout: { format: json, schema: { $ref: \'...\' } } }\n \'11\': { description: "Runtime not installed.", stderr: { format: json } }\n \'12\': { description: "Adapter error.", stderr: { format: json } }\n\nAdd AgentAuditResult, AgentFinding, AgentRecommendedAction, AgentEvidence\nto components/schemas if not already present.\n\n### Step 8: Update README\n\nAdd "Agent-Native Toolchain" section after mechanical features:\n- Intro: tool encapsulates domain-specific semantic reasoning\n- Deterministic checks first, then semantic audit\n- Structured findings (AgentAuditResult/AgentFinding)\n- LLM Adapter Configuration table\n- Add agent-contracts-runtime, agent-contracts, cli-contracts to Technology Stack\n',
|
|
689
693
|
target_agent: "llm-feature-implementer",
|
|
690
694
|
allowed_from_agents: [
|
|
691
695
|
"llm-feature-implementer"
|
|
@@ -707,7 +711,7 @@ var implementLlmFeature = {
|
|
|
707
711
|
"dsl/ directory contains valid DSL definitions that pass agent-runtime generate",
|
|
708
712
|
"agent-runtime.config.yaml points to the DSL with correct generated_dir",
|
|
709
713
|
"src/generated/dsl/ contains generated contracts (agentRegistry, taskRegistry, handoffSchemas, workflowRegistry)",
|
|
710
|
-
"src/agents/orchestrator.ts uses
|
|
714
|
+
"src/agents/orchestrator.ts uses runWorkflow from agent-contracts-runtime (never runTask directly, no direct adapter.send calls)",
|
|
711
715
|
"src/agents/orchestrator.ts dynamic-imports the runtime and adapters with correct exit codes (11, 12)",
|
|
712
716
|
"src/agents/context-builder.ts contains only domain data (file contents, config, scan results) \u2014 no hardcoded agent instructions, evaluation criteria, or output format specs",
|
|
713
717
|
"src/agents/context-builder.ts caps input at 16KB",
|
|
@@ -749,7 +753,7 @@ var auditDsl = {
|
|
|
749
753
|
};
|
|
750
754
|
var auditRuntime = {
|
|
751
755
|
id: "audit-runtime",
|
|
752
|
-
description: "Audit the runtime integration layer of an LLM command integration.\n\nScan src/agents/orchestrator.ts (or equivalent runtime module):\n\nCRITICAL violations (category: runtime-orchestrator):\n- adapter.send() or adapter.sendExecution() called directly\n- adapter.followUp() called directly\n- Custom adapter class defined (not imported from runtime)\n-
|
|
756
|
+
description: "Audit the runtime integration layer of an LLM command integration.\n\nScan src/agents/orchestrator.ts (or equivalent runtime module):\n\nCRITICAL violations (category: runtime-orchestrator):\n- adapter.send() or adapter.sendExecution() called directly\n- adapter.followUp() called directly\n- Custom adapter class defined (not imported from runtime)\n- runWorkflow not imported from agent-contracts-runtime\n- runTask used instead of runWorkflow \u2014 consumer projects must\n use runWorkflow() which orchestrates through the DSL workflow\n DAG, activates workflow-level plugin hooks (beforeWorkflow/\n afterWorkflow), handles gate steps and step dependencies.\n runTask() is a low-level internal API; calling it directly\n bypasses workflow orchestration entirely\n\nERROR violations (category: runtime-registry):\n- Generated registries not imported from src/generated/dsl/\n- Registries not passed to runWorkflow options\n- Hard-coded agent/task definitions instead of registry lookup\n\nERROR violations (category: runtime-adapter):\n- Adapter packages imported statically (not dynamic import)\n- Missing exit code 11 when runtime import fails\n- Missing exit code 12 when adapter creation fails\n- CursorSdkAdapter created with constructor (must use static .create())\n\nERROR violations (category: runtime-handler):\n- Project has cli-contracts generated code (src/generated/program.ts\n or src/generated/cli/program.ts exporting CommandHandlers and\n createProgram) but CLI entry point manually creates Commander\n commands instead of using createProgram(handlers, version)\n- LLM command handlers are not wired through the generated\n CommandHandlers interface \u2014 handler signatures drift from the\n cli-contract.yaml definition without type errors\n- CLI entry point calls runTask directly instead of going through\n the command handler \u2192 context-builder \u2192 orchestrator chain\n\nWARNING violations (category: runtime-plugin):\n- Plugin hooks explicitly bypassed or ignored\n\nCategory vocabulary: runtime-orchestrator, runtime-registry,\nruntime-adapter, runtime-handler, runtime-plugin.\n\nOutput a partial audit-result with findings only from the runtime layer.\n",
|
|
753
757
|
target_agent: "implementation-auditor",
|
|
754
758
|
allowed_from_agents: [
|
|
755
759
|
"implementation-auditor"
|
|
@@ -760,12 +764,14 @@ var auditRuntime = {
|
|
|
760
764
|
input_artifacts: [],
|
|
761
765
|
responsibilities: [
|
|
762
766
|
"Scan orchestrator code for direct adapter usage",
|
|
767
|
+
"Verify runWorkflow is used (not runTask) for LLM command execution",
|
|
763
768
|
"Verify registry imports and passing",
|
|
764
769
|
"Check adapter creation patterns and exit codes",
|
|
765
770
|
"Verify cli-contracts handler wiring (CommandHandlers + createProgram used in CLI entry point)"
|
|
766
771
|
],
|
|
767
772
|
completion_criteria: [
|
|
768
773
|
"All orchestrator files scanned for adapter.send / adapter.followUp",
|
|
774
|
+
"No runTask usage found (runWorkflow must be used instead)",
|
|
769
775
|
"Registry usage verified",
|
|
770
776
|
"Exit code 11/12 patterns checked",
|
|
771
777
|
"cli-contracts handler integration verified (CommandHandlers interface used, createProgram called)"
|
|
@@ -817,7 +823,7 @@ The context-builder's role is to assemble domain-specific DATA (file
|
|
|
817
823
|
contents, configuration, scan results, schema context) into the user
|
|
818
824
|
prompt. Agent INSTRUCTIONS (how to evaluate, what rules to apply,
|
|
819
825
|
what patterns to look for, output format) belong in the DSL agent
|
|
820
|
-
definition
|
|
826
|
+
definition and are injected by buildTaskPrompt / runWorkflow.
|
|
821
827
|
|
|
822
828
|
Detect any of the following in context-builder source code:
|
|
823
829
|
- Sections titled "## Instructions", "## Required Patterns",
|
|
@@ -859,6 +865,12 @@ ERROR: adapter cwd propagation (category: architecture-adapter-cwd):
|
|
|
859
865
|
- Agentic adapters (claude, cursor) instantiated without cwd \u2014
|
|
860
866
|
their file tools will operate in an undefined directory
|
|
861
867
|
|
|
868
|
+
CRITICAL: runTask usage (category: architecture-handler):
|
|
869
|
+
- runTask() imported or called anywhere in the consumer project \u2014
|
|
870
|
+
consumer projects must use runWorkflow() exclusively; runTask()
|
|
871
|
+
is a low-level internal API that bypasses workflow DAG
|
|
872
|
+
orchestration, workflow-level plugin hooks, and gate steps
|
|
873
|
+
|
|
862
874
|
ERROR: cli-contracts handler wiring (category: architecture-handler):
|
|
863
875
|
- Project has cli-contracts generated code (src/generated/program.ts
|
|
864
876
|
or src/generated/cli/program.ts with CommandHandlers) but CLI
|
|
@@ -964,7 +976,7 @@ var AuditResultSchema = z.object({
|
|
|
964
976
|
location: z.string().optional(),
|
|
965
977
|
message: z.string(),
|
|
966
978
|
recommendation: z.string().optional(),
|
|
967
|
-
confidence: z.number().optional()
|
|
979
|
+
confidence: z.number().min(0).max(1).optional()
|
|
968
980
|
})),
|
|
969
981
|
recommendedActions: z.array(z.object({
|
|
970
982
|
kind: z.enum(["run_command", "edit_file", "review", "confirm", "block", "ignore"]),
|