agent-contracts-runtime 0.0.2 → 0.0.3
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/adapters/claude-agent-sdk.d.ts +1 -1
- package/dist/adapters/cursor-sdk.d.ts +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +16 -3
- package/dist/index.js +164 -82
- package/dist/index.js.map +1 -1
- package/dist/task-runner-CuYWldNc.d.ts +105 -0
- package/package.json +1 -1
- package/dist/task-runner-B5SV4eCS.d.ts +0 -66
package/dist/adapters/mock.d.ts
CHANGED
package/dist/cli/index.js
CHANGED
|
@@ -30,7 +30,7 @@ function createProgram(handlers2, version) {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
// src/cli/index.ts
|
|
33
|
-
var VERSION = "0.0.
|
|
33
|
+
var VERSION = "0.0.3";
|
|
34
34
|
var handlers = {
|
|
35
35
|
async init(options, _globalOpts) {
|
|
36
36
|
console.log("agent-runtime init \u2014 not yet implemented (Phase 2)");
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/generated/cli/program.ts","../../src/cli/index.ts"],"sourcesContent":["// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; dryRun?: boolean; autoApproveGates?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n replay: (runDir: string | undefined, options: { validateOnly?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"<workflow-id>\", \"ID of the workflow to execute (e.g. feature-implement, issue-fix).\")\n .argument(\"<user-request>\", \"Natural language description of what to do.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) => {\n await handlers.replay(runDir, opts, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n * Handler implementations are stubs for v0.0.x — full logic in Phase 2.\n */\n\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\n\nconst VERSION = \"0.0.
|
|
1
|
+
{"version":3,"sources":["../../src/generated/cli/program.ts","../../src/cli/index.ts"],"sourcesContent":["// Auto-generated by cli-contracts. Do not edit.\nimport { Command } from \"commander\";\n\nexport interface CommandHandlers {\n init: (options: { adapter?: string; output?: string; force?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n generate: (options: { clean?: boolean; check?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n run: (workflowId: string | undefined, userRequest: string | undefined, options: { adapter?: string; maxRetries?: string; dryRun?: boolean; autoApproveGates?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n list: (resource: string | undefined, options: { format?: string }, parentOpts: Record<string, unknown>) => Promise<void>;\n doctor: (parentOpts: Record<string, unknown>) => Promise<void>;\n replay: (runDir: string | undefined, options: { validateOnly?: boolean }, parentOpts: Record<string, unknown>) => Promise<void>;\n}\n\nexport function createProgram(\n handlers: CommandHandlers,\n version: string,\n): Command {\n const program = new Command();\n program\n .name(\"agent-runtime\")\n .version(version, \"-V, --version\")\n .description(\"CLI for agent-contracts-runtime — generate, run, and manage agent workflows.\");\n\n program.option(\"-c, --config <value>\", \"Path to agent-runtime.config.yaml.\", \"./agent-runtime.config.yaml\");\n program.option(\"-v, --verbose\", \"Enable verbose output.\", false);\n program.option(\"-q, --quiet\", \"Suppress non-error output.\", false);\n\n program\n .command(\"init\")\n .description(\"Initialize runtime scaffolding for a project.\")\n .option(\"-a, --adapter <value>\", \"Default SDK adapter to configure.\", \"mock\")\n .option(\"-o, --output <value>\", \"Output directory for generated scaffolding.\", \".\")\n .option(\"-f, --force\", \"Overwrite existing files without prompting.\", false)\n .action(async (opts, cmd) => {\n await handlers.init(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"generate\")\n .description(\"Generate runtime contracts and hooks from DSL.\")\n .option(\"--clean\", \"Delete generated_dir before regenerating.\\nRemoves stale files that may remain from previous generations.\\n\", false)\n .option(\"--check\", \"Dry-run mode for CI. Does not write files.\\nCompares current generated output with what would be regenerated.\\nExits with code 1 if any differences are found.\\n\", false)\n .action(async (opts, cmd) => {\n await handlers.generate(opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"run\")\n .description(\"Execute a workflow.\")\n .argument(\"<workflow-id>\", \"ID of the workflow to execute (e.g. feature-implement, issue-fix).\")\n .argument(\"<user-request>\", \"Natural language description of what to do.\")\n .option(\"-a, --adapter <value>\", \"SDK adapter to use. Overrides config.\")\n .option(\"-r, --max-retries <value>\", \"Override default max retries per step.\")\n .option(\"-n, --dry-run\", \"Simulate execution without calling the SDK adapter.\", false)\n .option(\"--auto-approve-gates\", \"Automatically approve all gate steps.\", false)\n .action(async (workflowId, userRequest, opts, cmd) => {\n await handlers.run(workflowId, userRequest, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"list\")\n .description(\"List available workflows, tasks, or agents.\")\n .argument(\"<resource>\", \"Type of resource to list.\")\n .option(\"--format <value>\", \"Output format.\", \"table\")\n .action(async (resource, opts, cmd) => {\n await handlers.list(resource, opts, cmd.optsWithGlobals());\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify configuration, generated files, and SDK connectivity.\")\n .action(async (opts, cmd) => {\n await handlers.doctor({}, cmd.optsWithGlobals());\n });\n\n program\n .command(\"replay\")\n .description(\"Replay a past workflow execution from logs.\")\n .argument(\"<run-dir>\", \"Path to the .agent-runs/<run-id> directory.\")\n .option(\"--validate-only\", \"Only validate the run log without re-execution.\", false)\n .action(async (runDir, opts, cmd) => {\n await handlers.replay(runDir, opts, cmd.optsWithGlobals());\n });\n\n return program;\n}\n","#!/usr/bin/env node\n\n/**\n * agent-runtime CLI entry point\n *\n * Uses auto-generated program from cli-contract.yaml.\n * Handler implementations are stubs for v0.0.x — full logic in Phase 2.\n */\n\nimport { createProgram, type CommandHandlers } from \"../generated/cli/program.js\";\n\nconst VERSION = \"0.0.3\";\n\nconst handlers: CommandHandlers = {\n async init(options, _globalOpts) {\n console.log(\"agent-runtime init — not yet implemented (Phase 2)\");\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async generate(options, _globalOpts) {\n console.log(\"agent-runtime generate — not yet implemented (Phase 2)\");\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async run(workflowId, userRequest, options, _globalOpts) {\n console.log(\"agent-runtime run — not yet implemented (Phase 2)\");\n console.log(`Workflow: ${workflowId}, Request: ${userRequest}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async list(resource, options, _globalOpts) {\n console.log(\"agent-runtime list — not yet implemented (Phase 2)\");\n console.log(`Resource: ${resource}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n\n async doctor(_globalOpts) {\n console.log(\"agent-runtime doctor — not yet implemented (Phase 2)\");\n },\n\n async replay(runDir, options, _globalOpts) {\n console.log(\"agent-runtime replay — not yet implemented (Phase 3)\");\n console.log(`Run dir: ${runDir}`);\n console.log(\"Options:\", JSON.stringify(options));\n },\n};\n\nconst program = createProgram(handlers, VERSION);\nprogram.parse();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EA,MAAM,OAAO,aAAa;AACxB,YAAQ,IAAI,2DAAsD;AAAA,EACpE;AAAA,EAEA,MAAM,OAAO,QAAQ,SAAS,aAAa;AACzC,YAAQ,IAAI,2DAAsD;AAClE,YAAQ,IAAI,YAAY,MAAM,EAAE;AAChC,YAAQ,IAAI,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,EACjD;AACF;AAEA,IAAM,UAAU,cAAc,UAAU,OAAO;AAC/C,QAAQ,MAAM;","names":["handlers","program"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,20 @@
|
|
|
1
|
-
import { T as TaskOutcome, a as TaskContext, S as SdkAdapter, b as TaskContractLike, A as AgentContractLike } from './task-runner-
|
|
2
|
-
export { c as
|
|
1
|
+
import { T as TaskOutcome, a as TaskContext, S as SdkAdapter, b as TaskContractLike, A as AgentContractLike } from './task-runner-CuYWldNc.js';
|
|
2
|
+
export { R as RetryDecision, c as TaskRunOptions, d as TaskRunResult, e as buildRetryFollowUp, f as buildTaskPrompt, g as extractStructuredResult, r as runTask } from './task-runner-CuYWldNc.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Workflow Runner — orchestrates a DSL workflow as a sequence of task executions
|
|
7
|
+
*
|
|
8
|
+
* Programmatic control flow that replaces LLM-driven step interpretation:
|
|
9
|
+
*
|
|
10
|
+
* 1. Load workflow contract (ordered steps)
|
|
11
|
+
* 2. Run plugin beforeWorkflow hooks
|
|
12
|
+
* 3. For each step:
|
|
13
|
+
* - delegate → call task-runner with followUp/retry recovery
|
|
14
|
+
* - gate → pause and wait for user input
|
|
15
|
+
* 4. Validate each result against handoff schema
|
|
16
|
+
* 5. Accumulate context between steps
|
|
17
|
+
* 6. Run plugin afterWorkflow hooks
|
|
7
18
|
*/
|
|
8
19
|
|
|
9
20
|
interface DelegateStep {
|
|
@@ -42,6 +53,7 @@ interface StepResult {
|
|
|
42
53
|
} | {
|
|
43
54
|
status: "skipped";
|
|
44
55
|
};
|
|
56
|
+
follow_ups_used: number;
|
|
45
57
|
retries_used: number;
|
|
46
58
|
elapsed_ms: number;
|
|
47
59
|
}
|
|
@@ -52,6 +64,7 @@ interface StepCompleteEvent {
|
|
|
52
64
|
task_id?: string;
|
|
53
65
|
gate_kind?: string;
|
|
54
66
|
outcome_status: string;
|
|
67
|
+
follow_ups_used: number;
|
|
55
68
|
retries_used: number;
|
|
56
69
|
elapsed_ms: number;
|
|
57
70
|
}
|
|
@@ -109,4 +122,4 @@ declare class PluginRegistry {
|
|
|
109
122
|
}
|
|
110
123
|
declare const pluginRegistry: PluginRegistry;
|
|
111
124
|
|
|
112
|
-
export { type AgentPlugin, PluginRegistry, SdkAdapter, type StepCompleteEvent, type StepResult, TaskContext, TaskOutcome, type WorkflowResult, type WorkflowRunOptions, pluginRegistry, runWorkflow };
|
|
125
|
+
export { AgentContractLike, type AgentPlugin, type DelegateStep, type GateStep, type GuardrailResult, PluginRegistry, SdkAdapter, type StepCompleteEvent, type StepResult, TaskContext, TaskContractLike, TaskOutcome, type WorkflowContractLike, type WorkflowResult, type WorkflowRunOptions, type WorkflowStep, pluginRegistry, runWorkflow };
|
package/dist/index.js
CHANGED
|
@@ -158,61 +158,145 @@ function extractStructuredResult(raw) {
|
|
|
158
158
|
}
|
|
159
159
|
return null;
|
|
160
160
|
}
|
|
161
|
-
|
|
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
|
-
}
|
|
161
|
+
function validateOutput(fullOutput, task, schemas) {
|
|
182
162
|
if (!fullOutput.trim()) {
|
|
183
|
-
|
|
184
|
-
return pluginRegistry.runAfterTask(taskId, outcome2);
|
|
163
|
+
return { status: "error", message: "Agent returned empty output" };
|
|
185
164
|
}
|
|
186
165
|
const parsed = extractStructuredResult(fullOutput);
|
|
187
166
|
if (!parsed) {
|
|
188
|
-
|
|
167
|
+
return {
|
|
189
168
|
status: "validation_error",
|
|
190
169
|
errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
|
|
191
170
|
raw: fullOutput
|
|
192
171
|
};
|
|
193
|
-
return pluginRegistry.runAfterTask(taskId, outcome2);
|
|
194
172
|
}
|
|
195
173
|
const schema = schemas[task.result_handoff];
|
|
196
174
|
if (!schema) {
|
|
197
|
-
|
|
198
|
-
return pluginRegistry.runAfterTask(taskId, outcome2);
|
|
175
|
+
return { status: "success", data: parsed, raw: fullOutput };
|
|
199
176
|
}
|
|
200
177
|
const validation = schema.safeParse(parsed);
|
|
201
178
|
if (!validation.success) {
|
|
202
|
-
|
|
203
|
-
return pluginRegistry.runAfterTask(taskId, outcome2);
|
|
179
|
+
return { status: "validation_error", errors: validation.error, raw: fullOutput };
|
|
204
180
|
}
|
|
205
181
|
const data = validation.data;
|
|
206
182
|
if (data.escalation_needed === true) {
|
|
207
|
-
|
|
183
|
+
return {
|
|
208
184
|
status: "escalation",
|
|
209
185
|
reason: data.escalation_reasons ?? "Agent requested escalation",
|
|
210
186
|
raw: fullOutput
|
|
211
187
|
};
|
|
212
|
-
return pluginRegistry.runAfterTask(taskId, outcome2);
|
|
213
188
|
}
|
|
214
|
-
|
|
215
|
-
|
|
189
|
+
return { status: "success", data: validation.data, raw: fullOutput };
|
|
190
|
+
}
|
|
191
|
+
function buildRetryFollowUp(task, lastOutcome) {
|
|
192
|
+
const sections = [];
|
|
193
|
+
sections.push(
|
|
194
|
+
"Your previous response could not be validated. The task work itself is fine \u2014 please re-output only the structured result block in the correct format."
|
|
195
|
+
);
|
|
196
|
+
if (lastOutcome.status === "validation_error") {
|
|
197
|
+
sections.push(`Validation errors:
|
|
198
|
+
${lastOutcome.errors.message}`);
|
|
199
|
+
} else if (lastOutcome.status === "error") {
|
|
200
|
+
sections.push(`Error: ${lastOutcome.message}`);
|
|
201
|
+
}
|
|
202
|
+
sections.push(
|
|
203
|
+
`Required format: Return your result as a YAML block matching the "${task.result_handoff}" schema. Include all required fields.`
|
|
204
|
+
);
|
|
205
|
+
return sections.join("\n\n");
|
|
206
|
+
}
|
|
207
|
+
function defaultDecideRetryStrategy(outcome, _counts) {
|
|
208
|
+
if (outcome.status === "validation_error") {
|
|
209
|
+
return "follow_up";
|
|
210
|
+
}
|
|
211
|
+
if (outcome.status === "error") {
|
|
212
|
+
if (outcome.message === "Agent returned empty output") return "retry";
|
|
213
|
+
return "abort";
|
|
214
|
+
}
|
|
215
|
+
return "abort";
|
|
216
|
+
}
|
|
217
|
+
async function runTask(adapter, taskId, context, options) {
|
|
218
|
+
const taskReg = options?.taskRegistry ?? {};
|
|
219
|
+
const agentReg = options?.agentRegistry ?? {};
|
|
220
|
+
const schemas = options?.handoffSchemas ?? {};
|
|
221
|
+
const task = taskReg[taskId];
|
|
222
|
+
if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
|
|
223
|
+
const agentContract = agentReg[task.target_agent];
|
|
224
|
+
if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
|
|
225
|
+
const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
|
|
226
|
+
if (modifiedContext === null) {
|
|
227
|
+
return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
|
|
228
|
+
}
|
|
229
|
+
let prompt = buildTaskPrompt(agentContract, task, modifiedContext);
|
|
230
|
+
prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, modifiedContext);
|
|
231
|
+
const isReadonly = agentContract.mode === "read-only";
|
|
232
|
+
const maxFollowUps = options?.maxFollowUps ?? 2;
|
|
233
|
+
const maxRetries = options?.maxRetries ?? 0;
|
|
234
|
+
const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
|
|
235
|
+
let followUpsUsed = 0;
|
|
236
|
+
let retriesUsed = 0;
|
|
237
|
+
let fullOutput;
|
|
238
|
+
try {
|
|
239
|
+
fullOutput = await adapter.send(prompt, { readonly: isReadonly });
|
|
240
|
+
} catch (err) {
|
|
241
|
+
return { outcome: { status: "error", message: `SDK error: ${err.message}` }, follow_ups_used: 0, retries_used: 0 };
|
|
242
|
+
}
|
|
243
|
+
let outcome = validateOutput(fullOutput, task, schemas);
|
|
244
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
245
|
+
while (outcome.status === "validation_error" || outcome.status === "error") {
|
|
246
|
+
const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
|
|
247
|
+
if (decision === "abort") break;
|
|
248
|
+
let effectiveDecision = decision;
|
|
249
|
+
if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
|
|
250
|
+
effectiveDecision = "retry";
|
|
251
|
+
}
|
|
252
|
+
if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
if (effectiveDecision === "follow_up") {
|
|
256
|
+
followUpsUsed++;
|
|
257
|
+
const followUpPrompt = buildRetryFollowUp(task, outcome);
|
|
258
|
+
try {
|
|
259
|
+
if (adapter.followUp) {
|
|
260
|
+
fullOutput = await adapter.followUp(followUpPrompt);
|
|
261
|
+
} else {
|
|
262
|
+
const retryContext = {
|
|
263
|
+
...modifiedContext,
|
|
264
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
265
|
+
|
|
266
|
+
--- FollowUp ${followUpsUsed} ---
|
|
267
|
+
${followUpPrompt}`
|
|
268
|
+
};
|
|
269
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
|
|
270
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
271
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });
|
|
272
|
+
}
|
|
273
|
+
} catch (err) {
|
|
274
|
+
outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
} else {
|
|
278
|
+
retriesUsed++;
|
|
279
|
+
const retryContext = {
|
|
280
|
+
...modifiedContext,
|
|
281
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
282
|
+
|
|
283
|
+
--- Full Retry ${retriesUsed} ---
|
|
284
|
+
Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
|
|
285
|
+
Please re-execute the entire task.`
|
|
286
|
+
};
|
|
287
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
|
|
288
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
289
|
+
try {
|
|
290
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });
|
|
291
|
+
} catch (err) {
|
|
292
|
+
outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
outcome = validateOutput(fullOutput, task, schemas);
|
|
297
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
298
|
+
}
|
|
299
|
+
return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
|
|
216
300
|
}
|
|
217
301
|
|
|
218
302
|
// src/lib/workflow-runner.ts
|
|
@@ -259,6 +343,7 @@ async function runWorkflow(adapter, workflowId, options, registries) {
|
|
|
259
343
|
step_index: i,
|
|
260
344
|
task_id: step.task,
|
|
261
345
|
outcome: { status: "skipped" },
|
|
346
|
+
follow_ups_used: 0,
|
|
262
347
|
retries_used: 0,
|
|
263
348
|
elapsed_ms: Date.now() - stepStart
|
|
264
349
|
};
|
|
@@ -267,15 +352,25 @@ async function runWorkflow(adapter, workflowId, options, registries) {
|
|
|
267
352
|
continue;
|
|
268
353
|
}
|
|
269
354
|
}
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
355
|
+
const context = {
|
|
356
|
+
user_request: options.user_request,
|
|
357
|
+
prior_context: accumulatedContext
|
|
358
|
+
};
|
|
359
|
+
const taskResult = await runTask(adapter, step.task, context, {
|
|
360
|
+
maxFollowUps: step.max_retries ?? 2,
|
|
361
|
+
maxRetries: 1,
|
|
362
|
+
taskRegistry: registries?.taskRegistry,
|
|
363
|
+
agentRegistry: registries?.agentRegistry,
|
|
364
|
+
handoffSchemas: registries?.handoffSchemas
|
|
365
|
+
});
|
|
366
|
+
const result = {
|
|
367
|
+
step_index: i,
|
|
368
|
+
task_id: step.task,
|
|
369
|
+
outcome: taskResult.outcome,
|
|
370
|
+
follow_ups_used: taskResult.follow_ups_used,
|
|
371
|
+
retries_used: taskResult.retries_used,
|
|
372
|
+
elapsed_ms: Date.now() - stepStart
|
|
373
|
+
};
|
|
279
374
|
stepResults.push(result);
|
|
280
375
|
emitStepEvent(options, workflow.id, i, step, result);
|
|
281
376
|
if (result.outcome.status === "success") {
|
|
@@ -298,17 +393,15 @@ async function runWorkflow(adapter, workflowId, options, registries) {
|
|
|
298
393
|
return wfResult2;
|
|
299
394
|
}
|
|
300
395
|
if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
return wfResult2;
|
|
311
|
-
}
|
|
396
|
+
const wfResult2 = {
|
|
397
|
+
workflow_id: workflow.id,
|
|
398
|
+
status: "escalated",
|
|
399
|
+
steps: stepResults,
|
|
400
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
401
|
+
escalation_reason: `Task "${step.task}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
|
|
402
|
+
};
|
|
403
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
|
|
404
|
+
return wfResult2;
|
|
312
405
|
}
|
|
313
406
|
}
|
|
314
407
|
const wfResult = {
|
|
@@ -323,37 +416,24 @@ async function runWorkflow(adapter, workflowId, options, registries) {
|
|
|
323
416
|
async function handleGateStep(step, priorResults, options, stepIndex) {
|
|
324
417
|
const start = Date.now();
|
|
325
418
|
if (!options.onGate) {
|
|
326
|
-
return {
|
|
419
|
+
return {
|
|
420
|
+
step_index: stepIndex,
|
|
421
|
+
gate_kind: step.gate_kind,
|
|
422
|
+
outcome: { status: "gate_approved" },
|
|
423
|
+
follow_ups_used: 0,
|
|
424
|
+
retries_used: 0,
|
|
425
|
+
elapsed_ms: Date.now() - start
|
|
426
|
+
};
|
|
327
427
|
}
|
|
328
428
|
const approved = await options.onGate(step.gate_kind, step.description, priorResults);
|
|
329
|
-
return {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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 };
|
|
429
|
+
return {
|
|
430
|
+
step_index: stepIndex,
|
|
431
|
+
gate_kind: step.gate_kind,
|
|
432
|
+
outcome: { status: approved ? "gate_approved" : "gate_rejected" },
|
|
433
|
+
follow_ups_used: 0,
|
|
434
|
+
retries_used: 0,
|
|
435
|
+
elapsed_ms: Date.now() - start
|
|
436
|
+
};
|
|
357
437
|
}
|
|
358
438
|
function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
359
439
|
options.onStepComplete?.({
|
|
@@ -363,12 +443,14 @@ function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
|
363
443
|
task_id: step.type === "delegate" ? step.task : void 0,
|
|
364
444
|
gate_kind: step.type === "gate" ? step.gate_kind : void 0,
|
|
365
445
|
outcome_status: result.outcome.status,
|
|
446
|
+
follow_ups_used: result.follow_ups_used,
|
|
366
447
|
retries_used: result.retries_used,
|
|
367
448
|
elapsed_ms: result.elapsed_ms
|
|
368
449
|
});
|
|
369
450
|
}
|
|
370
451
|
export {
|
|
371
452
|
PluginRegistry,
|
|
453
|
+
buildRetryFollowUp,
|
|
372
454
|
buildTaskPrompt,
|
|
373
455
|
extractStructuredResult,
|
|
374
456
|
pluginRegistry,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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;AA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B,OAAO,QAAQ;AAAA,IAC/B,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,EACrB,CAAC;AACH;","names":["outcome","result","wfResult"]}
|
|
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 * Two recovery strategies:\n * - followUp: lightweight, same session — fix output format only\n * - retry: heavyweight, new session — re-execute entire task\n */\n\nimport { z } from \"zod\";\nimport * as yaml from \"yaml\";\n\nimport { pluginRegistry } from \"./plugin.js\";\n\n// Duck-typed contracts so the runtime doesn't depend on generated shapes.\n\nexport interface AgentContractLike {\n readonly id: string;\n readonly role_name: string;\n readonly purpose: string;\n readonly mode: \"read-write\" | \"read-only\";\n readonly responsibilities: readonly string[];\n readonly constraints: readonly string[];\n}\n\nexport interface TaskContractLike {\n readonly id: string;\n readonly description: string;\n readonly target_agent: string;\n readonly result_handoff: string;\n readonly completion_criteria: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// SDK adapter interface\n// ---------------------------------------------------------------------------\n\nexport interface SdkAdapter {\n /** Start a new task session and return the full text response. */\n send(prompt: string, options: { readonly: boolean }): 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// ---------------------------------------------------------------------------\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 * 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// 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// Internal: validate LLM output against handoff schema\n// ---------------------------------------------------------------------------\n\nfunction validateOutput(\n fullOutput: string,\n task: TaskContractLike,\n schemas: Record<string, z.ZodTypeAny>,\n): TaskOutcome {\n if (!fullOutput.trim()) {\n return { status: \"error\", message: \"Agent returned empty output\" };\n }\n\n const parsed = extractStructuredResult(fullOutput);\n if (!parsed) {\n return {\n status: \"validation_error\",\n errors: new z.ZodError([{ code: \"custom\", message: \"Could not extract structured result from agent output\", path: [] }]),\n raw: fullOutput,\n };\n }\n\n const schema = schemas[task.result_handoff];\n if (!schema) {\n return { status: \"success\", data: parsed, raw: fullOutput };\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n return { status: \"validation_error\", errors: validation.error, raw: fullOutput };\n }\n\n const data = validation.data as Record<string, unknown>;\n if (data.escalation_needed === true) {\n return {\n status: \"escalation\",\n reason: (data.escalation_reasons as string) ?? \"Agent requested escalation\",\n raw: fullOutput,\n };\n }\n\n return { status: \"success\", data: validation.data, raw: fullOutput };\n}\n\n// ---------------------------------------------------------------------------\n// Follow-up prompt builder (lightweight, output-format correction only)\n// ---------------------------------------------------------------------------\n\nexport function buildRetryFollowUp(\n task: TaskContractLike,\n lastOutcome: TaskOutcome,\n): 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 sections.push(\n `Required format: Return your result as a YAML block matching the \"${task.result_handoff}\" schema. ` +\n `Include all required fields.`,\n );\n\n return sections.join(\"\\n\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Default retry strategy\n// ---------------------------------------------------------------------------\n\nfunction defaultDecideRetryStrategy(\n outcome: TaskOutcome,\n _counts: { followUps: number; retries: number },\n): RetryDecision {\n if (outcome.status === \"validation_error\") {\n return \"follow_up\";\n }\n if (outcome.status === \"error\") {\n if (outcome.message === \"Agent returned empty output\") return \"retry\";\n return \"abort\";\n }\n return \"abort\";\n}\n\n// ---------------------------------------------------------------------------\n// Execute\n// ---------------------------------------------------------------------------\n\nexport async function runTask(\n adapter: SdkAdapter,\n taskId: string,\n context: TaskContext,\n options?: TaskRunOptions & {\n agentRegistry?: Record<string, AgentContractLike>;\n taskRegistry?: Record<string, TaskContractLike>;\n handoffSchemas?: Record<string, z.ZodTypeAny>;\n },\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 let prompt = buildTaskPrompt(agentContract, task, modifiedContext);\n prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, modifiedContext);\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 ---\n let fullOutput: string;\n try {\n fullOutput = await adapter.send(prompt, { readonly: isReadonly });\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);\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);\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 } 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 * Programmatic control flow that replaces LLM-driven step interpretation:\n *\n * 1. Load workflow contract (ordered steps)\n * 2. Run plugin beforeWorkflow hooks\n * 3. For each step:\n * - delegate → call task-runner with followUp/retry recovery\n * - gate → pause and wait for user input\n * 4. Validate each result against handoff schema\n * 5. Accumulate context between steps\n * 6. Run plugin afterWorkflow hooks\n */\n\nimport { pluginRegistry } from \"./plugin.js\";\nimport { runTask, type SdkAdapter, type TaskContext, type TaskOutcome, type TaskRunResult, type AgentContractLike, type TaskContractLike } from \"./task-runner.js\";\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Step types (duck-typed — generated contracts provide concrete values)\n// ---------------------------------------------------------------------------\n\nexport interface DelegateStep {\n readonly type: \"delegate\";\n readonly task: string;\n readonly from_agent: string;\n readonly description: string;\n readonly optional: boolean;\n readonly max_retries: number;\n}\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 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\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 follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n continue;\n }\n }\n\n // Execute task with followUp/retry recovery\n const context: TaskContext = {\n user_request: options.user_request,\n prior_context: accumulatedContext,\n };\n const taskResult: TaskRunResult = await runTask(adapter, step.task, context, {\n maxFollowUps: step.max_retries ?? 2,\n maxRetries: 1,\n taskRegistry: registries?.taskRegistry,\n agentRegistry: registries?.agentRegistry,\n handoffSchemas: registries?.handoffSchemas,\n });\n const result: StepResult = {\n step_index: i,\n task_id: step.task,\n outcome: taskResult.outcome,\n follow_ups_used: taskResult.follow_ups_used,\n retries_used: taskResult.retries_used,\n elapsed_ms: Date.now() - stepStart,\n };\n stepResults.push(result);\n emitStepEvent(options, workflow.id, i, step, result);\n\n // Accumulate context from successful steps\n if (result.outcome.status === \"success\") {\n const data = (result.outcome as { data: unknown }).data;\n accumulatedContext += `\\n\\n--- Step ${i + 1}: ${step.task} ---\\n`;\n accumulatedContext += typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n }\n\n // Escalation — stop workflow\n if (result.outcome.status === \"escalation\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: (result.outcome as { reason: string }).reason,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n\n // Unrecoverable failure after all recovery attempts\n if (result.outcome.status === \"error\" || result.outcome.status === \"validation_error\") {\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"escalated\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n escalation_reason: `Task \"${step.task}\" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n }\n }\n\n const wfResult: WorkflowResult = {\n workflow_id: workflow.id,\n status: \"completed\",\n steps: stepResults,\n total_elapsed_ms: Date.now() - workflowStart,\n };\n await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);\n return wfResult;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function handleGateStep(\n step: GateStep,\n priorResults: StepResult[],\n options: WorkflowRunOptions,\n stepIndex: number,\n): Promise<StepResult> {\n const start = Date.now();\n\n if (!options.onGate) {\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: \"gate_approved\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n }\n\n const approved = await options.onGate(step.gate_kind, step.description, priorResults);\n return {\n step_index: stepIndex,\n gate_kind: step.gate_kind,\n outcome: { status: approved ? \"gate_approved\" : \"gate_rejected\" },\n follow_ups_used: 0,\n retries_used: 0,\n elapsed_ms: Date.now() - start,\n };\n}\n\nfunction emitStepEvent(\n options: WorkflowRunOptions,\n workflowId: string,\n stepIndex: number,\n step: DelegateStep | GateStep,\n result: StepResult,\n): void {\n options.onStepComplete?.({\n workflow_id: workflowId,\n step_index: stepIndex,\n step_type: step.type,\n task_id: step.type === \"delegate\" ? (step as DelegateStep).task : undefined,\n gate_kind: step.type === \"gate\" ? (step as GateStep).gate_kind : undefined,\n outcome_status: result.outcome.status,\n follow_ups_used: result.follow_ups_used,\n retries_used: result.retries_used,\n elapsed_ms: result.elapsed_ms,\n });\n}\n"],"mappings":";AAiBA,SAAS,SAAS;AAClB,YAAY,UAAU;;;ACWf,IAAM,iBAAN,MAAqB;AAAA,EAClB,UAAyB,CAAC;AAAA,EAElC,SAAS,QAA2B;AAClC,QAAI,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,EAAE,GAAG;AAChD,YAAM,IAAI,MAAM,WAAW,OAAO,EAAE,yBAAyB;AAAA,IAC/D;AACA,SAAK,QAAQ,KAAK,MAAM;AAAA,EAC1B;AAAA,EAEA,SAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,cAAc,QAAgB,SAAmD;AACrF,QAAI,MAA0B;AAC9B,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,cAAc,QAAQ,KAAM;AACxC,YAAM,MAAM,OAAO,WAAW,QAAQ,GAAG;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,aAAa,QAAgB,SAA4C;AAC7E,QAAI,SAAS;AACb,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,UAAW;AACvB,eAAS,MAAM,OAAO,UAAU,QAAQ,MAAM;AAAA,IAChD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,qBAAqB,QAAgB,QAAgB,SAA8B;AACjF,QAAI,WAAW;AACf,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,eAAgB;AAC5B,iBAAW,OAAO,eAAe,QAAQ,UAAU,OAAO;AAAA,IAC5D;AACA,WAAO;AAAA,EACT;AAAA,EAEA,0BAA0B,SAAoC;AAC5D,UAAM,UAA6B,CAAC;AACpC,eAAW,UAAU,KAAK,SAAS;AACjC,UAAI,CAAC,OAAO,kBAAkB,gBAAiB;AAC/C,cAAQ,KAAK,GAAG,OAAO,iBAAiB,gBAAg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O;AAAA,IACP,kBAAkB,KAAK,IAAI,IAAI;AAAA,EACjC;AACA,QAAM,eAAe,iBAAiB,SAAS,IAAI,QAAQ;AAC3D,SAAO;AACT;AAMA,eAAe,eACb,MACA,cACA,SACA,WACqB;AACrB,QAAM,QAAQ,KAAK,IAAI;AAEvB,MAAI,CAAC,QAAQ,QAAQ;AACnB,WAAO;AAAA,MACL,YAAY;AAAA,MACZ,WAAW,KAAK;AAAA,MAChB,SAAS,EAAE,QAAQ,gBAAgB;AAAA,MACnC,iBAAiB;AAAA,MACjB,cAAc;AAAA,MACd,YAAY,KAAK,IAAI,IAAI;AAAA,IAC3B;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,QAAQ,OAAO,KAAK,WAAW,KAAK,aAAa,YAAY;AACpF,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,WAAW,KAAK;AAAA,IAChB,SAAS,EAAE,QAAQ,WAAW,kBAAkB,gBAAgB;AAAA,IAChE,iBAAiB;AAAA,IACjB,cAAc;AAAA,IACd,YAAY,KAAK,IAAI,IAAI;AAAA,EAC3B;AACF;AAEA,SAAS,cACP,SACA,YACA,WACA,MACA,QACM;AACN,UAAQ,iBAAiB;AAAA,IACvB,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,WAAW,KAAK;AAAA,IAChB,SAAS,KAAK,SAAS,aAAc,KAAsB,OAAO;AAAA,IAClE,WAAW,KAAK,SAAS,SAAU,KAAkB,YAAY;AAAA,IACjE,gBAAgB,OAAO,QAAQ;AAAA,IAC/B,iBAAiB,OAAO;AAAA,IACxB,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,EACrB,CAAC;AACH;","names":["result","wfResult"]}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Task Runner — runs a single DSL task via an SDK agent
|
|
5
|
+
*
|
|
6
|
+
* Responsibilities:
|
|
7
|
+
* 1. Resolve task contract → target agent contract
|
|
8
|
+
* 2. Build the agent prompt from contract + context
|
|
9
|
+
* 3. Apply plugin prompt enhancers and beforeTask hooks
|
|
10
|
+
* 4. Send to SDK agent (via abstract SdkAdapter) and stream result
|
|
11
|
+
* 5. Parse + validate result against handoff schema
|
|
12
|
+
* 6. Apply plugin afterTask hooks
|
|
13
|
+
* 7. Return typed result or escalation signal
|
|
14
|
+
*
|
|
15
|
+
* Two recovery strategies:
|
|
16
|
+
* - followUp: lightweight, same session — fix output format only
|
|
17
|
+
* - retry: heavyweight, new session — re-execute entire task
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
interface AgentContractLike {
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly role_name: string;
|
|
23
|
+
readonly purpose: string;
|
|
24
|
+
readonly mode: "read-write" | "read-only";
|
|
25
|
+
readonly responsibilities: readonly string[];
|
|
26
|
+
readonly constraints: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
interface TaskContractLike {
|
|
29
|
+
readonly id: string;
|
|
30
|
+
readonly description: string;
|
|
31
|
+
readonly target_agent: string;
|
|
32
|
+
readonly result_handoff: string;
|
|
33
|
+
readonly completion_criteria: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
interface SdkAdapter {
|
|
36
|
+
/** Start a new task session and return the full text response. */
|
|
37
|
+
send(prompt: string, options: {
|
|
38
|
+
readonly: boolean;
|
|
39
|
+
}): Promise<string>;
|
|
40
|
+
/**
|
|
41
|
+
* Send a follow-up message within the same agent session.
|
|
42
|
+
* Used for output-format corrections without re-executing the task.
|
|
43
|
+
* Falls back to send() if not implemented (stateless adapters like mock).
|
|
44
|
+
*/
|
|
45
|
+
followUp?(message: string): Promise<string>;
|
|
46
|
+
}
|
|
47
|
+
interface TaskContext {
|
|
48
|
+
user_request: string;
|
|
49
|
+
prior_context?: string;
|
|
50
|
+
relevant_paths?: string[];
|
|
51
|
+
acceptance_criteria?: string[];
|
|
52
|
+
}
|
|
53
|
+
type TaskOutcome = {
|
|
54
|
+
status: "success";
|
|
55
|
+
data: unknown;
|
|
56
|
+
raw: string;
|
|
57
|
+
} | {
|
|
58
|
+
status: "validation_error";
|
|
59
|
+
errors: z.ZodError;
|
|
60
|
+
raw: string;
|
|
61
|
+
} | {
|
|
62
|
+
status: "escalation";
|
|
63
|
+
reason: string;
|
|
64
|
+
raw: string;
|
|
65
|
+
} | {
|
|
66
|
+
status: "error";
|
|
67
|
+
message: string;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Retry strategy decision.
|
|
71
|
+
*
|
|
72
|
+
* - "follow_up": lightweight — same session, fix output format only
|
|
73
|
+
* - "retry": heavyweight — new send(), re-execute the entire task
|
|
74
|
+
* - "abort": stop retrying, return the current outcome
|
|
75
|
+
*/
|
|
76
|
+
type RetryDecision = "follow_up" | "retry" | "abort";
|
|
77
|
+
interface TaskRunOptions {
|
|
78
|
+
/** Max follow-up attempts (output format correction, same session). Default: 2 */
|
|
79
|
+
maxFollowUps?: number;
|
|
80
|
+
/** Max full retry attempts (re-execute entire task via send). Default: 0 */
|
|
81
|
+
maxRetries?: number;
|
|
82
|
+
/**
|
|
83
|
+
* Called on each failure to decide which recovery strategy to use.
|
|
84
|
+
* Default: validation_error → follow_up, empty output → retry, else abort.
|
|
85
|
+
*/
|
|
86
|
+
decideRetryStrategy?: (outcome: TaskOutcome, counts: {
|
|
87
|
+
followUps: number;
|
|
88
|
+
retries: number;
|
|
89
|
+
}) => Promise<RetryDecision> | RetryDecision;
|
|
90
|
+
}
|
|
91
|
+
interface TaskRunResult {
|
|
92
|
+
outcome: TaskOutcome;
|
|
93
|
+
follow_ups_used: number;
|
|
94
|
+
retries_used: number;
|
|
95
|
+
}
|
|
96
|
+
declare function buildTaskPrompt(agent: AgentContractLike, task: TaskContractLike, context: TaskContext): string;
|
|
97
|
+
declare function extractStructuredResult(raw: string): unknown | null;
|
|
98
|
+
declare function buildRetryFollowUp(task: TaskContractLike, lastOutcome: TaskOutcome): string;
|
|
99
|
+
declare function runTask(adapter: SdkAdapter, taskId: string, context: TaskContext, options?: TaskRunOptions & {
|
|
100
|
+
agentRegistry?: Record<string, AgentContractLike>;
|
|
101
|
+
taskRegistry?: Record<string, TaskContractLike>;
|
|
102
|
+
handoffSchemas?: Record<string, z.ZodTypeAny>;
|
|
103
|
+
}): Promise<TaskRunResult>;
|
|
104
|
+
|
|
105
|
+
export { type AgentContractLike as A, type RetryDecision as R, type SdkAdapter as S, type TaskOutcome as T, type TaskContext as a, type TaskContractLike as b, type TaskRunOptions as c, type TaskRunResult as d, buildRetryFollowUp as e, buildTaskPrompt as f, extractStructuredResult as g, runTask as r };
|
package/package.json
CHANGED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Task Runner — runs a single DSL task via an SDK agent
|
|
5
|
-
*
|
|
6
|
-
* Responsibilities:
|
|
7
|
-
* 1. Resolve task contract → target agent contract
|
|
8
|
-
* 2. Build the agent prompt from contract + context
|
|
9
|
-
* 3. Apply plugin prompt enhancers and beforeTask hooks
|
|
10
|
-
* 4. Send to SDK agent (via abstract SdkAdapter) and stream result
|
|
11
|
-
* 5. Parse + validate result against handoff schema
|
|
12
|
-
* 6. Apply plugin afterTask hooks
|
|
13
|
-
* 7. Return typed result or escalation signal
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
interface AgentContractLike {
|
|
17
|
-
readonly id: string;
|
|
18
|
-
readonly role_name: string;
|
|
19
|
-
readonly purpose: string;
|
|
20
|
-
readonly mode: "read-write" | "read-only";
|
|
21
|
-
readonly responsibilities: readonly string[];
|
|
22
|
-
readonly constraints: readonly string[];
|
|
23
|
-
}
|
|
24
|
-
interface TaskContractLike {
|
|
25
|
-
readonly id: string;
|
|
26
|
-
readonly description: string;
|
|
27
|
-
readonly target_agent: string;
|
|
28
|
-
readonly result_handoff: string;
|
|
29
|
-
readonly completion_criteria: readonly string[];
|
|
30
|
-
}
|
|
31
|
-
interface SdkAdapter {
|
|
32
|
-
send(prompt: string, options: {
|
|
33
|
-
readonly: boolean;
|
|
34
|
-
}): Promise<string>;
|
|
35
|
-
}
|
|
36
|
-
interface TaskContext {
|
|
37
|
-
user_request: string;
|
|
38
|
-
prior_context?: string;
|
|
39
|
-
relevant_paths?: string[];
|
|
40
|
-
acceptance_criteria?: string[];
|
|
41
|
-
}
|
|
42
|
-
type TaskOutcome = {
|
|
43
|
-
status: "success";
|
|
44
|
-
data: unknown;
|
|
45
|
-
raw: string;
|
|
46
|
-
} | {
|
|
47
|
-
status: "validation_error";
|
|
48
|
-
errors: z.ZodError;
|
|
49
|
-
raw: string;
|
|
50
|
-
} | {
|
|
51
|
-
status: "escalation";
|
|
52
|
-
reason: string;
|
|
53
|
-
raw: string;
|
|
54
|
-
} | {
|
|
55
|
-
status: "error";
|
|
56
|
-
message: string;
|
|
57
|
-
};
|
|
58
|
-
declare function buildTaskPrompt(agent: AgentContractLike, task: TaskContractLike, context: TaskContext): string;
|
|
59
|
-
declare function extractStructuredResult(raw: string): unknown | null;
|
|
60
|
-
declare function runTask(adapter: SdkAdapter, taskId: string, context: TaskContext, options?: {
|
|
61
|
-
agentRegistry?: Record<string, AgentContractLike>;
|
|
62
|
-
taskRegistry?: Record<string, TaskContractLike>;
|
|
63
|
-
handoffSchemas?: Record<string, z.ZodTypeAny>;
|
|
64
|
-
}): Promise<TaskOutcome>;
|
|
65
|
-
|
|
66
|
-
export { type AgentContractLike as A, type SdkAdapter as S, type TaskOutcome as T, type TaskContext as a, type TaskContractLike as b, buildTaskPrompt as c, extractStructuredResult as e, runTask as r };
|