agent-contracts-runtime 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +181 -48
- package/cli-contract.yaml +88 -0
- package/dist/adapters/claude-agent-sdk.d.ts +1 -1
- package/dist/adapters/cursor-sdk.d.ts +1 -1
- package/dist/adapters/mock.d.ts +1 -1
- package/dist/chunk-24SRKCWQ.js +595 -0
- package/dist/chunk-24SRKCWQ.js.map +1 -0
- package/dist/chunk-DNTCPVJN.js +433 -0
- package/dist/chunk-DNTCPVJN.js.map +1 -0
- package/dist/cli/index.js +99 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/generator/index.d.ts +153 -0
- package/dist/generator/index.js +15 -0
- package/dist/generator/index.js.map +1 -0
- package/dist/index.d.ts +29 -3
- package/dist/index.js +14 -451
- package/dist/index.js.map +1 -1
- package/dist/{task-runner-CuYWldNc.d.ts → task-runner-MQO5VR1Y.d.ts} +14 -3
- package/package.json +6 -1
- package/templates/agents.ts.hbs +54 -0
- package/templates/contracts-index.ts.hbs +4 -0
- package/templates/guardrails.ts.hbs +132 -0
- package/templates/handoffs.ts.hbs +19 -0
- package/templates/hooks-index.ts.hbs +31 -0
- package/templates/tasks.ts.hbs +38 -0
- package/templates/workflows.ts.hbs +60 -0
|
@@ -0,0 +1,595 @@
|
|
|
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
|
+
/**
|
|
34
|
+
* Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,
|
|
35
|
+
* or null to use the default buildTaskPrompt.
|
|
36
|
+
*/
|
|
37
|
+
applyPromptBuilder(args) {
|
|
38
|
+
for (const plugin of this.plugins) {
|
|
39
|
+
if (!plugin.promptBuilder) continue;
|
|
40
|
+
const result = plugin.promptBuilder(args);
|
|
41
|
+
if (result !== null) return result;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
applyPromptEnhancers(taskId, prompt, context) {
|
|
46
|
+
let enhanced = prompt;
|
|
47
|
+
for (const plugin of this.plugins) {
|
|
48
|
+
if (!plugin.promptEnhancer) continue;
|
|
49
|
+
enhanced = plugin.promptEnhancer(taskId, enhanced, context);
|
|
50
|
+
}
|
|
51
|
+
return enhanced;
|
|
52
|
+
}
|
|
53
|
+
evaluateCommandGuardrails(command) {
|
|
54
|
+
const results = [];
|
|
55
|
+
for (const plugin of this.plugins) {
|
|
56
|
+
if (!plugin.customGuardrails?.evaluateCommand) continue;
|
|
57
|
+
results.push(...plugin.customGuardrails.evaluateCommand(command));
|
|
58
|
+
}
|
|
59
|
+
return results;
|
|
60
|
+
}
|
|
61
|
+
evaluateFilePathGuardrails(filePath) {
|
|
62
|
+
const results = [];
|
|
63
|
+
for (const plugin of this.plugins) {
|
|
64
|
+
if (!plugin.customGuardrails?.evaluateFilePath) continue;
|
|
65
|
+
results.push(...plugin.customGuardrails.evaluateFilePath(filePath));
|
|
66
|
+
}
|
|
67
|
+
return results;
|
|
68
|
+
}
|
|
69
|
+
evaluateFileContentGuardrails(filePath, content) {
|
|
70
|
+
const results = [];
|
|
71
|
+
for (const plugin of this.plugins) {
|
|
72
|
+
if (!plugin.customGuardrails?.evaluateFileContent) continue;
|
|
73
|
+
results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));
|
|
74
|
+
}
|
|
75
|
+
return results;
|
|
76
|
+
}
|
|
77
|
+
async runBeforeWorkflow(workflowId, userRequest) {
|
|
78
|
+
for (const plugin of this.plugins) {
|
|
79
|
+
if (!plugin.beforeWorkflow) continue;
|
|
80
|
+
await plugin.beforeWorkflow(workflowId, userRequest);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async runAfterWorkflow(workflowId, result) {
|
|
84
|
+
for (const plugin of this.plugins) {
|
|
85
|
+
if (!plugin.afterWorkflow) continue;
|
|
86
|
+
await plugin.afterWorkflow(workflowId, result);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
var pluginRegistry = new PluginRegistry();
|
|
91
|
+
|
|
92
|
+
// src/lib/task-runner.ts
|
|
93
|
+
function zodTypeToString(schema) {
|
|
94
|
+
if (schema instanceof z.ZodString) return "string";
|
|
95
|
+
if (schema instanceof z.ZodNumber) return "number";
|
|
96
|
+
if (schema instanceof z.ZodBoolean) return "boolean";
|
|
97
|
+
if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
|
|
98
|
+
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.value)}"`;
|
|
99
|
+
if (schema instanceof z.ZodArray) {
|
|
100
|
+
const inner = zodTypeToString(schema._def.type);
|
|
101
|
+
return `${inner}[]`;
|
|
102
|
+
}
|
|
103
|
+
if (schema instanceof z.ZodObject) return "object";
|
|
104
|
+
if (schema instanceof z.ZodOptional) {
|
|
105
|
+
return zodTypeToString(schema._def.innerType);
|
|
106
|
+
}
|
|
107
|
+
if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
|
|
108
|
+
return "unknown";
|
|
109
|
+
}
|
|
110
|
+
function extractFieldDescriptors(schema) {
|
|
111
|
+
let shape = null;
|
|
112
|
+
if (schema instanceof z.ZodObject) {
|
|
113
|
+
shape = schema.shape;
|
|
114
|
+
}
|
|
115
|
+
if (!shape) return null;
|
|
116
|
+
return Object.entries(shape).map(([name, field]) => {
|
|
117
|
+
const isOptional = field instanceof z.ZodOptional;
|
|
118
|
+
const innerField = isOptional ? field._def.innerType : field;
|
|
119
|
+
const description = innerField._def.description ?? field._def.description;
|
|
120
|
+
return {
|
|
121
|
+
name,
|
|
122
|
+
type: zodTypeToString(field),
|
|
123
|
+
required: !isOptional,
|
|
124
|
+
description
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
function zodSchemaToPromptDescription(schema) {
|
|
129
|
+
const fields = extractFieldDescriptors(schema);
|
|
130
|
+
if (!fields || fields.length === 0) return "";
|
|
131
|
+
const header = "| Field | Type | Required | Description |";
|
|
132
|
+
const sep = "|-------|------|----------|-------------|";
|
|
133
|
+
const rows = fields.map(
|
|
134
|
+
(f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.description ?? ""} |`
|
|
135
|
+
);
|
|
136
|
+
return [header, sep, ...rows].join("\n");
|
|
137
|
+
}
|
|
138
|
+
function zodSchemaToYamlExample(schema) {
|
|
139
|
+
const fields = extractFieldDescriptors(schema);
|
|
140
|
+
if (!fields || fields.length === 0) return "";
|
|
141
|
+
const lines = [];
|
|
142
|
+
for (const f of fields) {
|
|
143
|
+
if (f.type.endsWith("[]")) {
|
|
144
|
+
const innerType = f.type.slice(0, -2);
|
|
145
|
+
if (innerType === "string") {
|
|
146
|
+
lines.push(`${f.name}:`);
|
|
147
|
+
lines.push(` - "example"`);
|
|
148
|
+
} else if (innerType === "object") {
|
|
149
|
+
lines.push(`${f.name}:`);
|
|
150
|
+
lines.push(` - key: "value"`);
|
|
151
|
+
} else {
|
|
152
|
+
lines.push(`${f.name}:`);
|
|
153
|
+
lines.push(` - "example"`);
|
|
154
|
+
}
|
|
155
|
+
} else if (f.type === "string") {
|
|
156
|
+
lines.push(`${f.name}: "..."`);
|
|
157
|
+
} else if (f.type === "number") {
|
|
158
|
+
lines.push(`${f.name}: 0`);
|
|
159
|
+
} else if (f.type === "boolean") {
|
|
160
|
+
lines.push(`${f.name}: false`);
|
|
161
|
+
} else if (f.type === "object") {
|
|
162
|
+
lines.push(`${f.name}:`);
|
|
163
|
+
lines.push(` key: "value"`);
|
|
164
|
+
} else {
|
|
165
|
+
lines.push(`${f.name}: "..."`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return lines.join("\n");
|
|
169
|
+
}
|
|
170
|
+
function buildTaskPrompt(agent, task, context, options) {
|
|
171
|
+
const sections = [];
|
|
172
|
+
sections.push(`# Role: ${agent.role_name}
|
|
173
|
+
|
|
174
|
+
${agent.purpose}`);
|
|
175
|
+
if (agent.responsibilities.length > 0) {
|
|
176
|
+
sections.push(
|
|
177
|
+
`## Responsibilities
|
|
178
|
+
|
|
179
|
+
${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (agent.constraints.length > 0) {
|
|
183
|
+
sections.push(
|
|
184
|
+
`## Constraints
|
|
185
|
+
|
|
186
|
+
${agent.constraints.map((c) => `- ${c}`).join("\n")}`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
sections.push(`## Task: ${task.id}
|
|
190
|
+
|
|
191
|
+
${task.description}`);
|
|
192
|
+
if (task.completion_criteria.length > 0) {
|
|
193
|
+
sections.push(
|
|
194
|
+
`## Completion Criteria
|
|
195
|
+
|
|
196
|
+
${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
sections.push(`## User Request
|
|
200
|
+
|
|
201
|
+
${context.user_request}`);
|
|
202
|
+
if (context.prior_context) {
|
|
203
|
+
sections.push(`## Prior Context
|
|
204
|
+
|
|
205
|
+
${context.prior_context}`);
|
|
206
|
+
}
|
|
207
|
+
if (context.relevant_paths && context.relevant_paths.length > 0) {
|
|
208
|
+
sections.push(
|
|
209
|
+
`## Relevant Files
|
|
210
|
+
|
|
211
|
+
${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
|
|
215
|
+
sections.push(
|
|
216
|
+
`## Acceptance Criteria
|
|
217
|
+
|
|
218
|
+
${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
const handoffId = task.result_handoff;
|
|
222
|
+
const schema = options?.handoffSchemas?.[handoffId];
|
|
223
|
+
let outputSection = `## Required Output Format
|
|
224
|
+
|
|
225
|
+
Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
226
|
+
if (schema) {
|
|
227
|
+
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
228
|
+
if (fieldTable) {
|
|
229
|
+
outputSection += `
|
|
230
|
+
|
|
231
|
+
${fieldTable}`;
|
|
232
|
+
}
|
|
233
|
+
const yamlExample = zodSchemaToYamlExample(schema);
|
|
234
|
+
if (yamlExample) {
|
|
235
|
+
outputSection += `
|
|
236
|
+
|
|
237
|
+
Example:
|
|
238
|
+
|
|
239
|
+
\`\`\`yaml
|
|
240
|
+
${yamlExample}
|
|
241
|
+
\`\`\``;
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
outputSection += ` Include all required fields.`;
|
|
245
|
+
}
|
|
246
|
+
sections.push(outputSection);
|
|
247
|
+
return sections.join("\n\n---\n\n");
|
|
248
|
+
}
|
|
249
|
+
function extractStructuredResult(raw) {
|
|
250
|
+
const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
|
|
251
|
+
if (yamlMatch) {
|
|
252
|
+
try {
|
|
253
|
+
return yaml.parse(yamlMatch[1]);
|
|
254
|
+
} catch {
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
|
|
258
|
+
if (jsonMatch) {
|
|
259
|
+
try {
|
|
260
|
+
return JSON.parse(jsonMatch[1]);
|
|
261
|
+
} catch {
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
return JSON.parse(raw);
|
|
266
|
+
} catch {
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
function validateOutput(fullOutput, task, schemas) {
|
|
271
|
+
if (!fullOutput.trim()) {
|
|
272
|
+
return { status: "error", message: "Agent returned empty output" };
|
|
273
|
+
}
|
|
274
|
+
const parsed = extractStructuredResult(fullOutput);
|
|
275
|
+
if (!parsed) {
|
|
276
|
+
return {
|
|
277
|
+
status: "validation_error",
|
|
278
|
+
errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
|
|
279
|
+
raw: fullOutput
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const schema = schemas[task.result_handoff];
|
|
283
|
+
if (!schema) {
|
|
284
|
+
return { status: "success", data: parsed, raw: fullOutput };
|
|
285
|
+
}
|
|
286
|
+
const validation = schema.safeParse(parsed);
|
|
287
|
+
if (!validation.success) {
|
|
288
|
+
return { status: "validation_error", errors: validation.error, raw: fullOutput };
|
|
289
|
+
}
|
|
290
|
+
const data = validation.data;
|
|
291
|
+
if (data.escalation_needed === true) {
|
|
292
|
+
return {
|
|
293
|
+
status: "escalation",
|
|
294
|
+
reason: data.escalation_reasons ?? "Agent requested escalation",
|
|
295
|
+
raw: fullOutput
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
return { status: "success", data: validation.data, raw: fullOutput };
|
|
299
|
+
}
|
|
300
|
+
function buildRetryFollowUp(task, lastOutcome, options) {
|
|
301
|
+
const sections = [];
|
|
302
|
+
sections.push(
|
|
303
|
+
"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."
|
|
304
|
+
);
|
|
305
|
+
if (lastOutcome.status === "validation_error") {
|
|
306
|
+
sections.push(`Validation errors:
|
|
307
|
+
${lastOutcome.errors.message}`);
|
|
308
|
+
} else if (lastOutcome.status === "error") {
|
|
309
|
+
sections.push(`Error: ${lastOutcome.message}`);
|
|
310
|
+
}
|
|
311
|
+
const handoffId = task.result_handoff;
|
|
312
|
+
const schema = options?.handoffSchemas?.[handoffId];
|
|
313
|
+
let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
314
|
+
if (schema) {
|
|
315
|
+
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
316
|
+
if (fieldTable) {
|
|
317
|
+
formatSection += `
|
|
318
|
+
|
|
319
|
+
${fieldTable}`;
|
|
320
|
+
}
|
|
321
|
+
const yamlExample = zodSchemaToYamlExample(schema);
|
|
322
|
+
if (yamlExample) {
|
|
323
|
+
formatSection += `
|
|
324
|
+
|
|
325
|
+
Example:
|
|
326
|
+
|
|
327
|
+
\`\`\`yaml
|
|
328
|
+
${yamlExample}
|
|
329
|
+
\`\`\``;
|
|
330
|
+
}
|
|
331
|
+
} else {
|
|
332
|
+
formatSection += ` Include all required fields.`;
|
|
333
|
+
}
|
|
334
|
+
sections.push(formatSection);
|
|
335
|
+
return sections.join("\n\n");
|
|
336
|
+
}
|
|
337
|
+
function defaultDecideRetryStrategy(outcome, _counts) {
|
|
338
|
+
if (outcome.status === "validation_error") {
|
|
339
|
+
return "follow_up";
|
|
340
|
+
}
|
|
341
|
+
if (outcome.status === "error") {
|
|
342
|
+
if (outcome.message === "Agent returned empty output") return "retry";
|
|
343
|
+
return "abort";
|
|
344
|
+
}
|
|
345
|
+
return "abort";
|
|
346
|
+
}
|
|
347
|
+
async function runTask(adapter, taskId, context, options) {
|
|
348
|
+
const taskReg = options?.taskRegistry ?? {};
|
|
349
|
+
const agentReg = options?.agentRegistry ?? {};
|
|
350
|
+
const schemas = options?.handoffSchemas ?? {};
|
|
351
|
+
const task = taskReg[taskId];
|
|
352
|
+
if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
|
|
353
|
+
const agentContract = agentReg[task.target_agent];
|
|
354
|
+
if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
|
|
355
|
+
const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
|
|
356
|
+
if (modifiedContext === null) {
|
|
357
|
+
return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
|
|
358
|
+
}
|
|
359
|
+
const promptOpts = { handoffSchemas: schemas };
|
|
360
|
+
const builderArgs = { agent: agentContract, task, context: modifiedContext, options: promptOpts };
|
|
361
|
+
let prompt = pluginRegistry.applyPromptBuilder(builderArgs) ?? buildTaskPrompt(agentContract, task, modifiedContext, promptOpts);
|
|
362
|
+
prompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, modifiedContext);
|
|
363
|
+
const isReadonly = agentContract.mode === "read-only";
|
|
364
|
+
const maxFollowUps = options?.maxFollowUps ?? 2;
|
|
365
|
+
const maxRetries = options?.maxRetries ?? 0;
|
|
366
|
+
const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
|
|
367
|
+
let followUpsUsed = 0;
|
|
368
|
+
let retriesUsed = 0;
|
|
369
|
+
let fullOutput;
|
|
370
|
+
try {
|
|
371
|
+
fullOutput = await adapter.send(prompt, { readonly: isReadonly });
|
|
372
|
+
} catch (err) {
|
|
373
|
+
return { outcome: { status: "error", message: `SDK error: ${err.message}` }, follow_ups_used: 0, retries_used: 0 };
|
|
374
|
+
}
|
|
375
|
+
let outcome = validateOutput(fullOutput, task, schemas);
|
|
376
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
377
|
+
while (outcome.status === "validation_error" || outcome.status === "error") {
|
|
378
|
+
const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
|
|
379
|
+
if (decision === "abort") break;
|
|
380
|
+
let effectiveDecision = decision;
|
|
381
|
+
if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
|
|
382
|
+
effectiveDecision = "retry";
|
|
383
|
+
}
|
|
384
|
+
if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
if (effectiveDecision === "follow_up") {
|
|
388
|
+
followUpsUsed++;
|
|
389
|
+
const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
|
|
390
|
+
try {
|
|
391
|
+
if (adapter.followUp) {
|
|
392
|
+
fullOutput = await adapter.followUp(followUpPrompt);
|
|
393
|
+
} else {
|
|
394
|
+
const retryContext = {
|
|
395
|
+
...modifiedContext,
|
|
396
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
397
|
+
|
|
398
|
+
--- FollowUp ${followUpsUsed} ---
|
|
399
|
+
${followUpPrompt}`
|
|
400
|
+
};
|
|
401
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
|
|
402
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
403
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });
|
|
404
|
+
}
|
|
405
|
+
} catch (err) {
|
|
406
|
+
outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
} else {
|
|
410
|
+
retriesUsed++;
|
|
411
|
+
const retryContext = {
|
|
412
|
+
...modifiedContext,
|
|
413
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
414
|
+
|
|
415
|
+
--- Full Retry ${retriesUsed} ---
|
|
416
|
+
Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
|
|
417
|
+
Please re-execute the entire task.`
|
|
418
|
+
};
|
|
419
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
|
|
420
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
421
|
+
try {
|
|
422
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly });
|
|
423
|
+
} catch (err) {
|
|
424
|
+
outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
outcome = validateOutput(fullOutput, task, schemas);
|
|
429
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
430
|
+
}
|
|
431
|
+
return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// src/lib/workflow-runner.ts
|
|
435
|
+
async function runWorkflow(adapter, workflowId, options, registries) {
|
|
436
|
+
const wfReg = registries?.workflowRegistry ?? {};
|
|
437
|
+
const workflow = wfReg[workflowId];
|
|
438
|
+
if (!workflow) {
|
|
439
|
+
return {
|
|
440
|
+
workflow_id: workflowId,
|
|
441
|
+
status: "error",
|
|
442
|
+
steps: [],
|
|
443
|
+
total_elapsed_ms: 0,
|
|
444
|
+
error_message: `Unknown workflow: ${workflowId}`
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);
|
|
448
|
+
const stepResults = [];
|
|
449
|
+
const workflowStart = Date.now();
|
|
450
|
+
let accumulatedContext = "";
|
|
451
|
+
for (let i = 0; i < workflow.steps.length; i++) {
|
|
452
|
+
const step = workflow.steps[i];
|
|
453
|
+
const stepStart = Date.now();
|
|
454
|
+
if (step.type === "gate") {
|
|
455
|
+
const result2 = await handleGateStep(step, stepResults, options, i);
|
|
456
|
+
stepResults.push(result2);
|
|
457
|
+
emitStepEvent(options, workflow.id, i, step, result2);
|
|
458
|
+
if (result2.outcome.status === "gate_rejected") {
|
|
459
|
+
const wfResult2 = {
|
|
460
|
+
workflow_id: workflow.id,
|
|
461
|
+
status: "gate_rejected",
|
|
462
|
+
steps: stepResults,
|
|
463
|
+
total_elapsed_ms: Date.now() - workflowStart
|
|
464
|
+
};
|
|
465
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
|
|
466
|
+
return wfResult2;
|
|
467
|
+
}
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (step.optional) {
|
|
471
|
+
const ctx = { user_request: options.user_request, prior_context: accumulatedContext };
|
|
472
|
+
const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
|
|
473
|
+
if (!shouldRun) {
|
|
474
|
+
const result2 = {
|
|
475
|
+
step_index: i,
|
|
476
|
+
task_id: step.task,
|
|
477
|
+
outcome: { status: "skipped" },
|
|
478
|
+
follow_ups_used: 0,
|
|
479
|
+
retries_used: 0,
|
|
480
|
+
elapsed_ms: Date.now() - stepStart
|
|
481
|
+
};
|
|
482
|
+
stepResults.push(result2);
|
|
483
|
+
emitStepEvent(options, workflow.id, i, step, result2);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const context = {
|
|
488
|
+
user_request: options.user_request,
|
|
489
|
+
prior_context: accumulatedContext
|
|
490
|
+
};
|
|
491
|
+
const taskResult = await runTask(adapter, step.task, context, {
|
|
492
|
+
maxFollowUps: options.maxFollowUps ?? 2,
|
|
493
|
+
maxRetries: options.maxRetries ?? step.max_retries ?? 0,
|
|
494
|
+
taskRegistry: registries?.taskRegistry,
|
|
495
|
+
agentRegistry: registries?.agentRegistry,
|
|
496
|
+
handoffSchemas: registries?.handoffSchemas
|
|
497
|
+
});
|
|
498
|
+
const result = {
|
|
499
|
+
step_index: i,
|
|
500
|
+
task_id: step.task,
|
|
501
|
+
outcome: taskResult.outcome,
|
|
502
|
+
follow_ups_used: taskResult.follow_ups_used,
|
|
503
|
+
retries_used: taskResult.retries_used,
|
|
504
|
+
elapsed_ms: Date.now() - stepStart
|
|
505
|
+
};
|
|
506
|
+
stepResults.push(result);
|
|
507
|
+
emitStepEvent(options, workflow.id, i, step, result);
|
|
508
|
+
if (result.outcome.status === "success") {
|
|
509
|
+
const data = result.outcome.data;
|
|
510
|
+
accumulatedContext += `
|
|
511
|
+
|
|
512
|
+
--- Step ${i + 1}: ${step.task} ---
|
|
513
|
+
`;
|
|
514
|
+
accumulatedContext += typeof data === "string" ? data : JSON.stringify(data, null, 2);
|
|
515
|
+
}
|
|
516
|
+
if (result.outcome.status === "escalation") {
|
|
517
|
+
const wfResult2 = {
|
|
518
|
+
workflow_id: workflow.id,
|
|
519
|
+
status: "escalated",
|
|
520
|
+
steps: stepResults,
|
|
521
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
522
|
+
escalation_reason: result.outcome.reason
|
|
523
|
+
};
|
|
524
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
|
|
525
|
+
return wfResult2;
|
|
526
|
+
}
|
|
527
|
+
if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
|
|
528
|
+
const wfResult2 = {
|
|
529
|
+
workflow_id: workflow.id,
|
|
530
|
+
status: "escalated",
|
|
531
|
+
steps: stepResults,
|
|
532
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
533
|
+
escalation_reason: `Task "${step.task}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
|
|
534
|
+
};
|
|
535
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult2);
|
|
536
|
+
return wfResult2;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const wfResult = {
|
|
540
|
+
workflow_id: workflow.id,
|
|
541
|
+
status: "completed",
|
|
542
|
+
steps: stepResults,
|
|
543
|
+
total_elapsed_ms: Date.now() - workflowStart
|
|
544
|
+
};
|
|
545
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
|
|
546
|
+
return wfResult;
|
|
547
|
+
}
|
|
548
|
+
async function handleGateStep(step, priorResults, options, stepIndex) {
|
|
549
|
+
const start = Date.now();
|
|
550
|
+
if (!options.onGate) {
|
|
551
|
+
return {
|
|
552
|
+
step_index: stepIndex,
|
|
553
|
+
gate_kind: step.gate_kind,
|
|
554
|
+
outcome: { status: "gate_approved" },
|
|
555
|
+
follow_ups_used: 0,
|
|
556
|
+
retries_used: 0,
|
|
557
|
+
elapsed_ms: Date.now() - start
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
const approved = await options.onGate(step.gate_kind, step.description, priorResults);
|
|
561
|
+
return {
|
|
562
|
+
step_index: stepIndex,
|
|
563
|
+
gate_kind: step.gate_kind,
|
|
564
|
+
outcome: { status: approved ? "gate_approved" : "gate_rejected" },
|
|
565
|
+
follow_ups_used: 0,
|
|
566
|
+
retries_used: 0,
|
|
567
|
+
elapsed_ms: Date.now() - start
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
571
|
+
options.onStepComplete?.({
|
|
572
|
+
workflow_id: workflowId,
|
|
573
|
+
step_index: stepIndex,
|
|
574
|
+
step_type: step.type,
|
|
575
|
+
task_id: step.type === "delegate" ? step.task : void 0,
|
|
576
|
+
gate_kind: step.type === "gate" ? step.gate_kind : void 0,
|
|
577
|
+
outcome_status: result.outcome.status,
|
|
578
|
+
follow_ups_used: result.follow_ups_used,
|
|
579
|
+
retries_used: result.retries_used,
|
|
580
|
+
elapsed_ms: result.elapsed_ms
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export {
|
|
585
|
+
PluginRegistry,
|
|
586
|
+
pluginRegistry,
|
|
587
|
+
zodSchemaToPromptDescription,
|
|
588
|
+
zodSchemaToYamlExample,
|
|
589
|
+
buildTaskPrompt,
|
|
590
|
+
extractStructuredResult,
|
|
591
|
+
buildRetryFollowUp,
|
|
592
|
+
runTask,
|
|
593
|
+
runWorkflow
|
|
594
|
+
};
|
|
595
|
+
//# sourceMappingURL=chunk-24SRKCWQ.js.map
|