@aaac/runtime 0.1.35 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1503 @@
1
+ import {
2
+ pluginRegistry
3
+ } from "./chunk-EH5VFZYJ.js";
4
+ import {
5
+ createExecutionEnvelope,
6
+ emitSubagentClose,
7
+ emitSubagentOpen
8
+ } from "./chunk-GNMSH3VC.js";
9
+ import {
10
+ jsonSchemaToZod
11
+ } from "./chunk-ET6TGQRT.js";
12
+
13
+ // src/lib/candidate-agents.ts
14
+ function renderAgentSystemPrompt(agent) {
15
+ const sections = [];
16
+ sections.push(`# Role: ${agent.role_name}
17
+
18
+ ${agent.purpose}`);
19
+ if (agent.responsibilities.length > 0) {
20
+ sections.push(
21
+ `## Responsibilities
22
+
23
+ ${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
24
+ );
25
+ }
26
+ if (agent.constraints.length > 0) {
27
+ sections.push(
28
+ `## Constraints
29
+
30
+ ${agent.constraints.map((c) => `- ${c}`).join("\n")}`
31
+ );
32
+ }
33
+ if (agent.rules && agent.rules.length > 0) {
34
+ const ruleLines = agent.rules.map(
35
+ (r) => `- **${r.id}** [${r.severity}]: ${r.description}`
36
+ );
37
+ sections.push(`## Rules
38
+
39
+ ${ruleLines.join("\n")}`);
40
+ }
41
+ return sections.join("\n\n");
42
+ }
43
+ function deriveDescription(purpose) {
44
+ const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
45
+ const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
46
+ if (sentenceEnd !== -1) {
47
+ return firstLine.slice(0, sentenceEnd + 1).trim();
48
+ }
49
+ return firstLine;
50
+ }
51
+ function buildCandidateAgents(agentRegistry, opts) {
52
+ const entryId = opts?.entryAgentId;
53
+ const allowed = opts?.allowedAgentIds;
54
+ const allowSet = allowed ? new Set(allowed) : void 0;
55
+ const candidates = [];
56
+ for (const [id, agent] of Object.entries(agentRegistry)) {
57
+ if (id === entryId) continue;
58
+ if (allowSet && !allowSet.has(id)) continue;
59
+ const agentTools = agent.can_execute_tools ? [...agent.can_execute_tools] : [];
60
+ const derivedToolchains = opts?.toolchainsByAgent?.get(id);
61
+ if (derivedToolchains) {
62
+ for (const tc of derivedToolchains) {
63
+ if (!agentTools.includes(tc.id)) {
64
+ agentTools.push(tc.id);
65
+ }
66
+ }
67
+ }
68
+ candidates.push({
69
+ name: id,
70
+ description: deriveDescription(agent.purpose),
71
+ prompt: renderAgentSystemPrompt(agent),
72
+ ...agentTools.length > 0 ? { tools: agentTools } : {}
73
+ });
74
+ }
75
+ return candidates;
76
+ }
77
+
78
+ // src/lib/analyzer-bridge.ts
79
+ var ANALYZER_PKG = "artifact-contracts-analyzer";
80
+ async function loadAnalyzerModule() {
81
+ const mod = await import(
82
+ /* webpackIgnore: true */
83
+ ANALYZER_PKG
84
+ );
85
+ return mod;
86
+ }
87
+ function createAnalyzerBridge(options) {
88
+ const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;
89
+ let cachedGraph = null;
90
+ let cachedFileContents = null;
91
+ let graphBuildPromise = null;
92
+ async function ensureGraph() {
93
+ if (cachedGraph) return cachedGraph;
94
+ if (graphBuildPromise) {
95
+ await graphBuildPromise;
96
+ return cachedGraph;
97
+ }
98
+ graphBuildPromise = doBuildGraph();
99
+ await graphBuildPromise;
100
+ return cachedGraph;
101
+ }
102
+ async function doBuildGraph() {
103
+ let mod;
104
+ try {
105
+ mod = await loadAnalyzerModule();
106
+ } catch (error) {
107
+ const msg = error instanceof Error ? error.message : String(error);
108
+ throw new Error(
109
+ `artifact-contracts-analyzer is not available. Install it to use analyzer features: ${msg}`
110
+ );
111
+ }
112
+ const patterns = artifactPatterns ?? /* @__PURE__ */ new Map();
113
+ const registry = mod.createDefaultRegistry();
114
+ const astResult = await mod.buildAstGraph({
115
+ projectRoot,
116
+ artifactPatterns: patterns,
117
+ registry
118
+ });
119
+ cachedFileContents = astResult.fileContents;
120
+ cachedGraph = await mod.buildDependencyGraph({
121
+ ast: astResult.graph,
122
+ projectRoot,
123
+ artifactPatterns: patterns,
124
+ manifests: manifests ?? []
125
+ });
126
+ }
127
+ const bridge = {
128
+ async buildGraph() {
129
+ await ensureGraph();
130
+ },
131
+ async getGraph() {
132
+ return ensureGraph();
133
+ },
134
+ async analyzeImpact(changed, opts) {
135
+ let mod;
136
+ try {
137
+ mod = await loadAnalyzerModule();
138
+ } catch {
139
+ return {
140
+ error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.",
141
+ changed
142
+ };
143
+ }
144
+ const graph = await ensureGraph();
145
+ return mod.analyzeImpact({
146
+ graph,
147
+ changed,
148
+ direction: opts?.direction ?? "downstream",
149
+ ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
150
+ ...opts?.limit !== void 0 ? { limit: opts.limit } : {},
151
+ ...navigationIndex ? { navigationIndex } : {}
152
+ });
153
+ },
154
+ async generateContextPack(changed, opts) {
155
+ let mod;
156
+ try {
157
+ mod = await loadAnalyzerModule();
158
+ } catch {
159
+ return {
160
+ entries: [],
161
+ metadata: {
162
+ totalTokens: 0,
163
+ budgetTokens: opts?.budgetTokens ?? 5e4,
164
+ filesIncluded: 0,
165
+ filesExcluded: 0,
166
+ filesReferenced: 0,
167
+ artifactsCovered: [],
168
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
169
+ }
170
+ };
171
+ }
172
+ const graph = await ensureGraph();
173
+ return mod.generateContextPack({
174
+ graph,
175
+ changed,
176
+ projectRoot,
177
+ ...opts?.budgetTokens !== void 0 ? { budgetTokens: opts.budgetTokens } : {},
178
+ ...opts?.granularity ? { granularity: opts.granularity } : {},
179
+ ...navigationIndex ? { navigationIndex } : {},
180
+ ...cachedFileContents ? { fileContents: cachedFileContents } : {}
181
+ });
182
+ },
183
+ async buildCallGraph(entry, opts) {
184
+ let mod;
185
+ try {
186
+ mod = await loadAnalyzerModule();
187
+ } catch {
188
+ return {
189
+ error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.",
190
+ entry
191
+ };
192
+ }
193
+ const graph = await ensureGraph();
194
+ return mod.buildCallGraph({
195
+ graph,
196
+ entry,
197
+ ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
198
+ ...opts?.direction ? { direction: opts.direction } : {}
199
+ });
200
+ },
201
+ invalidateCache() {
202
+ cachedGraph = null;
203
+ cachedFileContents = null;
204
+ graphBuildPromise = null;
205
+ },
206
+ buildAnalyzerTools() {
207
+ return [
208
+ {
209
+ name: "analyzer.analyzeImpact",
210
+ description: "Analyze the impact of changed files across the dependency graph",
211
+ inputSchema: {
212
+ type: "object",
213
+ properties: {
214
+ changed: {
215
+ type: "array",
216
+ items: { type: "string" },
217
+ description: "File paths that changed"
218
+ },
219
+ direction: {
220
+ type: "string",
221
+ enum: ["downstream", "upstream"],
222
+ description: "Traversal direction. downstream = what breaks if this changes"
223
+ },
224
+ maxDepth: {
225
+ type: "number",
226
+ description: "Maximum BFS depth to explore"
227
+ },
228
+ limit: {
229
+ type: "number",
230
+ description: "Cap the number of affected entries returned"
231
+ }
232
+ },
233
+ required: ["changed"]
234
+ },
235
+ handler: async (args) => {
236
+ const changed = args.changed;
237
+ const result = await bridge.analyzeImpact(changed, {
238
+ direction: args.direction,
239
+ maxDepth: args.maxDepth,
240
+ limit: args.limit
241
+ });
242
+ return JSON.stringify(result);
243
+ }
244
+ },
245
+ {
246
+ name: "analyzer.generateContextPack",
247
+ description: "Generate a token-budget-constrained context pack for changed files",
248
+ inputSchema: {
249
+ type: "object",
250
+ properties: {
251
+ changed: {
252
+ type: "array",
253
+ items: { type: "string" },
254
+ description: "File paths that changed"
255
+ },
256
+ budgetTokens: {
257
+ type: "number",
258
+ description: "Token budget for the context pack"
259
+ },
260
+ granularity: {
261
+ type: "string",
262
+ enum: ["file", "symbol"],
263
+ description: "Context granularity level"
264
+ }
265
+ },
266
+ required: ["changed"]
267
+ },
268
+ handler: async (args) => {
269
+ const changed = args.changed;
270
+ const result = await bridge.generateContextPack(changed, {
271
+ budgetTokens: args.budgetTokens,
272
+ granularity: args.granularity
273
+ });
274
+ return JSON.stringify(result);
275
+ }
276
+ },
277
+ {
278
+ name: "analyzer.buildCallGraph",
279
+ description: "Build a call graph rooted at a symbol",
280
+ inputSchema: {
281
+ type: "object",
282
+ properties: {
283
+ entry: {
284
+ type: "string",
285
+ description: "Entry symbolId (filePath#name) to root the call graph at"
286
+ },
287
+ maxDepth: {
288
+ type: "number",
289
+ description: "Maximum traversal depth"
290
+ },
291
+ direction: {
292
+ type: "string",
293
+ enum: ["forward", "reverse"],
294
+ description: "Traversal direction: forward (callees) or reverse (callers)"
295
+ }
296
+ },
297
+ required: ["entry"]
298
+ },
299
+ handler: async (args) => {
300
+ const entry = args.entry;
301
+ const result = await bridge.buildCallGraph(entry, {
302
+ maxDepth: args.maxDepth,
303
+ direction: args.direction
304
+ });
305
+ return JSON.stringify(result);
306
+ }
307
+ }
308
+ ];
309
+ }
310
+ };
311
+ return bridge;
312
+ }
313
+ function isContextPack(value) {
314
+ if (typeof value !== "object" || value === null) return false;
315
+ const obj = value;
316
+ if (!Array.isArray(obj.entries)) return false;
317
+ if (typeof obj.metadata !== "object" || obj.metadata === null) return false;
318
+ const meta = obj.metadata;
319
+ return typeof meta.totalTokens === "number" && typeof meta.budgetTokens === "number";
320
+ }
321
+ function renderContextPackPrompt(pack) {
322
+ const m = pack.metadata;
323
+ const sections = [];
324
+ sections.push("## Source Code Context");
325
+ sections.push(
326
+ `### Budget
327
+ - Tokens used: ${m.totalTokens} / ${m.budgetTokens}
328
+ - Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`
329
+ );
330
+ if (m.artifactsCovered.length > 0) {
331
+ sections.push(
332
+ `### Affected Artifacts
333
+ ${m.artifactsCovered.map((a) => `- ${a}`).join("\n")}`
334
+ );
335
+ }
336
+ if (pack.entries.length > 0) {
337
+ const fileBlocks = [];
338
+ for (const entry of pack.entries) {
339
+ const ext = entry.path.split(".").pop() ?? "";
340
+ const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;
341
+ const reason = `> ${entry.reason}`;
342
+ if (entry.content) {
343
+ fileBlocks.push(
344
+ `${header}
345
+ ${reason}
346
+
347
+ \`\`\`${ext}
348
+ ${entry.content}
349
+ \`\`\``
350
+ );
351
+ } else {
352
+ fileBlocks.push(`${header}
353
+ ${reason}`);
354
+ }
355
+ }
356
+ sections.push(`### Files
357
+ ${fileBlocks.join("\n\n")}`);
358
+ }
359
+ return sections.join("\n\n");
360
+ }
361
+
362
+ // src/lib/process-axis-bridge.ts
363
+ import { generateId } from "@aaac/observability";
364
+ function attrs(base) {
365
+ const out = {};
366
+ for (const [k, v] of Object.entries(base)) {
367
+ if (v !== void 0 && v !== "") out[k] = v;
368
+ }
369
+ return out;
370
+ }
371
+ var FILE_EDIT_TOOL_NAMES = /* @__PURE__ */ new Set([
372
+ "write",
373
+ "edit",
374
+ "multiedit",
375
+ "multi_edit",
376
+ "notebookedit",
377
+ "notebook_edit"
378
+ ]);
379
+ function isFileEditTool(toolName) {
380
+ if (!toolName) return false;
381
+ return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());
382
+ }
383
+ function emitProcessWorkflowOpen(options) {
384
+ if (!options.observer) return void 0;
385
+ const spanId = generateId();
386
+ options.observer({
387
+ source: "aaac-runtime",
388
+ eventType: "process.workflow",
389
+ lifecycle: "open",
390
+ spanId,
391
+ parentSpanId: options.parentSpanId,
392
+ attributes: attrs({
393
+ axis: "process",
394
+ "agent.session_id": options.sessionId,
395
+ "workflow.id": options.workflowId
396
+ })
397
+ });
398
+ return spanId;
399
+ }
400
+ function emitProcessWorkflowClose(spanId, options) {
401
+ if (!options.observer) return;
402
+ options.observer({
403
+ source: "aaac-runtime",
404
+ eventType: "process.workflow",
405
+ lifecycle: "close",
406
+ spanId,
407
+ attributes: attrs({
408
+ axis: "process",
409
+ "workflow.status": options.status,
410
+ ...options.durationMs !== void 0 ? { "workflow.duration_ms": options.durationMs } : {}
411
+ })
412
+ });
413
+ }
414
+ function emitProcessTaskOpen(options) {
415
+ if (!options.observer) return void 0;
416
+ const spanId = generateId();
417
+ options.observer({
418
+ source: "aaac-runtime",
419
+ eventType: "process.task",
420
+ lifecycle: "open",
421
+ spanId,
422
+ parentSpanId: options.parentSpanId,
423
+ attributes: attrs({
424
+ axis: "process",
425
+ "agent.session_id": options.sessionId,
426
+ "task.id": options.taskId,
427
+ "task.type": "implement",
428
+ "task.target_agent": options.targetAgent
429
+ })
430
+ });
431
+ return spanId;
432
+ }
433
+ function emitProcessTaskClose(spanId, options) {
434
+ if (!options.observer) return;
435
+ options.observer({
436
+ source: "aaac-runtime",
437
+ eventType: "process.task",
438
+ lifecycle: "close",
439
+ spanId,
440
+ attributes: attrs({
441
+ axis: "process",
442
+ "task.status": options.status,
443
+ ...options.durationMs !== void 0 ? { "task.duration_ms": options.durationMs } : {}
444
+ })
445
+ });
446
+ }
447
+ function emitProcessEdit(options) {
448
+ if (!options.observer) return void 0;
449
+ const spanId = generateId();
450
+ options.observer({
451
+ source: "aaac-runtime",
452
+ eventType: "process.edit",
453
+ lifecycle: "instant",
454
+ spanId,
455
+ parentSpanId: options.parentSpanId,
456
+ attributes: attrs({
457
+ axis: "process",
458
+ "agent.session_id": options.sessionId,
459
+ "edit.path": options.filePath,
460
+ "edit.artifact_id": options.artifactId
461
+ })
462
+ });
463
+ return spanId;
464
+ }
465
+
466
+ // src/lib/task-runner.ts
467
+ import { z } from "zod";
468
+ import * as yaml from "yaml";
469
+ function getZodChecks(schema) {
470
+ const def = schema._def;
471
+ return def?.checks ?? [];
472
+ }
473
+ function extractZodConstraints(schema) {
474
+ const inner = unwrapOptional(schema);
475
+ const parts = [];
476
+ if (inner instanceof z.ZodString) {
477
+ const str = inner;
478
+ if (str.minLength != null) parts.push(`min: ${str.minLength}`);
479
+ if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
480
+ for (const check of getZodChecks(inner)) {
481
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
482
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
483
+ if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
484
+ const def = check._zod?.def;
485
+ if (def?.format === "regex" && def.pattern instanceof RegExp) {
486
+ parts.push(`regex: ${def.pattern}`);
487
+ }
488
+ }
489
+ } else if (inner instanceof z.ZodNumber) {
490
+ let hasInt = false;
491
+ for (const check of getZodChecks(inner)) {
492
+ if (check.kind === "int") hasInt = true;
493
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
494
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
495
+ if (check.isInt) hasInt = true;
496
+ const def = check._zod?.def;
497
+ if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
498
+ if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
499
+ if (def?.check === "less_than") parts.push(`max: ${def.value}`);
500
+ }
501
+ if (hasInt) parts.unshift("int");
502
+ } else if (inner instanceof z.ZodArray) {
503
+ for (const check of getZodChecks(inner)) {
504
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
505
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
506
+ const def = check._zod?.def;
507
+ if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
508
+ if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
509
+ }
510
+ }
511
+ return parts.length > 0 ? parts.join(", ") : void 0;
512
+ }
513
+ function zodTypeToString(schema) {
514
+ if (schema instanceof z.ZodString) return "string";
515
+ if (schema instanceof z.ZodNumber) return "number";
516
+ if (schema instanceof z.ZodBoolean) return "boolean";
517
+ if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
518
+ if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
519
+ if (schema instanceof z.ZodArray) {
520
+ const element = schema._def.element;
521
+ const inner = zodTypeToString(element);
522
+ return `${inner}[]`;
523
+ }
524
+ if (schema instanceof z.ZodObject) return "object";
525
+ if (schema instanceof z.ZodOptional) {
526
+ return zodTypeToString(schema._def.innerType);
527
+ }
528
+ if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
529
+ return "unknown";
530
+ }
531
+ function unwrapOptional(schema) {
532
+ if (schema instanceof z.ZodOptional) {
533
+ return schema._def.innerType;
534
+ }
535
+ return schema;
536
+ }
537
+ function getArrayElement(schema) {
538
+ const inner = unwrapOptional(schema);
539
+ if (inner instanceof z.ZodArray) {
540
+ return inner._def.element;
541
+ }
542
+ return null;
543
+ }
544
+ function extractFieldDescriptors(schema) {
545
+ let shape = null;
546
+ if (schema instanceof z.ZodObject) {
547
+ shape = schema.shape;
548
+ }
549
+ if (!shape) return null;
550
+ return Object.entries(shape).map(([name, field]) => {
551
+ const isOptional = field instanceof z.ZodOptional;
552
+ const innerField = isOptional ? field._def.innerType : field;
553
+ const description = innerField.description ?? field.description;
554
+ return {
555
+ name,
556
+ type: zodTypeToString(field),
557
+ required: !isOptional,
558
+ description,
559
+ constraints: extractZodConstraints(innerField)
560
+ };
561
+ });
562
+ }
563
+ function zodSchemaToPromptDescription(schema) {
564
+ const tables = [];
565
+ collectFieldTables(schema, "", tables);
566
+ return tables.join("\n\n");
567
+ }
568
+ function collectFieldTables(schema, pathPrefix, tables) {
569
+ const fields = extractFieldDescriptors(schema);
570
+ if (!fields || fields.length === 0) return;
571
+ const title = pathPrefix ? `**${pathPrefix}**
572
+
573
+ ` : "";
574
+ const header = "| Field | Type | Required | Constraints | Description |";
575
+ const sep = "|-------|------|----------|-------------|-------------|";
576
+ const rows = fields.map(
577
+ (f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
578
+ );
579
+ tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
580
+ const shape = schema instanceof z.ZodObject ? schema.shape : null;
581
+ if (!shape) return;
582
+ for (const f of fields) {
583
+ const rawField = shape[f.name];
584
+ const inner = unwrapOptional(rawField);
585
+ if (inner instanceof z.ZodObject) {
586
+ collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
587
+ } else if (inner instanceof z.ZodArray) {
588
+ const element = inner._def.element;
589
+ if (element instanceof z.ZodObject) {
590
+ collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
591
+ }
592
+ }
593
+ }
594
+ }
595
+ function zodSchemaToYamlExample(schema, maxDepth = 3) {
596
+ return renderYamlObject(schema, 0, maxDepth);
597
+ }
598
+ function renderYamlObject(schema, indent, maxDepth) {
599
+ const fields = extractFieldDescriptors(schema);
600
+ if (!fields || fields.length === 0) return "";
601
+ const prefix = " ".repeat(indent);
602
+ const lines = [];
603
+ for (const f of fields) {
604
+ const shape = schema instanceof z.ZodObject ? schema.shape : null;
605
+ const rawField = shape?.[f.name];
606
+ if (f.type.endsWith("[]")) {
607
+ lines.push(`${prefix}${f.name}:`);
608
+ const element = rawField ? getArrayElement(rawField) : null;
609
+ if (element && element instanceof z.ZodObject && indent < maxDepth) {
610
+ const nested = renderYamlObject(element, indent + 2, maxDepth);
611
+ if (nested) {
612
+ const basePrefix = " ".repeat(indent + 2);
613
+ const nestedLines = nested.split("\n");
614
+ lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
615
+ for (let i = 1; i < nestedLines.length; i++) {
616
+ lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
617
+ }
618
+ } else {
619
+ lines.push(`${prefix} - key: "value"`);
620
+ }
621
+ } else if (f.type === "string[]") {
622
+ lines.push(`${prefix} - "example"`);
623
+ } else {
624
+ lines.push(`${prefix} - key: "value"`);
625
+ }
626
+ } else if (f.type === "object" && indent < maxDepth) {
627
+ const inner = rawField ? unwrapOptional(rawField) : null;
628
+ if (inner && inner instanceof z.ZodObject) {
629
+ lines.push(`${prefix}${f.name}:`);
630
+ const nested = renderYamlObject(inner, indent + 1, maxDepth);
631
+ if (nested) {
632
+ lines.push(nested);
633
+ } else {
634
+ lines.push(`${prefix} key: "value"`);
635
+ }
636
+ } else {
637
+ lines.push(`${prefix}${f.name}:`);
638
+ lines.push(`${prefix} key: "value"`);
639
+ }
640
+ } else if (f.type === "string") {
641
+ lines.push(`${prefix}${f.name}: "..."`);
642
+ } else if (f.type === "number") {
643
+ lines.push(`${prefix}${f.name}: 0`);
644
+ } else if (f.type === "boolean") {
645
+ lines.push(`${prefix}${f.name}: false`);
646
+ } else if (f.type.startsWith("enum(")) {
647
+ const enumVals = f.type.slice(5, -1).split(", ");
648
+ lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
649
+ } else {
650
+ lines.push(`${prefix}${f.name}: "..."`);
651
+ }
652
+ }
653
+ return lines.join("\n");
654
+ }
655
+ function isNavigationIndex(value) {
656
+ if (typeof value !== "object" || value === null) return false;
657
+ const obj = value;
658
+ return typeof obj.system === "object" && obj.system !== null && typeof obj.artifacts === "object" && obj.artifacts !== null;
659
+ }
660
+ function renderNavigationIndexPrompt(navigationIndex) {
661
+ const system = navigationIndex.system;
662
+ const artifacts = navigationIndex.artifacts ?? {};
663
+ const ids = Object.keys(artifacts);
664
+ const sections = ["## Project Navigation Index"];
665
+ const systemLabel = system?.name ? `${system.name}${system.id ? ` (${system.id})` : ""}` : system?.id ?? "unknown";
666
+ sections.push(
667
+ `System: ${systemLabel}
668
+ Artifacts: ${ids.length}`
669
+ );
670
+ if (ids.length > 0) {
671
+ const lines = [];
672
+ for (const id of ids) {
673
+ const node = artifacts[id] ?? {};
674
+ const props = node.properties ?? {};
675
+ const tags = [props.type, props.authority].filter((v) => typeof v === "string" && v.length > 0).join(", ");
676
+ const editPolicy = typeof props.manual_edit === "string" ? `, edit:${props.manual_edit}` : "";
677
+ lines.push(`- ${id}${tags || editPolicy ? ` [${tags}${editPolicy}]` : ""}`);
678
+ const patterns = node.files?.path_patterns;
679
+ if (Array.isArray(patterns) && patterns.length > 0) {
680
+ lines.push(` files: ${patterns.join(", ")}`);
681
+ }
682
+ const derived = node.relations?.derived_artifacts;
683
+ if (Array.isArray(derived) && derived.length > 0) {
684
+ lines.push(` derived \u2192 ${derived.join(", ")}`);
685
+ }
686
+ const owners = node.agents?.owners;
687
+ if (Array.isArray(owners) && owners.length > 0) {
688
+ lines.push(` owners: ${owners.join(", ")}`);
689
+ }
690
+ }
691
+ sections.push(lines.join("\n"));
692
+ }
693
+ return sections.join("\n\n");
694
+ }
695
+ function collectAnalyzerToolIds(registry) {
696
+ if (!registry) return [];
697
+ return registry.getAll().map((def) => def.toolId).filter((id) => id.startsWith("analyzer."));
698
+ }
699
+ function shouldInjectAnalyzerExplorationMandate(context) {
700
+ return isNavigationIndex(context.variables?.navigationIndex);
701
+ }
702
+ function renderAnalyzerExplorationMandatePrompt(toolIds) {
703
+ const tools = toolIds.length > 0 ? toolIds.map((id) => `- \`${id}\``).join("\n") : "- `analyzer.generateContextPack`\n- `analyzer.analyzeImpact`\n- `analyzer.buildCallGraph`";
704
+ return [
705
+ "## Codebase Exploration Protocol (Level 1)",
706
+ "",
707
+ "A Project Navigation Index is provided in the user prompt. When you need to",
708
+ "investigate the codebase (locate affected files, trace dependencies, or scope",
709
+ "changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:",
710
+ "",
711
+ "1. Use the navigation index to pick candidate artifacts and path patterns.",
712
+ "2. Call `analyzer.generateContextPack` with your `changed[]` paths and a token budget.",
713
+ "3. Call `analyzer.analyzeImpact` with the same `changed[]` paths.",
714
+ "4. Use Read/Grep/Glob only for gaps the analyzer output did not cover.",
715
+ "",
716
+ "Available analyzer tools:",
717
+ tools
718
+ ].join("\n");
719
+ }
720
+ function buildSplitTaskPrompt(agent, task, context, options) {
721
+ const system = [];
722
+ system.push(renderAgentSystemPrompt(agent));
723
+ if (options?.analyzerExploration?.toolIds.length && shouldInjectAnalyzerExplorationMandate(context)) {
724
+ system.push(
725
+ renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds)
726
+ );
727
+ }
728
+ system.push(`## Task: ${task.id}
729
+
730
+ ${task.description}`);
731
+ if (task.completion_criteria.length > 0) {
732
+ system.push(
733
+ `## Completion Criteria
734
+
735
+ ${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
736
+ );
737
+ }
738
+ const handoffId = task.result_handoff;
739
+ const schema = options?.handoffSchemas?.[handoffId];
740
+ let outputSection = `## Required Output Format
741
+
742
+ Return your result as a YAML block matching the "${handoffId}" schema.`;
743
+ if (schema) {
744
+ const fieldTable = zodSchemaToPromptDescription(schema);
745
+ if (fieldTable) {
746
+ outputSection += `
747
+
748
+ ${fieldTable}`;
749
+ }
750
+ const yamlExample = zodSchemaToYamlExample(schema);
751
+ if (yamlExample) {
752
+ outputSection += `
753
+
754
+ Example:
755
+
756
+ \`\`\`yaml
757
+ ${yamlExample}
758
+ \`\`\``;
759
+ }
760
+ } else {
761
+ outputSection += ` Include all required fields.`;
762
+ }
763
+ system.push(outputSection);
764
+ if (options?.retry) {
765
+ const r = options.retry;
766
+ let recoverySection = `## Recovery Instructions
767
+
768
+ If the task fails due to: "${r.condition}"
769
+ \u2192 Apply the recovery approach from task "${r.fix_task}"`;
770
+ if (r.revalidate_task) {
771
+ recoverySection += `
772
+ \u2192 Then revalidate using task "${r.revalidate_task}"`;
773
+ }
774
+ system.push(recoverySection);
775
+ }
776
+ const userSections = [];
777
+ if (context.handoff_input) {
778
+ const hi = context.handoff_input;
779
+ const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
780
+ userSections.push(`## User Request
781
+
782
+ ${context.user_request}`);
783
+ userSections.push(`## Handoff Input (${hi.type})
784
+
785
+ \`\`\`yaml
786
+ ${payloadStr}\`\`\``);
787
+ } else {
788
+ userSections.push(`## User Request
789
+
790
+ ${context.user_request}`);
791
+ }
792
+ if (context.prior_context) {
793
+ userSections.push(`## Prior Context
794
+
795
+ ${context.prior_context}`);
796
+ }
797
+ if (context.relevant_paths && context.relevant_paths.length > 0) {
798
+ userSections.push(
799
+ `## Relevant Files
800
+
801
+ ${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
802
+ );
803
+ }
804
+ if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
805
+ userSections.push(
806
+ `## Acceptance Criteria
807
+
808
+ ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
809
+ );
810
+ }
811
+ if (context.variables && Object.keys(context.variables).length > 0) {
812
+ const contextPack = context.variables.analyzerContextPack;
813
+ if (isContextPack(contextPack)) {
814
+ userSections.push(renderContextPackPrompt(contextPack));
815
+ }
816
+ const navigationIndex = context.variables.navigationIndex;
817
+ if (isNavigationIndex(navigationIndex)) {
818
+ userSections.push(renderNavigationIndexPrompt(navigationIndex));
819
+ }
820
+ const otherVars = Object.entries(context.variables).filter(
821
+ ([k]) => k !== "analyzerContextPack" && k !== "navigationIndex"
822
+ );
823
+ if (otherVars.length > 0) {
824
+ const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
825
+ userSections.push(`## Context Variables
826
+
827
+ ${varLines}`);
828
+ }
829
+ }
830
+ return {
831
+ system,
832
+ user: userSections.join("\n\n---\n\n")
833
+ };
834
+ }
835
+ function joinSplitPrompt(split) {
836
+ return [...split.system, split.user].join("\n\n---\n\n");
837
+ }
838
+ function buildTaskPrompt(agent, task, context, options) {
839
+ return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
840
+ }
841
+ function extractStructuredResult(raw) {
842
+ const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
843
+ if (yamlMatch) {
844
+ try {
845
+ return yaml.parse(yamlMatch[1]);
846
+ } catch {
847
+ }
848
+ }
849
+ const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
850
+ if (jsonMatch) {
851
+ try {
852
+ return JSON.parse(jsonMatch[1]);
853
+ } catch {
854
+ }
855
+ }
856
+ try {
857
+ return JSON.parse(raw);
858
+ } catch {
859
+ }
860
+ return null;
861
+ }
862
+ function validateOutput(fullOutput, task, schemas) {
863
+ if (!fullOutput.trim()) {
864
+ return { status: "error", message: "Agent returned empty output" };
865
+ }
866
+ const parsed = extractStructuredResult(fullOutput);
867
+ if (!parsed) {
868
+ return {
869
+ status: "validation_error",
870
+ errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
871
+ raw: fullOutput
872
+ };
873
+ }
874
+ const schema = schemas[task.result_handoff];
875
+ if (!schema) {
876
+ return { status: "success", data: parsed, raw: fullOutput };
877
+ }
878
+ const validation = schema.safeParse(parsed);
879
+ if (!validation.success) {
880
+ return { status: "validation_error", errors: validation.error, raw: fullOutput };
881
+ }
882
+ const data = validation.data;
883
+ if (data.escalation_needed === true) {
884
+ return {
885
+ status: "escalation",
886
+ reason: data.escalation_reasons ?? "Agent requested escalation",
887
+ raw: fullOutput
888
+ };
889
+ }
890
+ return { status: "success", data: validation.data, raw: fullOutput };
891
+ }
892
+ function attachMemoryRef(outcome, adapter) {
893
+ if (outcome.status !== "success") return outcome;
894
+ const ref = adapter.getLastMemoryRef?.();
895
+ if (!ref) return outcome;
896
+ return { ...outcome, memoryRef: ref };
897
+ }
898
+ function buildRetryFollowUp(task, lastOutcome, options) {
899
+ const sections = [];
900
+ sections.push(
901
+ "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."
902
+ );
903
+ if (lastOutcome.status === "validation_error") {
904
+ sections.push(`Validation errors:
905
+ ${lastOutcome.errors.message}`);
906
+ } else if (lastOutcome.status === "error") {
907
+ sections.push(`Error: ${lastOutcome.message}`);
908
+ }
909
+ const handoffId = task.result_handoff;
910
+ const schema = options?.handoffSchemas?.[handoffId];
911
+ let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
912
+ if (schema) {
913
+ const fieldTable = zodSchemaToPromptDescription(schema);
914
+ if (fieldTable) {
915
+ formatSection += `
916
+
917
+ ${fieldTable}`;
918
+ }
919
+ const yamlExample = zodSchemaToYamlExample(schema);
920
+ if (yamlExample) {
921
+ formatSection += `
922
+
923
+ Example:
924
+
925
+ \`\`\`yaml
926
+ ${yamlExample}
927
+ \`\`\``;
928
+ }
929
+ } else {
930
+ formatSection += ` Include all required fields.`;
931
+ }
932
+ sections.push(formatSection);
933
+ return sections.join("\n\n");
934
+ }
935
+ function defaultDecideRetryStrategy(outcome, _counts) {
936
+ if (outcome.status === "validation_error") {
937
+ return "follow_up";
938
+ }
939
+ if (outcome.status === "error") {
940
+ if (outcome.message === "Agent returned empty output") return "retry";
941
+ return "abort";
942
+ }
943
+ return "abort";
944
+ }
945
+ function summarizeToolInput(input) {
946
+ if (!input) return "";
947
+ const path = input.file_path ?? input.path ?? input.filename ?? input.file;
948
+ if (typeof path === "string") return ` \u2014 ${path}`;
949
+ const cmd = input.command ?? input.cmd;
950
+ if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
951
+ const query = input.query ?? input.search ?? input.pattern;
952
+ if (typeof query === "string") return ` \u2014 "${query}"`;
953
+ return "";
954
+ }
955
+ function timestamp() {
956
+ return (/* @__PURE__ */ new Date()).toISOString();
957
+ }
958
+ function formatProgressPrefix(event, taskId, agentId) {
959
+ const ts = timestamp();
960
+ const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
961
+ const agent = agentId ?? "-";
962
+ return `[${ts},${sid},${agent},${taskId}]`;
963
+ }
964
+ function formatProgressEvent(event, taskId, agentId) {
965
+ const prefix = formatProgressPrefix(event, taskId, agentId);
966
+ switch (event.type) {
967
+ case "tool_use":
968
+ return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
969
+ `;
970
+ case "tool_result":
971
+ return "";
972
+ case "text": {
973
+ if (!event.message) return "";
974
+ const trimmed = event.message.trim();
975
+ if (!trimmed) return "";
976
+ const firstLine = trimmed.split("\n")[0];
977
+ const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
978
+ return `${prefix} \u{1F4AD} ${preview}
979
+ `;
980
+ }
981
+ case "status":
982
+ return event.message ? `${prefix} \u25CF ${event.message}
983
+ ` : "";
984
+ default:
985
+ return "";
986
+ }
987
+ }
988
+ async function runTask(adapter, taskId, context, options) {
989
+ const taskReg = options?.taskRegistry ?? {};
990
+ const agentReg = options?.agentRegistry ?? {};
991
+ const schemas = options?.handoffSchemas ?? {};
992
+ const task = taskReg[taskId];
993
+ if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
994
+ const agentContract = agentReg[task.target_agent];
995
+ if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
996
+ const taskEnvelope = createExecutionEnvelope({
997
+ taskInstanceId: taskId,
998
+ componentId: agentContract.id,
999
+ fromAgent: agentContract.id,
1000
+ parentRunId: options?.parentSpanId,
1001
+ // correlates to agent.session run_id
1002
+ adapter: options?.envelopeAdapter,
1003
+ model: options?.envelopeModel
1004
+ });
1005
+ const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
1006
+ if (modifiedContext === null) {
1007
+ return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
1008
+ }
1009
+ const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
1010
+ const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);
1011
+ const promptOpts = {
1012
+ handoffSchemas: schemas,
1013
+ retry: options?.retry,
1014
+ ...analyzerToolIds.length > 0 && shouldInjectAnalyzerExplorationMandate(enrichedContext) ? { analyzerExploration: { toolIds: analyzerToolIds } } : {}
1015
+ };
1016
+ const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
1017
+ let prompt;
1018
+ let splitPrompt;
1019
+ const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
1020
+ if (pluginPrompt) {
1021
+ prompt = pluginPrompt;
1022
+ } else {
1023
+ const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
1024
+ splitPrompt = split;
1025
+ prompt = joinSplitPrompt(split);
1026
+ }
1027
+ const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
1028
+ if (enhancedPrompt !== prompt) {
1029
+ splitPrompt = void 0;
1030
+ prompt = enhancedPrompt;
1031
+ }
1032
+ const isReadonly = agentContract.mode === "read-only";
1033
+ const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
1034
+ const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
1035
+ entryAgentId: agentContract.id,
1036
+ allowedAgentIds: agentContract.can_invoke_agents
1037
+ }) : [];
1038
+ const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
1039
+ const maxFollowUps = options?.maxFollowUps ?? 2;
1040
+ const maxRetries = options?.maxRetries ?? 0;
1041
+ const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
1042
+ const taskExecStart = Date.now();
1043
+ const effectiveSessionId = options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;
1044
+ let processTaskSpanId;
1045
+ const emittedEditPaths = /* @__PURE__ */ new Set();
1046
+ const onProgress = options?.progressOutput || options?.observer ? (event) => {
1047
+ if (options?.progressOutput) {
1048
+ const line = formatProgressEvent(event, taskId, agentContract.id);
1049
+ if (line) options.progressOutput.write(line);
1050
+ }
1051
+ if (options?.observer && event.type === "tool_use" && isFileEditTool(event.tool_name)) {
1052
+ const input = event.input ?? {};
1053
+ const p = input.file_path ?? input.path ?? input.filename ?? input.file;
1054
+ if (typeof p === "string" && p.length > 0 && !emittedEditPaths.has(p)) {
1055
+ emittedEditPaths.add(p);
1056
+ emitProcessEdit({
1057
+ filePath: p,
1058
+ sessionId: effectiveSessionId,
1059
+ observer: options.observer
1060
+ });
1061
+ }
1062
+ }
1063
+ } : void 0;
1064
+ let followUpsUsed = 0;
1065
+ let retriesUsed = 0;
1066
+ let memoryRef = enrichedContext.memoryRef;
1067
+ if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
1068
+ console.warn(
1069
+ `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
1070
+ );
1071
+ memoryRef = void 0;
1072
+ }
1073
+ const subagentSpanId = emitSubagentOpen(
1074
+ options?.observer,
1075
+ taskEnvelope,
1076
+ options?.parentSpanId,
1077
+ taskId,
1078
+ agentContract.role_name,
1079
+ effectiveSessionId
1080
+ );
1081
+ processTaskSpanId = emitProcessTaskOpen({
1082
+ taskId,
1083
+ targetAgent: task.target_agent,
1084
+ sessionId: effectiveSessionId,
1085
+ parentSpanId: subagentSpanId ?? options?.parentSpanId,
1086
+ observer: options?.observer
1087
+ });
1088
+ let closeStatus = "error";
1089
+ let closeCause;
1090
+ let spanClosed = false;
1091
+ const closeSubagentSpan = () => {
1092
+ if (spanClosed) return;
1093
+ spanClosed = true;
1094
+ const durationMs = Date.now() - taskExecStart;
1095
+ const lastTokenUsage = adapter.getLastTokenUsage?.();
1096
+ taskEnvelope.execution_metadata = {
1097
+ ...taskEnvelope.execution_metadata ?? {},
1098
+ duration_ms: durationMs,
1099
+ ...lastTokenUsage ? {
1100
+ token_usage: {
1101
+ input_tokens: lastTokenUsage.inputTokens,
1102
+ output_tokens: lastTokenUsage.outputTokens,
1103
+ ...lastTokenUsage.totalTokens !== void 0 ? { total_tokens: lastTokenUsage.totalTokens } : {},
1104
+ ...lastTokenUsage.cacheReadTokens !== void 0 ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {},
1105
+ ...lastTokenUsage.cacheCreationTokens !== void 0 ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}
1106
+ }
1107
+ } : {}
1108
+ };
1109
+ emitSubagentClose(
1110
+ options?.observer,
1111
+ subagentSpanId ?? taskEnvelope.run_id,
1112
+ taskEnvelope,
1113
+ durationMs,
1114
+ closeStatus,
1115
+ agentContract.role_name,
1116
+ closeCause,
1117
+ effectiveSessionId
1118
+ );
1119
+ if (processTaskSpanId) {
1120
+ emitProcessTaskClose(processTaskSpanId, {
1121
+ status: closeStatus,
1122
+ durationMs,
1123
+ observer: options?.observer
1124
+ });
1125
+ }
1126
+ };
1127
+ try {
1128
+ let fullOutput;
1129
+ try {
1130
+ if (adapter.sendExecution) {
1131
+ fullOutput = await adapter.sendExecution({
1132
+ agentId: agentContract.id,
1133
+ taskId,
1134
+ prompt,
1135
+ handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
1136
+ schema: schemas[task.result_handoff] ? {
1137
+ handoffType: task.result_handoff,
1138
+ zodSchema: schemas[task.result_handoff],
1139
+ promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
1140
+ } : void 0,
1141
+ context: enrichedContext,
1142
+ memoryRef,
1143
+ splitPrompt,
1144
+ agents,
1145
+ options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 }
1146
+ });
1147
+ } else {
1148
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });
1149
+ }
1150
+ } catch (err) {
1151
+ closeStatus = "error";
1152
+ closeCause = `SDK error: ${err.message}`;
1153
+ return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
1154
+ }
1155
+ let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1156
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1157
+ while (outcome.status === "validation_error" || outcome.status === "error") {
1158
+ const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
1159
+ if (decision === "abort") break;
1160
+ let effectiveDecision = decision;
1161
+ if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
1162
+ effectiveDecision = "retry";
1163
+ }
1164
+ if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
1165
+ break;
1166
+ }
1167
+ if (effectiveDecision === "follow_up") {
1168
+ followUpsUsed++;
1169
+ const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
1170
+ try {
1171
+ if (adapter.followUp) {
1172
+ fullOutput = await adapter.followUp(followUpPrompt);
1173
+ } else {
1174
+ const retryContext = {
1175
+ ...modifiedContext,
1176
+ prior_context: (modifiedContext.prior_context ?? "") + `
1177
+
1178
+ --- FollowUp ${followUpsUsed} ---
1179
+ ${followUpPrompt}`
1180
+ };
1181
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
1182
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1183
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1184
+ }
1185
+ } catch (err) {
1186
+ outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
1187
+ continue;
1188
+ }
1189
+ } else {
1190
+ retriesUsed++;
1191
+ const retryContext = {
1192
+ ...modifiedContext,
1193
+ prior_context: (modifiedContext.prior_context ?? "") + `
1194
+
1195
+ --- Full Retry ${retriesUsed} ---
1196
+ Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
1197
+ Please re-execute the entire task.`
1198
+ };
1199
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
1200
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1201
+ try {
1202
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1203
+ } catch (err) {
1204
+ outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
1205
+ continue;
1206
+ }
1207
+ }
1208
+ outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1209
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1210
+ }
1211
+ closeStatus = outcome.status;
1212
+ const finalTokenUsage = adapter.getLastTokenUsage?.() ?? void 0;
1213
+ return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };
1214
+ } catch (err) {
1215
+ closeStatus = "error";
1216
+ closeCause = err.message;
1217
+ throw err;
1218
+ } finally {
1219
+ closeSubagentSpan();
1220
+ }
1221
+ }
1222
+
1223
+ // src/lib/dsl-context.ts
1224
+ import { readFile } from "fs/promises";
1225
+ import YAML from "yaml";
1226
+ var DslValidationError = class extends Error {
1227
+ missing;
1228
+ constructor(missing) {
1229
+ super(
1230
+ "Required entities missing after DSL merge:\n" + missing.map((m) => ` - ${m}`).join("\n")
1231
+ );
1232
+ this.name = "DslValidationError";
1233
+ this.missing = missing;
1234
+ }
1235
+ };
1236
+ function buildAgentRegistry(agents) {
1237
+ const registry = {};
1238
+ for (const [id, agent] of Object.entries(agents)) {
1239
+ const rawMode = agent.mode ?? "read-only";
1240
+ const mode = rawMode === "read-write" ? "read-write" : "read-only";
1241
+ registry[id] = {
1242
+ id,
1243
+ role_name: agent.role_name ?? id,
1244
+ purpose: agent.purpose ?? "",
1245
+ mode,
1246
+ responsibilities: agent.responsibilities ?? [],
1247
+ constraints: agent.constraints ?? [],
1248
+ rules: agent.rules ?? [],
1249
+ can_invoke_agents: agent.can_invoke_agents ?? void 0,
1250
+ can_execute_tools: agent.can_execute_tools ?? void 0
1251
+ };
1252
+ }
1253
+ return registry;
1254
+ }
1255
+ function buildTaskRegistry(tasks) {
1256
+ const registry = {};
1257
+ for (const [id, task] of Object.entries(tasks)) {
1258
+ registry[id] = {
1259
+ id,
1260
+ description: task.description ?? "",
1261
+ target_agent: task.target_agent ?? "",
1262
+ result_handoff: task.result_handoff ?? "",
1263
+ completion_criteria: task.completion_criteria ?? [],
1264
+ model_class: task.model_class
1265
+ };
1266
+ }
1267
+ return registry;
1268
+ }
1269
+ function buildWorkflowStep(step) {
1270
+ if (step.type === "gate") {
1271
+ return {
1272
+ type: "gate",
1273
+ gate_kind: step.gate_kind ?? "",
1274
+ description: step.description ?? "",
1275
+ depends_on: step.depends_on
1276
+ };
1277
+ }
1278
+ if (step.type === "evaluate") {
1279
+ return {
1280
+ type: "evaluate",
1281
+ task: step.task ?? "",
1282
+ from_agent: step.from_agent ?? "",
1283
+ evaluator_agent: step.evaluator_agent,
1284
+ description: step.description,
1285
+ loop_to: step.loop_to ?? "",
1286
+ max_iterations: step.max_iterations ?? 1,
1287
+ inject_as: step.inject_as,
1288
+ on_exhausted: step.on_exhausted,
1289
+ depends_on: step.depends_on
1290
+ };
1291
+ }
1292
+ return {
1293
+ type: "delegate",
1294
+ task: step.task ?? "",
1295
+ from_agent: step.from_agent ?? "",
1296
+ description: step.description ?? "",
1297
+ optional: step.optional ?? false,
1298
+ max_retries: step.max_retries ?? 0,
1299
+ max_follow_ups: step.max_follow_ups,
1300
+ depends_on: step.depends_on,
1301
+ instruction: step.instruction,
1302
+ receives: step.receives,
1303
+ retry: step.retry
1304
+ };
1305
+ }
1306
+ function buildWorkflowRegistry(workflows) {
1307
+ const registry = {};
1308
+ for (const [id, wf] of Object.entries(workflows)) {
1309
+ const steps = (wf.steps ?? []).map(buildWorkflowStep);
1310
+ registry[id] = { id, description: wf.description ?? "", steps };
1311
+ }
1312
+ return registry;
1313
+ }
1314
+ function buildHandoffSchemas(handoffTypes) {
1315
+ const schemas = {};
1316
+ for (const [id, ht] of Object.entries(handoffTypes)) {
1317
+ const schema = ht.schema;
1318
+ if (schema) {
1319
+ schemas[id] = jsonSchemaToZod(schema);
1320
+ }
1321
+ }
1322
+ return schemas;
1323
+ }
1324
+ function buildGuardrailRulesFromDsl(dsl) {
1325
+ const raw = dsl._guardrailRules;
1326
+ if (!raw) return void 0;
1327
+ return {
1328
+ commandRules: raw.commandRules ?? [],
1329
+ fileRules: raw.fileRules ?? [],
1330
+ contentRules: raw.contentRules ?? []
1331
+ };
1332
+ }
1333
+ function buildRegistriesFromDsl(dsl) {
1334
+ const agents = dsl.agents ?? {};
1335
+ const tasks = dsl.tasks ?? {};
1336
+ const workflows = dsl.workflow ?? {};
1337
+ const handoffTypes = dsl.handoff_types ?? {};
1338
+ return {
1339
+ agentRegistry: buildAgentRegistry(agents),
1340
+ taskRegistry: buildTaskRegistry(tasks),
1341
+ workflowRegistry: buildWorkflowRegistry(workflows),
1342
+ handoffSchemas: buildHandoffSchemas(handoffTypes)
1343
+ };
1344
+ }
1345
+ function validateRequiredEntities(dsl, required) {
1346
+ const missing = [];
1347
+ const workflows = dsl.workflow ?? {};
1348
+ const tasks = dsl.tasks ?? {};
1349
+ const handoffTypes = dsl.handoff_types ?? {};
1350
+ if (required.workflows) {
1351
+ for (const wfId of required.workflows) {
1352
+ if (!(wfId in workflows)) {
1353
+ missing.push(`workflow "${wfId}" is required by the CLI but not found in the resolved DSL`);
1354
+ }
1355
+ }
1356
+ }
1357
+ if (required.tasks) {
1358
+ for (const taskId of required.tasks) {
1359
+ if (!(taskId in tasks)) {
1360
+ missing.push(`task "${taskId}" is required by the CLI but not found in the resolved DSL`);
1361
+ continue;
1362
+ }
1363
+ const task = tasks[taskId];
1364
+ const invHandoff = task.invocation_handoff;
1365
+ const resHandoff = task.result_handoff;
1366
+ if (invHandoff && !(invHandoff in handoffTypes)) {
1367
+ missing.push(`handoff_type "${invHandoff}" (invocation_handoff of task "${taskId}") not found`);
1368
+ }
1369
+ if (resHandoff && !(resHandoff in handoffTypes)) {
1370
+ missing.push(`handoff_type "${resHandoff}" (result_handoff of task "${taskId}") not found`);
1371
+ }
1372
+ }
1373
+ }
1374
+ if (required.workflows) {
1375
+ for (const wfId of required.workflows) {
1376
+ if (!(wfId in workflows)) continue;
1377
+ const wf = workflows[wfId];
1378
+ const steps = wf.steps ?? [];
1379
+ for (const step of steps) {
1380
+ if (step.type !== "delegate") continue;
1381
+ const taskId = step.task;
1382
+ if (taskId && taskId in tasks) {
1383
+ const task = tasks[taskId];
1384
+ const resHandoff = task.result_handoff;
1385
+ if (resHandoff && !(resHandoff in handoffTypes)) {
1386
+ missing.push(`handoff_type "${resHandoff}" (result of task "${taskId}" in workflow "${wfId}") not found`);
1387
+ }
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+ if (missing.length > 0) {
1393
+ throw new DslValidationError(missing);
1394
+ }
1395
+ }
1396
+ async function loadDslContext(options) {
1397
+ let dsl;
1398
+ if (options.projectDslPath) {
1399
+ const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
1400
+ const raw = await readFile(options.projectDslPath, "utf8");
1401
+ const projectData = YAML.parse(raw);
1402
+ if (projectData.extends === "/$embedded/") {
1403
+ const { extends: _extends, ...projectOverrides } = projectData;
1404
+ const merged = mergeDsl(options.embeddedDsl, projectOverrides);
1405
+ dsl = expandDefaults(merged);
1406
+ } else {
1407
+ const projectResult = await resolveDsl(options.projectDslPath);
1408
+ const merged = mergeDsl(options.embeddedDsl, projectResult.data);
1409
+ dsl = expandDefaults(merged);
1410
+ }
1411
+ } else {
1412
+ dsl = options.embeddedDsl;
1413
+ }
1414
+ if (options.requiredEntities) {
1415
+ validateRequiredEntities(dsl, options.requiredEntities);
1416
+ }
1417
+ const registries = buildRegistriesFromDsl(dsl);
1418
+ const guardrailRules = buildGuardrailRulesFromDsl(dsl);
1419
+ return { registries, dsl, guardrailRules };
1420
+ }
1421
+
1422
+ // src/lib/navigation-context.ts
1423
+ async function buildNavigationContext(options) {
1424
+ const diagnostics = [];
1425
+ let dsl;
1426
+ if (options.embeddedDsl != null) {
1427
+ if (options.projectDslPath) {
1428
+ const ctx = await loadDslContext({
1429
+ embeddedDsl: options.embeddedDsl,
1430
+ projectDslPath: options.projectDslPath
1431
+ });
1432
+ dsl = ctx.dsl;
1433
+ } else {
1434
+ dsl = options.embeddedDsl;
1435
+ }
1436
+ } else if (options.projectDslPath) {
1437
+ const { resolve } = await import("agent-contracts");
1438
+ const result = await resolve(options.projectDslPath);
1439
+ dsl = result.data;
1440
+ } else {
1441
+ throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
1442
+ }
1443
+ if (options.artifactBinding) {
1444
+ const { resolveBound } = await import("agent-contracts");
1445
+ const boundResult = await resolveBound(dsl, {
1446
+ artifactBinding: options.artifactBinding,
1447
+ paths: options.paths
1448
+ });
1449
+ dsl = boundResult.data;
1450
+ for (const d of boundResult.diagnostics) {
1451
+ diagnostics.push({
1452
+ path: d.rule,
1453
+ message: d.message,
1454
+ severity: d.severity
1455
+ });
1456
+ }
1457
+ }
1458
+ const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
1459
+ const validation = validateSchema(dsl);
1460
+ for (const d of validation.diagnostics) {
1461
+ diagnostics.push({
1462
+ path: d.path,
1463
+ message: d.message,
1464
+ severity: d.severity ?? "error"
1465
+ });
1466
+ }
1467
+ const navigationIndex = buildNavigationIndex(
1468
+ validation.data ?? dsl
1469
+ );
1470
+ return { dsl, navigationIndex, diagnostics };
1471
+ }
1472
+
1473
+ export {
1474
+ renderAgentSystemPrompt,
1475
+ buildCandidateAgents,
1476
+ createAnalyzerBridge,
1477
+ isContextPack,
1478
+ renderContextPackPrompt,
1479
+ isFileEditTool,
1480
+ emitProcessWorkflowOpen,
1481
+ emitProcessWorkflowClose,
1482
+ emitProcessTaskOpen,
1483
+ emitProcessTaskClose,
1484
+ emitProcessEdit,
1485
+ zodSchemaToPromptDescription,
1486
+ zodSchemaToYamlExample,
1487
+ isNavigationIndex,
1488
+ renderNavigationIndexPrompt,
1489
+ collectAnalyzerToolIds,
1490
+ shouldInjectAnalyzerExplorationMandate,
1491
+ renderAnalyzerExplorationMandatePrompt,
1492
+ buildSplitTaskPrompt,
1493
+ buildTaskPrompt,
1494
+ extractStructuredResult,
1495
+ buildRetryFollowUp,
1496
+ runTask,
1497
+ DslValidationError,
1498
+ buildGuardrailRulesFromDsl,
1499
+ buildRegistriesFromDsl,
1500
+ loadDslContext,
1501
+ buildNavigationContext
1502
+ };
1503
+ //# sourceMappingURL=chunk-63RFYS7F.js.map