@aaac/runtime 0.1.54 → 0.2.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.
Files changed (71) hide show
  1. package/README.md +6 -11
  2. package/dist/adapters/adk-sdk.d.ts +3 -3
  3. package/dist/adapters/adk-sdk.js +6 -8
  4. package/dist/adapters/adk-sdk.js.map +1 -1
  5. package/dist/adapters/claude-agent-sdk.d.ts +3 -3
  6. package/dist/adapters/claude-agent-sdk.js +22 -23
  7. package/dist/adapters/claude-agent-sdk.js.map +1 -1
  8. package/dist/adapters/mock.d.ts +2 -3
  9. package/dist/adapters/openai-agents-sdk.d.ts +3 -3
  10. package/dist/adapters/openai-agents-sdk.js +6 -5
  11. package/dist/adapters/openai-agents-sdk.js.map +1 -1
  12. package/dist/chunk-2INQL5TG.js +298 -0
  13. package/dist/chunk-2INQL5TG.js.map +1 -0
  14. package/dist/chunk-3CLWG72V.js +47 -0
  15. package/dist/chunk-3CLWG72V.js.map +1 -0
  16. package/dist/chunk-3DDB34BU.js +237 -0
  17. package/dist/chunk-3DDB34BU.js.map +1 -0
  18. package/dist/chunk-ABXDSTUV.js +685 -0
  19. package/dist/chunk-ABXDSTUV.js.map +1 -0
  20. package/dist/{chunk-3H3PVPPF.js → chunk-F5R46S7I.js} +151 -204
  21. package/dist/chunk-F5R46S7I.js.map +1 -0
  22. package/dist/chunk-FKAI54OM.js +234 -0
  23. package/dist/chunk-FKAI54OM.js.map +1 -0
  24. package/dist/chunk-KTVMMG33.js +1111 -0
  25. package/dist/chunk-KTVMMG33.js.map +1 -0
  26. package/dist/chunk-MSVIEEGR.js +269 -0
  27. package/dist/chunk-MSVIEEGR.js.map +1 -0
  28. package/dist/chunk-VJXGCWSZ.js +36 -0
  29. package/dist/chunk-VJXGCWSZ.js.map +1 -0
  30. package/dist/claude-bundles/full.js +311 -309
  31. package/dist/claude-bundles/lean.js +6 -6
  32. package/dist/claude-bundles/prompt.js +17 -0
  33. package/dist/generator/index.d.ts +2 -2
  34. package/dist/generator/index.js +8 -7
  35. package/dist/guardrail-hooks-CB23nhZV.d.ts +202 -0
  36. package/dist/hook-protocol-CFnNudiV.d.ts +96 -0
  37. package/dist/hooks-lite-CoWWnCRH.d.ts +428 -0
  38. package/dist/index-BlSepCSZ.d.ts +296 -0
  39. package/dist/index.d.ts +785 -105
  40. package/dist/index.js +2235 -659
  41. package/dist/index.js.map +1 -1
  42. package/dist/lib/claude-native/hooks-lite.d.ts +3 -26
  43. package/dist/lib/claude-native/hooks-lite.js +18 -36
  44. package/dist/lib/claude-native/hooks-prompt.d.ts +5 -0
  45. package/dist/lib/claude-native/hooks-prompt.js +33 -0
  46. package/dist/lib/claude-native/hooks-prompt.js.map +1 -0
  47. package/dist/lib/claude-native/index.d.ts +56 -214
  48. package/dist/lib/claude-native/index.js +79 -280
  49. package/dist/lib/claude-native/index.js.map +1 -1
  50. package/dist/{navigation-context-D_E1NIUf.d.ts → navigation-context-B-RpUg3_.d.ts} +1 -1
  51. package/dist/navigation-index-prompt-CbrS5laO.d.ts +43 -0
  52. package/dist/{task-runner-CLc8iTzy.d.ts → task-runner-GWoI7_71.d.ts} +100 -478
  53. package/dist/workspace-user-prompt-submit-D11Iu0zO.d.ts +269 -0
  54. package/package.json +15 -6
  55. package/dist/chunk-3H3PVPPF.js.map +0 -1
  56. package/dist/chunk-DBM5XN67.js +0 -354
  57. package/dist/chunk-DBM5XN67.js.map +0 -1
  58. package/dist/chunk-KXGUWBGK.js +0 -370
  59. package/dist/chunk-KXGUWBGK.js.map +0 -1
  60. package/dist/chunk-LDCQZPDG.js +0 -11
  61. package/dist/chunk-LDCQZPDG.js.map +0 -1
  62. package/dist/chunk-N4KNGDYY.js +0 -1963
  63. package/dist/chunk-N4KNGDYY.js.map +0 -1
  64. package/dist/chunk-NMX4C6LC.js +0 -332
  65. package/dist/chunk-NMX4C6LC.js.map +0 -1
  66. package/dist/chunk-QVH5KKBR.js +0 -374
  67. package/dist/chunk-QVH5KKBR.js.map +0 -1
  68. package/dist/context-DKkamYX_.d.ts +0 -31
  69. package/dist/guardrail-hooks-slK-z0Dz.d.ts +0 -83
  70. package/dist/index-LqEvaRk-.d.ts +0 -299
  71. package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +0 -333
@@ -1,1963 +0,0 @@
1
- import {
2
- jsonSchemaToZod
3
- } from "./chunk-ET6TGQRT.js";
4
- import {
5
- createExecutionEnvelope,
6
- emitSubagentClose,
7
- emitSubagentOpen
8
- } from "./chunk-KXGUWBGK.js";
9
- import {
10
- buildGuardrailContext
11
- } from "./chunk-3H3PVPPF.js";
12
- import {
13
- pluginRegistry
14
- } from "./chunk-NMX4C6LC.js";
15
-
16
- // src/lib/candidate-agents.ts
17
- function renderAgentSystemPrompt(agent) {
18
- const sections = [];
19
- sections.push(`# Role: ${agent.role_name}
20
-
21
- ${agent.purpose}`);
22
- if (agent.responsibilities.length > 0) {
23
- sections.push(
24
- `## Responsibilities
25
-
26
- ${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
27
- );
28
- }
29
- if (agent.constraints.length > 0) {
30
- sections.push(
31
- `## Constraints
32
-
33
- ${agent.constraints.map((c) => `- ${c}`).join("\n")}`
34
- );
35
- }
36
- if (agent.rules && agent.rules.length > 0) {
37
- const ruleLines = agent.rules.map(
38
- (r) => `- **${r.id}** [${r.severity}]: ${r.description}`
39
- );
40
- sections.push(`## Rules
41
-
42
- ${ruleLines.join("\n")}`);
43
- }
44
- return sections.join("\n\n");
45
- }
46
- function deriveDescription(purpose) {
47
- const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
48
- const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
49
- if (sentenceEnd !== -1) {
50
- return firstLine.slice(0, sentenceEnd + 1).trim();
51
- }
52
- return firstLine;
53
- }
54
- function buildCandidateAgents(agentRegistry, opts) {
55
- const entryId = opts?.entryAgentId;
56
- const allowed = opts?.allowedAgentIds;
57
- const allowSet = allowed ? new Set(allowed) : void 0;
58
- const candidates = [];
59
- for (const [id, agent] of Object.entries(agentRegistry)) {
60
- if (id === entryId) continue;
61
- if (allowSet && !allowSet.has(id)) continue;
62
- const agentTools = agent.can_execute_tools ? [...agent.can_execute_tools] : [];
63
- const derivedToolchains = opts?.toolchainsByAgent?.get(id);
64
- if (derivedToolchains) {
65
- for (const tc of derivedToolchains) {
66
- if (!agentTools.includes(tc.id)) {
67
- agentTools.push(tc.id);
68
- }
69
- }
70
- }
71
- candidates.push({
72
- name: id,
73
- description: deriveDescription(agent.purpose),
74
- prompt: renderAgentSystemPrompt(agent),
75
- ...agentTools.length > 0 ? { tools: agentTools } : {}
76
- });
77
- }
78
- return candidates;
79
- }
80
-
81
- // src/lib/analyzer-bridge.ts
82
- var ANALYZER_PKG = "artifact-contracts-analyzer";
83
- async function loadAnalyzerModule() {
84
- const mod = await import(
85
- /* webpackIgnore: true */
86
- ANALYZER_PKG
87
- );
88
- return mod;
89
- }
90
- function createAnalyzerBridge(options) {
91
- const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;
92
- let cachedGraph = null;
93
- let cachedFileContents = null;
94
- let graphBuildPromise = null;
95
- async function ensureGraph() {
96
- if (cachedGraph) return cachedGraph;
97
- if (graphBuildPromise) {
98
- await graphBuildPromise;
99
- return cachedGraph;
100
- }
101
- graphBuildPromise = doBuildGraph();
102
- await graphBuildPromise;
103
- return cachedGraph;
104
- }
105
- async function doBuildGraph() {
106
- let mod;
107
- try {
108
- mod = await loadAnalyzerModule();
109
- } catch (error) {
110
- const msg = error instanceof Error ? error.message : String(error);
111
- throw new Error(
112
- `artifact-contracts-analyzer is not available. Install it to use analyzer features: ${msg}`
113
- );
114
- }
115
- const patterns = artifactPatterns ?? /* @__PURE__ */ new Map();
116
- const registry = mod.createDefaultRegistry();
117
- const astResult = await mod.buildAstGraph({
118
- projectRoot,
119
- artifactPatterns: patterns,
120
- registry
121
- });
122
- cachedFileContents = astResult.fileContents;
123
- cachedGraph = await mod.buildDependencyGraph({
124
- ast: astResult.graph,
125
- projectRoot,
126
- artifactPatterns: patterns,
127
- manifests: manifests ?? []
128
- });
129
- if (typeof mod.loadExternalProviders === "function" && typeof mod.integrateExternalInsights === "function") {
130
- try {
131
- const loadProviders = mod.loadExternalProviders;
132
- const integrate = mod.integrateExternalInsights;
133
- const providers = await loadProviders(projectRoot);
134
- if (providers.length > 0) {
135
- const integration = await integrate(
136
- cachedGraph,
137
- providers,
138
- { projectRoot }
139
- );
140
- cachedGraph = integration.graph;
141
- }
142
- } catch {
143
- }
144
- }
145
- }
146
- const bridge = {
147
- async buildGraph() {
148
- await ensureGraph();
149
- },
150
- async getGraph() {
151
- return ensureGraph();
152
- },
153
- async analyzeImpact(changed, opts) {
154
- let mod;
155
- try {
156
- mod = await loadAnalyzerModule();
157
- } catch {
158
- return {
159
- error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.",
160
- changed
161
- };
162
- }
163
- const graph = await ensureGraph();
164
- return mod.analyzeImpact({
165
- graph,
166
- changed,
167
- direction: opts?.direction ?? "downstream",
168
- ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
169
- ...opts?.limit !== void 0 ? { limit: opts.limit } : {},
170
- ...navigationIndex ? { navigationIndex } : {}
171
- });
172
- },
173
- async generateContextPack(changed, opts) {
174
- let mod;
175
- try {
176
- mod = await loadAnalyzerModule();
177
- } catch {
178
- return {
179
- entries: [],
180
- metadata: {
181
- totalTokens: 0,
182
- budgetTokens: opts?.budgetTokens ?? 5e4,
183
- filesIncluded: 0,
184
- filesExcluded: 0,
185
- filesReferenced: 0,
186
- artifactsCovered: [],
187
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
188
- }
189
- };
190
- }
191
- const graph = await ensureGraph();
192
- return mod.generateContextPack({
193
- graph,
194
- changed,
195
- projectRoot,
196
- ...opts?.budgetTokens !== void 0 ? { budgetTokens: opts.budgetTokens } : {},
197
- ...opts?.granularity ? { granularity: opts.granularity } : {},
198
- ...navigationIndex ? { navigationIndex } : {},
199
- ...cachedFileContents ? { fileContents: cachedFileContents } : {}
200
- });
201
- },
202
- async buildCallGraph(entry, opts) {
203
- let mod;
204
- try {
205
- mod = await loadAnalyzerModule();
206
- } catch {
207
- return {
208
- error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.",
209
- entry
210
- };
211
- }
212
- const graph = await ensureGraph();
213
- return mod.buildCallGraph({
214
- graph,
215
- entry,
216
- ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
217
- ...opts?.direction ? { direction: opts.direction } : {}
218
- });
219
- },
220
- async getContextMap(input) {
221
- let mod;
222
- try {
223
- mod = await loadAnalyzerModule();
224
- } catch {
225
- return {
226
- error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use context map analysis.",
227
- instruction: input.instruction
228
- };
229
- }
230
- const graph = await ensureGraph();
231
- return mod.getContextMap({
232
- graph,
233
- projectRoot,
234
- instruction: input.instruction,
235
- candidates: input.candidates,
236
- ...input.depth !== void 0 ? { depth: input.depth } : {},
237
- ...input.direction ? { direction: input.direction } : {},
238
- ...input.budgetTokens !== void 0 ? { budgetTokens: input.budgetTokens } : {},
239
- ...navigationIndex ? { navigationIndex } : {},
240
- ...cachedFileContents ? { fileContents: cachedFileContents } : {}
241
- });
242
- },
243
- invalidateCache() {
244
- cachedGraph = null;
245
- cachedFileContents = null;
246
- graphBuildPromise = null;
247
- },
248
- buildAnalyzerTools() {
249
- return [
250
- {
251
- name: "analyzer.analyzeImpact",
252
- description: "Analyze the impact of changed files across the dependency graph",
253
- inputSchema: {
254
- type: "object",
255
- properties: {
256
- changed: {
257
- type: "array",
258
- items: { type: "string" },
259
- description: "File paths that changed"
260
- },
261
- direction: {
262
- type: "string",
263
- enum: ["downstream", "upstream"],
264
- description: "Traversal direction. downstream = what breaks if this changes"
265
- },
266
- maxDepth: {
267
- type: "number",
268
- description: "Maximum BFS depth to explore"
269
- },
270
- limit: {
271
- type: "number",
272
- description: "Cap the number of affected entries returned"
273
- }
274
- },
275
- required: ["changed"]
276
- },
277
- handler: async (args) => {
278
- const changed = args.changed;
279
- const result = await bridge.analyzeImpact(changed, {
280
- direction: args.direction,
281
- maxDepth: args.maxDepth,
282
- limit: args.limit
283
- });
284
- return JSON.stringify(result);
285
- }
286
- },
287
- {
288
- name: "analyzer.generateContextPack",
289
- description: "Generate a token-budget-constrained context pack for changed files",
290
- inputSchema: {
291
- type: "object",
292
- properties: {
293
- changed: {
294
- type: "array",
295
- items: { type: "string" },
296
- description: "File paths that changed"
297
- },
298
- budgetTokens: {
299
- type: "number",
300
- description: "Token budget for the context pack"
301
- },
302
- granularity: {
303
- type: "string",
304
- enum: ["file", "symbol"],
305
- description: "Context granularity level"
306
- }
307
- },
308
- required: ["changed"]
309
- },
310
- handler: async (args) => {
311
- const changed = args.changed;
312
- const result = await bridge.generateContextPack(changed, {
313
- budgetTokens: args.budgetTokens,
314
- granularity: args.granularity
315
- });
316
- return JSON.stringify(result);
317
- }
318
- },
319
- {
320
- name: "analyzer.getContextMap",
321
- description: "Build a structured context map from instruction and candidate paths/artifacts/symbols",
322
- inputSchema: {
323
- type: "object",
324
- properties: {
325
- instruction: {
326
- type: "string",
327
- description: "Natural-language task instruction"
328
- },
329
- candidates: {
330
- type: "array",
331
- items: {
332
- type: "object",
333
- properties: {
334
- path: { type: "string" },
335
- symbolId: { type: "string" },
336
- artifactId: { type: "string" }
337
- }
338
- },
339
- description: "Candidate seeds from navigation-index (paths, symbols, artifacts)"
340
- },
341
- depth: {
342
- type: "number",
343
- description: "Traversal depth (default 2)"
344
- },
345
- direction: {
346
- type: "string",
347
- enum: ["downstream", "upstream", "both"],
348
- description: "Impact traversal direction"
349
- },
350
- budgetTokens: {
351
- type: "number",
352
- description: "Token budget for suggested read targets"
353
- }
354
- },
355
- required: ["instruction", "candidates"]
356
- },
357
- handler: async (args) => {
358
- const result = await bridge.getContextMap({
359
- instruction: args.instruction,
360
- candidates: args.candidates,
361
- depth: args.depth,
362
- direction: args.direction,
363
- budgetTokens: args.budgetTokens
364
- });
365
- return JSON.stringify(result);
366
- }
367
- },
368
- {
369
- name: "analyzer.buildCallGraph",
370
- description: "Build a call graph rooted at a symbol",
371
- inputSchema: {
372
- type: "object",
373
- properties: {
374
- entry: {
375
- type: "string",
376
- description: "Entry symbolId (filePath#name) to root the call graph at"
377
- },
378
- maxDepth: {
379
- type: "number",
380
- description: "Maximum traversal depth"
381
- },
382
- direction: {
383
- type: "string",
384
- enum: ["forward", "reverse"],
385
- description: "Traversal direction: forward (callees) or reverse (callers)"
386
- }
387
- },
388
- required: ["entry"]
389
- },
390
- handler: async (args) => {
391
- const entry = args.entry;
392
- const result = await bridge.buildCallGraph(entry, {
393
- maxDepth: args.maxDepth,
394
- direction: args.direction
395
- });
396
- return JSON.stringify(result);
397
- }
398
- }
399
- ];
400
- }
401
- };
402
- return bridge;
403
- }
404
- function isContextPack(value) {
405
- if (typeof value !== "object" || value === null) return false;
406
- const obj = value;
407
- if (!Array.isArray(obj.entries)) return false;
408
- if (typeof obj.metadata !== "object" || obj.metadata === null) return false;
409
- const meta = obj.metadata;
410
- return typeof meta.totalTokens === "number" && typeof meta.budgetTokens === "number";
411
- }
412
- function renderContextPackPrompt(pack) {
413
- const m = pack.metadata;
414
- const sections = [];
415
- sections.push("## Source Code Context");
416
- sections.push(
417
- `### Budget
418
- - Tokens used: ${m.totalTokens} / ${m.budgetTokens}
419
- - Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`
420
- );
421
- if (m.artifactsCovered.length > 0) {
422
- sections.push(
423
- `### Affected Artifacts
424
- ${m.artifactsCovered.map((a) => `- ${a}`).join("\n")}`
425
- );
426
- }
427
- if (pack.entries.length > 0) {
428
- const fileBlocks = [];
429
- for (const entry of pack.entries) {
430
- const ext = entry.path.split(".").pop() ?? "";
431
- const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;
432
- const reason = `> ${entry.reason}`;
433
- if (entry.content) {
434
- fileBlocks.push(
435
- `${header}
436
- ${reason}
437
-
438
- \`\`\`${ext}
439
- ${entry.content}
440
- \`\`\``
441
- );
442
- } else {
443
- fileBlocks.push(`${header}
444
- ${reason}`);
445
- }
446
- }
447
- sections.push(`### Files
448
- ${fileBlocks.join("\n\n")}`);
449
- }
450
- return sections.join("\n\n");
451
- }
452
-
453
- // src/lib/process-axis-bridge.ts
454
- import { generateId } from "@aaac/observability";
455
- function attrs(base) {
456
- const out = {};
457
- for (const [k, v] of Object.entries(base)) {
458
- if (v !== void 0 && v !== "") out[k] = v;
459
- }
460
- return out;
461
- }
462
- var FILE_EDIT_TOOL_NAMES = /* @__PURE__ */ new Set([
463
- "write",
464
- "edit",
465
- "multiedit",
466
- "multi_edit",
467
- "notebookedit",
468
- "notebook_edit"
469
- ]);
470
- function isFileEditTool(toolName) {
471
- if (!toolName) return false;
472
- return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());
473
- }
474
- function emitProcessWorkflowOpen(options) {
475
- if (!options.observer) return void 0;
476
- const spanId = generateId();
477
- options.observer({
478
- source: "aaac-runtime",
479
- eventType: "process.workflow",
480
- lifecycle: "open",
481
- spanId,
482
- parentSpanId: options.parentSpanId,
483
- attributes: attrs({
484
- axis: "process",
485
- "agent.session_id": options.sessionId,
486
- "workflow.id": options.workflowId
487
- })
488
- });
489
- return spanId;
490
- }
491
- function emitProcessWorkflowClose(spanId, options) {
492
- if (!options.observer) return;
493
- options.observer({
494
- source: "aaac-runtime",
495
- eventType: "process.workflow",
496
- lifecycle: "close",
497
- spanId,
498
- attributes: attrs({
499
- axis: "process",
500
- "workflow.status": options.status,
501
- ...options.durationMs !== void 0 ? { "workflow.duration_ms": options.durationMs } : {}
502
- })
503
- });
504
- }
505
- function emitProcessTaskOpen(options) {
506
- if (!options.observer) return void 0;
507
- const spanId = generateId();
508
- options.observer({
509
- source: "aaac-runtime",
510
- eventType: "process.task",
511
- lifecycle: "open",
512
- spanId,
513
- parentSpanId: options.parentSpanId,
514
- attributes: attrs({
515
- axis: "process",
516
- "agent.session_id": options.sessionId,
517
- "task.id": options.taskId,
518
- "task.type": "implement",
519
- "task.target_agent": options.targetAgent
520
- })
521
- });
522
- return spanId;
523
- }
524
- function emitProcessTaskClose(spanId, options) {
525
- if (!options.observer) return;
526
- options.observer({
527
- source: "aaac-runtime",
528
- eventType: "process.task",
529
- lifecycle: "close",
530
- spanId,
531
- attributes: attrs({
532
- axis: "process",
533
- "task.status": options.status,
534
- ...options.durationMs !== void 0 ? { "task.duration_ms": options.durationMs } : {}
535
- })
536
- });
537
- }
538
- function emitProcessEdit(options) {
539
- if (!options.observer) return void 0;
540
- const spanId = generateId();
541
- options.observer({
542
- source: "aaac-runtime",
543
- eventType: "process.edit",
544
- lifecycle: "instant",
545
- spanId,
546
- parentSpanId: options.parentSpanId,
547
- attributes: attrs({
548
- axis: "process",
549
- "agent.session_id": options.sessionId,
550
- "edit.path": options.filePath,
551
- "edit.artifact_id": options.artifactId
552
- })
553
- });
554
- return spanId;
555
- }
556
-
557
- // src/lib/task-runner.ts
558
- import { z } from "zod";
559
- import * as yaml from "yaml";
560
-
561
- // src/lib/model-pricing.ts
562
- function normalizeModelId(model) {
563
- return model.trim().toLowerCase();
564
- }
565
- var PRICING_TABLE = {
566
- // Anthropic Claude
567
- "claude-opus-4-6": { inputPerMillion: 15, outputPerMillion: 75 },
568
- "claude-opus-4": { inputPerMillion: 15, outputPerMillion: 75 },
569
- "claude-sonnet-4": { inputPerMillion: 3, outputPerMillion: 15 },
570
- "claude-sonnet-4-6": { inputPerMillion: 3, outputPerMillion: 15 },
571
- "claude-haiku-4": { inputPerMillion: 0.8, outputPerMillion: 4 },
572
- // OpenAI GPT
573
- "gpt-5.5": { inputPerMillion: 2.5, outputPerMillion: 10 },
574
- "gpt-5.3-codex": { inputPerMillion: 2.5, outputPerMillion: 10 },
575
- "gpt-4.1": { inputPerMillion: 2, outputPerMillion: 8 },
576
- "gpt-4o": { inputPerMillion: 2.5, outputPerMillion: 10 },
577
- "gpt-4o-mini": { inputPerMillion: 0.15, outputPerMillion: 0.6 },
578
- // Google Gemini
579
- "gemini-2.5-pro": { inputPerMillion: 1.25, outputPerMillion: 10 },
580
- "gemini-2.5-flash": { inputPerMillion: 0.15, outputPerMillion: 0.6 },
581
- "gemini-2.0-flash": { inputPerMillion: 0.1, outputPerMillion: 0.4 }
582
- };
583
- function resolveModelPricing(model) {
584
- if (!model) return void 0;
585
- const key = normalizeModelId(model);
586
- if (PRICING_TABLE[key]) return PRICING_TABLE[key];
587
- for (const [known, pricing] of Object.entries(PRICING_TABLE)) {
588
- if (key.startsWith(known)) return pricing;
589
- }
590
- return void 0;
591
- }
592
- function computeCostUsd(model, inputTokens, outputTokens) {
593
- const pricing = resolveModelPricing(model);
594
- if (!pricing) return void 0;
595
- if (inputTokens <= 0 && outputTokens <= 0) return void 0;
596
- const cost = (inputTokens * pricing.inputPerMillion + outputTokens * pricing.outputPerMillion) / 1e6;
597
- return Math.round(cost * 1e6) / 1e6;
598
- }
599
-
600
- // src/lib/task-runner.ts
601
- function getZodChecks(schema) {
602
- const def = schema._def;
603
- return def?.checks ?? [];
604
- }
605
- function extractZodConstraints(schema) {
606
- const inner = unwrapOptional(schema);
607
- const parts = [];
608
- if (inner instanceof z.ZodString) {
609
- const str = inner;
610
- if (str.minLength != null) parts.push(`min: ${str.minLength}`);
611
- if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
612
- for (const check of getZodChecks(inner)) {
613
- if (check.kind === "min") parts.push(`min: ${check.value}`);
614
- if (check.kind === "max") parts.push(`max: ${check.value}`);
615
- if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
616
- const def = check._zod?.def;
617
- if (def?.format === "regex" && def.pattern instanceof RegExp) {
618
- parts.push(`regex: ${def.pattern}`);
619
- }
620
- }
621
- } else if (inner instanceof z.ZodNumber) {
622
- let hasInt = false;
623
- for (const check of getZodChecks(inner)) {
624
- if (check.kind === "int") hasInt = true;
625
- if (check.kind === "min") parts.push(`min: ${check.value}`);
626
- if (check.kind === "max") parts.push(`max: ${check.value}`);
627
- if (check.isInt) hasInt = true;
628
- const def = check._zod?.def;
629
- if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
630
- if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
631
- if (def?.check === "less_than") parts.push(`max: ${def.value}`);
632
- }
633
- if (hasInt) parts.unshift("int");
634
- } else if (inner instanceof z.ZodArray) {
635
- for (const check of getZodChecks(inner)) {
636
- if (check.kind === "min") parts.push(`min: ${check.value}`);
637
- if (check.kind === "max") parts.push(`max: ${check.value}`);
638
- const def = check._zod?.def;
639
- if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
640
- if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
641
- }
642
- }
643
- return parts.length > 0 ? parts.join(", ") : void 0;
644
- }
645
- function zodTypeToString(schema) {
646
- if (schema instanceof z.ZodString) return "string";
647
- if (schema instanceof z.ZodNumber) return "number";
648
- if (schema instanceof z.ZodBoolean) return "boolean";
649
- if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
650
- if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
651
- if (schema instanceof z.ZodArray) {
652
- const element = schema._def.element;
653
- const inner = zodTypeToString(element);
654
- return `${inner}[]`;
655
- }
656
- if (schema instanceof z.ZodObject) return "object";
657
- if (schema instanceof z.ZodOptional) {
658
- return zodTypeToString(schema._def.innerType);
659
- }
660
- if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
661
- return "unknown";
662
- }
663
- function unwrapOptional(schema) {
664
- if (schema instanceof z.ZodOptional) {
665
- return schema._def.innerType;
666
- }
667
- return schema;
668
- }
669
- function getArrayElement(schema) {
670
- const inner = unwrapOptional(schema);
671
- if (inner instanceof z.ZodArray) {
672
- return inner._def.element;
673
- }
674
- return null;
675
- }
676
- function extractFieldDescriptors(schema) {
677
- let shape = null;
678
- if (schema instanceof z.ZodObject) {
679
- shape = schema.shape;
680
- }
681
- if (!shape) return null;
682
- return Object.entries(shape).map(([name, field]) => {
683
- const isOptional = field instanceof z.ZodOptional;
684
- const innerField = isOptional ? field._def.innerType : field;
685
- const description = innerField.description ?? field.description;
686
- return {
687
- name,
688
- type: zodTypeToString(field),
689
- required: !isOptional,
690
- description,
691
- constraints: extractZodConstraints(innerField)
692
- };
693
- });
694
- }
695
- function zodSchemaToPromptDescription(schema) {
696
- const tables = [];
697
- collectFieldTables(schema, "", tables);
698
- return tables.join("\n\n");
699
- }
700
- function collectFieldTables(schema, pathPrefix, tables) {
701
- const fields = extractFieldDescriptors(schema);
702
- if (!fields || fields.length === 0) return;
703
- const title = pathPrefix ? `**${pathPrefix}**
704
-
705
- ` : "";
706
- const header = "| Field | Type | Required | Constraints | Description |";
707
- const sep = "|-------|------|----------|-------------|-------------|";
708
- const rows = fields.map(
709
- (f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
710
- );
711
- tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
712
- const shape = schema instanceof z.ZodObject ? schema.shape : null;
713
- if (!shape) return;
714
- for (const f of fields) {
715
- const rawField = shape[f.name];
716
- const inner = unwrapOptional(rawField);
717
- if (inner instanceof z.ZodObject) {
718
- collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
719
- } else if (inner instanceof z.ZodArray) {
720
- const element = inner._def.element;
721
- if (element instanceof z.ZodObject) {
722
- collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
723
- }
724
- }
725
- }
726
- }
727
- function zodSchemaToYamlExample(schema, maxDepth = 3) {
728
- return renderYamlObject(schema, 0, maxDepth);
729
- }
730
- function renderYamlObject(schema, indent, maxDepth) {
731
- const fields = extractFieldDescriptors(schema);
732
- if (!fields || fields.length === 0) return "";
733
- const prefix = " ".repeat(indent);
734
- const lines = [];
735
- for (const f of fields) {
736
- const shape = schema instanceof z.ZodObject ? schema.shape : null;
737
- const rawField = shape?.[f.name];
738
- if (f.type.endsWith("[]")) {
739
- lines.push(`${prefix}${f.name}:`);
740
- const element = rawField ? getArrayElement(rawField) : null;
741
- if (element && element instanceof z.ZodObject && indent < maxDepth) {
742
- const nested = renderYamlObject(element, indent + 2, maxDepth);
743
- if (nested) {
744
- const basePrefix = " ".repeat(indent + 2);
745
- const nestedLines = nested.split("\n");
746
- lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
747
- for (let i = 1; i < nestedLines.length; i++) {
748
- lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
749
- }
750
- } else {
751
- lines.push(`${prefix} - key: "value"`);
752
- }
753
- } else if (f.type === "string[]") {
754
- lines.push(`${prefix} - "example"`);
755
- } else {
756
- lines.push(`${prefix} - key: "value"`);
757
- }
758
- } else if (f.type === "object" && indent < maxDepth) {
759
- const inner = rawField ? unwrapOptional(rawField) : null;
760
- if (inner && inner instanceof z.ZodObject) {
761
- lines.push(`${prefix}${f.name}:`);
762
- const nested = renderYamlObject(inner, indent + 1, maxDepth);
763
- if (nested) {
764
- lines.push(nested);
765
- } else {
766
- lines.push(`${prefix} key: "value"`);
767
- }
768
- } else {
769
- lines.push(`${prefix}${f.name}:`);
770
- lines.push(`${prefix} key: "value"`);
771
- }
772
- } else if (f.type === "string") {
773
- lines.push(`${prefix}${f.name}: "..."`);
774
- } else if (f.type === "number") {
775
- lines.push(`${prefix}${f.name}: 0`);
776
- } else if (f.type === "boolean") {
777
- lines.push(`${prefix}${f.name}: false`);
778
- } else if (f.type.startsWith("enum(")) {
779
- const enumVals = f.type.slice(5, -1).split(", ");
780
- lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
781
- } else {
782
- lines.push(`${prefix}${f.name}: "..."`);
783
- }
784
- }
785
- return lines.join("\n");
786
- }
787
- function isNavigationIndex(value) {
788
- if (typeof value !== "object" || value === null) return false;
789
- const obj = value;
790
- return typeof obj.system === "object" && obj.system !== null && typeof obj.artifacts === "object" && obj.artifacts !== null;
791
- }
792
- function renderNavigationIndexPrompt(navigationIndex) {
793
- const system = navigationIndex.system;
794
- const artifacts = navigationIndex.artifacts ?? {};
795
- const ids = Object.keys(artifacts);
796
- const sections = ["## Project Navigation Index"];
797
- const systemLabel = system?.name ? `${system.name}${system.id ? ` (${system.id})` : ""}` : system?.id ?? "unknown";
798
- sections.push(
799
- `System: ${systemLabel}
800
- Artifacts: ${ids.length}`
801
- );
802
- if (ids.length > 0) {
803
- const lines = [];
804
- for (const id of ids) {
805
- const node = artifacts[id] ?? {};
806
- const props = node.properties ?? {};
807
- const tags = [props.type, props.authority].filter((v) => typeof v === "string" && v.length > 0).join(", ");
808
- const editPolicy = typeof props.manual_edit === "string" ? `, edit:${props.manual_edit}` : "";
809
- lines.push(`- ${id}${tags || editPolicy ? ` [${tags}${editPolicy}]` : ""}`);
810
- const patterns = node.files?.path_patterns;
811
- if (Array.isArray(patterns) && patterns.length > 0) {
812
- lines.push(` files: ${patterns.join(", ")}`);
813
- }
814
- const derived = node.relations?.derived_artifacts;
815
- if (Array.isArray(derived) && derived.length > 0) {
816
- lines.push(` derived \u2192 ${derived.join(", ")}`);
817
- }
818
- const owners = node.agents?.owners;
819
- if (Array.isArray(owners) && owners.length > 0) {
820
- lines.push(` owners: ${owners.join(", ")}`);
821
- }
822
- }
823
- sections.push(lines.join("\n"));
824
- }
825
- return sections.join("\n\n");
826
- }
827
- function collectAnalyzerToolIds(registry) {
828
- if (!registry) return [];
829
- return registry.getAll().map((def) => def.toolId).filter((id) => id.startsWith("analyzer."));
830
- }
831
- function shouldInjectAnalyzerExplorationMandate(context) {
832
- return isNavigationIndex(context.variables?.navigationIndex);
833
- }
834
- function renderAnalyzerExplorationMandatePrompt(toolIds) {
835
- const tools = toolIds.length > 0 ? toolIds.map((id) => `- \`${id}\``).join("\n") : "- `analyzer.getContextMap`\n- `analyzer.analyzeImpact`\n- `analyzer.generateContextPack`\n- `analyzer.buildCallGraph`";
836
- return [
837
- "## Codebase Exploration Protocol (Level 2)",
838
- "",
839
- "A Project Navigation Index is provided in the user prompt. When you need to",
840
- "investigate the codebase (locate affected files, trace dependencies, or scope",
841
- "changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:",
842
- "",
843
- "1. Use the navigation index to pick candidate artifacts and path patterns.",
844
- "2. Call `analyzer.getContextMap` with your `instruction` and `candidates[]`.",
845
- "3. Review suggestedReadTargets / suggestedEditTargets / suggestedValidationTargets.",
846
- "4. Call `analyzer.analyzeImpact` when you need a flat impact report.",
847
- "5. Use Read/Grep/Glob only for gaps the analyzer output did not cover.",
848
- "",
849
- "Available analyzer tools:",
850
- tools
851
- ].join("\n");
852
- }
853
- function buildSplitTaskPrompt(agent, task, context, options) {
854
- const system = [];
855
- system.push(renderAgentSystemPrompt(agent));
856
- if (options?.analyzerExploration?.toolIds.length && shouldInjectAnalyzerExplorationMandate(context)) {
857
- system.push(
858
- renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds)
859
- );
860
- }
861
- system.push(`## Task: ${task.id}
862
-
863
- ${task.description}`);
864
- if (task.completion_criteria.length > 0) {
865
- system.push(
866
- `## Completion Criteria
867
-
868
- ${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
869
- );
870
- }
871
- const handoffId = task.result_handoff;
872
- const schema = options?.handoffSchemas?.[handoffId];
873
- let outputSection = `## Required Output Format
874
-
875
- Return your result as a YAML block matching the "${handoffId}" schema.`;
876
- if (schema) {
877
- const fieldTable = zodSchemaToPromptDescription(schema);
878
- if (fieldTable) {
879
- outputSection += `
880
-
881
- ${fieldTable}`;
882
- }
883
- const yamlExample = zodSchemaToYamlExample(schema);
884
- if (yamlExample) {
885
- outputSection += `
886
-
887
- Example:
888
-
889
- \`\`\`yaml
890
- ${yamlExample}
891
- \`\`\``;
892
- }
893
- } else {
894
- outputSection += ` Include all required fields.`;
895
- }
896
- system.push(outputSection);
897
- if (options?.retry) {
898
- const r = options.retry;
899
- let recoverySection = `## Recovery Instructions
900
-
901
- If the task fails due to: "${r.condition}"
902
- \u2192 Apply the recovery approach from task "${r.fix_task}"`;
903
- if (r.revalidate_task) {
904
- recoverySection += `
905
- \u2192 Then revalidate using task "${r.revalidate_task}"`;
906
- }
907
- system.push(recoverySection);
908
- }
909
- const userSections = [];
910
- if (context.handoff_input) {
911
- const hi = context.handoff_input;
912
- const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
913
- userSections.push(`## User Request
914
-
915
- ${context.user_request}`);
916
- userSections.push(`## Handoff Input (${hi.type})
917
-
918
- \`\`\`yaml
919
- ${payloadStr}\`\`\``);
920
- } else {
921
- userSections.push(`## User Request
922
-
923
- ${context.user_request}`);
924
- }
925
- if (context.prior_context) {
926
- userSections.push(`## Prior Context
927
-
928
- ${context.prior_context}`);
929
- }
930
- if (context.relevant_paths && context.relevant_paths.length > 0) {
931
- userSections.push(
932
- `## Relevant Files
933
-
934
- ${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
935
- );
936
- }
937
- if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
938
- userSections.push(
939
- `## Acceptance Criteria
940
-
941
- ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
942
- );
943
- }
944
- if (context.variables && Object.keys(context.variables).length > 0) {
945
- const contextPack = context.variables.analyzerContextPack;
946
- if (isContextPack(contextPack)) {
947
- userSections.push(renderContextPackPrompt(contextPack));
948
- }
949
- const navigationIndex = context.variables.navigationIndex;
950
- if (isNavigationIndex(navigationIndex)) {
951
- userSections.push(renderNavigationIndexPrompt(navigationIndex));
952
- }
953
- const otherVars = Object.entries(context.variables).filter(
954
- ([k]) => k !== "analyzerContextPack" && k !== "navigationIndex"
955
- );
956
- if (otherVars.length > 0) {
957
- const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
958
- userSections.push(`## Context Variables
959
-
960
- ${varLines}`);
961
- }
962
- }
963
- return {
964
- system,
965
- user: userSections.join("\n\n---\n\n")
966
- };
967
- }
968
- function joinSplitPrompt(split) {
969
- return [...split.system, split.user].join("\n\n---\n\n");
970
- }
971
- function buildTaskPrompt(agent, task, context, options) {
972
- return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
973
- }
974
- function extractStructuredResult(raw) {
975
- const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
976
- if (yamlMatch) {
977
- try {
978
- return yaml.parse(yamlMatch[1]);
979
- } catch {
980
- }
981
- }
982
- const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
983
- if (jsonMatch) {
984
- try {
985
- return JSON.parse(jsonMatch[1]);
986
- } catch {
987
- }
988
- }
989
- try {
990
- return JSON.parse(raw);
991
- } catch {
992
- }
993
- return null;
994
- }
995
- function validateOutput(fullOutput, task, schemas) {
996
- if (!fullOutput.trim()) {
997
- return { status: "error", message: "Agent returned empty output" };
998
- }
999
- const parsed = extractStructuredResult(fullOutput);
1000
- if (!parsed) {
1001
- return {
1002
- status: "validation_error",
1003
- errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
1004
- raw: fullOutput
1005
- };
1006
- }
1007
- const schema = schemas[task.result_handoff];
1008
- if (!schema) {
1009
- return { status: "success", data: parsed, raw: fullOutput };
1010
- }
1011
- const validation = schema.safeParse(parsed);
1012
- if (!validation.success) {
1013
- return { status: "validation_error", errors: validation.error, raw: fullOutput };
1014
- }
1015
- const data = validation.data;
1016
- if (data.escalation_needed === true) {
1017
- return {
1018
- status: "escalation",
1019
- reason: data.escalation_reasons ?? "Agent requested escalation",
1020
- raw: fullOutput
1021
- };
1022
- }
1023
- return { status: "success", data: validation.data, raw: fullOutput };
1024
- }
1025
- function attachMemoryRef(outcome, adapter) {
1026
- if (outcome.status !== "success") return outcome;
1027
- const ref = adapter.getLastMemoryRef?.();
1028
- if (!ref) return outcome;
1029
- return { ...outcome, memoryRef: ref };
1030
- }
1031
- function buildRetryFollowUp(task, lastOutcome, options) {
1032
- const sections = [];
1033
- sections.push(
1034
- "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."
1035
- );
1036
- if (lastOutcome.status === "validation_error") {
1037
- sections.push(`Validation errors:
1038
- ${lastOutcome.errors.message}`);
1039
- } else if (lastOutcome.status === "error") {
1040
- sections.push(`Error: ${lastOutcome.message}`);
1041
- }
1042
- const handoffId = task.result_handoff;
1043
- const schema = options?.handoffSchemas?.[handoffId];
1044
- let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
1045
- if (schema) {
1046
- const fieldTable = zodSchemaToPromptDescription(schema);
1047
- if (fieldTable) {
1048
- formatSection += `
1049
-
1050
- ${fieldTable}`;
1051
- }
1052
- const yamlExample = zodSchemaToYamlExample(schema);
1053
- if (yamlExample) {
1054
- formatSection += `
1055
-
1056
- Example:
1057
-
1058
- \`\`\`yaml
1059
- ${yamlExample}
1060
- \`\`\``;
1061
- }
1062
- } else {
1063
- formatSection += ` Include all required fields.`;
1064
- }
1065
- sections.push(formatSection);
1066
- return sections.join("\n\n");
1067
- }
1068
- function defaultDecideRetryStrategy(outcome, _counts) {
1069
- if (outcome.status === "validation_error") {
1070
- return "follow_up";
1071
- }
1072
- if (outcome.status === "error") {
1073
- if (outcome.message === "Agent returned empty output") return "retry";
1074
- return "abort";
1075
- }
1076
- return "abort";
1077
- }
1078
- function summarizeToolInput(input) {
1079
- if (!input) return "";
1080
- const path = input.file_path ?? input.path ?? input.filename ?? input.file;
1081
- if (typeof path === "string") return ` \u2014 ${path}`;
1082
- const cmd = input.command ?? input.cmd;
1083
- if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
1084
- const query = input.query ?? input.search ?? input.pattern;
1085
- if (typeof query === "string") return ` \u2014 "${query}"`;
1086
- return "";
1087
- }
1088
- function timestamp() {
1089
- return (/* @__PURE__ */ new Date()).toISOString();
1090
- }
1091
- function formatProgressPrefix(event, taskId, agentId) {
1092
- const ts = timestamp();
1093
- const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
1094
- const agent = agentId ?? "-";
1095
- return `[${ts},${sid},${agent},${taskId}]`;
1096
- }
1097
- function formatProgressEvent(event, taskId, agentId) {
1098
- const prefix = formatProgressPrefix(event, taskId, agentId);
1099
- switch (event.type) {
1100
- case "tool_use":
1101
- return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
1102
- `;
1103
- case "tool_result":
1104
- return "";
1105
- case "text": {
1106
- if (!event.message) return "";
1107
- const trimmed = event.message.trim();
1108
- if (!trimmed) return "";
1109
- const firstLine = trimmed.split("\n")[0];
1110
- const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
1111
- return `${prefix} \u{1F4AD} ${preview}
1112
- `;
1113
- }
1114
- case "status":
1115
- return event.message ? `${prefix} \u25CF ${event.message}
1116
- ` : "";
1117
- default:
1118
- return "";
1119
- }
1120
- }
1121
- async function runTask(adapter, taskId, context, options) {
1122
- const taskReg = options?.taskRegistry ?? {};
1123
- const agentReg = options?.agentRegistry ?? {};
1124
- const schemas = options?.handoffSchemas ?? {};
1125
- const task = taskReg[taskId];
1126
- if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
1127
- const agentContract = agentReg[task.target_agent];
1128
- if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
1129
- const taskEnvelope = createExecutionEnvelope({
1130
- taskInstanceId: taskId,
1131
- componentId: agentContract.id,
1132
- fromAgent: agentContract.id,
1133
- parentRunId: options?.parentSpanId,
1134
- // correlates to agent.session run_id
1135
- adapter: options?.envelopeAdapter,
1136
- model: options?.envelopeModel
1137
- });
1138
- const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
1139
- if (modifiedContext === null) {
1140
- return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
1141
- }
1142
- const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
1143
- const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);
1144
- const promptOpts = {
1145
- handoffSchemas: schemas,
1146
- retry: options?.retry,
1147
- ...analyzerToolIds.length > 0 && shouldInjectAnalyzerExplorationMandate(enrichedContext) ? { analyzerExploration: { toolIds: analyzerToolIds } } : {}
1148
- };
1149
- const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
1150
- let prompt;
1151
- let splitPrompt;
1152
- const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
1153
- if (pluginPrompt) {
1154
- prompt = pluginPrompt;
1155
- } else {
1156
- const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
1157
- splitPrompt = split;
1158
- prompt = joinSplitPrompt(split);
1159
- }
1160
- const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
1161
- if (enhancedPrompt !== prompt) {
1162
- splitPrompt = void 0;
1163
- prompt = enhancedPrompt;
1164
- }
1165
- const isReadonly = agentContract.mode === "read-only";
1166
- const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
1167
- const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
1168
- entryAgentId: agentContract.id,
1169
- allowedAgentIds: agentContract.can_invoke_agents
1170
- }) : [];
1171
- const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
1172
- const maxFollowUps = options?.maxFollowUps ?? 2;
1173
- const maxRetries = options?.maxRetries ?? 0;
1174
- const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
1175
- const taskExecStart = Date.now();
1176
- const effectiveSessionId = options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;
1177
- let processTaskSpanId;
1178
- const emittedEditPaths = /* @__PURE__ */ new Set();
1179
- const onProgress = options?.progressOutput || options?.observer ? (event) => {
1180
- if (options?.progressOutput) {
1181
- const line = formatProgressEvent(event, taskId, agentContract.id);
1182
- if (line) options.progressOutput.write(line);
1183
- }
1184
- if (options?.observer && event.type === "tool_use" && isFileEditTool(event.tool_name)) {
1185
- const input = event.input ?? {};
1186
- const p = input.file_path ?? input.path ?? input.filename ?? input.file;
1187
- if (typeof p === "string" && p.length > 0 && !emittedEditPaths.has(p)) {
1188
- emittedEditPaths.add(p);
1189
- emitProcessEdit({
1190
- filePath: p,
1191
- sessionId: effectiveSessionId,
1192
- observer: options.observer
1193
- });
1194
- }
1195
- }
1196
- } : void 0;
1197
- let followUpsUsed = 0;
1198
- let retriesUsed = 0;
1199
- let memoryRef = enrichedContext.memoryRef;
1200
- if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
1201
- console.warn(
1202
- `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
1203
- );
1204
- memoryRef = void 0;
1205
- }
1206
- const subagentSpanId = emitSubagentOpen(
1207
- options?.observer,
1208
- taskEnvelope,
1209
- options?.parentSpanId,
1210
- taskId,
1211
- agentContract.role_name,
1212
- effectiveSessionId
1213
- );
1214
- processTaskSpanId = emitProcessTaskOpen({
1215
- taskId,
1216
- targetAgent: task.target_agent,
1217
- sessionId: effectiveSessionId,
1218
- parentSpanId: subagentSpanId ?? options?.parentSpanId,
1219
- observer: options?.observer
1220
- });
1221
- let closeStatus = "error";
1222
- let closeCause;
1223
- let spanClosed = false;
1224
- const closeSubagentSpan = () => {
1225
- if (spanClosed) return;
1226
- spanClosed = true;
1227
- const durationMs = Date.now() - taskExecStart;
1228
- const lastTokenUsage = adapter.getLastTokenUsage?.();
1229
- taskEnvelope.execution_metadata = {
1230
- ...taskEnvelope.execution_metadata ?? {},
1231
- duration_ms: durationMs,
1232
- ...lastTokenUsage ? {
1233
- token_usage: {
1234
- input_tokens: lastTokenUsage.inputTokens,
1235
- output_tokens: lastTokenUsage.outputTokens,
1236
- ...lastTokenUsage.totalTokens !== void 0 ? { total_tokens: lastTokenUsage.totalTokens } : {},
1237
- ...lastTokenUsage.cacheReadTokens !== void 0 ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {},
1238
- ...lastTokenUsage.cacheCreationTokens !== void 0 ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}
1239
- }
1240
- } : {}
1241
- };
1242
- if (lastTokenUsage) {
1243
- const costUsd = computeCostUsd(
1244
- taskEnvelope.model,
1245
- lastTokenUsage.inputTokens,
1246
- lastTokenUsage.outputTokens
1247
- );
1248
- if (costUsd !== void 0) {
1249
- taskEnvelope.execution_metadata = {
1250
- ...taskEnvelope.execution_metadata,
1251
- cost_usd: costUsd
1252
- };
1253
- }
1254
- }
1255
- emitSubagentClose(
1256
- options?.observer,
1257
- subagentSpanId ?? taskEnvelope.run_id,
1258
- taskEnvelope,
1259
- durationMs,
1260
- closeStatus,
1261
- agentContract.role_name,
1262
- closeCause,
1263
- effectiveSessionId
1264
- );
1265
- if (processTaskSpanId) {
1266
- emitProcessTaskClose(processTaskSpanId, {
1267
- status: closeStatus,
1268
- durationMs,
1269
- observer: options?.observer
1270
- });
1271
- }
1272
- };
1273
- try {
1274
- let fullOutput;
1275
- try {
1276
- if (adapter.sendExecution) {
1277
- fullOutput = await adapter.sendExecution({
1278
- agentId: agentContract.id,
1279
- taskId,
1280
- prompt,
1281
- handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
1282
- schema: schemas[task.result_handoff] ? {
1283
- handoffType: task.result_handoff,
1284
- zodSchema: schemas[task.result_handoff],
1285
- promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
1286
- } : void 0,
1287
- context: enrichedContext,
1288
- memoryRef,
1289
- splitPrompt,
1290
- agents,
1291
- options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 }
1292
- });
1293
- } else {
1294
- fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });
1295
- }
1296
- } catch (err) {
1297
- closeStatus = "error";
1298
- closeCause = `SDK error: ${err.message}`;
1299
- return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
1300
- }
1301
- let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1302
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1303
- while (outcome.status === "validation_error" || outcome.status === "error") {
1304
- const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
1305
- if (decision === "abort") break;
1306
- let effectiveDecision = decision;
1307
- if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
1308
- effectiveDecision = "retry";
1309
- }
1310
- if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
1311
- break;
1312
- }
1313
- if (effectiveDecision === "follow_up") {
1314
- followUpsUsed++;
1315
- const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
1316
- try {
1317
- if (adapter.followUp) {
1318
- fullOutput = await adapter.followUp(followUpPrompt);
1319
- } else {
1320
- const retryContext = {
1321
- ...modifiedContext,
1322
- prior_context: (modifiedContext.prior_context ?? "") + `
1323
-
1324
- --- FollowUp ${followUpsUsed} ---
1325
- ${followUpPrompt}`
1326
- };
1327
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
1328
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1329
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1330
- }
1331
- } catch (err) {
1332
- outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
1333
- continue;
1334
- }
1335
- } else {
1336
- retriesUsed++;
1337
- const retryContext = {
1338
- ...modifiedContext,
1339
- prior_context: (modifiedContext.prior_context ?? "") + `
1340
-
1341
- --- Full Retry ${retriesUsed} ---
1342
- Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
1343
- Please re-execute the entire task.`
1344
- };
1345
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
1346
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1347
- try {
1348
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1349
- } catch (err) {
1350
- outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
1351
- continue;
1352
- }
1353
- }
1354
- outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1355
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1356
- }
1357
- closeStatus = outcome.status;
1358
- const finalTokenUsage = adapter.getLastTokenUsage?.() ?? void 0;
1359
- return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };
1360
- } catch (err) {
1361
- closeStatus = "error";
1362
- closeCause = err.message;
1363
- throw err;
1364
- } finally {
1365
- closeSubagentSpan();
1366
- }
1367
- }
1368
-
1369
- // src/lib/artifact-resolver.ts
1370
- import { readFile } from "fs/promises";
1371
- import YAML from "yaml";
1372
- async function loadArtifactRegistry(source) {
1373
- let content;
1374
- try {
1375
- content = await readFile(source, "utf8");
1376
- } catch {
1377
- throw new Error(
1378
- `Failed to read artifact registry: ${source} (declared by the project manifest's \`artifacts:\`).`
1379
- );
1380
- }
1381
- let parsed;
1382
- try {
1383
- parsed = YAML.parse(content);
1384
- } catch (err) {
1385
- throw new Error(
1386
- `Invalid YAML in artifact registry ${source}: ${err.message}`
1387
- );
1388
- }
1389
- const artifacts = parsed?.artifacts;
1390
- if (artifacts && typeof artifacts === "object" && !Array.isArray(artifacts)) {
1391
- return artifacts;
1392
- }
1393
- return {};
1394
- }
1395
- async function resolveArtifacts(options) {
1396
- if (!options.artifactBinding) {
1397
- return { dsl: options.dsl, diagnostics: [] };
1398
- }
1399
- const { resolveArtifactBinding } = await import("agent-contracts");
1400
- const registry = await loadArtifactRegistry(options.artifactBinding.source);
1401
- const dslArtifacts = options.dsl.artifacts ?? {};
1402
- const mappings = options.artifactBinding.mappings;
1403
- const claimed = new Set(
1404
- Object.keys(dslArtifacts).map((id) => mappings?.[id] ?? id)
1405
- );
1406
- const composed = Object.keys(registry).filter(
1407
- (id) => !claimed.has(id) && !(id in dslArtifacts)
1408
- );
1409
- const bound = resolveArtifactBinding(
1410
- {
1411
- ...Object.fromEntries(composed.map((id) => [id, {}])),
1412
- ...dslArtifacts
1413
- },
1414
- { artifacts: registry },
1415
- mappings,
1416
- options.paths
1417
- );
1418
- return {
1419
- dsl: { ...options.dsl, artifacts: bound.artifacts },
1420
- diagnostics: bound.diagnostics.map((d) => ({
1421
- path: d.rule,
1422
- message: d.message,
1423
- severity: d.severity
1424
- }))
1425
- };
1426
- }
1427
-
1428
- // src/lib/dsl-context.ts
1429
- import { readFile as readFile2 } from "fs/promises";
1430
- import YAML2 from "yaml";
1431
- var DslValidationError = class extends Error {
1432
- missing;
1433
- constructor(missing) {
1434
- super(
1435
- "Required entities missing after DSL merge:\n" + missing.map((m) => ` - ${m}`).join("\n")
1436
- );
1437
- this.name = "DslValidationError";
1438
- this.missing = missing;
1439
- }
1440
- };
1441
- function buildAgentRegistry(agents) {
1442
- const registry = {};
1443
- for (const [id, agent] of Object.entries(agents)) {
1444
- const rawMode = agent.mode ?? "read-only";
1445
- const mode = rawMode === "read-write" ? "read-write" : "read-only";
1446
- registry[id] = {
1447
- id,
1448
- role_name: agent.role_name ?? id,
1449
- purpose: agent.purpose ?? "",
1450
- mode,
1451
- responsibilities: agent.responsibilities ?? [],
1452
- constraints: agent.constraints ?? [],
1453
- rules: agent.rules ?? [],
1454
- can_invoke_agents: agent.can_invoke_agents ?? void 0,
1455
- can_execute_tools: agent.can_execute_tools ?? void 0
1456
- };
1457
- }
1458
- return registry;
1459
- }
1460
- function buildTaskRegistry(tasks) {
1461
- const registry = {};
1462
- for (const [id, task] of Object.entries(tasks)) {
1463
- registry[id] = {
1464
- id,
1465
- description: task.description ?? "",
1466
- target_agent: task.target_agent ?? "",
1467
- result_handoff: task.result_handoff ?? "",
1468
- completion_criteria: task.completion_criteria ?? [],
1469
- model_class: task.model_class
1470
- };
1471
- }
1472
- return registry;
1473
- }
1474
- function buildWorkflowStep(step) {
1475
- if (step.type === "gate") {
1476
- return {
1477
- type: "gate",
1478
- gate_kind: step.gate_kind ?? "",
1479
- description: step.description ?? "",
1480
- depends_on: step.depends_on
1481
- };
1482
- }
1483
- if (step.type === "evaluate") {
1484
- return {
1485
- type: "evaluate",
1486
- task: step.task ?? "",
1487
- from_agent: step.from_agent ?? "",
1488
- evaluator_agent: step.evaluator_agent,
1489
- description: step.description,
1490
- loop_to: step.loop_to ?? "",
1491
- max_iterations: step.max_iterations ?? 1,
1492
- inject_as: step.inject_as,
1493
- on_exhausted: step.on_exhausted,
1494
- depends_on: step.depends_on
1495
- };
1496
- }
1497
- return {
1498
- type: "delegate",
1499
- task: step.task ?? "",
1500
- from_agent: step.from_agent ?? "",
1501
- description: step.description ?? "",
1502
- optional: step.optional ?? false,
1503
- max_retries: step.max_retries ?? 0,
1504
- max_follow_ups: step.max_follow_ups,
1505
- depends_on: step.depends_on,
1506
- instruction: step.instruction,
1507
- receives: step.receives,
1508
- retry: step.retry
1509
- };
1510
- }
1511
- function buildWorkflowRegistry(workflows) {
1512
- const registry = {};
1513
- for (const [id, wf] of Object.entries(workflows)) {
1514
- const steps = (wf.steps ?? []).map(buildWorkflowStep);
1515
- registry[id] = { id, description: wf.description ?? "", steps };
1516
- }
1517
- return registry;
1518
- }
1519
- function buildHandoffSchemas(handoffTypes) {
1520
- const schemas = {};
1521
- for (const [id, ht] of Object.entries(handoffTypes)) {
1522
- const schema = ht.schema;
1523
- if (schema) {
1524
- schemas[id] = jsonSchemaToZod(schema);
1525
- }
1526
- }
1527
- return schemas;
1528
- }
1529
- function buildRegistriesFromDsl(dsl) {
1530
- const agents = dsl.agents ?? {};
1531
- const tasks = dsl.tasks ?? {};
1532
- const workflows = dsl.workflow ?? {};
1533
- const handoffTypes = dsl.handoff_types ?? {};
1534
- return {
1535
- agentRegistry: buildAgentRegistry(agents),
1536
- taskRegistry: buildTaskRegistry(tasks),
1537
- workflowRegistry: buildWorkflowRegistry(workflows),
1538
- handoffSchemas: buildHandoffSchemas(handoffTypes)
1539
- };
1540
- }
1541
- function validateRequiredEntities(dsl, required) {
1542
- const missing = [];
1543
- const workflows = dsl.workflow ?? {};
1544
- const tasks = dsl.tasks ?? {};
1545
- const handoffTypes = dsl.handoff_types ?? {};
1546
- if (required.workflows) {
1547
- for (const wfId of required.workflows) {
1548
- if (!(wfId in workflows)) {
1549
- missing.push(`workflow "${wfId}" is required by the CLI but not found in the resolved DSL`);
1550
- }
1551
- }
1552
- }
1553
- if (required.tasks) {
1554
- for (const taskId of required.tasks) {
1555
- if (!(taskId in tasks)) {
1556
- missing.push(`task "${taskId}" is required by the CLI but not found in the resolved DSL`);
1557
- continue;
1558
- }
1559
- const task = tasks[taskId];
1560
- const invHandoff = task.invocation_handoff;
1561
- const resHandoff = task.result_handoff;
1562
- if (invHandoff && !(invHandoff in handoffTypes)) {
1563
- missing.push(`handoff_type "${invHandoff}" (invocation_handoff of task "${taskId}") not found`);
1564
- }
1565
- if (resHandoff && !(resHandoff in handoffTypes)) {
1566
- missing.push(`handoff_type "${resHandoff}" (result_handoff of task "${taskId}") not found`);
1567
- }
1568
- }
1569
- }
1570
- if (required.workflows) {
1571
- for (const wfId of required.workflows) {
1572
- if (!(wfId in workflows)) continue;
1573
- const wf = workflows[wfId];
1574
- const steps = wf.steps ?? [];
1575
- for (const step of steps) {
1576
- if (step.type !== "delegate") continue;
1577
- const taskId = step.task;
1578
- if (taskId && taskId in tasks) {
1579
- const task = tasks[taskId];
1580
- const resHandoff = task.result_handoff;
1581
- if (resHandoff && !(resHandoff in handoffTypes)) {
1582
- missing.push(`handoff_type "${resHandoff}" (result of task "${taskId}" in workflow "${wfId}") not found`);
1583
- }
1584
- }
1585
- }
1586
- }
1587
- }
1588
- if (missing.length > 0) {
1589
- throw new DslValidationError(missing);
1590
- }
1591
- }
1592
- async function loadDslContext(options) {
1593
- let dsl;
1594
- if (options.projectDslPath) {
1595
- const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
1596
- const raw = await readFile2(options.projectDslPath, "utf8");
1597
- const projectData = YAML2.parse(raw);
1598
- if (projectData.extends === "/$embedded/") {
1599
- const { extends: _extends, ...projectOverrides } = projectData;
1600
- const merged = mergeDsl(options.embeddedDsl, projectOverrides);
1601
- dsl = expandDefaults(merged);
1602
- } else {
1603
- const projectResult = await resolveDsl(options.projectDslPath);
1604
- const merged = mergeDsl(options.embeddedDsl, projectResult.data);
1605
- dsl = expandDefaults(merged);
1606
- }
1607
- } else {
1608
- dsl = options.embeddedDsl;
1609
- }
1610
- if (options.requiredEntities) {
1611
- validateRequiredEntities(dsl, options.requiredEntities);
1612
- }
1613
- const registries = buildRegistriesFromDsl(dsl);
1614
- return { registries, dsl };
1615
- }
1616
-
1617
- // src/lib/bound-resolver.ts
1618
- import { readFile as readFile3 } from "fs/promises";
1619
- import YAML3 from "yaml";
1620
- function getEffectiveGuardrailIds(dsl, agentId) {
1621
- const ids = /* @__PURE__ */ new Set();
1622
- const agents = dsl.agents ?? {};
1623
- const agent = agents[agentId];
1624
- if (agent) {
1625
- for (const ref of agent.guardrails ?? []) {
1626
- ids.add(ref);
1627
- }
1628
- }
1629
- const guardrails = dsl.guardrails ?? {};
1630
- for (const [guardrailId, guardrail] of Object.entries(guardrails)) {
1631
- if (guardrail.scope?.agents?.includes(agentId)) {
1632
- ids.add(guardrailId);
1633
- }
1634
- }
1635
- return ids;
1636
- }
1637
- function guardrailCheckToCommandRule(c) {
1638
- return {
1639
- guardrail_id: c.guardrail_id,
1640
- pattern: c.pattern,
1641
- action: c.action,
1642
- message: c.message
1643
- };
1644
- }
1645
- function guardrailCheckToFileRule(c) {
1646
- return {
1647
- guardrail_id: c.guardrail_id,
1648
- pattern: c.pattern,
1649
- action: c.action,
1650
- message: c.message,
1651
- ...c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}
1652
- };
1653
- }
1654
- function guardrailCheckToContentRule(c) {
1655
- return {
1656
- guardrail_id: c.guardrail_id,
1657
- pattern: c.pattern,
1658
- action: c.action,
1659
- message: c.message,
1660
- ...c.file_glob ? { file_glob: c.file_glob } : {},
1661
- ...c.exclude_glob ? { exclude_glob: c.exclude_glob } : {}
1662
- };
1663
- }
1664
- function guardrailContextToRuleData(ctx, effectiveIds) {
1665
- const filter = (checks) => effectiveIds ? checks.filter((c) => effectiveIds.has(c.guardrail_id)) : checks;
1666
- return {
1667
- commandRules: filter(ctx.commandChecks).map(guardrailCheckToCommandRule),
1668
- fileRules: filter(ctx.fileChecks).map(guardrailCheckToFileRule),
1669
- contentRules: filter(ctx.contentChecks).map(guardrailCheckToContentRule)
1670
- };
1671
- }
1672
- function buildPerAgentGuardrails(dsl, guardrailCtx) {
1673
- const perAgent = /* @__PURE__ */ new Map();
1674
- const agents = dsl.agents ?? {};
1675
- for (const agentId of Object.keys(agents)) {
1676
- const effectiveIds = getEffectiveGuardrailIds(dsl, agentId);
1677
- const rules = guardrailContextToRuleData(guardrailCtx, effectiveIds);
1678
- if (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0) {
1679
- perAgent.set(agentId, rules);
1680
- }
1681
- }
1682
- return perAgent;
1683
- }
1684
- var EMPTY_GUARDRAIL_CONTEXT = {
1685
- commandChecks: [],
1686
- fileChecks: [],
1687
- contentChecks: [],
1688
- allChecks: [],
1689
- hasGuardrails: false
1690
- };
1691
- async function resolveGuardrailContext(dsl, bindingPaths, activeGuardrailPolicy, options) {
1692
- if (!bindingPaths || bindingPaths.length === 0) {
1693
- return EMPTY_GUARDRAIL_CONTEXT;
1694
- }
1695
- const merged = {
1696
- commandChecks: [],
1697
- fileChecks: [],
1698
- contentChecks: [],
1699
- allChecks: [],
1700
- hasGuardrails: false
1701
- };
1702
- for (const bindingPath of bindingPaths) {
1703
- let raw;
1704
- try {
1705
- raw = await readFile3(bindingPath, "utf8");
1706
- } catch (err) {
1707
- if (options?.skipMissing && err.code === "ENOENT") continue;
1708
- throw err;
1709
- }
1710
- const binding = YAML3.parse(raw);
1711
- const ctx = buildGuardrailContext(dsl, binding, activeGuardrailPolicy);
1712
- merged.commandChecks.push(...ctx.commandChecks);
1713
- merged.fileChecks.push(...ctx.fileChecks);
1714
- merged.contentChecks.push(...ctx.contentChecks);
1715
- merged.allChecks.push(...ctx.allChecks);
1716
- merged.hasGuardrails = merged.hasGuardrails || ctx.hasGuardrails;
1717
- }
1718
- return merged;
1719
- }
1720
- function hasGuardrailRules(rules) {
1721
- return rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0;
1722
- }
1723
- function mergeDerivedWithAgentTools(derivedTools, agentToolIds, allToolchains) {
1724
- const merged = /* @__PURE__ */ new Map();
1725
- for (const tc of derivedTools) {
1726
- merged.set(tc.id, tc);
1727
- }
1728
- for (const toolId of agentToolIds) {
1729
- if (!merged.has(toolId)) {
1730
- if (allToolchains[toolId]) {
1731
- merged.set(toolId, { ...allToolchains[toolId], source: "merged" });
1732
- }
1733
- } else {
1734
- const existing = merged.get(toolId);
1735
- merged.set(toolId, { ...existing, source: "merged" });
1736
- }
1737
- }
1738
- return Array.from(merged.values());
1739
- }
1740
- function deriveToolchainsForAgents(dsl, toolchains) {
1741
- const result = /* @__PURE__ */ new Map();
1742
- const agents = dsl.agents ?? {};
1743
- for (const [agentId, agent] of Object.entries(agents)) {
1744
- const derivedTools = [];
1745
- const canReadArtifacts = agent.can_read_artifacts ?? [];
1746
- const canWriteArtifacts = agent.can_write_artifacts ?? [];
1747
- const agentArtifacts = agent.artifacts;
1748
- const readArtifacts = /* @__PURE__ */ new Set([
1749
- ...canReadArtifacts,
1750
- ...agentArtifacts?.consumes ?? []
1751
- ]);
1752
- const writeArtifacts = /* @__PURE__ */ new Set([
1753
- ...canWriteArtifacts,
1754
- ...agentArtifacts?.produces ?? []
1755
- ]);
1756
- for (const tc of Object.values(toolchains)) {
1757
- let matched = false;
1758
- for (const artifactId of tc.artifacts.consumes) {
1759
- if (readArtifacts.has(artifactId) || writeArtifacts.has(artifactId)) {
1760
- matched = true;
1761
- break;
1762
- }
1763
- }
1764
- if (!matched) {
1765
- for (const artifactId of tc.artifacts.produces) {
1766
- if (writeArtifacts.has(artifactId)) {
1767
- matched = true;
1768
- break;
1769
- }
1770
- }
1771
- }
1772
- if (matched) {
1773
- derivedTools.push(tc);
1774
- }
1775
- }
1776
- if (derivedTools.length > 0) {
1777
- const agentTools = agent.can_execute_tools ?? [];
1778
- const mergedTools = mergeDerivedWithAgentTools(
1779
- derivedTools,
1780
- agentTools,
1781
- toolchains
1782
- );
1783
- result.set(agentId, mergedTools);
1784
- }
1785
- }
1786
- return result;
1787
- }
1788
- var BoundResolver = class {
1789
- cache = /* @__PURE__ */ new Map();
1790
- /**
1791
- * Resolve binding + policy in one pass. Results are cached by component id.
1792
- */
1793
- async resolve(opts) {
1794
- const cached = this.cache.get(opts.id);
1795
- if (cached) return cached;
1796
- const diagnostics = [];
1797
- let dsl;
1798
- if (opts.embeddedDsl) {
1799
- dsl = opts.embeddedDsl;
1800
- } else if (opts.dslPath) {
1801
- const { resolve: resolveDsl } = await import("agent-contracts");
1802
- const result = await resolveDsl(opts.dslPath);
1803
- dsl = result.data;
1804
- } else {
1805
- throw new Error("BoundResolver.resolve requires embeddedDsl or dslPath");
1806
- }
1807
- if (opts.artifactBinding) {
1808
- const bound = await resolveArtifacts({
1809
- dsl,
1810
- artifactBinding: opts.artifactBinding,
1811
- paths: opts.paths
1812
- });
1813
- dsl = bound.dsl;
1814
- diagnostics.push(...bound.diagnostics);
1815
- }
1816
- let guardrailCtx;
1817
- guardrailCtx = await resolveGuardrailContext(
1818
- dsl,
1819
- opts.bindingPaths,
1820
- opts.activeGuardrailPolicy
1821
- );
1822
- const perAgent = guardrailCtx.hasGuardrails ? buildPerAgentGuardrails(dsl, guardrailCtx) : /* @__PURE__ */ new Map();
1823
- let toolchains;
1824
- let toolchainsByAgent;
1825
- if (opts.toolchainContractsPath) {
1826
- const toolchainPkg = "@aaac/toolchain";
1827
- const mod = await import(
1828
- /* webpackIgnore: true */
1829
- toolchainPkg
1830
- );
1831
- const tcDoc = await mod.loadToolchainContracts(opts.toolchainContractsPath);
1832
- toolchains = {};
1833
- for (const [id, tc] of Object.entries(tcDoc.toolchains)) {
1834
- toolchains[id] = {
1835
- id,
1836
- kind: tc.kind,
1837
- description: tc.description,
1838
- module: tc.module,
1839
- command: tc.command,
1840
- cli_contract: tc.cli_contract,
1841
- component_contract: tc.component_contract,
1842
- artifacts: {
1843
- consumes: [...tc.artifacts.consumes],
1844
- produces: [...tc.artifacts.produces]
1845
- },
1846
- operations: tc.operations ? [...tc.operations] : void 0,
1847
- source: "toolchain-contracts"
1848
- };
1849
- }
1850
- toolchainsByAgent = deriveToolchainsForAgents(dsl, toolchains);
1851
- }
1852
- const component = {
1853
- id: opts.id,
1854
- dsl,
1855
- registries: buildRegistriesFromDsl(dsl),
1856
- guardrails: { perAgent },
1857
- diagnostics,
1858
- ...toolchains ? { toolchains } : {},
1859
- ...toolchainsByAgent ? { toolchainsByAgent } : {}
1860
- };
1861
- this.cache.set(opts.id, component);
1862
- return component;
1863
- }
1864
- /** Clear cached components (e.g. for testing). */
1865
- clearCache() {
1866
- this.cache.clear();
1867
- }
1868
- };
1869
- function getGuardrailRulesForAgent(component, agentId) {
1870
- const perAgent = component.guardrails.perAgent.get(agentId);
1871
- return perAgent && hasGuardrailRules(perAgent) ? perAgent : void 0;
1872
- }
1873
-
1874
- // src/lib/navigation-context.ts
1875
- async function buildNavigationContext(options) {
1876
- const diagnostics = [];
1877
- let dsl;
1878
- if (options.embeddedDsl != null) {
1879
- if (options.projectDslPath) {
1880
- const ctx = await loadDslContext({
1881
- embeddedDsl: options.embeddedDsl,
1882
- projectDslPath: options.projectDslPath
1883
- });
1884
- dsl = ctx.dsl;
1885
- } else {
1886
- dsl = options.embeddedDsl;
1887
- }
1888
- } else if (options.projectDslPath) {
1889
- const { resolve } = await import("agent-contracts");
1890
- const result = await resolve(options.projectDslPath);
1891
- dsl = result.data;
1892
- } else {
1893
- throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
1894
- }
1895
- if (options.artifactBinding) {
1896
- const bound = await resolveArtifacts({
1897
- dsl,
1898
- artifactBinding: options.artifactBinding,
1899
- paths: options.paths
1900
- });
1901
- dsl = bound.dsl;
1902
- diagnostics.push(...bound.diagnostics);
1903
- }
1904
- const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
1905
- const validation = validateSchema(dsl);
1906
- for (const d of validation.diagnostics) {
1907
- diagnostics.push({
1908
- path: d.path,
1909
- message: d.message,
1910
- severity: d.severity ?? "error"
1911
- });
1912
- }
1913
- const navigationIndex = buildNavigationIndex(
1914
- validation.data ?? dsl
1915
- );
1916
- const guardrailCtx = await resolveGuardrailContext(
1917
- dsl,
1918
- options.bindingPaths,
1919
- options.activeGuardrailPolicy
1920
- );
1921
- const guardrailRules = guardrailCtx.hasGuardrails ? guardrailContextToRuleData(guardrailCtx) : void 0;
1922
- return { dsl, navigationIndex, guardrailRules, diagnostics };
1923
- }
1924
-
1925
- export {
1926
- renderAgentSystemPrompt,
1927
- buildCandidateAgents,
1928
- createAnalyzerBridge,
1929
- isContextPack,
1930
- renderContextPackPrompt,
1931
- computeCostUsd,
1932
- isFileEditTool,
1933
- emitProcessWorkflowOpen,
1934
- emitProcessWorkflowClose,
1935
- emitProcessTaskOpen,
1936
- emitProcessTaskClose,
1937
- emitProcessEdit,
1938
- zodSchemaToPromptDescription,
1939
- zodSchemaToYamlExample,
1940
- isNavigationIndex,
1941
- renderNavigationIndexPrompt,
1942
- collectAnalyzerToolIds,
1943
- shouldInjectAnalyzerExplorationMandate,
1944
- renderAnalyzerExplorationMandatePrompt,
1945
- buildSplitTaskPrompt,
1946
- buildTaskPrompt,
1947
- extractStructuredResult,
1948
- buildRetryFollowUp,
1949
- runTask,
1950
- resolveArtifacts,
1951
- DslValidationError,
1952
- buildRegistriesFromDsl,
1953
- loadDslContext,
1954
- getEffectiveGuardrailIds,
1955
- guardrailContextToRuleData,
1956
- buildPerAgentGuardrails,
1957
- resolveGuardrailContext,
1958
- deriveToolchainsForAgents,
1959
- BoundResolver,
1960
- getGuardrailRulesForAgent,
1961
- buildNavigationContext
1962
- };
1963
- //# sourceMappingURL=chunk-N4KNGDYY.js.map