agent-contracts-runtime 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/mock.ts"],"sourcesContent":["/**\n * Mock SDK Adapter — for testing and demo purposes\n */\n\nimport type { SdkAdapter } from \"../lib/task-runner.js\";\n\nexport class MockAdapter implements SdkAdapter {\n private responses: Record<string, (userRequest: string) => string>;\n private defaultLatencyMs: number;\n\n constructor(options?: {\n responses?: Record<string, (userRequest: string) => string>;\n defaultLatencyMs?: number;\n }) {\n this.responses = options?.responses ?? {};\n this.defaultLatencyMs = options?.defaultLatencyMs ?? 0;\n }\n\n async send(prompt: string, _options: { readonly: boolean }): Promise<string> {\n const match = prompt.match(/## Task: (\\S+)/);\n const taskId = match?.[1] ?? \"unknown\";\n\n const reqMatch = prompt.match(/## User Request\\n\\n([\\s\\S]*?)(?:\\n\\n---|$)/);\n const userRequest = reqMatch?.[1]?.trim() ?? \"\";\n\n if (this.defaultLatencyMs > 0) {\n await new Promise((r) => setTimeout(r, this.defaultLatencyMs));\n }\n\n const responseFn = this.responses[taskId];\n if (!responseFn) {\n return `Task \"${taskId}\" completed but no structured output available.`;\n }\n\n return responseFn(userRequest);\n }\n}\n"],"mappings":";AAMO,IAAM,cAAN,MAAwC;AAAA,EACrC;AAAA,EACA;AAAA,EAER,YAAY,SAGT;AACD,SAAK,YAAY,SAAS,aAAa,CAAC;AACxC,SAAK,mBAAmB,SAAS,oBAAoB;AAAA,EACvD;AAAA,EAEA,MAAM,KAAK,QAAgB,UAAkD;AAC3E,UAAM,QAAQ,OAAO,MAAM,gBAAgB;AAC3C,UAAM,SAAS,QAAQ,CAAC,KAAK;AAE7B,UAAM,WAAW,OAAO,MAAM,4CAA4C;AAC1E,UAAM,cAAc,WAAW,CAAC,GAAG,KAAK,KAAK;AAE7C,QAAI,KAAK,mBAAmB,GAAG;AAC7B,YAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,KAAK,gBAAgB,CAAC;AAAA,IAC/D;AAEA,UAAM,aAAa,KAAK,UAAU,MAAM;AACxC,QAAI,CAAC,YAAY;AACf,aAAO,SAAS,MAAM;AAAA,IACxB;AAEA,WAAO,WAAW,WAAW;AAAA,EAC/B;AACF;","names":[]}
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/index.ts
4
+ import { Command } from "commander";
5
+ var program = new Command();
6
+ program.name("agent-runtime").description("Runtime bridge for executing agent-contracts workflows on Agent SDKs").version("0.0.1");
7
+ program.command("init").description("Initialize runtime scaffolding for a project").option("-a, --adapter <adapter>", "Default SDK adapter", "mock").option("-o, --output <dir>", "Output directory", ".").option("-f, --force", "Overwrite existing files").action((_opts) => {
8
+ console.log("agent-runtime init \u2014 not yet implemented (Phase 2)");
9
+ process.exit(0);
10
+ });
11
+ program.command("generate").description("Generate runtime contracts and hooks from DSL").option("--clean", "Delete generated_dir before regenerating").option("--check", "Dry-run: verify generated files are up to date").action((_opts) => {
12
+ console.log("agent-runtime generate \u2014 not yet implemented (Phase 2)");
13
+ process.exit(0);
14
+ });
15
+ program.command("run <workflow-id> <user-request>").description("Execute a workflow").option("-a, --adapter <adapter>", "SDK adapter to use").option("-r, --max-retries <n>", "Override max retries per step").option("-n, --dry-run", "Simulate without calling SDK").option("--auto-approve-gates", "Auto-approve all gate steps").action((_workflowId, _userRequest, _opts) => {
16
+ console.log("agent-runtime run \u2014 not yet implemented (Phase 2)");
17
+ process.exit(0);
18
+ });
19
+ program.command("list <resource>").description("List available workflows, tasks, or agents").option("--format <format>", "Output format (table or json)", "table").action((_resource, _opts) => {
20
+ console.log("agent-runtime list \u2014 not yet implemented (Phase 2)");
21
+ process.exit(0);
22
+ });
23
+ program.command("doctor").description("Verify configuration, generated files, and SDK connectivity").action(() => {
24
+ console.log("agent-runtime doctor \u2014 not yet implemented (Phase 2)");
25
+ process.exit(0);
26
+ });
27
+ program.command("replay <run-dir>").description("Replay a past workflow execution from logs").option("--validate-only", "Only validate without re-execution").action((_runDir, _opts) => {
28
+ console.log("agent-runtime replay \u2014 not yet implemented (Phase 3)");
29
+ process.exit(0);
30
+ });
31
+ program.parse();
32
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Stub for v0.0.1 — prints version and available commands.\n * Full implementation in Phase 2.\n */\n\nimport { Command } from \"commander\";\n\nconst program = new Command();\n\nprogram\n .name(\"agent-runtime\")\n .description(\"Runtime bridge for executing agent-contracts workflows on Agent SDKs\")\n .version(\"0.0.1\");\n\nprogram\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project\")\n .option(\"-a, --adapter <adapter>\", \"Default SDK adapter\", \"mock\")\n .option(\"-o, --output <dir>\", \"Output directory\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files\")\n .action((_opts) => {\n console.log(\"agent-runtime init — not yet implemented (Phase 2)\");\n process.exit(0);\n });\n\nprogram\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL\")\n .option(\"--clean\", \"Delete generated_dir before regenerating\")\n .option(\"--check\", \"Dry-run: verify generated files are up to date\")\n .action((_opts) => {\n console.log(\"agent-runtime generate — not yet implemented (Phase 2)\");\n process.exit(0);\n });\n\nprogram\n .command(\"run <workflow-id> <user-request>\")\n .description(\"Execute a workflow\")\n .option(\"-a, --adapter <adapter>\", \"SDK adapter to use\")\n .option(\"-r, --max-retries <n>\", \"Override max retries per step\")\n .option(\"-n, --dry-run\", \"Simulate without calling SDK\")\n .option(\"--auto-approve-gates\", \"Auto-approve all gate steps\")\n .action((_workflowId, _userRequest, _opts) => {\n console.log(\"agent-runtime run — not yet implemented (Phase 2)\");\n process.exit(0);\n });\n\nprogram\n .command(\"list <resource>\")\n .description(\"List available workflows, tasks, or agents\")\n .option(\"--format <format>\", \"Output format (table or json)\", \"table\")\n .action((_resource, _opts) => {\n console.log(\"agent-runtime list — not yet implemented (Phase 2)\");\n process.exit(0);\n });\n\nprogram\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity\")\n .action(() => {\n console.log(\"agent-runtime doctor — not yet implemented (Phase 2)\");\n process.exit(0);\n });\n\nprogram\n .command(\"replay <run-dir>\")\n .description(\"Replay a past workflow execution from logs\")\n .option(\"--validate-only\", \"Only validate without re-execution\")\n .action((_runDir, _opts) => {\n console.log(\"agent-runtime replay — not yet implemented (Phase 3)\");\n process.exit(0);\n });\n\nprogram.parse();\n"],"mappings":";;;AASA,SAAS,eAAe;AAExB,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,eAAe,EACpB,YAAY,sEAAsE,EAClF,QAAQ,OAAO;AAElB,QACG,QAAQ,MAAM,EACd,YAAY,8CAA8C,EAC1D,OAAO,2BAA2B,uBAAuB,MAAM,EAC/D,OAAO,sBAAsB,oBAAoB,GAAG,EACpD,OAAO,eAAe,0BAA0B,EAChD,OAAO,CAAC,UAAU;AACjB,UAAQ,IAAI,yDAAoD;AAChE,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,+CAA+C,EAC3D,OAAO,WAAW,0CAA0C,EAC5D,OAAO,WAAW,gDAAgD,EAClE,OAAO,CAAC,UAAU;AACjB,UAAQ,IAAI,6DAAwD;AACpE,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QACG,QAAQ,kCAAkC,EAC1C,YAAY,oBAAoB,EAChC,OAAO,2BAA2B,oBAAoB,EACtD,OAAO,yBAAyB,+BAA+B,EAC/D,OAAO,iBAAiB,8BAA8B,EACtD,OAAO,wBAAwB,6BAA6B,EAC5D,OAAO,CAAC,aAAa,cAAc,UAAU;AAC5C,UAAQ,IAAI,wDAAmD;AAC/D,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QACG,QAAQ,iBAAiB,EACzB,YAAY,4CAA4C,EACxD,OAAO,qBAAqB,iCAAiC,OAAO,EACpE,OAAO,CAAC,WAAW,UAAU;AAC5B,UAAQ,IAAI,yDAAoD;AAChE,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QACG,QAAQ,QAAQ,EAChB,YAAY,6DAA6D,EACzE,OAAO,MAAM;AACZ,UAAQ,IAAI,2DAAsD;AAClE,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QACG,QAAQ,kBAAkB,EAC1B,YAAY,4CAA4C,EACxD,OAAO,mBAAmB,oCAAoC,EAC9D,OAAO,CAAC,SAAS,UAAU;AAC1B,UAAQ,IAAI,2DAAsD;AAClE,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QAAQ,MAAM;","names":[]}
@@ -0,0 +1,112 @@
1
+ import { T as TaskOutcome, a as TaskContext, S as SdkAdapter, b as TaskContractLike, A as AgentContractLike } from './task-runner-B5SV4eCS.js';
2
+ export { c as buildTaskPrompt, e as extractStructuredResult, r as runTask } from './task-runner-B5SV4eCS.js';
3
+ import { z } from 'zod';
4
+
5
+ /**
6
+ * Workflow Runner — orchestrates a DSL workflow as a sequence of task executions
7
+ */
8
+
9
+ interface DelegateStep {
10
+ readonly type: "delegate";
11
+ readonly task: string;
12
+ readonly from_agent: string;
13
+ readonly description: string;
14
+ readonly optional: boolean;
15
+ readonly max_retries: number;
16
+ }
17
+ interface GateStep {
18
+ readonly type: "gate";
19
+ readonly gate_kind: string;
20
+ readonly description: string;
21
+ }
22
+ type WorkflowStep = DelegateStep | GateStep;
23
+ interface WorkflowContractLike {
24
+ readonly id: string;
25
+ readonly description: string;
26
+ readonly steps: readonly WorkflowStep[];
27
+ }
28
+ interface WorkflowRunOptions {
29
+ user_request: string;
30
+ onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;
31
+ onStepComplete?: (event: StepCompleteEvent) => void;
32
+ onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;
33
+ }
34
+ interface StepResult {
35
+ step_index: number;
36
+ task_id?: string;
37
+ gate_kind?: string;
38
+ outcome: TaskOutcome | {
39
+ status: "gate_approved";
40
+ } | {
41
+ status: "gate_rejected";
42
+ } | {
43
+ status: "skipped";
44
+ };
45
+ retries_used: number;
46
+ elapsed_ms: number;
47
+ }
48
+ interface StepCompleteEvent {
49
+ workflow_id: string;
50
+ step_index: number;
51
+ step_type: "delegate" | "gate";
52
+ task_id?: string;
53
+ gate_kind?: string;
54
+ outcome_status: string;
55
+ retries_used: number;
56
+ elapsed_ms: number;
57
+ }
58
+ interface WorkflowResult {
59
+ workflow_id: string;
60
+ status: "completed" | "escalated" | "gate_rejected" | "error";
61
+ steps: StepResult[];
62
+ total_elapsed_ms: number;
63
+ escalation_reason?: string;
64
+ error_message?: string;
65
+ }
66
+ declare function runWorkflow(adapter: SdkAdapter, workflowId: string, options: WorkflowRunOptions, registries?: {
67
+ workflowRegistry?: Record<string, WorkflowContractLike>;
68
+ taskRegistry?: Record<string, TaskContractLike>;
69
+ agentRegistry?: Record<string, AgentContractLike>;
70
+ handoffSchemas?: Record<string, z.ZodTypeAny>;
71
+ }): Promise<WorkflowResult>;
72
+
73
+ /**
74
+ * Plugin Interface — extension points for user code injection
75
+ */
76
+
77
+ interface GuardrailResult {
78
+ matched: boolean;
79
+ guardrail_id: string;
80
+ severity: "critical" | "mandatory" | "warning" | "info";
81
+ action: "block" | "warn" | "shadow" | "info";
82
+ message: string;
83
+ }
84
+ interface AgentPlugin {
85
+ readonly id: string;
86
+ beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;
87
+ afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
88
+ promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;
89
+ customGuardrails?: {
90
+ evaluateCommand?(command: string): GuardrailResult[];
91
+ evaluateFilePath?(filePath: string): GuardrailResult[];
92
+ evaluateFileContent?(filePath: string, content: string): GuardrailResult[];
93
+ };
94
+ beforeWorkflow?(workflowId: string, userRequest: string): Promise<void>;
95
+ afterWorkflow?(workflowId: string, result: WorkflowResult): Promise<void>;
96
+ }
97
+ declare class PluginRegistry {
98
+ private plugins;
99
+ register(plugin: AgentPlugin): void;
100
+ getAll(): readonly AgentPlugin[];
101
+ runBeforeTask(taskId: string, context: TaskContext): Promise<TaskContext | null>;
102
+ runAfterTask(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;
103
+ applyPromptEnhancers(taskId: string, prompt: string, context: TaskContext): string;
104
+ evaluateCommandGuardrails(command: string): GuardrailResult[];
105
+ evaluateFilePathGuardrails(filePath: string): GuardrailResult[];
106
+ evaluateFileContentGuardrails(filePath: string, content: string): GuardrailResult[];
107
+ runBeforeWorkflow(workflowId: string, userRequest: string): Promise<void>;
108
+ runAfterWorkflow(workflowId: string, result: WorkflowResult): Promise<void>;
109
+ }
110
+ declare const pluginRegistry: PluginRegistry;
111
+
112
+ export { type AgentPlugin, PluginRegistry, SdkAdapter, type StepCompleteEvent, type StepResult, TaskContext, TaskOutcome, type WorkflowResult, type WorkflowRunOptions, pluginRegistry, runWorkflow };
package/dist/index.js ADDED
@@ -0,0 +1,378 @@
1
+ // src/lib/task-runner.ts
2
+ import { z } from "zod";
3
+ import * as yaml from "yaml";
4
+
5
+ // src/lib/plugin.ts
6
+ var PluginRegistry = class {
7
+ plugins = [];
8
+ register(plugin) {
9
+ if (this.plugins.some((p) => p.id === plugin.id)) {
10
+ throw new Error(`Plugin "${plugin.id}" is already registered`);
11
+ }
12
+ this.plugins.push(plugin);
13
+ }
14
+ getAll() {
15
+ return this.plugins;
16
+ }
17
+ async runBeforeTask(taskId, context) {
18
+ let ctx = context;
19
+ for (const plugin of this.plugins) {
20
+ if (!plugin.beforeTask || ctx === null) continue;
21
+ ctx = await plugin.beforeTask(taskId, ctx);
22
+ }
23
+ return ctx;
24
+ }
25
+ async runAfterTask(taskId, outcome) {
26
+ let result = outcome;
27
+ for (const plugin of this.plugins) {
28
+ if (!plugin.afterTask) continue;
29
+ result = await plugin.afterTask(taskId, result);
30
+ }
31
+ return result;
32
+ }
33
+ applyPromptEnhancers(taskId, prompt, context) {
34
+ let enhanced = prompt;
35
+ for (const plugin of this.plugins) {
36
+ if (!plugin.promptEnhancer) continue;
37
+ enhanced = plugin.promptEnhancer(taskId, enhanced, context);
38
+ }
39
+ return enhanced;
40
+ }
41
+ evaluateCommandGuardrails(command) {
42
+ const results = [];
43
+ for (const plugin of this.plugins) {
44
+ if (!plugin.customGuardrails?.evaluateCommand) continue;
45
+ results.push(...plugin.customGuardrails.evaluateCommand(command));
46
+ }
47
+ return results;
48
+ }
49
+ evaluateFilePathGuardrails(filePath) {
50
+ const results = [];
51
+ for (const plugin of this.plugins) {
52
+ if (!plugin.customGuardrails?.evaluateFilePath) continue;
53
+ results.push(...plugin.customGuardrails.evaluateFilePath(filePath));
54
+ }
55
+ return results;
56
+ }
57
+ evaluateFileContentGuardrails(filePath, content) {
58
+ const results = [];
59
+ for (const plugin of this.plugins) {
60
+ if (!plugin.customGuardrails?.evaluateFileContent) continue;
61
+ results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));
62
+ }
63
+ return results;
64
+ }
65
+ async runBeforeWorkflow(workflowId, userRequest) {
66
+ for (const plugin of this.plugins) {
67
+ if (!plugin.beforeWorkflow) continue;
68
+ await plugin.beforeWorkflow(workflowId, userRequest);
69
+ }
70
+ }
71
+ async runAfterWorkflow(workflowId, result) {
72
+ for (const plugin of this.plugins) {
73
+ if (!plugin.afterWorkflow) continue;
74
+ await plugin.afterWorkflow(workflowId, result);
75
+ }
76
+ }
77
+ };
78
+ var pluginRegistry = new PluginRegistry();
79
+
80
+ // src/lib/task-runner.ts
81
+ function buildTaskPrompt(agent, task, context) {
82
+ const sections = [];
83
+ sections.push(`# Role: ${agent.role_name}
84
+
85
+ ${agent.purpose}`);
86
+ if (agent.responsibilities.length > 0) {
87
+ sections.push(
88
+ `## Responsibilities
89
+
90
+ ${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
91
+ );
92
+ }
93
+ if (agent.constraints.length > 0) {
94
+ sections.push(
95
+ `## Constraints
96
+
97
+ ${agent.constraints.map((c) => `- ${c}`).join("\n")}`
98
+ );
99
+ }
100
+ sections.push(`## Task: ${task.id}
101
+
102
+ ${task.description}`);
103
+ if (task.completion_criteria.length > 0) {
104
+ sections.push(
105
+ `## Completion Criteria
106
+
107
+ ${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
108
+ );
109
+ }
110
+ sections.push(`## User Request
111
+
112
+ ${context.user_request}`);
113
+ if (context.prior_context) {
114
+ sections.push(`## Prior Context
115
+
116
+ ${context.prior_context}`);
117
+ }
118
+ if (context.relevant_paths && context.relevant_paths.length > 0) {
119
+ sections.push(
120
+ `## Relevant Files
121
+
122
+ ${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
123
+ );
124
+ }
125
+ if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
126
+ sections.push(
127
+ `## Acceptance Criteria
128
+
129
+ ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
130
+ );
131
+ }
132
+ const handoffId = task.result_handoff;
133
+ sections.push(
134
+ `## Required Output Format
135
+
136
+ Return your result as a YAML block matching the "${handoffId}" schema. Include all required fields.`
137
+ );
138
+ return sections.join("\n\n---\n\n");
139
+ }
140
+ function extractStructuredResult(raw) {
141
+ const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
142
+ if (yamlMatch) {
143
+ try {
144
+ return yaml.parse(yamlMatch[1]);
145
+ } catch {
146
+ }
147
+ }
148
+ const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
149
+ if (jsonMatch) {
150
+ try {
151
+ return JSON.parse(jsonMatch[1]);
152
+ } catch {
153
+ }
154
+ }
155
+ try {
156
+ return JSON.parse(raw);
157
+ } catch {
158
+ }
159
+ return null;
160
+ }
161
+ async function runTask(adapter, taskId, context, options) {
162
+ const taskReg = options?.taskRegistry ?? {};
163
+ const agentReg = options?.agentRegistry ?? {};
164
+ const schemas = options?.handoffSchemas ?? {};
165
+ const task = taskReg[taskId];
166
+ if (!task) return { status: "error", message: `Unknown task: ${taskId}` };
167
+ const agentContract = agentReg[task.target_agent];
168
+ if (!agentContract) return { status: "error", message: `Unknown agent: ${task.target_agent}` };
169
+ const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
170
+ if (modifiedContext === null) {
171
+ return { status: "error", message: `Task "${taskId}" skipped by plugin` };
172
+ }
173
+ let prompt = buildTaskPrompt(agentContract, task, modifiedContext);
174
+ prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, modifiedContext);
175
+ const isReadonly = agentContract.mode === "read-only";
176
+ let fullOutput;
177
+ try {
178
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly });
179
+ } catch (err) {
180
+ return { status: "error", message: `SDK error: ${err.message}` };
181
+ }
182
+ if (!fullOutput.trim()) {
183
+ const outcome2 = { status: "error", message: "Agent returned empty output" };
184
+ return pluginRegistry.runAfterTask(taskId, outcome2);
185
+ }
186
+ const parsed = extractStructuredResult(fullOutput);
187
+ if (!parsed) {
188
+ const outcome2 = {
189
+ status: "validation_error",
190
+ errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
191
+ raw: fullOutput
192
+ };
193
+ return pluginRegistry.runAfterTask(taskId, outcome2);
194
+ }
195
+ const schema = schemas[task.result_handoff];
196
+ if (!schema) {
197
+ const outcome2 = { status: "success", data: parsed, raw: fullOutput };
198
+ return pluginRegistry.runAfterTask(taskId, outcome2);
199
+ }
200
+ const validation = schema.safeParse(parsed);
201
+ if (!validation.success) {
202
+ const outcome2 = { status: "validation_error", errors: validation.error, raw: fullOutput };
203
+ return pluginRegistry.runAfterTask(taskId, outcome2);
204
+ }
205
+ const data = validation.data;
206
+ if (data.escalation_needed === true) {
207
+ const outcome2 = {
208
+ status: "escalation",
209
+ reason: data.escalation_reasons ?? "Agent requested escalation",
210
+ raw: fullOutput
211
+ };
212
+ return pluginRegistry.runAfterTask(taskId, outcome2);
213
+ }
214
+ const outcome = { status: "success", data: validation.data, raw: fullOutput };
215
+ return pluginRegistry.runAfterTask(taskId, outcome);
216
+ }
217
+
218
+ // src/lib/workflow-runner.ts
219
+ async function runWorkflow(adapter, workflowId, options, registries) {
220
+ const wfReg = registries?.workflowRegistry ?? {};
221
+ const workflow = wfReg[workflowId];
222
+ if (!workflow) {
223
+ return {
224
+ workflow_id: workflowId,
225
+ status: "error",
226
+ steps: [],
227
+ total_elapsed_ms: 0,
228
+ error_message: `Unknown workflow: ${workflowId}`
229
+ };
230
+ }
231
+ await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);
232
+ const stepResults = [];
233
+ const workflowStart = Date.now();
234
+ let accumulatedContext = "";
235
+ for (let i = 0; i < workflow.steps.length; i++) {
236
+ const step = workflow.steps[i];
237
+ const stepStart = Date.now();
238
+ if (step.type === "gate") {
239
+ const result2 = await handleGateStep(step, stepResults, options, i);
240
+ stepResults.push(result2);
241
+ emitStepEvent(options, workflow.id, i, step, result2);
242
+ if (result2.outcome.status === "gate_rejected") {
243
+ const wfResult2 = {
244
+ workflow_id: workflow.id,
245
+ status: "gate_rejected",
246
+ steps: stepResults,
247
+ total_elapsed_ms: Date.now() - workflowStart
248
+ };
249
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
250
+ return wfResult2;
251
+ }
252
+ continue;
253
+ }
254
+ if (step.optional) {
255
+ const ctx = { user_request: options.user_request, prior_context: accumulatedContext };
256
+ const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
257
+ if (!shouldRun) {
258
+ const result2 = {
259
+ step_index: i,
260
+ task_id: step.task,
261
+ outcome: { status: "skipped" },
262
+ retries_used: 0,
263
+ elapsed_ms: Date.now() - stepStart
264
+ };
265
+ stepResults.push(result2);
266
+ emitStepEvent(options, workflow.id, i, step, result2);
267
+ continue;
268
+ }
269
+ }
270
+ const result = await executeDelegateWithRetry(
271
+ adapter,
272
+ step,
273
+ i,
274
+ options.user_request,
275
+ accumulatedContext,
276
+ stepStart,
277
+ { taskRegistry: registries?.taskRegistry, agentRegistry: registries?.agentRegistry, handoffSchemas: registries?.handoffSchemas }
278
+ );
279
+ stepResults.push(result);
280
+ emitStepEvent(options, workflow.id, i, step, result);
281
+ if (result.outcome.status === "success") {
282
+ const data = result.outcome.data;
283
+ accumulatedContext += `
284
+
285
+ --- Step ${i + 1}: ${step.task} ---
286
+ `;
287
+ accumulatedContext += typeof data === "string" ? data : JSON.stringify(data, null, 2);
288
+ }
289
+ if (result.outcome.status === "escalation") {
290
+ const wfResult2 = {
291
+ workflow_id: workflow.id,
292
+ status: "escalated",
293
+ steps: stepResults,
294
+ total_elapsed_ms: Date.now() - workflowStart,
295
+ escalation_reason: result.outcome.reason
296
+ };
297
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
298
+ return wfResult2;
299
+ }
300
+ if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
301
+ if (result.retries_used >= (step.max_retries ?? 2)) {
302
+ const wfResult2 = {
303
+ workflow_id: workflow.id,
304
+ status: "escalated",
305
+ steps: stepResults,
306
+ total_elapsed_ms: Date.now() - workflowStart,
307
+ escalation_reason: `Task "${step.task}" failed after ${result.retries_used} retries`
308
+ };
309
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
310
+ return wfResult2;
311
+ }
312
+ }
313
+ }
314
+ const wfResult = {
315
+ workflow_id: workflow.id,
316
+ status: "completed",
317
+ steps: stepResults,
318
+ total_elapsed_ms: Date.now() - workflowStart
319
+ };
320
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
321
+ return wfResult;
322
+ }
323
+ async function handleGateStep(step, priorResults, options, stepIndex) {
324
+ const start = Date.now();
325
+ if (!options.onGate) {
326
+ return { step_index: stepIndex, gate_kind: step.gate_kind, outcome: { status: "gate_approved" }, retries_used: 0, elapsed_ms: Date.now() - start };
327
+ }
328
+ const approved = await options.onGate(step.gate_kind, step.description, priorResults);
329
+ return { step_index: stepIndex, gate_kind: step.gate_kind, outcome: { status: approved ? "gate_approved" : "gate_rejected" }, retries_used: 0, elapsed_ms: Date.now() - start };
330
+ }
331
+ async function executeDelegateWithRetry(adapter, step, stepIndex, userRequest, priorContext, stepStart, regs) {
332
+ const maxRetries = step.max_retries ?? 2;
333
+ let lastOutcome;
334
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
335
+ const context = { user_request: userRequest, prior_context: priorContext };
336
+ if (attempt > 0 && lastOutcome) {
337
+ context.prior_context += `
338
+
339
+ --- Retry ${attempt} ---
340
+ Previous attempt failed:
341
+ `;
342
+ if (lastOutcome.status === "validation_error") {
343
+ context.prior_context += `Validation errors: ${lastOutcome.errors.message}
344
+ Raw output:
345
+ ${lastOutcome.raw}`;
346
+ } else if (lastOutcome.status === "error") {
347
+ context.prior_context += lastOutcome.message;
348
+ }
349
+ }
350
+ const outcome = await runTask(adapter, step.task, context, regs);
351
+ lastOutcome = outcome;
352
+ if (outcome.status === "success" || outcome.status === "escalation") {
353
+ return { step_index: stepIndex, task_id: step.task, outcome, retries_used: attempt, elapsed_ms: Date.now() - stepStart };
354
+ }
355
+ }
356
+ return { step_index: stepIndex, task_id: step.task, outcome: lastOutcome, retries_used: maxRetries, elapsed_ms: Date.now() - stepStart };
357
+ }
358
+ function emitStepEvent(options, workflowId, stepIndex, step, result) {
359
+ options.onStepComplete?.({
360
+ workflow_id: workflowId,
361
+ step_index: stepIndex,
362
+ step_type: step.type,
363
+ task_id: step.type === "delegate" ? step.task : void 0,
364
+ gate_kind: step.type === "gate" ? step.gate_kind : void 0,
365
+ outcome_status: result.outcome.status,
366
+ retries_used: result.retries_used,
367
+ elapsed_ms: result.elapsed_ms
368
+ });
369
+ }
370
+ export {
371
+ PluginRegistry,
372
+ buildTaskPrompt,
373
+ extractStructuredResult,
374
+ pluginRegistry,
375
+ runTask,
376
+ runWorkflow
377
+ };
378
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/task-runner.ts","../src/lib/plugin.ts","../src/lib/workflow-runner.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\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Re-exported from generated contracts at runtime — these are duck-typed\n// so the runtime doesn't depend on specific generated contract shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\nexport interface SdkAdapter {\n send(prompt: string, options: { readonly: boolean }): 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\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// Prompt builder\n// ---------------------------------------------------------------------------\n\nexport function buildTaskPrompt(\n agent: AgentContractLike,\n task: TaskContractLike,\n context: TaskContext,\n): string {\n const sections: string[] = [];\n\n sections.push(`# Role: ${agent.role_name}\\n\\n${agent.purpose}`);\n\n if (agent.responsibilities.length > 0) {\n sections.push(\n `## Responsibilities\\n\\n${agent.responsibilities.map((r) => `- ${r}`).join(\"\\n\")}`,\n );\n }\n\n if (agent.constraints.length > 0) {\n sections.push(\n `## Constraints\\n\\n${agent.constraints.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## Task: ${task.id}\\n\\n${task.description}`);\n\n if (task.completion_criteria.length > 0) {\n sections.push(\n `## Completion Criteria\\n\\n${task.completion_criteria.map((c) => `- ${c}`).join(\"\\n\")}`,\n );\n }\n\n sections.push(`## User Request\\n\\n${context.user_request}`);\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 sections.push(\n `## Required Output Format\\n\\nReturn your result as a YAML block matching the \"${handoffId}\" schema. ` +\n `Include all required fields.`,\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// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n },\n): Promise<TaskOutcome> {\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 { status: \"error\", message: `Unknown task: ${taskId}` };\n\n const agentContract = agentReg[task.target_agent];\n if (!agentContract) return { status: \"error\", message: `Unknown agent: ${task.target_agent}` };\n\n const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);\n if (modifiedContext === null) {\n return { status: \"error\", message: `Task \"${taskId}\" skipped by plugin` };\n }\n\n let prompt = buildTaskPrompt(agentContract, task, modifiedContext);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, modifiedContext);\n\n const isReadonly = agentContract.mode === \"read-only\";\n let fullOutput: string;\n try {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\n } catch (err) {\n return { status: \"error\", message: `SDK error: ${(err as Error).message}` };\n }\n\n if (!fullOutput.trim()) {\n const outcome: TaskOutcome = { status: \"error\", message: \"Agent returned empty output\" };\n return pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n const outcome: TaskOutcome = {\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 return pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n const outcome: TaskOutcome = { status: \"success\", data: parsed, raw: fullOutput };\n return pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n const outcome: TaskOutcome = { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n return pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n const outcome: TaskOutcome = {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n return pluginRegistry.runAfterTask(taskId, outcome);\n }\n\n const outcome: TaskOutcome = { status: \"success\", data: validation.data, raw: fullOutput };\n return pluginRegistry.runAfterTask(taskId, outcome);\n}\n","/**\n * Plugin Interface — extension points for user code injection\n */\n\nimport type { TaskContext, TaskOutcome } 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 AgentPlugin {\n readonly id: string;\n beforeTask?(taskId: string, context: TaskContext): Promise<TaskContext | null>;\n afterTask?(taskId: string, outcome: TaskOutcome): Promise<TaskOutcome>;\n promptEnhancer?(taskId: string, prompt: string, context: TaskContext): string;\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 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\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n}\n\nexport interface GateStep {\n readonly type: \"gate\";\n readonly gate_kind: string;\n readonly description: string;\n}\n\nexport type WorkflowStep = DelegateStep | GateStep;\n\nexport interface WorkflowContractLike {\n readonly id: string;\n readonly description: string;\n readonly steps: readonly WorkflowStep[];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkflowRunOptions {\n user_request: string;\n onGate?: (gateKind: string, description: string, stepResults: StepResult[]) => Promise<boolean>;\n onStepComplete?: (event: StepCompleteEvent) => void;\n onOptionalStep?: (step: DelegateStep, context: TaskContext) => Promise<boolean>;\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 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 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\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\nexport async function runWorkflow(\n adapter: SdkAdapter,\n workflowId: string,\n options: WorkflowRunOptions,\n registries?: {\n workflowRegistry?: Record<string, WorkflowContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n agentRegistry?: Record<string, AgentContractLike>;\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n },\n): Promise<WorkflowResult> {\n const wfReg = registries?.workflowRegistry ?? {};\n const workflow = wfReg[workflowId];\n if (!workflow) {\n return {\n workflow_id: workflowId,\n status: \"error\",\n steps: [],\n total_elapsed_ms: 0,\n error_message: `Unknown workflow: ${workflowId}`,\n };\n }\n\n await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);\n\n const stepResults: StepResult[] = [];\n const workflowStart = Date.now();\n let accumulatedContext = \"\";\n\n for (let i = 0; i < workflow.steps.length; i++) {\n const step = workflow.steps[i];\n const stepStart = Date.now();\n\n if (step.type === \"gate\") {\n const result = await handleGateStep(step, stepResults, options, i);\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"gate_rejected\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"gate_rejected\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n continue;\n }\n\n // Optional steps\n if (step.optional) {\n const ctx: TaskContext = { user_request: options.user_request, prior_context: accumulatedContext };\n const shouldRun = options.onOptionalStep\n ? await options.onOptionalStep(step, ctx)\n : false;\n\n if (!shouldRun) {\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: { status: \"skipped\" },\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n const result = await executeDelegateWithRetry(\n adapter, step, i, options.user_request, accumulatedContext, stepStart,\n { taskRegistry: registries?.taskRegistry, agentRegistry: registries?.agentRegistry, handoffSchemas: registries?.handoffSchemas },\n );\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n if (result.retries_used >= (step.max_retries ?? 2)) {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n if (!options.onGate) {\n return { step_index: stepIndex, gate_kind: step.gate_kind, outcome: { status: \"gate_approved\" }, retries_used: 0, elapsed_ms: Date.now() - start };\n }\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return { step_index: stepIndex, gate_kind: step.gate_kind, outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" }, retries_used: 0, elapsed_ms: Date.now() - start };\n}\n\nasync function executeDelegateWithRetry(\n adapter: SdkAdapter,\n step: DelegateStep,\n stepIndex: number,\n userRequest: string,\n priorContext: string,\n stepStart: number,\n regs?: { taskRegistry?: Record<string, TaskContractLike>; agentRegistry?: Record<string, AgentContractLike>; handoffSchemas?: Record<string, z.ZodTypeAny> },\n): Promise<StepResult> {\n const maxRetries = step.max_retries ?? 2;\n let lastOutcome: TaskOutcome | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const context: TaskContext = { user_request: userRequest, prior_context: priorContext };\n\n if (attempt > 0 && lastOutcome) {\n context.prior_context += `\\n\\n--- Retry ${attempt} ---\\nPrevious attempt failed:\\n`;\n if (lastOutcome.status === \"validation_error\") {\n context.prior_context += `Validation errors: ${lastOutcome.errors.message}\\nRaw output:\\n${lastOutcome.raw}`;\n } else if (lastOutcome.status === \"error\") {\n context.prior_context += lastOutcome.message;\n }\n }\n\n const outcome = await runTask(adapter, step.task, context, regs);\n lastOutcome = outcome;\n\n if (outcome.status === \"success\" || outcome.status === \"escalation\") {\n return { step_index: stepIndex, task_id: step.task, outcome, retries_used: attempt, elapsed_ms: Date.now() - stepStart };\n }\n }\n\n return { step_index: stepIndex, task_id: step.task, outcome: lastOutcome!, retries_used: maxRetries, elapsed_ms: Date.now() - stepStart };\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 retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n"],"mappings":";AAaA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACef,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,QA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