@aaac/runtime 0.0.1 → 0.1.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/dist/adapters/adk-sdk.d.ts +129 -0
- package/dist/adapters/adk-sdk.js +185 -0
- package/dist/adapters/adk-sdk.js.map +1 -0
- package/dist/adapters/claude-agent-sdk.d.ts +97 -0
- package/dist/adapters/claude-agent-sdk.js +244 -0
- package/dist/adapters/claude-agent-sdk.js.map +1 -0
- package/dist/adapters/mock.d.ts +18 -0
- package/dist/adapters/mock.js +41 -0
- package/dist/adapters/mock.js.map +1 -0
- package/dist/adapters/openai-agents-sdk.d.ts +123 -0
- package/dist/adapters/openai-agents-sdk.js +239 -0
- package/dist/adapters/openai-agents-sdk.js.map +1 -0
- package/dist/chunk-LTZA6QWC.js +296 -0
- package/dist/chunk-LTZA6QWC.js.map +1 -0
- package/dist/chunk-MGRZBGQL.js +321 -0
- package/dist/chunk-MGRZBGQL.js.map +1 -0
- package/dist/context-B_bekYiE.d.ts +106 -0
- package/dist/generator/index.d.ts +140 -0
- package/dist/generator/index.js +308 -0
- package/dist/generator/index.js.map +1 -0
- package/dist/guardrail-hooks-C8G5NGsj.d.ts +83 -0
- package/dist/index.d.ts +805 -2
- package/dist/index.js +2505 -2
- package/dist/index.js.map +1 -1
- package/dist/task-runner-CNj3Ujy0.d.ts +492 -0
- package/package.json +51 -4
package/dist/index.js
CHANGED
|
@@ -1,6 +1,2509 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PluginRegistry,
|
|
3
|
+
createGuardrailHooks,
|
|
4
|
+
createGuardrailHooksForAgent,
|
|
5
|
+
createGuardrailHooksFromRules,
|
|
6
|
+
getBlockingViolations,
|
|
7
|
+
getWarnings,
|
|
8
|
+
hasBlockingViolation,
|
|
9
|
+
pluginRegistry
|
|
10
|
+
} from "./chunk-MGRZBGQL.js";
|
|
11
|
+
import {
|
|
12
|
+
buildGuardrailContext
|
|
13
|
+
} from "./chunk-LTZA6QWC.js";
|
|
14
|
+
|
|
1
15
|
// src/index.ts
|
|
2
|
-
|
|
16
|
+
import { createRequire } from "module";
|
|
17
|
+
|
|
18
|
+
// src/lib/task-runner.ts
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import * as yaml from "yaml";
|
|
21
|
+
|
|
22
|
+
// src/lib/candidate-agents.ts
|
|
23
|
+
function renderAgentSystemPrompt(agent) {
|
|
24
|
+
const sections = [];
|
|
25
|
+
sections.push(`# Role: ${agent.role_name}
|
|
26
|
+
|
|
27
|
+
${agent.purpose}`);
|
|
28
|
+
if (agent.responsibilities.length > 0) {
|
|
29
|
+
sections.push(
|
|
30
|
+
`## Responsibilities
|
|
31
|
+
|
|
32
|
+
${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
if (agent.constraints.length > 0) {
|
|
36
|
+
sections.push(
|
|
37
|
+
`## Constraints
|
|
38
|
+
|
|
39
|
+
${agent.constraints.map((c) => `- ${c}`).join("\n")}`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
if (agent.rules && agent.rules.length > 0) {
|
|
43
|
+
const ruleLines = agent.rules.map(
|
|
44
|
+
(r) => `- **${r.id}** [${r.severity}]: ${r.description}`
|
|
45
|
+
);
|
|
46
|
+
sections.push(`## Rules
|
|
47
|
+
|
|
48
|
+
${ruleLines.join("\n")}`);
|
|
49
|
+
}
|
|
50
|
+
return sections.join("\n\n");
|
|
51
|
+
}
|
|
52
|
+
function deriveDescription(purpose) {
|
|
53
|
+
const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
54
|
+
const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
|
|
55
|
+
if (sentenceEnd !== -1) {
|
|
56
|
+
return firstLine.slice(0, sentenceEnd + 1).trim();
|
|
57
|
+
}
|
|
58
|
+
return firstLine;
|
|
59
|
+
}
|
|
60
|
+
function buildCandidateAgents(agentRegistry, opts) {
|
|
61
|
+
const entryId = opts?.entryAgentId;
|
|
62
|
+
const allowed = opts?.allowedAgentIds;
|
|
63
|
+
const allowSet = allowed ? new Set(allowed) : void 0;
|
|
64
|
+
const candidates = [];
|
|
65
|
+
for (const [id, agent] of Object.entries(agentRegistry)) {
|
|
66
|
+
if (id === entryId) continue;
|
|
67
|
+
if (allowSet && !allowSet.has(id)) continue;
|
|
68
|
+
const tools = agent.can_execute_tools;
|
|
69
|
+
candidates.push({
|
|
70
|
+
name: id,
|
|
71
|
+
description: deriveDescription(agent.purpose),
|
|
72
|
+
prompt: renderAgentSystemPrompt(agent),
|
|
73
|
+
...tools && tools.length > 0 ? { tools: [...tools] } : {}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return candidates;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/lib/observability-bridge.ts
|
|
80
|
+
import { generateId } from "@aaac/observability";
|
|
81
|
+
function createExecutionEnvelope(params = {}) {
|
|
82
|
+
const envelope = {
|
|
83
|
+
run_id: generateId(),
|
|
84
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
85
|
+
};
|
|
86
|
+
if (params.parentRunId !== void 0) envelope.parent_run_id = params.parentRunId;
|
|
87
|
+
if (params.componentId !== void 0) envelope.component_id = params.componentId;
|
|
88
|
+
if (params.fromAgent !== void 0) envelope.from_agent = params.fromAgent;
|
|
89
|
+
if (params.toAgent !== void 0) envelope.to_agent = params.toAgent;
|
|
90
|
+
if (params.contractVersion !== void 0) envelope.contract_version = params.contractVersion;
|
|
91
|
+
if (params.adapter !== void 0) envelope.adapter = params.adapter;
|
|
92
|
+
if (params.model !== void 0) envelope.model = params.model;
|
|
93
|
+
if (params.taskInstanceId !== void 0) envelope.task_instance_id = params.taskInstanceId;
|
|
94
|
+
return envelope;
|
|
95
|
+
}
|
|
96
|
+
function attrs(base) {
|
|
97
|
+
const out = {};
|
|
98
|
+
for (const [k, v] of Object.entries(base)) {
|
|
99
|
+
if (v !== void 0 && v !== "") out[k] = v;
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
function tokenAttrs(meta) {
|
|
104
|
+
const out = {};
|
|
105
|
+
const tu = meta.token_usage;
|
|
106
|
+
if (tu && typeof tu === "object") {
|
|
107
|
+
const t = tu;
|
|
108
|
+
if (typeof t.input_tokens === "number") out["token_usage.input"] = t.input_tokens;
|
|
109
|
+
if (typeof t.output_tokens === "number") out["token_usage.output"] = t.output_tokens;
|
|
110
|
+
if (typeof t.total_tokens === "number") out["token_usage.total"] = t.total_tokens;
|
|
111
|
+
if (typeof t.cache_read_input_tokens === "number") out["token_usage.cache_read"] = t.cache_read_input_tokens;
|
|
112
|
+
if (typeof t.cache_creation_input_tokens === "number") out["token_usage.cache_creation"] = t.cache_creation_input_tokens;
|
|
113
|
+
}
|
|
114
|
+
if (typeof meta.cost_usd === "number") out["cost_usd"] = meta.cost_usd;
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
function emitSessionOpen(observer, envelope, workflowId) {
|
|
118
|
+
if (!observer) return void 0;
|
|
119
|
+
const spanId = envelope.run_id;
|
|
120
|
+
observer({
|
|
121
|
+
source: "aaac-runtime",
|
|
122
|
+
eventType: "agent.session",
|
|
123
|
+
lifecycle: "open",
|
|
124
|
+
spanId,
|
|
125
|
+
parentSpanId: envelope.parent_run_id,
|
|
126
|
+
attributes: attrs({
|
|
127
|
+
axis: "agent",
|
|
128
|
+
"agent.session_id": envelope.run_id,
|
|
129
|
+
"agent.run_id": envelope.run_id,
|
|
130
|
+
"workflow.id": workflowId,
|
|
131
|
+
"agent.component_id": envelope.component_id,
|
|
132
|
+
"agent.model": envelope.model,
|
|
133
|
+
adapter: envelope.adapter,
|
|
134
|
+
contract_version: envelope.contract_version
|
|
135
|
+
})
|
|
136
|
+
});
|
|
137
|
+
return spanId;
|
|
138
|
+
}
|
|
139
|
+
function emitSessionClose(observer, spanId, envelope, durationMs, status) {
|
|
140
|
+
if (!observer) return;
|
|
141
|
+
const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
|
|
142
|
+
observer({
|
|
143
|
+
source: "aaac-runtime",
|
|
144
|
+
eventType: "agent.session",
|
|
145
|
+
lifecycle: "close",
|
|
146
|
+
spanId,
|
|
147
|
+
attributes: {
|
|
148
|
+
...attrs({
|
|
149
|
+
axis: "agent",
|
|
150
|
+
"agent.session_id": envelope.run_id,
|
|
151
|
+
"agent.session.duration_ms": durationMs,
|
|
152
|
+
"agent.status": status
|
|
153
|
+
}),
|
|
154
|
+
...metaAttrs
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function emitSubagentOpen(observer, envelope, parentSpanId, taskId, agentRole) {
|
|
159
|
+
if (!observer) return void 0;
|
|
160
|
+
const spanId = envelope.run_id;
|
|
161
|
+
observer({
|
|
162
|
+
source: "aaac-runtime",
|
|
163
|
+
eventType: "agent.subagent",
|
|
164
|
+
lifecycle: "open",
|
|
165
|
+
spanId,
|
|
166
|
+
parentSpanId,
|
|
167
|
+
attributes: attrs({
|
|
168
|
+
axis: "agent",
|
|
169
|
+
"agent.role": agentRole,
|
|
170
|
+
"agent.kind": "task",
|
|
171
|
+
"task.id": taskId,
|
|
172
|
+
"agent.run_id": envelope.run_id,
|
|
173
|
+
"agent.parent_run_id": envelope.parent_run_id,
|
|
174
|
+
"agent.model": envelope.model,
|
|
175
|
+
adapter: envelope.adapter,
|
|
176
|
+
"agent.component_id": envelope.component_id,
|
|
177
|
+
"agent.from_agent": envelope.from_agent,
|
|
178
|
+
"agent.to_agent": envelope.to_agent
|
|
179
|
+
})
|
|
180
|
+
});
|
|
181
|
+
return spanId;
|
|
182
|
+
}
|
|
183
|
+
function emitSubagentClose(observer, spanId, envelope, durationMs, status, agentRole) {
|
|
184
|
+
if (!observer) return;
|
|
185
|
+
const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
|
|
186
|
+
observer({
|
|
187
|
+
source: "aaac-runtime",
|
|
188
|
+
eventType: "agent.subagent",
|
|
189
|
+
lifecycle: "close",
|
|
190
|
+
spanId,
|
|
191
|
+
attributes: {
|
|
192
|
+
...attrs({
|
|
193
|
+
axis: "agent",
|
|
194
|
+
"agent.role": agentRole,
|
|
195
|
+
"agent.status": status,
|
|
196
|
+
"agent.duration_ms": durationMs
|
|
197
|
+
}),
|
|
198
|
+
...metaAttrs
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/lib/task-runner.ts
|
|
204
|
+
function getZodChecks(schema) {
|
|
205
|
+
const def = schema._def;
|
|
206
|
+
return def?.checks ?? [];
|
|
207
|
+
}
|
|
208
|
+
function extractZodConstraints(schema) {
|
|
209
|
+
const inner = unwrapOptional(schema);
|
|
210
|
+
const parts = [];
|
|
211
|
+
if (inner instanceof z.ZodString) {
|
|
212
|
+
const str = inner;
|
|
213
|
+
if (str.minLength != null) parts.push(`min: ${str.minLength}`);
|
|
214
|
+
if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
|
|
215
|
+
for (const check of getZodChecks(inner)) {
|
|
216
|
+
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
217
|
+
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
218
|
+
if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
|
|
219
|
+
const def = check._zod?.def;
|
|
220
|
+
if (def?.format === "regex" && def.pattern instanceof RegExp) {
|
|
221
|
+
parts.push(`regex: ${def.pattern}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
} else if (inner instanceof z.ZodNumber) {
|
|
225
|
+
let hasInt = false;
|
|
226
|
+
for (const check of getZodChecks(inner)) {
|
|
227
|
+
if (check.kind === "int") hasInt = true;
|
|
228
|
+
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
229
|
+
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
230
|
+
if (check.isInt) hasInt = true;
|
|
231
|
+
const def = check._zod?.def;
|
|
232
|
+
if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
|
|
233
|
+
if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
|
|
234
|
+
if (def?.check === "less_than") parts.push(`max: ${def.value}`);
|
|
235
|
+
}
|
|
236
|
+
if (hasInt) parts.unshift("int");
|
|
237
|
+
} else if (inner instanceof z.ZodArray) {
|
|
238
|
+
for (const check of getZodChecks(inner)) {
|
|
239
|
+
if (check.kind === "min") parts.push(`min: ${check.value}`);
|
|
240
|
+
if (check.kind === "max") parts.push(`max: ${check.value}`);
|
|
241
|
+
const def = check._zod?.def;
|
|
242
|
+
if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
|
|
243
|
+
if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return parts.length > 0 ? parts.join(", ") : void 0;
|
|
247
|
+
}
|
|
248
|
+
function zodTypeToString(schema) {
|
|
249
|
+
if (schema instanceof z.ZodString) return "string";
|
|
250
|
+
if (schema instanceof z.ZodNumber) return "number";
|
|
251
|
+
if (schema instanceof z.ZodBoolean) return "boolean";
|
|
252
|
+
if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
|
|
253
|
+
if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
|
|
254
|
+
if (schema instanceof z.ZodArray) {
|
|
255
|
+
const element = schema._def.element;
|
|
256
|
+
const inner = zodTypeToString(element);
|
|
257
|
+
return `${inner}[]`;
|
|
258
|
+
}
|
|
259
|
+
if (schema instanceof z.ZodObject) return "object";
|
|
260
|
+
if (schema instanceof z.ZodOptional) {
|
|
261
|
+
return zodTypeToString(schema._def.innerType);
|
|
262
|
+
}
|
|
263
|
+
if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
|
|
264
|
+
return "unknown";
|
|
265
|
+
}
|
|
266
|
+
function unwrapOptional(schema) {
|
|
267
|
+
if (schema instanceof z.ZodOptional) {
|
|
268
|
+
return schema._def.innerType;
|
|
269
|
+
}
|
|
270
|
+
return schema;
|
|
271
|
+
}
|
|
272
|
+
function getArrayElement(schema) {
|
|
273
|
+
const inner = unwrapOptional(schema);
|
|
274
|
+
if (inner instanceof z.ZodArray) {
|
|
275
|
+
return inner._def.element;
|
|
276
|
+
}
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
function extractFieldDescriptors(schema) {
|
|
280
|
+
let shape = null;
|
|
281
|
+
if (schema instanceof z.ZodObject) {
|
|
282
|
+
shape = schema.shape;
|
|
283
|
+
}
|
|
284
|
+
if (!shape) return null;
|
|
285
|
+
return Object.entries(shape).map(([name, field]) => {
|
|
286
|
+
const isOptional = field instanceof z.ZodOptional;
|
|
287
|
+
const innerField = isOptional ? field._def.innerType : field;
|
|
288
|
+
const description = innerField.description ?? field.description;
|
|
289
|
+
return {
|
|
290
|
+
name,
|
|
291
|
+
type: zodTypeToString(field),
|
|
292
|
+
required: !isOptional,
|
|
293
|
+
description,
|
|
294
|
+
constraints: extractZodConstraints(innerField)
|
|
295
|
+
};
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function zodSchemaToPromptDescription(schema) {
|
|
299
|
+
const tables = [];
|
|
300
|
+
collectFieldTables(schema, "", tables);
|
|
301
|
+
return tables.join("\n\n");
|
|
302
|
+
}
|
|
303
|
+
function collectFieldTables(schema, pathPrefix, tables) {
|
|
304
|
+
const fields = extractFieldDescriptors(schema);
|
|
305
|
+
if (!fields || fields.length === 0) return;
|
|
306
|
+
const title = pathPrefix ? `**${pathPrefix}**
|
|
307
|
+
|
|
308
|
+
` : "";
|
|
309
|
+
const header = "| Field | Type | Required | Constraints | Description |";
|
|
310
|
+
const sep = "|-------|------|----------|-------------|-------------|";
|
|
311
|
+
const rows = fields.map(
|
|
312
|
+
(f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
|
|
313
|
+
);
|
|
314
|
+
tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
|
|
315
|
+
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
316
|
+
if (!shape) return;
|
|
317
|
+
for (const f of fields) {
|
|
318
|
+
const rawField = shape[f.name];
|
|
319
|
+
const inner = unwrapOptional(rawField);
|
|
320
|
+
if (inner instanceof z.ZodObject) {
|
|
321
|
+
collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
|
|
322
|
+
} else if (inner instanceof z.ZodArray) {
|
|
323
|
+
const element = inner._def.element;
|
|
324
|
+
if (element instanceof z.ZodObject) {
|
|
325
|
+
collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function zodSchemaToYamlExample(schema, maxDepth = 3) {
|
|
331
|
+
return renderYamlObject(schema, 0, maxDepth);
|
|
332
|
+
}
|
|
333
|
+
function renderYamlObject(schema, indent, maxDepth) {
|
|
334
|
+
const fields = extractFieldDescriptors(schema);
|
|
335
|
+
if (!fields || fields.length === 0) return "";
|
|
336
|
+
const prefix = " ".repeat(indent);
|
|
337
|
+
const lines = [];
|
|
338
|
+
for (const f of fields) {
|
|
339
|
+
const shape = schema instanceof z.ZodObject ? schema.shape : null;
|
|
340
|
+
const rawField = shape?.[f.name];
|
|
341
|
+
if (f.type.endsWith("[]")) {
|
|
342
|
+
lines.push(`${prefix}${f.name}:`);
|
|
343
|
+
const element = rawField ? getArrayElement(rawField) : null;
|
|
344
|
+
if (element && element instanceof z.ZodObject && indent < maxDepth) {
|
|
345
|
+
const nested = renderYamlObject(element, indent + 2, maxDepth);
|
|
346
|
+
if (nested) {
|
|
347
|
+
const basePrefix = " ".repeat(indent + 2);
|
|
348
|
+
const nestedLines = nested.split("\n");
|
|
349
|
+
lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
|
|
350
|
+
for (let i = 1; i < nestedLines.length; i++) {
|
|
351
|
+
lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
lines.push(`${prefix} - key: "value"`);
|
|
355
|
+
}
|
|
356
|
+
} else if (f.type === "string[]") {
|
|
357
|
+
lines.push(`${prefix} - "example"`);
|
|
358
|
+
} else {
|
|
359
|
+
lines.push(`${prefix} - key: "value"`);
|
|
360
|
+
}
|
|
361
|
+
} else if (f.type === "object" && indent < maxDepth) {
|
|
362
|
+
const inner = rawField ? unwrapOptional(rawField) : null;
|
|
363
|
+
if (inner && inner instanceof z.ZodObject) {
|
|
364
|
+
lines.push(`${prefix}${f.name}:`);
|
|
365
|
+
const nested = renderYamlObject(inner, indent + 1, maxDepth);
|
|
366
|
+
if (nested) {
|
|
367
|
+
lines.push(nested);
|
|
368
|
+
} else {
|
|
369
|
+
lines.push(`${prefix} key: "value"`);
|
|
370
|
+
}
|
|
371
|
+
} else {
|
|
372
|
+
lines.push(`${prefix}${f.name}:`);
|
|
373
|
+
lines.push(`${prefix} key: "value"`);
|
|
374
|
+
}
|
|
375
|
+
} else if (f.type === "string") {
|
|
376
|
+
lines.push(`${prefix}${f.name}: "..."`);
|
|
377
|
+
} else if (f.type === "number") {
|
|
378
|
+
lines.push(`${prefix}${f.name}: 0`);
|
|
379
|
+
} else if (f.type === "boolean") {
|
|
380
|
+
lines.push(`${prefix}${f.name}: false`);
|
|
381
|
+
} else if (f.type.startsWith("enum(")) {
|
|
382
|
+
const enumVals = f.type.slice(5, -1).split(", ");
|
|
383
|
+
lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
|
|
384
|
+
} else {
|
|
385
|
+
lines.push(`${prefix}${f.name}: "..."`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return lines.join("\n");
|
|
389
|
+
}
|
|
390
|
+
function buildSplitTaskPrompt(agent, task, context, options) {
|
|
391
|
+
const system = [];
|
|
392
|
+
system.push(renderAgentSystemPrompt(agent));
|
|
393
|
+
system.push(`## Task: ${task.id}
|
|
394
|
+
|
|
395
|
+
${task.description}`);
|
|
396
|
+
if (task.completion_criteria.length > 0) {
|
|
397
|
+
system.push(
|
|
398
|
+
`## Completion Criteria
|
|
399
|
+
|
|
400
|
+
${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
const handoffId = task.result_handoff;
|
|
404
|
+
const schema = options?.handoffSchemas?.[handoffId];
|
|
405
|
+
let outputSection = `## Required Output Format
|
|
406
|
+
|
|
407
|
+
Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
408
|
+
if (schema) {
|
|
409
|
+
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
410
|
+
if (fieldTable) {
|
|
411
|
+
outputSection += `
|
|
412
|
+
|
|
413
|
+
${fieldTable}`;
|
|
414
|
+
}
|
|
415
|
+
const yamlExample = zodSchemaToYamlExample(schema);
|
|
416
|
+
if (yamlExample) {
|
|
417
|
+
outputSection += `
|
|
418
|
+
|
|
419
|
+
Example:
|
|
420
|
+
|
|
421
|
+
\`\`\`yaml
|
|
422
|
+
${yamlExample}
|
|
423
|
+
\`\`\``;
|
|
424
|
+
}
|
|
425
|
+
} else {
|
|
426
|
+
outputSection += ` Include all required fields.`;
|
|
427
|
+
}
|
|
428
|
+
system.push(outputSection);
|
|
429
|
+
if (options?.retry) {
|
|
430
|
+
const r = options.retry;
|
|
431
|
+
let recoverySection = `## Recovery Instructions
|
|
432
|
+
|
|
433
|
+
If the task fails due to: "${r.condition}"
|
|
434
|
+
\u2192 Apply the recovery approach from task "${r.fix_task}"`;
|
|
435
|
+
if (r.revalidate_task) {
|
|
436
|
+
recoverySection += `
|
|
437
|
+
\u2192 Then revalidate using task "${r.revalidate_task}"`;
|
|
438
|
+
}
|
|
439
|
+
system.push(recoverySection);
|
|
440
|
+
}
|
|
441
|
+
const userSections = [];
|
|
442
|
+
if (context.handoff_input) {
|
|
443
|
+
const hi = context.handoff_input;
|
|
444
|
+
const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
|
|
445
|
+
userSections.push(`## User Request
|
|
446
|
+
|
|
447
|
+
${context.user_request}`);
|
|
448
|
+
userSections.push(`## Handoff Input (${hi.type})
|
|
449
|
+
|
|
450
|
+
\`\`\`yaml
|
|
451
|
+
${payloadStr}\`\`\``);
|
|
452
|
+
} else {
|
|
453
|
+
userSections.push(`## User Request
|
|
454
|
+
|
|
455
|
+
${context.user_request}`);
|
|
456
|
+
}
|
|
457
|
+
if (context.prior_context) {
|
|
458
|
+
userSections.push(`## Prior Context
|
|
459
|
+
|
|
460
|
+
${context.prior_context}`);
|
|
461
|
+
}
|
|
462
|
+
if (context.relevant_paths && context.relevant_paths.length > 0) {
|
|
463
|
+
userSections.push(
|
|
464
|
+
`## Relevant Files
|
|
465
|
+
|
|
466
|
+
${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
|
|
470
|
+
userSections.push(
|
|
471
|
+
`## Acceptance Criteria
|
|
472
|
+
|
|
473
|
+
${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
return {
|
|
477
|
+
system,
|
|
478
|
+
user: userSections.join("\n\n---\n\n")
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
function joinSplitPrompt(split) {
|
|
482
|
+
return [...split.system, split.user].join("\n\n---\n\n");
|
|
483
|
+
}
|
|
484
|
+
function buildTaskPrompt(agent, task, context, options) {
|
|
485
|
+
return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
|
|
486
|
+
}
|
|
487
|
+
function extractStructuredResult(raw) {
|
|
488
|
+
const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
|
|
489
|
+
if (yamlMatch) {
|
|
490
|
+
try {
|
|
491
|
+
return yaml.parse(yamlMatch[1]);
|
|
492
|
+
} catch {
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
|
|
496
|
+
if (jsonMatch) {
|
|
497
|
+
try {
|
|
498
|
+
return JSON.parse(jsonMatch[1]);
|
|
499
|
+
} catch {
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
return JSON.parse(raw);
|
|
504
|
+
} catch {
|
|
505
|
+
}
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
function validateOutput(fullOutput, task, schemas) {
|
|
509
|
+
if (!fullOutput.trim()) {
|
|
510
|
+
return { status: "error", message: "Agent returned empty output" };
|
|
511
|
+
}
|
|
512
|
+
const parsed = extractStructuredResult(fullOutput);
|
|
513
|
+
if (!parsed) {
|
|
514
|
+
return {
|
|
515
|
+
status: "validation_error",
|
|
516
|
+
errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
|
|
517
|
+
raw: fullOutput
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
const schema = schemas[task.result_handoff];
|
|
521
|
+
if (!schema) {
|
|
522
|
+
return { status: "success", data: parsed, raw: fullOutput };
|
|
523
|
+
}
|
|
524
|
+
const validation = schema.safeParse(parsed);
|
|
525
|
+
if (!validation.success) {
|
|
526
|
+
return { status: "validation_error", errors: validation.error, raw: fullOutput };
|
|
527
|
+
}
|
|
528
|
+
const data = validation.data;
|
|
529
|
+
if (data.escalation_needed === true) {
|
|
530
|
+
return {
|
|
531
|
+
status: "escalation",
|
|
532
|
+
reason: data.escalation_reasons ?? "Agent requested escalation",
|
|
533
|
+
raw: fullOutput
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
return { status: "success", data: validation.data, raw: fullOutput };
|
|
537
|
+
}
|
|
538
|
+
function attachMemoryRef(outcome, adapter) {
|
|
539
|
+
if (outcome.status !== "success") return outcome;
|
|
540
|
+
const ref = adapter.getLastMemoryRef?.();
|
|
541
|
+
if (!ref) return outcome;
|
|
542
|
+
return { ...outcome, memoryRef: ref };
|
|
543
|
+
}
|
|
544
|
+
function buildRetryFollowUp(task, lastOutcome, options) {
|
|
545
|
+
const sections = [];
|
|
546
|
+
sections.push(
|
|
547
|
+
"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."
|
|
548
|
+
);
|
|
549
|
+
if (lastOutcome.status === "validation_error") {
|
|
550
|
+
sections.push(`Validation errors:
|
|
551
|
+
${lastOutcome.errors.message}`);
|
|
552
|
+
} else if (lastOutcome.status === "error") {
|
|
553
|
+
sections.push(`Error: ${lastOutcome.message}`);
|
|
554
|
+
}
|
|
555
|
+
const handoffId = task.result_handoff;
|
|
556
|
+
const schema = options?.handoffSchemas?.[handoffId];
|
|
557
|
+
let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
|
|
558
|
+
if (schema) {
|
|
559
|
+
const fieldTable = zodSchemaToPromptDescription(schema);
|
|
560
|
+
if (fieldTable) {
|
|
561
|
+
formatSection += `
|
|
562
|
+
|
|
563
|
+
${fieldTable}`;
|
|
564
|
+
}
|
|
565
|
+
const yamlExample = zodSchemaToYamlExample(schema);
|
|
566
|
+
if (yamlExample) {
|
|
567
|
+
formatSection += `
|
|
568
|
+
|
|
569
|
+
Example:
|
|
570
|
+
|
|
571
|
+
\`\`\`yaml
|
|
572
|
+
${yamlExample}
|
|
573
|
+
\`\`\``;
|
|
574
|
+
}
|
|
575
|
+
} else {
|
|
576
|
+
formatSection += ` Include all required fields.`;
|
|
577
|
+
}
|
|
578
|
+
sections.push(formatSection);
|
|
579
|
+
return sections.join("\n\n");
|
|
580
|
+
}
|
|
581
|
+
function defaultDecideRetryStrategy(outcome, _counts) {
|
|
582
|
+
if (outcome.status === "validation_error") {
|
|
583
|
+
return "follow_up";
|
|
584
|
+
}
|
|
585
|
+
if (outcome.status === "error") {
|
|
586
|
+
if (outcome.message === "Agent returned empty output") return "retry";
|
|
587
|
+
return "abort";
|
|
588
|
+
}
|
|
589
|
+
return "abort";
|
|
590
|
+
}
|
|
591
|
+
function summarizeToolInput(input) {
|
|
592
|
+
if (!input) return "";
|
|
593
|
+
const path = input.file_path ?? input.path ?? input.filename ?? input.file;
|
|
594
|
+
if (typeof path === "string") return ` \u2014 ${path}`;
|
|
595
|
+
const cmd = input.command ?? input.cmd;
|
|
596
|
+
if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
|
|
597
|
+
const query = input.query ?? input.search ?? input.pattern;
|
|
598
|
+
if (typeof query === "string") return ` \u2014 "${query}"`;
|
|
599
|
+
return "";
|
|
600
|
+
}
|
|
601
|
+
function timestamp() {
|
|
602
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
603
|
+
}
|
|
604
|
+
function formatProgressPrefix(event, taskId, agentId) {
|
|
605
|
+
const ts = timestamp();
|
|
606
|
+
const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
|
|
607
|
+
const agent = agentId ?? "-";
|
|
608
|
+
return `[${ts},${sid},${agent},${taskId}]`;
|
|
609
|
+
}
|
|
610
|
+
function formatProgressEvent(event, taskId, agentId) {
|
|
611
|
+
const prefix = formatProgressPrefix(event, taskId, agentId);
|
|
612
|
+
switch (event.type) {
|
|
613
|
+
case "tool_use":
|
|
614
|
+
return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
|
|
615
|
+
`;
|
|
616
|
+
case "tool_result":
|
|
617
|
+
return "";
|
|
618
|
+
case "text": {
|
|
619
|
+
if (!event.message) return "";
|
|
620
|
+
const trimmed = event.message.trim();
|
|
621
|
+
if (!trimmed) return "";
|
|
622
|
+
const firstLine = trimmed.split("\n")[0];
|
|
623
|
+
const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
|
|
624
|
+
return `${prefix} \u{1F4AD} ${preview}
|
|
625
|
+
`;
|
|
626
|
+
}
|
|
627
|
+
case "status":
|
|
628
|
+
return event.message ? `${prefix} \u25CF ${event.message}
|
|
629
|
+
` : "";
|
|
630
|
+
default:
|
|
631
|
+
return "";
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
async function runTask(adapter, taskId, context, options) {
|
|
635
|
+
const taskReg = options?.taskRegistry ?? {};
|
|
636
|
+
const agentReg = options?.agentRegistry ?? {};
|
|
637
|
+
const schemas = options?.handoffSchemas ?? {};
|
|
638
|
+
const task = taskReg[taskId];
|
|
639
|
+
if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
|
|
640
|
+
const agentContract = agentReg[task.target_agent];
|
|
641
|
+
if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
|
|
642
|
+
const taskEnvelope = createExecutionEnvelope({
|
|
643
|
+
taskInstanceId: taskId,
|
|
644
|
+
componentId: agentContract.id,
|
|
645
|
+
fromAgent: agentContract.id,
|
|
646
|
+
parentRunId: options?.parentSpanId
|
|
647
|
+
// correlates to agent.session run_id
|
|
648
|
+
});
|
|
649
|
+
const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
|
|
650
|
+
if (modifiedContext === null) {
|
|
651
|
+
return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
|
|
652
|
+
}
|
|
653
|
+
const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
|
|
654
|
+
const promptOpts = { handoffSchemas: schemas, retry: options?.retry };
|
|
655
|
+
const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
|
|
656
|
+
let prompt;
|
|
657
|
+
let splitPrompt;
|
|
658
|
+
const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
|
|
659
|
+
if (pluginPrompt) {
|
|
660
|
+
prompt = pluginPrompt;
|
|
661
|
+
} else {
|
|
662
|
+
const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
|
|
663
|
+
splitPrompt = split;
|
|
664
|
+
prompt = joinSplitPrompt(split);
|
|
665
|
+
}
|
|
666
|
+
const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
|
|
667
|
+
if (enhancedPrompt !== prompt) {
|
|
668
|
+
splitPrompt = void 0;
|
|
669
|
+
prompt = enhancedPrompt;
|
|
670
|
+
}
|
|
671
|
+
const isReadonly = agentContract.mode === "read-only";
|
|
672
|
+
const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
|
|
673
|
+
const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
|
|
674
|
+
entryAgentId: agentContract.id,
|
|
675
|
+
allowedAgentIds: agentContract.can_invoke_agents
|
|
676
|
+
}) : [];
|
|
677
|
+
const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
|
|
678
|
+
const maxFollowUps = options?.maxFollowUps ?? 2;
|
|
679
|
+
const maxRetries = options?.maxRetries ?? 0;
|
|
680
|
+
const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
|
|
681
|
+
const onProgress = options?.progressOutput ? (event) => {
|
|
682
|
+
const line = formatProgressEvent(event, taskId, agentContract.id);
|
|
683
|
+
if (line) options.progressOutput.write(line);
|
|
684
|
+
} : void 0;
|
|
685
|
+
let followUpsUsed = 0;
|
|
686
|
+
let retriesUsed = 0;
|
|
687
|
+
let memoryRef = enrichedContext.memoryRef;
|
|
688
|
+
if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
|
|
689
|
+
console.warn(
|
|
690
|
+
`Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
|
|
691
|
+
);
|
|
692
|
+
memoryRef = void 0;
|
|
693
|
+
}
|
|
694
|
+
const taskExecStart = Date.now();
|
|
695
|
+
const subagentSpanId = emitSubagentOpen(
|
|
696
|
+
options?.observer,
|
|
697
|
+
taskEnvelope,
|
|
698
|
+
options?.parentSpanId,
|
|
699
|
+
taskId,
|
|
700
|
+
agentContract.role_name
|
|
701
|
+
);
|
|
702
|
+
let fullOutput;
|
|
703
|
+
try {
|
|
704
|
+
if (adapter.sendExecution) {
|
|
705
|
+
fullOutput = await adapter.sendExecution({
|
|
706
|
+
agentId: agentContract.id,
|
|
707
|
+
taskId,
|
|
708
|
+
prompt,
|
|
709
|
+
handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
|
|
710
|
+
schema: schemas[task.result_handoff] ? {
|
|
711
|
+
handoffType: task.result_handoff,
|
|
712
|
+
zodSchema: schemas[task.result_handoff],
|
|
713
|
+
promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
|
|
714
|
+
} : void 0,
|
|
715
|
+
context: enrichedContext,
|
|
716
|
+
memoryRef,
|
|
717
|
+
splitPrompt,
|
|
718
|
+
agents,
|
|
719
|
+
options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, maxFollowUps, attempt: 0 }
|
|
720
|
+
});
|
|
721
|
+
} else {
|
|
722
|
+
fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow });
|
|
723
|
+
}
|
|
724
|
+
} catch (err) {
|
|
725
|
+
const errDurationMs = Date.now() - taskExecStart;
|
|
726
|
+
taskEnvelope.execution_metadata = { duration_ms: errDurationMs };
|
|
727
|
+
emitSubagentClose(
|
|
728
|
+
options?.observer,
|
|
729
|
+
subagentSpanId ?? taskEnvelope.run_id,
|
|
730
|
+
taskEnvelope,
|
|
731
|
+
errDurationMs,
|
|
732
|
+
"error",
|
|
733
|
+
agentContract.role_name
|
|
734
|
+
);
|
|
735
|
+
return { outcome: { status: "error", message: `SDK error: ${err.message}` }, follow_ups_used: 0, retries_used: 0 };
|
|
736
|
+
}
|
|
737
|
+
let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
|
|
738
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
739
|
+
while (outcome.status === "validation_error" || outcome.status === "error") {
|
|
740
|
+
const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
|
|
741
|
+
if (decision === "abort") break;
|
|
742
|
+
let effectiveDecision = decision;
|
|
743
|
+
if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
|
|
744
|
+
effectiveDecision = "retry";
|
|
745
|
+
}
|
|
746
|
+
if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
if (effectiveDecision === "follow_up") {
|
|
750
|
+
followUpsUsed++;
|
|
751
|
+
const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
|
|
752
|
+
try {
|
|
753
|
+
if (adapter.followUp) {
|
|
754
|
+
fullOutput = await adapter.followUp(followUpPrompt);
|
|
755
|
+
} else {
|
|
756
|
+
const retryContext = {
|
|
757
|
+
...modifiedContext,
|
|
758
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
759
|
+
|
|
760
|
+
--- FollowUp ${followUpsUsed} ---
|
|
761
|
+
${followUpPrompt}`
|
|
762
|
+
};
|
|
763
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
|
|
764
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
765
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
|
|
766
|
+
}
|
|
767
|
+
} catch (err) {
|
|
768
|
+
outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
} else {
|
|
772
|
+
retriesUsed++;
|
|
773
|
+
const retryContext = {
|
|
774
|
+
...modifiedContext,
|
|
775
|
+
prior_context: (modifiedContext.prior_context ?? "") + `
|
|
776
|
+
|
|
777
|
+
--- Full Retry ${retriesUsed} ---
|
|
778
|
+
Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
|
|
779
|
+
Please re-execute the entire task.`
|
|
780
|
+
};
|
|
781
|
+
let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
|
|
782
|
+
retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
|
|
783
|
+
try {
|
|
784
|
+
fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
|
|
785
|
+
} catch (err) {
|
|
786
|
+
outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
|
|
791
|
+
outcome = await pluginRegistry.runAfterTask(taskId, outcome);
|
|
792
|
+
}
|
|
793
|
+
const totalDurationMs = Date.now() - taskExecStart;
|
|
794
|
+
taskEnvelope.execution_metadata = {
|
|
795
|
+
...taskEnvelope.execution_metadata ?? {},
|
|
796
|
+
duration_ms: totalDurationMs
|
|
797
|
+
};
|
|
798
|
+
emitSubagentClose(
|
|
799
|
+
options?.observer,
|
|
800
|
+
subagentSpanId ?? taskEnvelope.run_id,
|
|
801
|
+
taskEnvelope,
|
|
802
|
+
totalDurationMs,
|
|
803
|
+
outcome.status,
|
|
804
|
+
agentContract.role_name
|
|
805
|
+
);
|
|
806
|
+
return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// src/lib/workflow-runner.ts
|
|
810
|
+
function isAdapterFactory(v) {
|
|
811
|
+
return typeof v === "function" && !("send" in v);
|
|
812
|
+
}
|
|
813
|
+
function resolveAdapter(adapterOrFactory) {
|
|
814
|
+
if (isAdapterFactory(adapterOrFactory)) {
|
|
815
|
+
const result = adapterOrFactory();
|
|
816
|
+
if (result && typeof result.then === "function") {
|
|
817
|
+
throw new Error("ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.");
|
|
818
|
+
}
|
|
819
|
+
return { adapter: result, factory: adapterOrFactory };
|
|
820
|
+
}
|
|
821
|
+
return { adapter: adapterOrFactory, factory: void 0 };
|
|
822
|
+
}
|
|
823
|
+
function resolveInvocation(invocation) {
|
|
824
|
+
let userRequest;
|
|
825
|
+
if (invocation.handoff) {
|
|
826
|
+
const h = invocation.handoff;
|
|
827
|
+
userRequest = invocation.user_request ? invocation.user_request : typeof h.payload === "string" ? h.payload : JSON.stringify(h.payload, null, 2);
|
|
828
|
+
} else {
|
|
829
|
+
userRequest = invocation.user_request ?? "";
|
|
830
|
+
}
|
|
831
|
+
const ctx = invocation.context;
|
|
832
|
+
const variables = { ...ctx?.variables };
|
|
833
|
+
if (ctx?.cwd) variables.cwd = ctx.cwd;
|
|
834
|
+
if (ctx?.environment) variables.environment = ctx.environment;
|
|
835
|
+
if (ctx?.artifacts) variables.artifacts = ctx.artifacts;
|
|
836
|
+
return {
|
|
837
|
+
workflowId: invocation.workflow,
|
|
838
|
+
options: {
|
|
839
|
+
user_request: userRequest,
|
|
840
|
+
maxFollowUps: invocation.runtime?.maxFollowUps,
|
|
841
|
+
maxRetries: invocation.runtime?.maxRetries,
|
|
842
|
+
variables: Object.keys(variables).length > 0 ? variables : void 0,
|
|
843
|
+
onGate: invocation.hooks?.onGate,
|
|
844
|
+
onStepComplete: invocation.hooks?.onStepComplete,
|
|
845
|
+
onOptionalStep: invocation.hooks?.onOptionalStep,
|
|
846
|
+
progressOutput: invocation.progressOutput,
|
|
847
|
+
observer: invocation.observer
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRegistries, maybeRegistries) {
|
|
852
|
+
const { adapter: primaryAdapter, factory: adapterFactory } = resolveAdapter(adapterOrFactory);
|
|
853
|
+
let workflowId;
|
|
854
|
+
let options;
|
|
855
|
+
let registries;
|
|
856
|
+
let invocationHandoff;
|
|
857
|
+
if (typeof workflowIdOrInvocation === "string") {
|
|
858
|
+
workflowId = workflowIdOrInvocation;
|
|
859
|
+
options = optionsOrRegistries;
|
|
860
|
+
registries = maybeRegistries;
|
|
861
|
+
} else {
|
|
862
|
+
const resolved = resolveInvocation(workflowIdOrInvocation);
|
|
863
|
+
workflowId = resolved.workflowId;
|
|
864
|
+
options = resolved.options;
|
|
865
|
+
registries = optionsOrRegistries;
|
|
866
|
+
invocationHandoff = workflowIdOrInvocation.handoff;
|
|
867
|
+
}
|
|
868
|
+
if (invocationHandoff && registries?.handoffSchemas) {
|
|
869
|
+
const inputSchema = registries.handoffSchemas[invocationHandoff.type];
|
|
870
|
+
if (inputSchema) {
|
|
871
|
+
const validation = inputSchema.safeParse(invocationHandoff.payload);
|
|
872
|
+
if (!validation.success) {
|
|
873
|
+
return {
|
|
874
|
+
workflow_id: workflowId,
|
|
875
|
+
status: "error",
|
|
876
|
+
steps: [],
|
|
877
|
+
total_elapsed_ms: 0,
|
|
878
|
+
error_message: `Input handoff validation failed for "${invocationHandoff.type}": ${validation.error.message}`
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
const wfReg = registries?.workflowRegistry ?? {};
|
|
884
|
+
const workflow = wfReg[workflowId];
|
|
885
|
+
if (!workflow) {
|
|
886
|
+
return {
|
|
887
|
+
workflow_id: workflowId,
|
|
888
|
+
status: "error",
|
|
889
|
+
steps: [],
|
|
890
|
+
total_elapsed_ms: 0,
|
|
891
|
+
error_message: `Unknown workflow: ${workflowId}`
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
await pluginRegistry.runBeforeWorkflow(workflowId, options.user_request);
|
|
895
|
+
const sessionEnvelope = createExecutionEnvelope({ componentId: workflowId });
|
|
896
|
+
const sessionSpanId = emitSessionOpen(options.observer, sessionEnvelope, workflowId);
|
|
897
|
+
const workflowStart = Date.now();
|
|
898
|
+
const stepId = (i) => {
|
|
899
|
+
const s = workflow.steps[i];
|
|
900
|
+
return s.type === "delegate" ? s.task : `gate:${s.gate_kind}`;
|
|
901
|
+
};
|
|
902
|
+
const depsByIndex = workflow.steps.map((step, i) => {
|
|
903
|
+
if (step.depends_on !== void 0) {
|
|
904
|
+
return step.depends_on.map((dep) => {
|
|
905
|
+
const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);
|
|
906
|
+
if (idx === -1) {
|
|
907
|
+
throw new Error(`depends_on "${dep}" in step ${i} (${stepId(i)}) not found among preceding steps`);
|
|
908
|
+
}
|
|
909
|
+
return idx;
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);
|
|
913
|
+
});
|
|
914
|
+
const completed = /* @__PURE__ */ new Set();
|
|
915
|
+
const stepResults = new Array(workflow.steps.length);
|
|
916
|
+
const stepContexts = new Array(workflow.steps.length).fill("");
|
|
917
|
+
let abortResult;
|
|
918
|
+
function contextFor(stepIndex) {
|
|
919
|
+
const deps = depsByIndex[stepIndex];
|
|
920
|
+
if (deps.length === 0) return "";
|
|
921
|
+
return deps.filter((d) => completed.has(d)).map((d) => stepContexts[d]).filter(Boolean).join("");
|
|
922
|
+
}
|
|
923
|
+
async function executeStep(i, stepAdapter) {
|
|
924
|
+
const step = workflow.steps[i];
|
|
925
|
+
const stepStart = Date.now();
|
|
926
|
+
if (step.type === "gate") {
|
|
927
|
+
return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);
|
|
928
|
+
}
|
|
929
|
+
if (step.optional) {
|
|
930
|
+
const ctx = { user_request: options.user_request, prior_context: contextFor(i), variables: options.variables };
|
|
931
|
+
const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
|
|
932
|
+
if (!shouldRun) {
|
|
933
|
+
return {
|
|
934
|
+
step_index: i,
|
|
935
|
+
task_id: step.task,
|
|
936
|
+
outcome: { status: "skipped" },
|
|
937
|
+
follow_ups_used: 0,
|
|
938
|
+
retries_used: 0,
|
|
939
|
+
elapsed_ms: Date.now() - stepStart
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
const context = {
|
|
944
|
+
user_request: options.user_request,
|
|
945
|
+
prior_context: contextFor(i),
|
|
946
|
+
variables: options.variables,
|
|
947
|
+
...invocationHandoff ? { handoff_input: invocationHandoff } : {}
|
|
948
|
+
};
|
|
949
|
+
const taskResult = await runTask(stepAdapter, step.task, context, {
|
|
950
|
+
maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,
|
|
951
|
+
maxRetries: options.maxRetries ?? step.max_retries ?? 0,
|
|
952
|
+
taskRegistry: registries?.taskRegistry,
|
|
953
|
+
agentRegistry: registries?.agentRegistry,
|
|
954
|
+
handoffSchemas: registries?.handoffSchemas,
|
|
955
|
+
retry: step.retry,
|
|
956
|
+
progressOutput: options.progressOutput,
|
|
957
|
+
// ── Phase 1-2: Observer Bridge ────────────────────────────────────────
|
|
958
|
+
// Thread observer and session span ID so task-runner can emit agent.subagent
|
|
959
|
+
// spans correlated to this session (parent_run_id → parentSpanId).
|
|
960
|
+
observer: options.observer,
|
|
961
|
+
parentSpanId: sessionSpanId
|
|
962
|
+
});
|
|
963
|
+
return {
|
|
964
|
+
step_index: i,
|
|
965
|
+
task_id: step.task,
|
|
966
|
+
outcome: taskResult.outcome,
|
|
967
|
+
follow_ups_used: taskResult.follow_ups_used,
|
|
968
|
+
retries_used: taskResult.retries_used,
|
|
969
|
+
elapsed_ms: Date.now() - stepStart
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
while (completed.size < workflow.steps.length) {
|
|
973
|
+
const ready = [];
|
|
974
|
+
for (let i = 0; i < workflow.steps.length; i++) {
|
|
975
|
+
if (completed.has(i)) continue;
|
|
976
|
+
if (depsByIndex[i].every((d) => completed.has(d))) {
|
|
977
|
+
ready.push(i);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (ready.length === 0) {
|
|
981
|
+
abortResult = {
|
|
982
|
+
workflow_id: workflow.id,
|
|
983
|
+
status: "error",
|
|
984
|
+
steps: stepResults.filter(Boolean),
|
|
985
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
986
|
+
error_message: "Dependency cycle detected: no steps are ready to execute"
|
|
987
|
+
};
|
|
988
|
+
break;
|
|
989
|
+
}
|
|
990
|
+
const batchResults = await Promise.all(ready.map(async (i) => {
|
|
991
|
+
const step = workflow.steps[i];
|
|
992
|
+
const modelClass = step.type === "delegate" ? registries?.taskRegistry?.[step.task]?.model_class : void 0;
|
|
993
|
+
let stepAdapter;
|
|
994
|
+
if (ready.length > 1 && adapterFactory) {
|
|
995
|
+
const result = adapterFactory(modelClass);
|
|
996
|
+
stepAdapter = result && typeof result.then === "function" ? await result : result;
|
|
997
|
+
} else if (modelClass && adapterFactory) {
|
|
998
|
+
const result = adapterFactory(modelClass);
|
|
999
|
+
stepAdapter = result && typeof result.then === "function" ? await result : result;
|
|
1000
|
+
} else {
|
|
1001
|
+
stepAdapter = primaryAdapter;
|
|
1002
|
+
}
|
|
1003
|
+
return executeStep(i, stepAdapter);
|
|
1004
|
+
}));
|
|
1005
|
+
for (let b = 0; b < ready.length; b++) {
|
|
1006
|
+
const i = ready[b];
|
|
1007
|
+
const result = batchResults[b];
|
|
1008
|
+
const step = workflow.steps[i];
|
|
1009
|
+
stepResults[i] = result;
|
|
1010
|
+
completed.add(i);
|
|
1011
|
+
emitStepEvent(options, workflow.id, i, step, result);
|
|
1012
|
+
if (result.outcome.status === "success") {
|
|
1013
|
+
const data = result.outcome.data;
|
|
1014
|
+
stepContexts[i] = `
|
|
1015
|
+
|
|
1016
|
+
--- Step ${i + 1}: ${stepId(i)} ---
|
|
1017
|
+
` + (typeof data === "string" ? data : JSON.stringify(data, null, 2));
|
|
1018
|
+
}
|
|
1019
|
+
if (result.outcome.status === "gate_rejected") {
|
|
1020
|
+
abortResult = {
|
|
1021
|
+
workflow_id: workflow.id,
|
|
1022
|
+
status: "gate_rejected",
|
|
1023
|
+
steps: stepResults.filter(Boolean),
|
|
1024
|
+
total_elapsed_ms: Date.now() - workflowStart
|
|
1025
|
+
};
|
|
1026
|
+
} else if (result.outcome.status === "escalation") {
|
|
1027
|
+
abortResult = {
|
|
1028
|
+
workflow_id: workflow.id,
|
|
1029
|
+
status: "escalated",
|
|
1030
|
+
steps: stepResults.filter(Boolean),
|
|
1031
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
1032
|
+
escalation_reason: result.outcome.reason
|
|
1033
|
+
};
|
|
1034
|
+
} else if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
|
|
1035
|
+
const taskId = step.type === "delegate" ? step.task : step.gate_kind;
|
|
1036
|
+
abortResult = {
|
|
1037
|
+
workflow_id: workflow.id,
|
|
1038
|
+
status: "escalated",
|
|
1039
|
+
steps: stepResults.filter(Boolean),
|
|
1040
|
+
total_elapsed_ms: Date.now() - workflowStart,
|
|
1041
|
+
escalation_reason: `Task "${taskId}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
if (abortResult) break;
|
|
1046
|
+
}
|
|
1047
|
+
const wfResult = abortResult ?? {
|
|
1048
|
+
workflow_id: workflow.id,
|
|
1049
|
+
status: "completed",
|
|
1050
|
+
steps: stepResults.filter(Boolean),
|
|
1051
|
+
total_elapsed_ms: Date.now() - workflowStart
|
|
1052
|
+
};
|
|
1053
|
+
await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
|
|
1054
|
+
if (sessionSpanId) {
|
|
1055
|
+
sessionEnvelope.execution_metadata = { duration_ms: wfResult.total_elapsed_ms };
|
|
1056
|
+
emitSessionClose(
|
|
1057
|
+
options.observer,
|
|
1058
|
+
sessionSpanId,
|
|
1059
|
+
sessionEnvelope,
|
|
1060
|
+
wfResult.total_elapsed_ms,
|
|
1061
|
+
wfResult.status
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
return wfResult;
|
|
1065
|
+
}
|
|
1066
|
+
async function handleGateStep(step, priorResults, options, stepIndex, adapter) {
|
|
1067
|
+
const start = Date.now();
|
|
1068
|
+
if (options.onGate) {
|
|
1069
|
+
const approved = await options.onGate(step.gate_kind, step.description, priorResults);
|
|
1070
|
+
return {
|
|
1071
|
+
step_index: stepIndex,
|
|
1072
|
+
gate_kind: step.gate_kind,
|
|
1073
|
+
outcome: { status: approved ? "gate_approved" : "gate_rejected" },
|
|
1074
|
+
follow_ups_used: 0,
|
|
1075
|
+
retries_used: 0,
|
|
1076
|
+
elapsed_ms: Date.now() - start
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
if (adapter && step.description) {
|
|
1080
|
+
const approved = await evaluateGateWithLlm(adapter, step, priorResults);
|
|
1081
|
+
return {
|
|
1082
|
+
step_index: stepIndex,
|
|
1083
|
+
gate_kind: step.gate_kind,
|
|
1084
|
+
outcome: { status: approved ? "gate_approved" : "gate_rejected" },
|
|
1085
|
+
follow_ups_used: 0,
|
|
1086
|
+
retries_used: 0,
|
|
1087
|
+
elapsed_ms: Date.now() - start
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
return {
|
|
1091
|
+
step_index: stepIndex,
|
|
1092
|
+
gate_kind: step.gate_kind,
|
|
1093
|
+
outcome: { status: "gate_approved" },
|
|
1094
|
+
follow_ups_used: 0,
|
|
1095
|
+
retries_used: 0,
|
|
1096
|
+
elapsed_ms: Date.now() - start
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
async function evaluateGateWithLlm(adapter, step, priorResults) {
|
|
1100
|
+
const priorContext = priorResults.map((r) => {
|
|
1101
|
+
const id = r.task_id ?? r.gate_kind ?? `step_${r.step_index}`;
|
|
1102
|
+
const data = "data" in r.outcome ? r.outcome.data : void 0;
|
|
1103
|
+
return `- ${id}: status=${r.outcome.status}${data ? `, data=${typeof data === "string" ? data : JSON.stringify(data)}` : ""}`;
|
|
1104
|
+
}).join("\n");
|
|
1105
|
+
const prompt = buildGateEvaluationPrompt(step, priorContext);
|
|
1106
|
+
try {
|
|
1107
|
+
const response = await adapter.send(prompt, { readonly: true });
|
|
1108
|
+
return parseGateEvaluationResponse(response);
|
|
1109
|
+
} catch {
|
|
1110
|
+
return false;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
function buildGateEvaluationPrompt(step, priorContext) {
|
|
1114
|
+
return `You are a gate evaluator in a workflow pipeline. Your job is to decide whether the workflow should proceed based on prior step results.
|
|
1115
|
+
|
|
1116
|
+
## Gate
|
|
1117
|
+
- kind: ${step.gate_kind}
|
|
1118
|
+
- condition: ${step.description}
|
|
1119
|
+
|
|
1120
|
+
## Prior Step Results
|
|
1121
|
+
${priorContext || "(no prior results)"}
|
|
1122
|
+
|
|
1123
|
+
## Instructions
|
|
1124
|
+
Evaluate whether the gate condition is satisfied based on the prior step results.
|
|
1125
|
+
Respond with ONLY a JSON object (no markdown fences, no extra text):
|
|
1126
|
+
|
|
1127
|
+
{"approved": true, "reason": "brief explanation"}
|
|
1128
|
+
|
|
1129
|
+
or
|
|
1130
|
+
|
|
1131
|
+
{"approved": false, "reason": "brief explanation"}`;
|
|
1132
|
+
}
|
|
1133
|
+
function parseGateEvaluationResponse(response) {
|
|
1134
|
+
const jsonMatch = response.match(/\{[\s\S]*?"approved"\s*:\s*(true|false)[\s\S]*?\}/);
|
|
1135
|
+
if (jsonMatch) {
|
|
1136
|
+
try {
|
|
1137
|
+
const parsed = JSON.parse(jsonMatch[0]);
|
|
1138
|
+
return parsed.approved === true;
|
|
1139
|
+
} catch {
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
const lower = response.toLowerCase();
|
|
1143
|
+
if (lower.includes('"approved": true') || lower.includes('"approved":true')) {
|
|
1144
|
+
return true;
|
|
1145
|
+
}
|
|
1146
|
+
if (lower.includes('"approved": false') || lower.includes('"approved":false')) {
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
return false;
|
|
1150
|
+
}
|
|
1151
|
+
function emitStepEvent(options, workflowId, stepIndex, step, result) {
|
|
1152
|
+
options.onStepComplete?.({
|
|
1153
|
+
workflow_id: workflowId,
|
|
1154
|
+
step_index: stepIndex,
|
|
1155
|
+
step_type: step.type,
|
|
1156
|
+
task_id: step.type === "delegate" ? step.task : void 0,
|
|
1157
|
+
gate_kind: step.type === "gate" ? step.gate_kind : void 0,
|
|
1158
|
+
outcome_status: result.outcome.status,
|
|
1159
|
+
follow_ups_used: result.follow_ups_used,
|
|
1160
|
+
retries_used: result.retries_used,
|
|
1161
|
+
elapsed_ms: result.elapsed_ms
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// src/lib/bound-resolver.ts
|
|
1166
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
1167
|
+
import YAML2 from "yaml";
|
|
1168
|
+
|
|
1169
|
+
// src/lib/dsl-context.ts
|
|
1170
|
+
import { readFile } from "fs/promises";
|
|
1171
|
+
import YAML from "yaml";
|
|
1172
|
+
|
|
1173
|
+
// src/lib/schema-converter.ts
|
|
1174
|
+
import { z as z2 } from "zod";
|
|
1175
|
+
function applyStringValidations(schema, def) {
|
|
1176
|
+
let s = schema;
|
|
1177
|
+
if (typeof def.minLength === "number") s = s.min(def.minLength);
|
|
1178
|
+
if (typeof def.maxLength === "number") s = s.max(def.maxLength);
|
|
1179
|
+
if (typeof def.pattern === "string") s = s.regex(new RegExp(def.pattern));
|
|
1180
|
+
return s;
|
|
1181
|
+
}
|
|
1182
|
+
function applyNumberValidations(schema, def, isInteger) {
|
|
1183
|
+
let n = schema;
|
|
1184
|
+
if (isInteger) n = n.int();
|
|
1185
|
+
if (typeof def.minimum === "number") n = n.min(def.minimum);
|
|
1186
|
+
if (typeof def.maximum === "number") n = n.max(def.maximum);
|
|
1187
|
+
return n;
|
|
1188
|
+
}
|
|
1189
|
+
function applyArrayValidations(schema, def) {
|
|
1190
|
+
let a = schema;
|
|
1191
|
+
if (typeof def.minItems === "number") a = a.min(def.minItems);
|
|
1192
|
+
if (typeof def.maxItems === "number") a = a.max(def.maxItems);
|
|
1193
|
+
return a;
|
|
1194
|
+
}
|
|
1195
|
+
function jsonSchemaToZod(schema) {
|
|
1196
|
+
if (!schema || typeof schema !== "object") return z2.unknown();
|
|
1197
|
+
if (schema.enum) {
|
|
1198
|
+
const vals = schema.enum;
|
|
1199
|
+
if (vals.length === 0) return z2.unknown();
|
|
1200
|
+
return z2.enum(vals);
|
|
1201
|
+
}
|
|
1202
|
+
if (schema.const !== void 0) {
|
|
1203
|
+
const val = schema.const;
|
|
1204
|
+
if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
|
|
1205
|
+
return z2.literal(val);
|
|
1206
|
+
}
|
|
1207
|
+
return z2.unknown();
|
|
1208
|
+
}
|
|
1209
|
+
const type = schema.type;
|
|
1210
|
+
if (type === "string") return applyStringValidations(z2.string(), schema);
|
|
1211
|
+
if (type === "integer") return applyNumberValidations(z2.number(), schema, true);
|
|
1212
|
+
if (type === "number") return applyNumberValidations(z2.number(), schema, false);
|
|
1213
|
+
if (type === "boolean") return z2.boolean();
|
|
1214
|
+
if (type === "array") {
|
|
1215
|
+
const items = schema.items;
|
|
1216
|
+
const inner = items ? jsonSchemaToZod(items) : z2.unknown();
|
|
1217
|
+
return applyArrayValidations(z2.array(inner), schema);
|
|
1218
|
+
}
|
|
1219
|
+
if (type === "object") {
|
|
1220
|
+
const props = schema.properties;
|
|
1221
|
+
if (!props) return z2.record(z2.string(), z2.unknown());
|
|
1222
|
+
const required = new Set(schema.required ?? []);
|
|
1223
|
+
const shape = {};
|
|
1224
|
+
for (const [key, val] of Object.entries(props)) {
|
|
1225
|
+
const fieldSchema = jsonSchemaToZod(val);
|
|
1226
|
+
shape[key] = required.has(key) ? fieldSchema : fieldSchema.optional();
|
|
1227
|
+
}
|
|
1228
|
+
return z2.object(shape).passthrough();
|
|
1229
|
+
}
|
|
1230
|
+
if (schema.allOf) {
|
|
1231
|
+
const parts = schema.allOf.map(jsonSchemaToZod);
|
|
1232
|
+
if (parts.length === 0) return z2.unknown();
|
|
1233
|
+
if (parts.length === 1) return parts[0];
|
|
1234
|
+
let merged = parts[0];
|
|
1235
|
+
for (let i = 1; i < parts.length; i++) {
|
|
1236
|
+
const part = parts[i];
|
|
1237
|
+
if (merged instanceof z2.ZodObject && part instanceof z2.ZodObject) {
|
|
1238
|
+
merged = merged.merge(part);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
return merged;
|
|
1242
|
+
}
|
|
1243
|
+
return z2.unknown();
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
// src/lib/dsl-context.ts
|
|
1247
|
+
var DslValidationError = class extends Error {
|
|
1248
|
+
missing;
|
|
1249
|
+
constructor(missing) {
|
|
1250
|
+
super(
|
|
1251
|
+
"Required entities missing after DSL merge:\n" + missing.map((m) => ` - ${m}`).join("\n")
|
|
1252
|
+
);
|
|
1253
|
+
this.name = "DslValidationError";
|
|
1254
|
+
this.missing = missing;
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
function buildAgentRegistry(agents) {
|
|
1258
|
+
const registry = {};
|
|
1259
|
+
for (const [id, agent] of Object.entries(agents)) {
|
|
1260
|
+
const rawMode = agent.mode ?? "read-only";
|
|
1261
|
+
const mode = rawMode === "read-write" ? "read-write" : "read-only";
|
|
1262
|
+
registry[id] = {
|
|
1263
|
+
id,
|
|
1264
|
+
role_name: agent.role_name ?? id,
|
|
1265
|
+
purpose: agent.purpose ?? "",
|
|
1266
|
+
mode,
|
|
1267
|
+
responsibilities: agent.responsibilities ?? [],
|
|
1268
|
+
constraints: agent.constraints ?? [],
|
|
1269
|
+
rules: agent.rules ?? [],
|
|
1270
|
+
can_invoke_agents: agent.can_invoke_agents ?? void 0,
|
|
1271
|
+
can_execute_tools: agent.can_execute_tools ?? void 0
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
return registry;
|
|
1275
|
+
}
|
|
1276
|
+
function buildTaskRegistry(tasks) {
|
|
1277
|
+
const registry = {};
|
|
1278
|
+
for (const [id, task] of Object.entries(tasks)) {
|
|
1279
|
+
registry[id] = {
|
|
1280
|
+
id,
|
|
1281
|
+
description: task.description ?? "",
|
|
1282
|
+
target_agent: task.target_agent ?? "",
|
|
1283
|
+
result_handoff: task.result_handoff ?? "",
|
|
1284
|
+
completion_criteria: task.completion_criteria ?? [],
|
|
1285
|
+
model_class: task.model_class
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
return registry;
|
|
1289
|
+
}
|
|
1290
|
+
function buildWorkflowStep(step) {
|
|
1291
|
+
if (step.type === "gate") {
|
|
1292
|
+
return {
|
|
1293
|
+
type: "gate",
|
|
1294
|
+
gate_kind: step.gate_kind ?? "",
|
|
1295
|
+
description: step.description ?? "",
|
|
1296
|
+
depends_on: step.depends_on
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
return {
|
|
1300
|
+
type: "delegate",
|
|
1301
|
+
task: step.task ?? "",
|
|
1302
|
+
from_agent: step.from_agent ?? "",
|
|
1303
|
+
description: step.description ?? "",
|
|
1304
|
+
optional: step.optional ?? false,
|
|
1305
|
+
max_retries: step.max_retries ?? 0,
|
|
1306
|
+
max_follow_ups: step.max_follow_ups,
|
|
1307
|
+
depends_on: step.depends_on,
|
|
1308
|
+
retry: step.retry
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
function buildWorkflowRegistry(workflows) {
|
|
1312
|
+
const registry = {};
|
|
1313
|
+
for (const [id, wf] of Object.entries(workflows)) {
|
|
1314
|
+
const steps = (wf.steps ?? []).map(buildWorkflowStep);
|
|
1315
|
+
registry[id] = { id, description: wf.description ?? "", steps };
|
|
1316
|
+
}
|
|
1317
|
+
return registry;
|
|
1318
|
+
}
|
|
1319
|
+
function buildHandoffSchemas(handoffTypes) {
|
|
1320
|
+
const schemas = {};
|
|
1321
|
+
for (const [id, ht] of Object.entries(handoffTypes)) {
|
|
1322
|
+
const schema = ht.schema;
|
|
1323
|
+
if (schema) {
|
|
1324
|
+
schemas[id] = jsonSchemaToZod(schema);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
return schemas;
|
|
1328
|
+
}
|
|
1329
|
+
function buildGuardrailRulesFromDsl(dsl) {
|
|
1330
|
+
const raw = dsl._guardrailRules;
|
|
1331
|
+
if (!raw) return void 0;
|
|
1332
|
+
return {
|
|
1333
|
+
commandRules: raw.commandRules ?? [],
|
|
1334
|
+
fileRules: raw.fileRules ?? [],
|
|
1335
|
+
contentRules: raw.contentRules ?? []
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
function buildRegistriesFromDsl(dsl) {
|
|
1339
|
+
const agents = dsl.agents ?? {};
|
|
1340
|
+
const tasks = dsl.tasks ?? {};
|
|
1341
|
+
const workflows = dsl.workflow ?? {};
|
|
1342
|
+
const handoffTypes = dsl.handoff_types ?? {};
|
|
1343
|
+
return {
|
|
1344
|
+
agentRegistry: buildAgentRegistry(agents),
|
|
1345
|
+
taskRegistry: buildTaskRegistry(tasks),
|
|
1346
|
+
workflowRegistry: buildWorkflowRegistry(workflows),
|
|
1347
|
+
handoffSchemas: buildHandoffSchemas(handoffTypes)
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
function validateRequiredEntities(dsl, required) {
|
|
1351
|
+
const missing = [];
|
|
1352
|
+
const workflows = dsl.workflow ?? {};
|
|
1353
|
+
const tasks = dsl.tasks ?? {};
|
|
1354
|
+
const handoffTypes = dsl.handoff_types ?? {};
|
|
1355
|
+
if (required.workflows) {
|
|
1356
|
+
for (const wfId of required.workflows) {
|
|
1357
|
+
if (!(wfId in workflows)) {
|
|
1358
|
+
missing.push(`workflow "${wfId}" is required by the CLI but not found in the resolved DSL`);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
if (required.tasks) {
|
|
1363
|
+
for (const taskId of required.tasks) {
|
|
1364
|
+
if (!(taskId in tasks)) {
|
|
1365
|
+
missing.push(`task "${taskId}" is required by the CLI but not found in the resolved DSL`);
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
const task = tasks[taskId];
|
|
1369
|
+
const invHandoff = task.invocation_handoff;
|
|
1370
|
+
const resHandoff = task.result_handoff;
|
|
1371
|
+
if (invHandoff && !(invHandoff in handoffTypes)) {
|
|
1372
|
+
missing.push(`handoff_type "${invHandoff}" (invocation_handoff of task "${taskId}") not found`);
|
|
1373
|
+
}
|
|
1374
|
+
if (resHandoff && !(resHandoff in handoffTypes)) {
|
|
1375
|
+
missing.push(`handoff_type "${resHandoff}" (result_handoff of task "${taskId}") not found`);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
if (required.workflows) {
|
|
1380
|
+
for (const wfId of required.workflows) {
|
|
1381
|
+
if (!(wfId in workflows)) continue;
|
|
1382
|
+
const wf = workflows[wfId];
|
|
1383
|
+
const steps = wf.steps ?? [];
|
|
1384
|
+
for (const step of steps) {
|
|
1385
|
+
if (step.type !== "delegate") continue;
|
|
1386
|
+
const taskId = step.task;
|
|
1387
|
+
if (taskId && taskId in tasks) {
|
|
1388
|
+
const task = tasks[taskId];
|
|
1389
|
+
const resHandoff = task.result_handoff;
|
|
1390
|
+
if (resHandoff && !(resHandoff in handoffTypes)) {
|
|
1391
|
+
missing.push(`handoff_type "${resHandoff}" (result of task "${taskId}" in workflow "${wfId}") not found`);
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
if (missing.length > 0) {
|
|
1398
|
+
throw new DslValidationError(missing);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
async function loadDslContext(options) {
|
|
1402
|
+
let dsl;
|
|
1403
|
+
if (options.projectDslPath) {
|
|
1404
|
+
const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
|
|
1405
|
+
const raw = await readFile(options.projectDslPath, "utf8");
|
|
1406
|
+
const projectData = YAML.parse(raw);
|
|
1407
|
+
if (projectData.extends === "/$embedded/") {
|
|
1408
|
+
const { extends: _extends, ...projectOverrides } = projectData;
|
|
1409
|
+
const merged = mergeDsl(options.embeddedDsl, projectOverrides);
|
|
1410
|
+
dsl = expandDefaults(merged);
|
|
1411
|
+
} else {
|
|
1412
|
+
const projectResult = await resolveDsl(options.projectDslPath);
|
|
1413
|
+
const merged = mergeDsl(options.embeddedDsl, projectResult.data);
|
|
1414
|
+
dsl = expandDefaults(merged);
|
|
1415
|
+
}
|
|
1416
|
+
} else {
|
|
1417
|
+
dsl = options.embeddedDsl;
|
|
1418
|
+
}
|
|
1419
|
+
if (options.requiredEntities) {
|
|
1420
|
+
validateRequiredEntities(dsl, options.requiredEntities);
|
|
1421
|
+
}
|
|
1422
|
+
const registries = buildRegistriesFromDsl(dsl);
|
|
1423
|
+
const guardrailRules = buildGuardrailRulesFromDsl(dsl);
|
|
1424
|
+
return { registries, dsl, guardrailRules };
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// src/lib/bound-resolver.ts
|
|
1428
|
+
function getEffectiveGuardrailIds(dsl, agentId) {
|
|
1429
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1430
|
+
const agents = dsl.agents ?? {};
|
|
1431
|
+
const agent = agents[agentId];
|
|
1432
|
+
if (agent) {
|
|
1433
|
+
for (const ref of agent.guardrails ?? []) {
|
|
1434
|
+
ids.add(ref);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
const guardrails = dsl.guardrails ?? {};
|
|
1438
|
+
for (const [guardrailId, guardrail] of Object.entries(guardrails)) {
|
|
1439
|
+
if (guardrail.scope?.agents?.includes(agentId)) {
|
|
1440
|
+
ids.add(guardrailId);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return ids;
|
|
1444
|
+
}
|
|
1445
|
+
function guardrailCheckToCommandRule(c) {
|
|
1446
|
+
return {
|
|
1447
|
+
guardrail_id: c.guardrail_id,
|
|
1448
|
+
pattern: c.pattern,
|
|
1449
|
+
action: c.action,
|
|
1450
|
+
message: c.message
|
|
1451
|
+
};
|
|
1452
|
+
}
|
|
1453
|
+
function guardrailCheckToFileRule(c) {
|
|
1454
|
+
return {
|
|
1455
|
+
guardrail_id: c.guardrail_id,
|
|
1456
|
+
pattern: c.pattern,
|
|
1457
|
+
action: c.action,
|
|
1458
|
+
message: c.message,
|
|
1459
|
+
...c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
function guardrailCheckToContentRule(c) {
|
|
1463
|
+
return {
|
|
1464
|
+
guardrail_id: c.guardrail_id,
|
|
1465
|
+
pattern: c.pattern,
|
|
1466
|
+
action: c.action,
|
|
1467
|
+
message: c.message,
|
|
1468
|
+
...c.file_glob ? { file_glob: c.file_glob } : {},
|
|
1469
|
+
...c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
function guardrailContextToRuleData(ctx, effectiveIds) {
|
|
1473
|
+
const filter = (checks) => effectiveIds ? checks.filter((c) => effectiveIds.has(c.guardrail_id)) : checks;
|
|
1474
|
+
return {
|
|
1475
|
+
commandRules: filter(ctx.commandChecks).map(guardrailCheckToCommandRule),
|
|
1476
|
+
fileRules: filter(ctx.fileChecks).map(guardrailCheckToFileRule),
|
|
1477
|
+
contentRules: filter(ctx.contentChecks).map(guardrailCheckToContentRule)
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
function buildPerAgentGuardrails(dsl, guardrailCtx) {
|
|
1481
|
+
const perAgent = /* @__PURE__ */ new Map();
|
|
1482
|
+
const agents = dsl.agents ?? {};
|
|
1483
|
+
for (const agentId of Object.keys(agents)) {
|
|
1484
|
+
const effectiveIds = getEffectiveGuardrailIds(dsl, agentId);
|
|
1485
|
+
const rules = guardrailContextToRuleData(guardrailCtx, effectiveIds);
|
|
1486
|
+
if (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0) {
|
|
1487
|
+
perAgent.set(agentId, rules);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
return perAgent;
|
|
1491
|
+
}
|
|
1492
|
+
function hasGuardrailRules(rules) {
|
|
1493
|
+
return rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0;
|
|
1494
|
+
}
|
|
1495
|
+
var BoundResolver = class {
|
|
1496
|
+
cache = /* @__PURE__ */ new Map();
|
|
1497
|
+
/**
|
|
1498
|
+
* Resolve binding + policy in one pass. Results are cached by component id.
|
|
1499
|
+
*/
|
|
1500
|
+
async resolve(opts) {
|
|
1501
|
+
const cached = this.cache.get(opts.id);
|
|
1502
|
+
if (cached) return cached;
|
|
1503
|
+
const diagnostics = [];
|
|
1504
|
+
let dsl;
|
|
1505
|
+
if (opts.embeddedDsl) {
|
|
1506
|
+
dsl = opts.embeddedDsl;
|
|
1507
|
+
} else if (opts.dslPath) {
|
|
1508
|
+
const { resolve: resolveDsl } = await import("agent-contracts");
|
|
1509
|
+
const result = await resolveDsl(opts.dslPath);
|
|
1510
|
+
dsl = result.data;
|
|
1511
|
+
} else {
|
|
1512
|
+
throw new Error("BoundResolver.resolve requires embeddedDsl or dslPath");
|
|
1513
|
+
}
|
|
1514
|
+
if (opts.artifactBinding) {
|
|
1515
|
+
const { resolveBound } = await import("agent-contracts");
|
|
1516
|
+
const boundResult = await resolveBound(dsl, {
|
|
1517
|
+
artifactBinding: opts.artifactBinding,
|
|
1518
|
+
paths: opts.paths
|
|
1519
|
+
});
|
|
1520
|
+
dsl = boundResult.data;
|
|
1521
|
+
for (const d of boundResult.diagnostics) {
|
|
1522
|
+
diagnostics.push({
|
|
1523
|
+
path: d.rule,
|
|
1524
|
+
message: d.message,
|
|
1525
|
+
severity: d.severity
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
let guardrailCtx = {
|
|
1530
|
+
commandChecks: [],
|
|
1531
|
+
fileChecks: [],
|
|
1532
|
+
contentChecks: [],
|
|
1533
|
+
allChecks: [],
|
|
1534
|
+
hasGuardrails: false
|
|
1535
|
+
};
|
|
1536
|
+
if (opts.bindingPaths && opts.bindingPaths.length > 0) {
|
|
1537
|
+
for (const bindingPath of opts.bindingPaths) {
|
|
1538
|
+
const raw = await readFile2(bindingPath, "utf8");
|
|
1539
|
+
const binding = YAML2.parse(raw);
|
|
1540
|
+
guardrailCtx = buildGuardrailContext(
|
|
1541
|
+
dsl,
|
|
1542
|
+
binding,
|
|
1543
|
+
opts.activeGuardrailPolicy
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
const perAgent = guardrailCtx.hasGuardrails ? buildPerAgentGuardrails(dsl, guardrailCtx) : /* @__PURE__ */ new Map();
|
|
1548
|
+
const component = {
|
|
1549
|
+
id: opts.id,
|
|
1550
|
+
dsl,
|
|
1551
|
+
registries: buildRegistriesFromDsl(dsl),
|
|
1552
|
+
guardrails: { perAgent },
|
|
1553
|
+
diagnostics
|
|
1554
|
+
};
|
|
1555
|
+
this.cache.set(opts.id, component);
|
|
1556
|
+
return component;
|
|
1557
|
+
}
|
|
1558
|
+
/** Clear cached components (e.g. for testing). */
|
|
1559
|
+
clearCache() {
|
|
1560
|
+
this.cache.clear();
|
|
1561
|
+
}
|
|
1562
|
+
};
|
|
1563
|
+
function getGuardrailRulesForAgent(component, agentId, fallbackDsl) {
|
|
1564
|
+
const perAgent = component.guardrails.perAgent.get(agentId);
|
|
1565
|
+
if (perAgent && hasGuardrailRules(perAgent)) {
|
|
1566
|
+
return perAgent;
|
|
1567
|
+
}
|
|
1568
|
+
if (fallbackDsl) {
|
|
1569
|
+
const raw = fallbackDsl._guardrailRules;
|
|
1570
|
+
if (raw) {
|
|
1571
|
+
return {
|
|
1572
|
+
commandRules: raw.commandRules ?? [],
|
|
1573
|
+
fileRules: raw.fileRules ?? [],
|
|
1574
|
+
contentRules: raw.contentRules ?? []
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
return void 0;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// src/lib/builder.ts
|
|
1582
|
+
function createRuntime(config) {
|
|
1583
|
+
return {
|
|
1584
|
+
workflow(workflowId) {
|
|
1585
|
+
return new WorkflowBuilder(config.adapter, workflowId, config.registries);
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
var WorkflowBuilder = class {
|
|
1590
|
+
adapter;
|
|
1591
|
+
invocation;
|
|
1592
|
+
registries;
|
|
1593
|
+
constructor(adapter, workflowId, registries) {
|
|
1594
|
+
this.adapter = adapter;
|
|
1595
|
+
this.invocation = { workflow: workflowId };
|
|
1596
|
+
this.registries = registries;
|
|
1597
|
+
}
|
|
1598
|
+
/** Set a typed handoff envelope as input. */
|
|
1599
|
+
handoff(input) {
|
|
1600
|
+
this.invocation = { ...this.invocation, handoff: input };
|
|
1601
|
+
return this;
|
|
1602
|
+
}
|
|
1603
|
+
/** Set a simple string request (convenience shorthand). */
|
|
1604
|
+
request(userRequest) {
|
|
1605
|
+
this.invocation = { ...this.invocation, user_request: userRequest };
|
|
1606
|
+
return this;
|
|
1607
|
+
}
|
|
1608
|
+
maxFollowUps(n) {
|
|
1609
|
+
this.invocation = {
|
|
1610
|
+
...this.invocation,
|
|
1611
|
+
runtime: { ...this.invocation.runtime, maxFollowUps: n }
|
|
1612
|
+
};
|
|
1613
|
+
return this;
|
|
1614
|
+
}
|
|
1615
|
+
maxRetries(n) {
|
|
1616
|
+
this.invocation = {
|
|
1617
|
+
...this.invocation,
|
|
1618
|
+
runtime: { ...this.invocation.runtime, maxRetries: n }
|
|
1619
|
+
};
|
|
1620
|
+
return this;
|
|
1621
|
+
}
|
|
1622
|
+
onStepComplete(cb) {
|
|
1623
|
+
this.invocation = {
|
|
1624
|
+
...this.invocation,
|
|
1625
|
+
hooks: { ...this.invocation.hooks, onStepComplete: cb }
|
|
1626
|
+
};
|
|
1627
|
+
return this;
|
|
1628
|
+
}
|
|
1629
|
+
onGate(cb) {
|
|
1630
|
+
this.invocation = {
|
|
1631
|
+
...this.invocation,
|
|
1632
|
+
hooks: { ...this.invocation.hooks, onGate: cb }
|
|
1633
|
+
};
|
|
1634
|
+
return this;
|
|
1635
|
+
}
|
|
1636
|
+
onOptionalStep(cb) {
|
|
1637
|
+
this.invocation = {
|
|
1638
|
+
...this.invocation,
|
|
1639
|
+
hooks: { ...this.invocation.hooks, onOptionalStep: cb }
|
|
1640
|
+
};
|
|
1641
|
+
return this;
|
|
1642
|
+
}
|
|
1643
|
+
/** Set progress output sink for real-time execution visibility. */
|
|
1644
|
+
progressOutput(sink) {
|
|
1645
|
+
this.invocation = { ...this.invocation, progressOutput: sink };
|
|
1646
|
+
return this;
|
|
1647
|
+
}
|
|
1648
|
+
async run() {
|
|
1649
|
+
return runWorkflow(this.adapter, this.invocation, this.registries);
|
|
1650
|
+
}
|
|
1651
|
+
};
|
|
1652
|
+
|
|
1653
|
+
// src/lib/plugin-loader.ts
|
|
1654
|
+
import { existsSync } from "fs";
|
|
1655
|
+
import { readdir } from "fs/promises";
|
|
1656
|
+
import { resolve, join } from "path";
|
|
1657
|
+
var PLUGIN_EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
|
|
1658
|
+
function isPluginLike(obj) {
|
|
1659
|
+
return typeof obj === "object" && obj !== null && typeof obj.id === "string";
|
|
1660
|
+
}
|
|
1661
|
+
async function scanDirectory(dir) {
|
|
1662
|
+
if (!existsSync(dir)) return [];
|
|
1663
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
1664
|
+
return entries.filter(
|
|
1665
|
+
(e) => e.isFile() && PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) && !e.name.startsWith("_") && !e.name.endsWith(".d.ts") && !e.name.endsWith(".test.ts") && !e.name.endsWith(".spec.ts")
|
|
1666
|
+
).map((e) => resolve(dir, e.name));
|
|
1667
|
+
}
|
|
1668
|
+
async function loadPluginModule(modulePath) {
|
|
1669
|
+
const mod = await import(new URL(`file://${modulePath}`).href);
|
|
1670
|
+
let count = 0;
|
|
1671
|
+
for (const exportValue of Object.values(mod)) {
|
|
1672
|
+
if (isPluginLike(exportValue)) {
|
|
1673
|
+
try {
|
|
1674
|
+
pluginRegistry.register(exportValue);
|
|
1675
|
+
count++;
|
|
1676
|
+
} catch {
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
return count;
|
|
1681
|
+
}
|
|
1682
|
+
async function loadPluginsFromPaths(paths, baseDir) {
|
|
1683
|
+
const result = { loaded: 0, files: [], errors: [] };
|
|
1684
|
+
for (const p of paths) {
|
|
1685
|
+
const absPath = resolve(baseDir, p);
|
|
1686
|
+
if (!existsSync(absPath)) {
|
|
1687
|
+
result.errors.push({ file: p, error: `File not found: ${absPath}` });
|
|
1688
|
+
continue;
|
|
1689
|
+
}
|
|
1690
|
+
try {
|
|
1691
|
+
const count = await loadPluginModule(absPath);
|
|
1692
|
+
result.loaded += count;
|
|
1693
|
+
result.files.push(absPath);
|
|
1694
|
+
} catch (err) {
|
|
1695
|
+
result.errors.push({
|
|
1696
|
+
file: p,
|
|
1697
|
+
error: err.message
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
return result;
|
|
1702
|
+
}
|
|
1703
|
+
async function loadPluginsFromDirectory(dir) {
|
|
1704
|
+
const result = { loaded: 0, files: [], errors: [] };
|
|
1705
|
+
const candidates = await scanDirectory(dir);
|
|
1706
|
+
for (const filePath of candidates) {
|
|
1707
|
+
try {
|
|
1708
|
+
const count = await loadPluginModule(filePath);
|
|
1709
|
+
result.loaded += count;
|
|
1710
|
+
result.files.push(filePath);
|
|
1711
|
+
} catch (err) {
|
|
1712
|
+
result.errors.push({
|
|
1713
|
+
file: filePath,
|
|
1714
|
+
error: err.message
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
return result;
|
|
1719
|
+
}
|
|
1720
|
+
async function loadPlugins(options) {
|
|
1721
|
+
if (options.pluginPaths && options.pluginPaths.length > 0) {
|
|
1722
|
+
return loadPluginsFromPaths(options.pluginPaths, options.projectDir);
|
|
1723
|
+
}
|
|
1724
|
+
const conventionDir = join(options.projectDir, "src", "plugins");
|
|
1725
|
+
return loadPluginsFromDirectory(conventionDir);
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
// src/lib/model-resolver.ts
|
|
1729
|
+
var ENV_PREFIX = "AGENT_RUNTIME_MODEL";
|
|
1730
|
+
var CLASS_ENV_KEYS = {
|
|
1731
|
+
fast: `${ENV_PREFIX}_FAST`,
|
|
1732
|
+
standard: `${ENV_PREFIX}_STANDARD`,
|
|
1733
|
+
thinking: `${ENV_PREFIX}_THINKING`
|
|
1734
|
+
};
|
|
1735
|
+
function parseEnvValue(value, fallbackAdapter) {
|
|
1736
|
+
const colonIdx = value.indexOf(":");
|
|
1737
|
+
if (colonIdx === -1) {
|
|
1738
|
+
return { adapter: fallbackAdapter, model: value || void 0 };
|
|
1739
|
+
}
|
|
1740
|
+
const adapter = value.slice(0, colonIdx) || fallbackAdapter;
|
|
1741
|
+
const model = value.slice(colonIdx + 1) || void 0;
|
|
1742
|
+
return { adapter, model };
|
|
1743
|
+
}
|
|
1744
|
+
function createModelResolver(options) {
|
|
1745
|
+
const env = options.env ?? process.env;
|
|
1746
|
+
return {
|
|
1747
|
+
resolve(modelClass) {
|
|
1748
|
+
const fallback = {
|
|
1749
|
+
adapter: options.fallbackAdapter,
|
|
1750
|
+
model: options.fallbackModel
|
|
1751
|
+
};
|
|
1752
|
+
if (!modelClass) return fallback;
|
|
1753
|
+
const classEnv = env[CLASS_ENV_KEYS[modelClass]];
|
|
1754
|
+
if (classEnv) {
|
|
1755
|
+
return parseEnvValue(classEnv, options.fallbackAdapter);
|
|
1756
|
+
}
|
|
1757
|
+
const catchAllEnv = env[ENV_PREFIX];
|
|
1758
|
+
if (catchAllEnv) {
|
|
1759
|
+
return parseEnvValue(catchAllEnv, options.fallbackAdapter);
|
|
1760
|
+
}
|
|
1761
|
+
const entry = options.modelMapping?.[modelClass];
|
|
1762
|
+
if (entry) {
|
|
1763
|
+
return { adapter: entry.adapter, model: entry.model };
|
|
1764
|
+
}
|
|
1765
|
+
return fallback;
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
// src/lib/progress-sink.ts
|
|
1771
|
+
import { openSync, writeSync, closeSync, mkdirSync } from "fs";
|
|
1772
|
+
import { dirname, join as join2, basename, extname } from "path";
|
|
1773
|
+
function resolveFilePath(base, naming, label) {
|
|
1774
|
+
if (naming === "single") return base;
|
|
1775
|
+
const dir = dirname(base);
|
|
1776
|
+
const ext = extname(base);
|
|
1777
|
+
const stem = basename(base, ext);
|
|
1778
|
+
const now = /* @__PURE__ */ new Date();
|
|
1779
|
+
if (naming === "daily") {
|
|
1780
|
+
const date = now.toISOString().slice(0, 10);
|
|
1781
|
+
return join2(dir, `${stem}-${date}${ext}`);
|
|
1782
|
+
}
|
|
1783
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1784
|
+
const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}T${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
1785
|
+
const suffix = label ? `-${label}` : "";
|
|
1786
|
+
return join2(dir, `${stem}-${ts}${suffix}${ext}`);
|
|
1787
|
+
}
|
|
1788
|
+
function createProgressSink(options) {
|
|
1789
|
+
const useStderr = options.stderr ?? false;
|
|
1790
|
+
let fd = null;
|
|
1791
|
+
let resolvedPath;
|
|
1792
|
+
if (options.file) {
|
|
1793
|
+
const naming = options.naming ?? "single";
|
|
1794
|
+
resolvedPath = resolveFilePath(options.file, naming, options.label);
|
|
1795
|
+
mkdirSync(dirname(resolvedPath), { recursive: true });
|
|
1796
|
+
fd = openSync(resolvedPath, "a");
|
|
1797
|
+
}
|
|
1798
|
+
if (!useStderr && fd === null) {
|
|
1799
|
+
return { write() {
|
|
1800
|
+
}, close() {
|
|
1801
|
+
} };
|
|
1802
|
+
}
|
|
1803
|
+
return {
|
|
1804
|
+
write(chunk) {
|
|
1805
|
+
if (useStderr) process.stderr.write(chunk);
|
|
1806
|
+
if (fd !== null) writeSync(fd, chunk);
|
|
1807
|
+
},
|
|
1808
|
+
close() {
|
|
1809
|
+
if (fd !== null) {
|
|
1810
|
+
closeSync(fd);
|
|
1811
|
+
fd = null;
|
|
1812
|
+
}
|
|
1813
|
+
},
|
|
1814
|
+
get filePath() {
|
|
1815
|
+
return resolvedPath;
|
|
1816
|
+
}
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// src/lib/memory-store.ts
|
|
1821
|
+
var InMemoryStore = class {
|
|
1822
|
+
data = /* @__PURE__ */ new Map();
|
|
1823
|
+
async save(ref, content) {
|
|
1824
|
+
this.data.set(ref.id, content);
|
|
1825
|
+
}
|
|
1826
|
+
async load(ref) {
|
|
1827
|
+
return this.data.get(ref.id) ?? null;
|
|
1828
|
+
}
|
|
1829
|
+
async delete(ref) {
|
|
1830
|
+
this.data.delete(ref.id);
|
|
1831
|
+
}
|
|
1832
|
+
};
|
|
1833
|
+
|
|
1834
|
+
// src/lib/file-memory-store.ts
|
|
1835
|
+
import { mkdir, readFile as readFile3, unlink, writeFile } from "fs/promises";
|
|
1836
|
+
import { join as join3 } from "path";
|
|
1837
|
+
function resolveFilePath2(baseDir, ref) {
|
|
1838
|
+
const runId = ref.parent_run_id ?? "unknown";
|
|
1839
|
+
return join3(baseDir, `${runId}_${ref.id}.json`);
|
|
1840
|
+
}
|
|
1841
|
+
var FileMemoryStore = class {
|
|
1842
|
+
baseDir;
|
|
1843
|
+
constructor(options) {
|
|
1844
|
+
this.baseDir = options?.baseDir ?? ".agent-logs/memories";
|
|
1845
|
+
}
|
|
1846
|
+
async save(ref, content) {
|
|
1847
|
+
await mkdir(this.baseDir, { recursive: true });
|
|
1848
|
+
const filePath = resolveFilePath2(this.baseDir, ref);
|
|
1849
|
+
await writeFile(filePath, JSON.stringify(content, null, 2), "utf-8");
|
|
1850
|
+
}
|
|
1851
|
+
async load(ref) {
|
|
1852
|
+
const filePath = resolveFilePath2(this.baseDir, ref);
|
|
1853
|
+
try {
|
|
1854
|
+
const raw = await readFile3(filePath, "utf-8");
|
|
1855
|
+
return JSON.parse(raw);
|
|
1856
|
+
} catch (error) {
|
|
1857
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1858
|
+
return null;
|
|
1859
|
+
}
|
|
1860
|
+
throw error;
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
async delete(ref) {
|
|
1864
|
+
const filePath = resolveFilePath2(this.baseDir, ref);
|
|
1865
|
+
try {
|
|
1866
|
+
await unlink(filePath);
|
|
1867
|
+
} catch (error) {
|
|
1868
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
throw error;
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
// src/lib/agent-log-writer.ts
|
|
1877
|
+
import { mkdir as mkdir2, readFile as readFile4, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
|
|
1878
|
+
import { join as join4 } from "path";
|
|
1879
|
+
var AgentLogWriter = class {
|
|
1880
|
+
baseDir;
|
|
1881
|
+
memoryStore;
|
|
1882
|
+
constructor(options) {
|
|
1883
|
+
this.baseDir = options?.baseDir ?? ".agent-logs";
|
|
1884
|
+
this.memoryStore = new FileMemoryStore({
|
|
1885
|
+
baseDir: join4(this.baseDir, "memories")
|
|
1886
|
+
});
|
|
1887
|
+
}
|
|
1888
|
+
getMemoryStore() {
|
|
1889
|
+
return this.memoryStore;
|
|
1890
|
+
}
|
|
1891
|
+
async writeRunEvent(runId, event) {
|
|
1892
|
+
const runsDir = join4(this.baseDir, "runs");
|
|
1893
|
+
await mkdir2(runsDir, { recursive: true });
|
|
1894
|
+
const filePath = join4(runsDir, `${runId}.jsonl`);
|
|
1895
|
+
await appendFile(filePath, `${JSON.stringify(event)}
|
|
1896
|
+
`, "utf-8");
|
|
1897
|
+
}
|
|
1898
|
+
async readRunLog(runId) {
|
|
1899
|
+
const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
|
|
1900
|
+
try {
|
|
1901
|
+
const raw = await readFile4(filePath, "utf-8");
|
|
1902
|
+
return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
|
|
1903
|
+
} catch (error) {
|
|
1904
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1905
|
+
return [];
|
|
1906
|
+
}
|
|
1907
|
+
throw error;
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
async writeHandoff(runId, step, data) {
|
|
1911
|
+
const handoffsDir = join4(this.baseDir, "handoffs");
|
|
1912
|
+
await mkdir2(handoffsDir, { recursive: true });
|
|
1913
|
+
const filePath = join4(handoffsDir, `${runId}_${step}.json`);
|
|
1914
|
+
await writeFile2(filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
1915
|
+
}
|
|
1916
|
+
async readHandoff(runId, step) {
|
|
1917
|
+
const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
|
|
1918
|
+
try {
|
|
1919
|
+
const raw = await readFile4(filePath, "utf-8");
|
|
1920
|
+
return JSON.parse(raw);
|
|
1921
|
+
} catch (error) {
|
|
1922
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1923
|
+
return null;
|
|
1924
|
+
}
|
|
1925
|
+
throw error;
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
async cleanOlderThan(maxAgeMs) {
|
|
1929
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
1930
|
+
let deleted = 0;
|
|
1931
|
+
const subdirs = ["memories", "runs", "handoffs"];
|
|
1932
|
+
for (const subdir of subdirs) {
|
|
1933
|
+
const dirPath = join4(this.baseDir, subdir);
|
|
1934
|
+
let entries;
|
|
1935
|
+
try {
|
|
1936
|
+
entries = await readdir2(dirPath);
|
|
1937
|
+
} catch (error) {
|
|
1938
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
throw error;
|
|
1942
|
+
}
|
|
1943
|
+
for (const entry of entries) {
|
|
1944
|
+
const filePath = join4(dirPath, entry);
|
|
1945
|
+
const fileStat = await stat(filePath);
|
|
1946
|
+
if (fileStat.mtimeMs < cutoff) {
|
|
1947
|
+
await unlink2(filePath);
|
|
1948
|
+
deleted++;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
return { deleted };
|
|
1953
|
+
}
|
|
1954
|
+
};
|
|
1955
|
+
|
|
1956
|
+
// src/lib/library-tool-binding.ts
|
|
1957
|
+
function createLibraryToolRegistry() {
|
|
1958
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1959
|
+
const moduleCache = /* @__PURE__ */ new Map();
|
|
1960
|
+
return {
|
|
1961
|
+
register(def) {
|
|
1962
|
+
definitions.set(def.toolId, def);
|
|
1963
|
+
},
|
|
1964
|
+
get(toolId) {
|
|
1965
|
+
return definitions.get(toolId);
|
|
1966
|
+
},
|
|
1967
|
+
getAll() {
|
|
1968
|
+
return [...definitions.values()];
|
|
1969
|
+
},
|
|
1970
|
+
async execute(toolId, input) {
|
|
1971
|
+
const def = definitions.get(toolId);
|
|
1972
|
+
if (!def) {
|
|
1973
|
+
throw new Error(`Library tool not found: ${toolId}`);
|
|
1974
|
+
}
|
|
1975
|
+
let mod = moduleCache.get(def.module);
|
|
1976
|
+
if (!mod) {
|
|
1977
|
+
try {
|
|
1978
|
+
mod = await import(def.module);
|
|
1979
|
+
moduleCache.set(def.module, mod);
|
|
1980
|
+
} catch (error) {
|
|
1981
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1982
|
+
throw new Error(
|
|
1983
|
+
`Failed to import module "${def.module}" for tool "${toolId}": ${message}`
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
const fn = mod[def.exportName];
|
|
1988
|
+
if (typeof fn !== "function") {
|
|
1989
|
+
throw new Error(
|
|
1990
|
+
`Export "${def.exportName}" not found in module "${def.module}" for tool "${toolId}"`
|
|
1991
|
+
);
|
|
1992
|
+
}
|
|
1993
|
+
return fn(input);
|
|
1994
|
+
}
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
// src/lib/adapter-factory.ts
|
|
1999
|
+
var ADAPTER_PACKAGES = {
|
|
2000
|
+
claude: "@anthropic-ai/claude-agent-sdk",
|
|
2001
|
+
gemini: "@google/adk",
|
|
2002
|
+
openai: "@openai/agents"
|
|
2003
|
+
};
|
|
2004
|
+
async function createAdapter(name, options) {
|
|
2005
|
+
const { model, cwd, tools, permissionMode, guardrailHooks } = options ?? {};
|
|
2006
|
+
switch (name) {
|
|
2007
|
+
case "mock": {
|
|
2008
|
+
const { MockAdapter } = await import("./adapters/mock.js");
|
|
2009
|
+
return new MockAdapter();
|
|
2010
|
+
}
|
|
2011
|
+
case "claude": {
|
|
2012
|
+
try {
|
|
2013
|
+
const { ClaudeAgentSdkAdapter } = await import("./adapters/claude-agent-sdk.js");
|
|
2014
|
+
return new ClaudeAgentSdkAdapter({
|
|
2015
|
+
guardrailHooks,
|
|
2016
|
+
...model ? { model } : {},
|
|
2017
|
+
...cwd ? { cwd } : {},
|
|
2018
|
+
...tools ? { tools } : {},
|
|
2019
|
+
...permissionMode ? { permissionMode } : {}
|
|
2020
|
+
});
|
|
2021
|
+
} catch (err) {
|
|
2022
|
+
throwMissingPackageError("claude", err);
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
case "gemini": {
|
|
2026
|
+
try {
|
|
2027
|
+
const { AdkSdkAdapter } = await import("./adapters/adk-sdk.js");
|
|
2028
|
+
return new AdkSdkAdapter({
|
|
2029
|
+
guardrailHooks,
|
|
2030
|
+
...model ? { model } : {}
|
|
2031
|
+
});
|
|
2032
|
+
} catch (err) {
|
|
2033
|
+
throwMissingPackageError("gemini", err);
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
case "openai": {
|
|
2037
|
+
try {
|
|
2038
|
+
const { OpenAIAgentsSdkAdapter } = await import("./adapters/openai-agents-sdk.js");
|
|
2039
|
+
return new OpenAIAgentsSdkAdapter({
|
|
2040
|
+
guardrailHooks,
|
|
2041
|
+
...model ? { model } : {}
|
|
2042
|
+
});
|
|
2043
|
+
} catch (err) {
|
|
2044
|
+
throwMissingPackageError("openai", err);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
default:
|
|
2048
|
+
throw new Error(
|
|
2049
|
+
`Unknown adapter: "${name}". Available: mock, claude, openai, gemini`
|
|
2050
|
+
);
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
function throwMissingPackageError(adapter, err) {
|
|
2054
|
+
const cause = err;
|
|
2055
|
+
if (cause?.message?.includes("Cannot find package")) {
|
|
2056
|
+
const pkg2 = ADAPTER_PACKAGES[adapter];
|
|
2057
|
+
throw new Error(
|
|
2058
|
+
`Adapter "${adapter}" requires package "${pkg2}" which is not installed.
|
|
2059
|
+
Install it with: npm install ${pkg2}`
|
|
2060
|
+
);
|
|
2061
|
+
}
|
|
2062
|
+
throw cause;
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
// src/lib/execute.ts
|
|
2066
|
+
import { resolve as resolve2 } from "path";
|
|
2067
|
+
async function resolveExecutionContext(options, requiredEntities) {
|
|
2068
|
+
const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
|
|
2069
|
+
if (useBoundResolver) {
|
|
2070
|
+
const component = options.resolvedComponent ?? await new BoundResolver().resolve({
|
|
2071
|
+
id: options.componentId ?? "default",
|
|
2072
|
+
embeddedDsl: options.dsl,
|
|
2073
|
+
bindingPaths: options.bindingPaths,
|
|
2074
|
+
activeGuardrailPolicy: options.activeGuardrailPolicy,
|
|
2075
|
+
artifactBinding: options.artifactBinding,
|
|
2076
|
+
paths: options.paths
|
|
2077
|
+
});
|
|
2078
|
+
if (requiredEntities) {
|
|
2079
|
+
const ctx2 = await loadDslContext({
|
|
2080
|
+
embeddedDsl: component.dsl,
|
|
2081
|
+
requiredEntities
|
|
2082
|
+
});
|
|
2083
|
+
return { registries: ctx2.registries, dsl: component.dsl, resolvedComponent: component };
|
|
2084
|
+
}
|
|
2085
|
+
return {
|
|
2086
|
+
registries: component.registries,
|
|
2087
|
+
dsl: component.dsl,
|
|
2088
|
+
resolvedComponent: component
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
const ctx = await loadDslContext({
|
|
2092
|
+
embeddedDsl: options.dsl,
|
|
2093
|
+
projectDslPath: options.projectDslPath,
|
|
2094
|
+
requiredEntities
|
|
2095
|
+
});
|
|
2096
|
+
return { registries: ctx.registries, dsl: ctx.dsl };
|
|
2097
|
+
}
|
|
2098
|
+
function injectGuardrailHooks(adapterOptions, execCtx, targetAgentId) {
|
|
2099
|
+
if (adapterOptions.guardrailHooks) return;
|
|
2100
|
+
if (execCtx.resolvedComponent && targetAgentId) {
|
|
2101
|
+
const rules2 = getGuardrailRulesForAgent(
|
|
2102
|
+
execCtx.resolvedComponent,
|
|
2103
|
+
targetAgentId,
|
|
2104
|
+
execCtx.dsl
|
|
2105
|
+
);
|
|
2106
|
+
if (rules2 && (rules2.commandRules.length > 0 || rules2.fileRules.length > 0 || rules2.contentRules.length > 0)) {
|
|
2107
|
+
adapterOptions.guardrailHooks = createGuardrailHooksFromRules(rules2);
|
|
2108
|
+
}
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
const rules = buildGuardrailRulesFromDsl(execCtx.dsl);
|
|
2112
|
+
if (rules && (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0)) {
|
|
2113
|
+
adapterOptions.guardrailHooks = createGuardrailHooksFromRules(rules);
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
async function executeTask(taskId, options) {
|
|
2117
|
+
const execCtx = await resolveExecutionContext(options, { tasks: [taskId] });
|
|
2118
|
+
const targetAgentId = execCtx.registries.taskRegistry?.[taskId]?.target_agent;
|
|
2119
|
+
const adapterOptions = { ...options.adapterOptions };
|
|
2120
|
+
injectGuardrailHooks(adapterOptions, execCtx, targetAgentId);
|
|
2121
|
+
const adapter = await createAdapter(options.adapter, {
|
|
2122
|
+
model: options.model,
|
|
2123
|
+
...adapterOptions
|
|
2124
|
+
});
|
|
2125
|
+
const progressSink = createProgressSink(
|
|
2126
|
+
options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
|
|
2127
|
+
);
|
|
2128
|
+
try {
|
|
2129
|
+
if (options.hooks?.beforeTask) {
|
|
2130
|
+
await options.hooks.beforeTask({ adapter, registries: execCtx.registries, taskId });
|
|
2131
|
+
}
|
|
2132
|
+
const result = await runTask(adapter, taskId, { user_request: options.request }, {
|
|
2133
|
+
maxFollowUps: options.maxFollowUps ?? 2,
|
|
2134
|
+
maxRetries: options.maxRetries ?? 0,
|
|
2135
|
+
progressOutput: progressSink,
|
|
2136
|
+
...execCtx.registries
|
|
2137
|
+
});
|
|
2138
|
+
if (options.hooks?.afterTask) {
|
|
2139
|
+
await options.hooks.afterTask(result);
|
|
2140
|
+
}
|
|
2141
|
+
return result;
|
|
2142
|
+
} finally {
|
|
2143
|
+
progressSink.close();
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
async function executeWorkflow(workflowId, options) {
|
|
2147
|
+
const execCtx = await resolveExecutionContext(options, { workflows: [workflowId] });
|
|
2148
|
+
const adapterOptions = { ...options.adapterOptions };
|
|
2149
|
+
injectGuardrailHooks(adapterOptions, execCtx);
|
|
2150
|
+
const adapter = await createAdapter(options.adapter, {
|
|
2151
|
+
model: options.model,
|
|
2152
|
+
...adapterOptions
|
|
2153
|
+
});
|
|
2154
|
+
const progressSink = createProgressSink(
|
|
2155
|
+
options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
|
|
2156
|
+
);
|
|
2157
|
+
try {
|
|
2158
|
+
if (options.hooks?.beforeWorkflow) {
|
|
2159
|
+
await options.hooks.beforeWorkflow({ adapter, registries: execCtx.registries, workflowId });
|
|
2160
|
+
}
|
|
2161
|
+
const invocation = {
|
|
2162
|
+
workflow: workflowId,
|
|
2163
|
+
user_request: options.request,
|
|
2164
|
+
handoff: options.handoff,
|
|
2165
|
+
progressOutput: progressSink,
|
|
2166
|
+
runtime: {
|
|
2167
|
+
maxFollowUps: options.maxFollowUps ?? 2,
|
|
2168
|
+
maxRetries: options.maxRetries ?? 0
|
|
2169
|
+
},
|
|
2170
|
+
hooks: {
|
|
2171
|
+
onStepComplete: options.hooks?.onStepComplete,
|
|
2172
|
+
onGate: options.hooks?.onGate ?? (options.autoApproveGates ? async () => true : void 0),
|
|
2173
|
+
onOptionalStep: options.hooks?.onOptionalStep
|
|
2174
|
+
},
|
|
2175
|
+
context: options.context
|
|
2176
|
+
};
|
|
2177
|
+
const result = await runWorkflow(adapter, invocation, execCtx.registries);
|
|
2178
|
+
if (options.hooks?.afterWorkflow) {
|
|
2179
|
+
await options.hooks.afterWorkflow(result);
|
|
2180
|
+
}
|
|
2181
|
+
return result;
|
|
2182
|
+
} finally {
|
|
2183
|
+
progressSink.close();
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
// src/component-binding.ts
|
|
2188
|
+
import { randomUUID } from "crypto";
|
|
2189
|
+
var DEFAULT_MEMORY_PROVIDER = "aaac-runtime";
|
|
2190
|
+
var DEFAULT_MEMORY_COMPAT = "aaac/0.1";
|
|
2191
|
+
function getMemoryRefConfig(op) {
|
|
2192
|
+
return op.memoryRef;
|
|
2193
|
+
}
|
|
2194
|
+
function attachMemoryRef2(result, memoryRef) {
|
|
2195
|
+
if (result !== null && typeof result === "object" && !Array.isArray(result)) {
|
|
2196
|
+
return { ...result, _memoryRef: memoryRef };
|
|
2197
|
+
}
|
|
2198
|
+
return { value: result, _memoryRef: memoryRef };
|
|
2199
|
+
}
|
|
2200
|
+
function createRuntimeBinding(component, handlers) {
|
|
2201
|
+
const operations = component.operations;
|
|
2202
|
+
return {
|
|
2203
|
+
getOperationNames() {
|
|
2204
|
+
return Object.keys(operations);
|
|
2205
|
+
},
|
|
2206
|
+
getOperationIR(name) {
|
|
2207
|
+
return operations[name];
|
|
2208
|
+
},
|
|
2209
|
+
async execute(operationName, options, input, ctx) {
|
|
2210
|
+
const op = operations[operationName];
|
|
2211
|
+
if (!op) {
|
|
2212
|
+
throw new Error(`Unknown operation: ${operationName}`);
|
|
2213
|
+
}
|
|
2214
|
+
const memoryConfig = getMemoryRefConfig(op);
|
|
2215
|
+
const runId = ctx.runId ?? ctx.parentRunId ?? randomUUID();
|
|
2216
|
+
const execCtx = { ...ctx, runId };
|
|
2217
|
+
if (ctx.memoryRef && ctx.memoryStore) {
|
|
2218
|
+
const stored = await ctx.memoryStore.load(ctx.memoryRef);
|
|
2219
|
+
if (stored !== null) {
|
|
2220
|
+
const entry = stored;
|
|
2221
|
+
execCtx.resumedState = entry.result ?? stored;
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
await ctx.policy?.assertAllowed(operationName);
|
|
2225
|
+
ctx.observer?.onOperationStart?.(operationName, input);
|
|
2226
|
+
const startTime = Date.now();
|
|
2227
|
+
if (ctx.logWriter) {
|
|
2228
|
+
await ctx.logWriter.writeRunEvent(runId, {
|
|
2229
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2230
|
+
type: "operation_start",
|
|
2231
|
+
runId,
|
|
2232
|
+
operationName,
|
|
2233
|
+
data: { input }
|
|
2234
|
+
});
|
|
2235
|
+
}
|
|
2236
|
+
try {
|
|
2237
|
+
const result = await dispatchOperation(
|
|
2238
|
+
operationName,
|
|
2239
|
+
op,
|
|
2240
|
+
options,
|
|
2241
|
+
input,
|
|
2242
|
+
execCtx,
|
|
2243
|
+
handlers
|
|
2244
|
+
);
|
|
2245
|
+
let finalResult = result;
|
|
2246
|
+
let newMemoryRef;
|
|
2247
|
+
if (memoryConfig?.output && ctx.memoryStore) {
|
|
2248
|
+
newMemoryRef = {
|
|
2249
|
+
id: randomUUID(),
|
|
2250
|
+
provider: memoryConfig.provider ?? DEFAULT_MEMORY_PROVIDER,
|
|
2251
|
+
compat: memoryConfig.compat ?? DEFAULT_MEMORY_COMPAT,
|
|
2252
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2253
|
+
parent_run_id: runId
|
|
2254
|
+
};
|
|
2255
|
+
const entry = {
|
|
2256
|
+
result,
|
|
2257
|
+
memoryRef: newMemoryRef
|
|
2258
|
+
};
|
|
2259
|
+
await ctx.memoryStore.save(newMemoryRef, entry);
|
|
2260
|
+
finalResult = attachMemoryRef2(result, newMemoryRef);
|
|
2261
|
+
}
|
|
2262
|
+
ctx.observer?.onOperationEnd?.(operationName, finalResult);
|
|
2263
|
+
if (ctx.logWriter) {
|
|
2264
|
+
await ctx.logWriter.writeRunEvent(runId, {
|
|
2265
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2266
|
+
type: "operation_end",
|
|
2267
|
+
runId,
|
|
2268
|
+
operationName,
|
|
2269
|
+
durationMs: Date.now() - startTime,
|
|
2270
|
+
data: { output: finalResult }
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
return finalResult;
|
|
2274
|
+
} catch (error) {
|
|
2275
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
2276
|
+
ctx.observer?.onOperationError?.(operationName, err);
|
|
2277
|
+
if (ctx.logWriter) {
|
|
2278
|
+
await ctx.logWriter.writeRunEvent(runId, {
|
|
2279
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2280
|
+
type: "operation_error",
|
|
2281
|
+
runId,
|
|
2282
|
+
operationName,
|
|
2283
|
+
durationMs: Date.now() - startTime,
|
|
2284
|
+
error: err.message
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
throw err;
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
};
|
|
2291
|
+
}
|
|
2292
|
+
async function dispatchOperation(operationName, op, options, input, ctx, handlers) {
|
|
2293
|
+
if (op.agentWorkflow) {
|
|
2294
|
+
return ctx.runtime.runWorkflow(op.agentWorkflow, options, input, ctx);
|
|
2295
|
+
}
|
|
2296
|
+
if (op.agentTask) {
|
|
2297
|
+
return ctx.runtime.runTask(op.agentTask, options, input, ctx);
|
|
2298
|
+
}
|
|
2299
|
+
if (op.handler) {
|
|
2300
|
+
const handler = handlers?.[operationName];
|
|
2301
|
+
if (!handler) {
|
|
2302
|
+
throw new Error(
|
|
2303
|
+
`No handler provided for deterministic operation "${operationName}"`
|
|
2304
|
+
);
|
|
2305
|
+
}
|
|
2306
|
+
return handler(options, input, ctx);
|
|
2307
|
+
}
|
|
2308
|
+
throw new Error(`Operation "${operationName}" has no dispatch target`);
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
// src/component-scope.ts
|
|
2312
|
+
function buildToolsByAgent(componentIR, resolved) {
|
|
2313
|
+
const operationNames = new Set(Object.keys(componentIR.operations));
|
|
2314
|
+
const toolsByAgent = /* @__PURE__ */ new Map();
|
|
2315
|
+
if (!resolved) {
|
|
2316
|
+
return toolsByAgent;
|
|
2317
|
+
}
|
|
2318
|
+
const dsl = resolved.dsl;
|
|
2319
|
+
const tools = dsl.tools ?? {};
|
|
2320
|
+
for (const tool of Object.values(tools)) {
|
|
2321
|
+
const command = tool.command;
|
|
2322
|
+
if (!command || !operationNames.has(command)) {
|
|
2323
|
+
continue;
|
|
2324
|
+
}
|
|
2325
|
+
for (const agentId of tool.invokable_by ?? []) {
|
|
2326
|
+
appendToolForAgent(toolsByAgent, agentId, command);
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
const agents = dsl.agents ?? {};
|
|
2330
|
+
for (const [agentId, agent] of Object.entries(agents)) {
|
|
2331
|
+
for (const toolName of agent.can_execute_tools ?? []) {
|
|
2332
|
+
if (operationNames.has(toolName)) {
|
|
2333
|
+
appendToolForAgent(toolsByAgent, agentId, toolName);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
return toolsByAgent;
|
|
2338
|
+
}
|
|
2339
|
+
function appendToolForAgent(toolsByAgent, agentId, operationName) {
|
|
2340
|
+
const existing = toolsByAgent.get(agentId) ?? [];
|
|
2341
|
+
if (existing.includes(operationName)) {
|
|
2342
|
+
return;
|
|
2343
|
+
}
|
|
2344
|
+
toolsByAgent.set(agentId, [...existing, operationName]);
|
|
2345
|
+
}
|
|
2346
|
+
function buildGuardrailsByAgent(resolved) {
|
|
2347
|
+
const guardrailsByAgent = /* @__PURE__ */ new Map();
|
|
2348
|
+
if (!resolved) {
|
|
2349
|
+
return guardrailsByAgent;
|
|
2350
|
+
}
|
|
2351
|
+
for (const [agentId, rules] of resolved.guardrails.perAgent) {
|
|
2352
|
+
guardrailsByAgent.set(agentId, [rules]);
|
|
2353
|
+
}
|
|
2354
|
+
return guardrailsByAgent;
|
|
2355
|
+
}
|
|
2356
|
+
function buildLibraryTools(defs) {
|
|
2357
|
+
if (!defs || defs.length === 0) {
|
|
2358
|
+
return void 0;
|
|
2359
|
+
}
|
|
2360
|
+
const registry = createLibraryToolRegistry();
|
|
2361
|
+
for (const def of defs) {
|
|
2362
|
+
registry.register(def);
|
|
2363
|
+
}
|
|
2364
|
+
return registry;
|
|
2365
|
+
}
|
|
2366
|
+
function createComponentScope(componentIR, binding, options) {
|
|
2367
|
+
const resolved = options?.resolvedComponent;
|
|
2368
|
+
return {
|
|
2369
|
+
componentId: componentIR.info.id,
|
|
2370
|
+
componentIR,
|
|
2371
|
+
binding,
|
|
2372
|
+
toolsByAgent: buildToolsByAgent(componentIR, resolved),
|
|
2373
|
+
guardrailsByAgent: buildGuardrailsByAgent(resolved),
|
|
2374
|
+
libraryTools: buildLibraryTools(options?.libraryToolDefs)
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
// src/lib/navigation-context.ts
|
|
2379
|
+
async function buildNavigationContext(options) {
|
|
2380
|
+
const diagnostics = [];
|
|
2381
|
+
let dsl;
|
|
2382
|
+
if (options.embeddedDsl != null) {
|
|
2383
|
+
if (options.projectDslPath) {
|
|
2384
|
+
const ctx = await loadDslContext({
|
|
2385
|
+
embeddedDsl: options.embeddedDsl,
|
|
2386
|
+
projectDslPath: options.projectDslPath
|
|
2387
|
+
});
|
|
2388
|
+
dsl = ctx.dsl;
|
|
2389
|
+
} else {
|
|
2390
|
+
dsl = options.embeddedDsl;
|
|
2391
|
+
}
|
|
2392
|
+
} else if (options.projectDslPath) {
|
|
2393
|
+
const { resolve: resolve3 } = await import("agent-contracts");
|
|
2394
|
+
const result = await resolve3(options.projectDslPath);
|
|
2395
|
+
dsl = result.data;
|
|
2396
|
+
} else {
|
|
2397
|
+
throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
|
|
2398
|
+
}
|
|
2399
|
+
if (options.artifactBinding) {
|
|
2400
|
+
const { resolveBound } = await import("agent-contracts");
|
|
2401
|
+
const boundResult = await resolveBound(dsl, {
|
|
2402
|
+
artifactBinding: options.artifactBinding,
|
|
2403
|
+
paths: options.paths
|
|
2404
|
+
});
|
|
2405
|
+
dsl = boundResult.data;
|
|
2406
|
+
for (const d of boundResult.diagnostics) {
|
|
2407
|
+
diagnostics.push({
|
|
2408
|
+
path: d.rule,
|
|
2409
|
+
message: d.message,
|
|
2410
|
+
severity: d.severity
|
|
2411
|
+
});
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
|
|
2415
|
+
const validation = validateSchema(dsl);
|
|
2416
|
+
for (const d of validation.diagnostics) {
|
|
2417
|
+
diagnostics.push({
|
|
2418
|
+
path: d.path,
|
|
2419
|
+
message: d.message,
|
|
2420
|
+
severity: d.severity ?? "error"
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
const navigationIndex = buildNavigationIndex(
|
|
2424
|
+
validation.data ?? dsl
|
|
2425
|
+
);
|
|
2426
|
+
return { dsl, navigationIndex, diagnostics };
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
// src/lib/artifact-resolver.ts
|
|
2430
|
+
async function resolveArtifacts(options) {
|
|
2431
|
+
if (!options.artifactBinding) {
|
|
2432
|
+
return { dsl: options.dsl, diagnostics: [] };
|
|
2433
|
+
}
|
|
2434
|
+
const { resolveBound } = await import("agent-contracts");
|
|
2435
|
+
const result = await resolveBound(options.dsl, {
|
|
2436
|
+
artifactBinding: options.artifactBinding,
|
|
2437
|
+
paths: options.paths
|
|
2438
|
+
});
|
|
2439
|
+
return {
|
|
2440
|
+
dsl: result.data,
|
|
2441
|
+
diagnostics: result.diagnostics.map((d) => ({
|
|
2442
|
+
path: d.rule,
|
|
2443
|
+
message: d.message,
|
|
2444
|
+
severity: d.severity
|
|
2445
|
+
}))
|
|
2446
|
+
};
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// src/index.ts
|
|
2450
|
+
var require2 = createRequire(import.meta.url);
|
|
2451
|
+
var pkg = require2("../package.json");
|
|
2452
|
+
var version = pkg.version;
|
|
3
2453
|
export {
|
|
4
|
-
|
|
2454
|
+
AgentLogWriter,
|
|
2455
|
+
BoundResolver,
|
|
2456
|
+
DslValidationError,
|
|
2457
|
+
FileMemoryStore,
|
|
2458
|
+
InMemoryStore,
|
|
2459
|
+
PluginRegistry,
|
|
2460
|
+
WorkflowBuilder,
|
|
2461
|
+
buildCandidateAgents,
|
|
2462
|
+
buildGateEvaluationPrompt,
|
|
2463
|
+
buildGuardrailRulesFromDsl,
|
|
2464
|
+
buildNavigationContext,
|
|
2465
|
+
buildPerAgentGuardrails,
|
|
2466
|
+
buildRegistriesFromDsl,
|
|
2467
|
+
buildRetryFollowUp,
|
|
2468
|
+
buildSplitTaskPrompt,
|
|
2469
|
+
buildTaskPrompt,
|
|
2470
|
+
createAdapter,
|
|
2471
|
+
createComponentScope,
|
|
2472
|
+
createExecutionEnvelope,
|
|
2473
|
+
createGuardrailHooks,
|
|
2474
|
+
createGuardrailHooksForAgent,
|
|
2475
|
+
createGuardrailHooksFromRules,
|
|
2476
|
+
createLibraryToolRegistry,
|
|
2477
|
+
createModelResolver,
|
|
2478
|
+
createProgressSink,
|
|
2479
|
+
createRuntime,
|
|
2480
|
+
createRuntimeBinding,
|
|
2481
|
+
emitSessionClose,
|
|
2482
|
+
emitSessionOpen,
|
|
2483
|
+
emitSubagentClose,
|
|
2484
|
+
emitSubagentOpen,
|
|
2485
|
+
executeTask,
|
|
2486
|
+
executeWorkflow,
|
|
2487
|
+
extractStructuredResult,
|
|
2488
|
+
getBlockingViolations,
|
|
2489
|
+
getEffectiveGuardrailIds,
|
|
2490
|
+
getGuardrailRulesForAgent,
|
|
2491
|
+
getWarnings,
|
|
2492
|
+
guardrailContextToRuleData,
|
|
2493
|
+
hasBlockingViolation,
|
|
2494
|
+
jsonSchemaToZod,
|
|
2495
|
+
loadDslContext,
|
|
2496
|
+
loadPlugins,
|
|
2497
|
+
loadPluginsFromDirectory,
|
|
2498
|
+
loadPluginsFromPaths,
|
|
2499
|
+
parseGateEvaluationResponse,
|
|
2500
|
+
pluginRegistry,
|
|
2501
|
+
renderAgentSystemPrompt,
|
|
2502
|
+
resolveArtifacts,
|
|
2503
|
+
runTask,
|
|
2504
|
+
runWorkflow,
|
|
2505
|
+
version,
|
|
2506
|
+
zodSchemaToPromptDescription,
|
|
2507
|
+
zodSchemaToYamlExample
|
|
5
2508
|
};
|
|
6
2509
|
//# sourceMappingURL=index.js.map
|