@aaac/runtime 0.1.36 → 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.
package/dist/index.js CHANGED
@@ -1,3 +1,40 @@
1
+ import {
2
+ buildSdkFunctionTools
3
+ } from "./chunk-IQGCUM7E.js";
4
+ import {
5
+ buildGuardrailContext,
6
+ loadProjectConfig
7
+ } from "./chunk-735UA5HV.js";
8
+ import {
9
+ DslValidationError,
10
+ buildCandidateAgents,
11
+ buildGuardrailRulesFromDsl,
12
+ buildNavigationContext,
13
+ buildRegistriesFromDsl,
14
+ buildRetryFollowUp,
15
+ buildSplitTaskPrompt,
16
+ buildTaskPrompt,
17
+ collectAnalyzerToolIds,
18
+ createAnalyzerBridge,
19
+ emitProcessEdit,
20
+ emitProcessTaskClose,
21
+ emitProcessTaskOpen,
22
+ emitProcessWorkflowClose,
23
+ emitProcessWorkflowOpen,
24
+ extractStructuredResult,
25
+ isContextPack,
26
+ isFileEditTool,
27
+ isNavigationIndex,
28
+ loadDslContext,
29
+ renderAgentSystemPrompt,
30
+ renderAnalyzerExplorationMandatePrompt,
31
+ renderContextPackPrompt,
32
+ renderNavigationIndexPrompt,
33
+ runTask,
34
+ shouldInjectAnalyzerExplorationMandate,
35
+ zodSchemaToPromptDescription,
36
+ zodSchemaToYamlExample
37
+ } from "./chunk-63RFYS7F.js";
1
38
  import {
2
39
  PluginRegistry,
3
40
  createGuardrailHooks,
@@ -7,11 +44,10 @@ import {
7
44
  getWarnings,
8
45
  hasBlockingViolation,
9
46
  pluginRegistry
10
- } from "./chunk-GZCEEIXQ.js";
47
+ } from "./chunk-EH5VFZYJ.js";
11
48
  import {
12
49
  OBSERVABILITY_ENV_VARS,
13
50
  buildObservabilityEnv,
14
- buildSdkFunctionTools,
15
51
  createExecutionEnvelope,
16
52
  emitIterationClose,
17
53
  emitIterationMetric,
@@ -27,11 +63,7 @@ import {
27
63
  emitToolchainClose,
28
64
  emitToolchainOpen,
29
65
  serializeObserverEmit
30
- } from "./chunk-Y4CI7UQO.js";
31
- import {
32
- buildGuardrailContext,
33
- loadProjectConfig
34
- } from "./chunk-735UA5HV.js";
66
+ } from "./chunk-GNMSH3VC.js";
35
67
  import {
36
68
  jsonSchemaToZod
37
69
  } from "./chunk-ET6TGQRT.js";
@@ -39,1241 +71,29 @@ import {
39
71
  // src/index.ts
40
72
  import { createRequire } from "module";
41
73
 
42
- // src/lib/task-runner.ts
43
- import { z } from "zod";
44
- import * as yaml from "yaml";
45
-
46
- // src/lib/candidate-agents.ts
47
- function renderAgentSystemPrompt(agent) {
48
- const sections = [];
49
- sections.push(`# Role: ${agent.role_name}
50
-
51
- ${agent.purpose}`);
52
- if (agent.responsibilities.length > 0) {
53
- sections.push(
54
- `## Responsibilities
55
-
56
- ${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
57
- );
58
- }
59
- if (agent.constraints.length > 0) {
60
- sections.push(
61
- `## Constraints
62
-
63
- ${agent.constraints.map((c) => `- ${c}`).join("\n")}`
64
- );
65
- }
66
- if (agent.rules && agent.rules.length > 0) {
67
- const ruleLines = agent.rules.map(
68
- (r) => `- **${r.id}** [${r.severity}]: ${r.description}`
69
- );
70
- sections.push(`## Rules
71
-
72
- ${ruleLines.join("\n")}`);
73
- }
74
- return sections.join("\n\n");
75
- }
76
- function deriveDescription(purpose) {
77
- const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
78
- const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
79
- if (sentenceEnd !== -1) {
80
- return firstLine.slice(0, sentenceEnd + 1).trim();
81
- }
82
- return firstLine;
83
- }
84
- function buildCandidateAgents(agentRegistry, opts) {
85
- const entryId = opts?.entryAgentId;
86
- const allowed = opts?.allowedAgentIds;
87
- const allowSet = allowed ? new Set(allowed) : void 0;
88
- const candidates = [];
89
- for (const [id, agent] of Object.entries(agentRegistry)) {
90
- if (id === entryId) continue;
91
- if (allowSet && !allowSet.has(id)) continue;
92
- const agentTools = agent.can_execute_tools ? [...agent.can_execute_tools] : [];
93
- const derivedToolchains = opts?.toolchainsByAgent?.get(id);
94
- if (derivedToolchains) {
95
- for (const tc of derivedToolchains) {
96
- if (!agentTools.includes(tc.id)) {
97
- agentTools.push(tc.id);
98
- }
99
- }
100
- }
101
- candidates.push({
102
- name: id,
103
- description: deriveDescription(agent.purpose),
104
- prompt: renderAgentSystemPrompt(agent),
105
- ...agentTools.length > 0 ? { tools: agentTools } : {}
106
- });
107
- }
108
- return candidates;
109
- }
110
-
111
- // src/lib/analyzer-bridge.ts
112
- var ANALYZER_PKG = "artifact-contracts-analyzer";
113
- async function loadAnalyzerModule() {
114
- const mod = await import(
115
- /* webpackIgnore: true */
116
- ANALYZER_PKG
117
- );
118
- return mod;
119
- }
120
- function createAnalyzerBridge(options) {
121
- const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;
122
- let cachedGraph = null;
123
- let cachedFileContents = null;
124
- let graphBuildPromise = null;
125
- async function ensureGraph() {
126
- if (cachedGraph) return cachedGraph;
127
- if (graphBuildPromise) {
128
- await graphBuildPromise;
129
- return cachedGraph;
130
- }
131
- graphBuildPromise = doBuildGraph();
132
- await graphBuildPromise;
133
- return cachedGraph;
134
- }
135
- async function doBuildGraph() {
136
- let mod;
137
- try {
138
- mod = await loadAnalyzerModule();
139
- } catch (error) {
140
- const msg = error instanceof Error ? error.message : String(error);
141
- throw new Error(
142
- `artifact-contracts-analyzer is not available. Install it to use analyzer features: ${msg}`
143
- );
144
- }
145
- const patterns = artifactPatterns ?? /* @__PURE__ */ new Map();
146
- const registry = mod.createDefaultRegistry();
147
- const astResult = await mod.buildAstGraph({
148
- projectRoot,
149
- artifactPatterns: patterns,
150
- registry
151
- });
152
- cachedFileContents = astResult.fileContents;
153
- cachedGraph = await mod.buildDependencyGraph({
154
- ast: astResult.graph,
155
- projectRoot,
156
- artifactPatterns: patterns,
157
- manifests: manifests ?? []
158
- });
159
- }
160
- const bridge = {
161
- async buildGraph() {
162
- await ensureGraph();
163
- },
164
- async getGraph() {
165
- return ensureGraph();
166
- },
167
- async analyzeImpact(changed, opts) {
168
- let mod;
169
- try {
170
- mod = await loadAnalyzerModule();
171
- } catch {
172
- return {
173
- error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.",
174
- changed
175
- };
176
- }
177
- const graph = await ensureGraph();
178
- return mod.analyzeImpact({
179
- graph,
180
- changed,
181
- direction: opts?.direction ?? "downstream",
182
- ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
183
- ...opts?.limit !== void 0 ? { limit: opts.limit } : {},
184
- ...navigationIndex ? { navigationIndex } : {}
185
- });
186
- },
187
- async generateContextPack(changed, opts) {
188
- let mod;
189
- try {
190
- mod = await loadAnalyzerModule();
191
- } catch {
192
- return {
193
- entries: [],
194
- metadata: {
195
- totalTokens: 0,
196
- budgetTokens: opts?.budgetTokens ?? 5e4,
197
- filesIncluded: 0,
198
- filesExcluded: 0,
199
- filesReferenced: 0,
200
- artifactsCovered: [],
201
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
202
- }
203
- };
204
- }
205
- const graph = await ensureGraph();
206
- return mod.generateContextPack({
207
- graph,
208
- changed,
209
- projectRoot,
210
- ...opts?.budgetTokens !== void 0 ? { budgetTokens: opts.budgetTokens } : {},
211
- ...opts?.granularity ? { granularity: opts.granularity } : {},
212
- ...navigationIndex ? { navigationIndex } : {},
213
- ...cachedFileContents ? { fileContents: cachedFileContents } : {}
214
- });
215
- },
216
- async buildCallGraph(entry, opts) {
217
- let mod;
218
- try {
219
- mod = await loadAnalyzerModule();
220
- } catch {
221
- return {
222
- error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.",
223
- entry
224
- };
225
- }
226
- const graph = await ensureGraph();
227
- return mod.buildCallGraph({
228
- graph,
229
- entry,
230
- ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
231
- ...opts?.direction ? { direction: opts.direction } : {}
232
- });
233
- },
234
- invalidateCache() {
235
- cachedGraph = null;
236
- cachedFileContents = null;
237
- graphBuildPromise = null;
238
- },
239
- buildAnalyzerTools() {
240
- return [
241
- {
242
- name: "analyzer.analyzeImpact",
243
- description: "Analyze the impact of changed files across the dependency graph",
244
- inputSchema: {
245
- type: "object",
246
- properties: {
247
- changed: {
248
- type: "array",
249
- items: { type: "string" },
250
- description: "File paths that changed"
251
- },
252
- direction: {
253
- type: "string",
254
- enum: ["downstream", "upstream"],
255
- description: "Traversal direction. downstream = what breaks if this changes"
256
- },
257
- maxDepth: {
258
- type: "number",
259
- description: "Maximum BFS depth to explore"
260
- },
261
- limit: {
262
- type: "number",
263
- description: "Cap the number of affected entries returned"
264
- }
265
- },
266
- required: ["changed"]
267
- },
268
- handler: async (args) => {
269
- const changed = args.changed;
270
- const result = await bridge.analyzeImpact(changed, {
271
- direction: args.direction,
272
- maxDepth: args.maxDepth,
273
- limit: args.limit
274
- });
275
- return JSON.stringify(result);
276
- }
277
- },
278
- {
279
- name: "analyzer.generateContextPack",
280
- description: "Generate a token-budget-constrained context pack for changed files",
281
- inputSchema: {
282
- type: "object",
283
- properties: {
284
- changed: {
285
- type: "array",
286
- items: { type: "string" },
287
- description: "File paths that changed"
288
- },
289
- budgetTokens: {
290
- type: "number",
291
- description: "Token budget for the context pack"
292
- },
293
- granularity: {
294
- type: "string",
295
- enum: ["file", "symbol"],
296
- description: "Context granularity level"
297
- }
298
- },
299
- required: ["changed"]
300
- },
301
- handler: async (args) => {
302
- const changed = args.changed;
303
- const result = await bridge.generateContextPack(changed, {
304
- budgetTokens: args.budgetTokens,
305
- granularity: args.granularity
306
- });
307
- return JSON.stringify(result);
308
- }
309
- },
310
- {
311
- name: "analyzer.buildCallGraph",
312
- description: "Build a call graph rooted at a symbol",
313
- inputSchema: {
314
- type: "object",
315
- properties: {
316
- entry: {
317
- type: "string",
318
- description: "Entry symbolId (filePath#name) to root the call graph at"
319
- },
320
- maxDepth: {
321
- type: "number",
322
- description: "Maximum traversal depth"
323
- },
324
- direction: {
325
- type: "string",
326
- enum: ["forward", "reverse"],
327
- description: "Traversal direction: forward (callees) or reverse (callers)"
328
- }
329
- },
330
- required: ["entry"]
331
- },
332
- handler: async (args) => {
333
- const entry = args.entry;
334
- const result = await bridge.buildCallGraph(entry, {
335
- maxDepth: args.maxDepth,
336
- direction: args.direction
337
- });
338
- return JSON.stringify(result);
339
- }
340
- }
341
- ];
342
- }
343
- };
344
- return bridge;
345
- }
346
- function isContextPack(value) {
347
- if (typeof value !== "object" || value === null) return false;
348
- const obj = value;
349
- if (!Array.isArray(obj.entries)) return false;
350
- if (typeof obj.metadata !== "object" || obj.metadata === null) return false;
351
- const meta = obj.metadata;
352
- return typeof meta.totalTokens === "number" && typeof meta.budgetTokens === "number";
353
- }
354
- function renderContextPackPrompt(pack) {
355
- const m = pack.metadata;
356
- const sections = [];
357
- sections.push("## Source Code Context");
358
- sections.push(
359
- `### Budget
360
- - Tokens used: ${m.totalTokens} / ${m.budgetTokens}
361
- - Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`
362
- );
363
- if (m.artifactsCovered.length > 0) {
364
- sections.push(
365
- `### Affected Artifacts
366
- ${m.artifactsCovered.map((a) => `- ${a}`).join("\n")}`
367
- );
368
- }
369
- if (pack.entries.length > 0) {
370
- const fileBlocks = [];
371
- for (const entry of pack.entries) {
372
- const ext = entry.path.split(".").pop() ?? "";
373
- const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;
374
- const reason = `> ${entry.reason}`;
375
- if (entry.content) {
376
- fileBlocks.push(
377
- `${header}
378
- ${reason}
379
-
380
- \`\`\`${ext}
381
- ${entry.content}
382
- \`\`\``
383
- );
384
- } else {
385
- fileBlocks.push(`${header}
386
- ${reason}`);
387
- }
388
- }
389
- sections.push(`### Files
390
- ${fileBlocks.join("\n\n")}`);
391
- }
392
- return sections.join("\n\n");
393
- }
394
-
395
- // src/lib/process-axis-bridge.ts
396
- import { generateId } from "@aaac/observability";
397
- function attrs(base) {
398
- const out = {};
399
- for (const [k, v] of Object.entries(base)) {
400
- if (v !== void 0 && v !== "") out[k] = v;
401
- }
402
- return out;
403
- }
404
- var FILE_EDIT_TOOL_NAMES = /* @__PURE__ */ new Set([
405
- "write",
406
- "edit",
407
- "multiedit",
408
- "multi_edit",
409
- "notebookedit",
410
- "notebook_edit"
411
- ]);
412
- function isFileEditTool(toolName) {
413
- if (!toolName) return false;
414
- return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());
415
- }
416
- function emitProcessWorkflowOpen(options) {
417
- if (!options.observer) return void 0;
418
- const spanId = generateId();
419
- options.observer({
420
- source: "aaac-runtime",
421
- eventType: "process.workflow",
422
- lifecycle: "open",
423
- spanId,
424
- parentSpanId: options.parentSpanId,
425
- attributes: attrs({
426
- axis: "process",
427
- "agent.session_id": options.sessionId,
428
- "workflow.id": options.workflowId
429
- })
430
- });
431
- return spanId;
432
- }
433
- function emitProcessWorkflowClose(spanId, options) {
434
- if (!options.observer) return;
435
- options.observer({
436
- source: "aaac-runtime",
437
- eventType: "process.workflow",
438
- lifecycle: "close",
439
- spanId,
440
- attributes: attrs({
441
- axis: "process",
442
- "workflow.status": options.status,
443
- ...options.durationMs !== void 0 ? { "workflow.duration_ms": options.durationMs } : {}
444
- })
445
- });
446
- }
447
- function emitProcessTaskOpen(options) {
448
- if (!options.observer) return void 0;
449
- const spanId = generateId();
450
- options.observer({
451
- source: "aaac-runtime",
452
- eventType: "process.task",
453
- lifecycle: "open",
454
- spanId,
455
- parentSpanId: options.parentSpanId,
456
- attributes: attrs({
457
- axis: "process",
458
- "agent.session_id": options.sessionId,
459
- "task.id": options.taskId,
460
- "task.type": "implement",
461
- "task.target_agent": options.targetAgent
462
- })
463
- });
464
- return spanId;
465
- }
466
- function emitProcessTaskClose(spanId, options) {
467
- if (!options.observer) return;
468
- options.observer({
469
- source: "aaac-runtime",
470
- eventType: "process.task",
471
- lifecycle: "close",
472
- spanId,
473
- attributes: attrs({
474
- axis: "process",
475
- "task.status": options.status,
476
- ...options.durationMs !== void 0 ? { "task.duration_ms": options.durationMs } : {}
477
- })
478
- });
479
- }
480
- function emitProcessEdit(options) {
481
- if (!options.observer) return void 0;
482
- const spanId = generateId();
483
- options.observer({
484
- source: "aaac-runtime",
485
- eventType: "process.edit",
486
- lifecycle: "instant",
487
- spanId,
488
- parentSpanId: options.parentSpanId,
489
- attributes: attrs({
490
- axis: "process",
491
- "agent.session_id": options.sessionId,
492
- "edit.path": options.filePath,
493
- "edit.artifact_id": options.artifactId
494
- })
495
- });
496
- return spanId;
497
- }
498
-
499
- // src/lib/task-runner.ts
500
- function getZodChecks(schema) {
501
- const def = schema._def;
502
- return def?.checks ?? [];
503
- }
504
- function extractZodConstraints(schema) {
505
- const inner = unwrapOptional(schema);
506
- const parts = [];
507
- if (inner instanceof z.ZodString) {
508
- const str = inner;
509
- if (str.minLength != null) parts.push(`min: ${str.minLength}`);
510
- if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
511
- for (const check of getZodChecks(inner)) {
512
- if (check.kind === "min") parts.push(`min: ${check.value}`);
513
- if (check.kind === "max") parts.push(`max: ${check.value}`);
514
- if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
515
- const def = check._zod?.def;
516
- if (def?.format === "regex" && def.pattern instanceof RegExp) {
517
- parts.push(`regex: ${def.pattern}`);
518
- }
519
- }
520
- } else if (inner instanceof z.ZodNumber) {
521
- let hasInt = false;
522
- for (const check of getZodChecks(inner)) {
523
- if (check.kind === "int") hasInt = true;
524
- if (check.kind === "min") parts.push(`min: ${check.value}`);
525
- if (check.kind === "max") parts.push(`max: ${check.value}`);
526
- if (check.isInt) hasInt = true;
527
- const def = check._zod?.def;
528
- if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
529
- if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
530
- if (def?.check === "less_than") parts.push(`max: ${def.value}`);
531
- }
532
- if (hasInt) parts.unshift("int");
533
- } else if (inner instanceof z.ZodArray) {
534
- for (const check of getZodChecks(inner)) {
535
- if (check.kind === "min") parts.push(`min: ${check.value}`);
536
- if (check.kind === "max") parts.push(`max: ${check.value}`);
537
- const def = check._zod?.def;
538
- if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
539
- if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
540
- }
541
- }
542
- return parts.length > 0 ? parts.join(", ") : void 0;
543
- }
544
- function zodTypeToString(schema) {
545
- if (schema instanceof z.ZodString) return "string";
546
- if (schema instanceof z.ZodNumber) return "number";
547
- if (schema instanceof z.ZodBoolean) return "boolean";
548
- if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
549
- if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
550
- if (schema instanceof z.ZodArray) {
551
- const element = schema._def.element;
552
- const inner = zodTypeToString(element);
553
- return `${inner}[]`;
554
- }
555
- if (schema instanceof z.ZodObject) return "object";
556
- if (schema instanceof z.ZodOptional) {
557
- return zodTypeToString(schema._def.innerType);
558
- }
559
- if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
560
- return "unknown";
561
- }
562
- function unwrapOptional(schema) {
563
- if (schema instanceof z.ZodOptional) {
564
- return schema._def.innerType;
565
- }
566
- return schema;
567
- }
568
- function getArrayElement(schema) {
569
- const inner = unwrapOptional(schema);
570
- if (inner instanceof z.ZodArray) {
571
- return inner._def.element;
572
- }
573
- return null;
574
- }
575
- function extractFieldDescriptors(schema) {
576
- let shape = null;
577
- if (schema instanceof z.ZodObject) {
578
- shape = schema.shape;
579
- }
580
- if (!shape) return null;
581
- return Object.entries(shape).map(([name, field]) => {
582
- const isOptional = field instanceof z.ZodOptional;
583
- const innerField = isOptional ? field._def.innerType : field;
584
- const description = innerField.description ?? field.description;
585
- return {
586
- name,
587
- type: zodTypeToString(field),
588
- required: !isOptional,
589
- description,
590
- constraints: extractZodConstraints(innerField)
591
- };
592
- });
593
- }
594
- function zodSchemaToPromptDescription(schema) {
595
- const tables = [];
596
- collectFieldTables(schema, "", tables);
597
- return tables.join("\n\n");
598
- }
599
- function collectFieldTables(schema, pathPrefix, tables) {
600
- const fields = extractFieldDescriptors(schema);
601
- if (!fields || fields.length === 0) return;
602
- const title = pathPrefix ? `**${pathPrefix}**
603
-
604
- ` : "";
605
- const header = "| Field | Type | Required | Constraints | Description |";
606
- const sep = "|-------|------|----------|-------------|-------------|";
607
- const rows = fields.map(
608
- (f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
609
- );
610
- tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
611
- const shape = schema instanceof z.ZodObject ? schema.shape : null;
612
- if (!shape) return;
613
- for (const f of fields) {
614
- const rawField = shape[f.name];
615
- const inner = unwrapOptional(rawField);
616
- if (inner instanceof z.ZodObject) {
617
- collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
618
- } else if (inner instanceof z.ZodArray) {
619
- const element = inner._def.element;
620
- if (element instanceof z.ZodObject) {
621
- collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
622
- }
623
- }
624
- }
625
- }
626
- function zodSchemaToYamlExample(schema, maxDepth = 3) {
627
- return renderYamlObject(schema, 0, maxDepth);
628
- }
629
- function renderYamlObject(schema, indent, maxDepth) {
630
- const fields = extractFieldDescriptors(schema);
631
- if (!fields || fields.length === 0) return "";
632
- const prefix = " ".repeat(indent);
633
- const lines = [];
634
- for (const f of fields) {
635
- const shape = schema instanceof z.ZodObject ? schema.shape : null;
636
- const rawField = shape?.[f.name];
637
- if (f.type.endsWith("[]")) {
638
- lines.push(`${prefix}${f.name}:`);
639
- const element = rawField ? getArrayElement(rawField) : null;
640
- if (element && element instanceof z.ZodObject && indent < maxDepth) {
641
- const nested = renderYamlObject(element, indent + 2, maxDepth);
642
- if (nested) {
643
- const basePrefix = " ".repeat(indent + 2);
644
- const nestedLines = nested.split("\n");
645
- lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
646
- for (let i = 1; i < nestedLines.length; i++) {
647
- lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
648
- }
649
- } else {
650
- lines.push(`${prefix} - key: "value"`);
651
- }
652
- } else if (f.type === "string[]") {
653
- lines.push(`${prefix} - "example"`);
654
- } else {
655
- lines.push(`${prefix} - key: "value"`);
656
- }
657
- } else if (f.type === "object" && indent < maxDepth) {
658
- const inner = rawField ? unwrapOptional(rawField) : null;
659
- if (inner && inner instanceof z.ZodObject) {
660
- lines.push(`${prefix}${f.name}:`);
661
- const nested = renderYamlObject(inner, indent + 1, maxDepth);
662
- if (nested) {
663
- lines.push(nested);
664
- } else {
665
- lines.push(`${prefix} key: "value"`);
666
- }
667
- } else {
668
- lines.push(`${prefix}${f.name}:`);
669
- lines.push(`${prefix} key: "value"`);
670
- }
671
- } else if (f.type === "string") {
672
- lines.push(`${prefix}${f.name}: "..."`);
673
- } else if (f.type === "number") {
674
- lines.push(`${prefix}${f.name}: 0`);
675
- } else if (f.type === "boolean") {
676
- lines.push(`${prefix}${f.name}: false`);
677
- } else if (f.type.startsWith("enum(")) {
678
- const enumVals = f.type.slice(5, -1).split(", ");
679
- lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
680
- } else {
681
- lines.push(`${prefix}${f.name}: "..."`);
682
- }
683
- }
684
- return lines.join("\n");
685
- }
686
- function isNavigationIndex(value) {
687
- if (typeof value !== "object" || value === null) return false;
688
- const obj = value;
689
- return typeof obj.system === "object" && obj.system !== null && typeof obj.artifacts === "object" && obj.artifacts !== null;
690
- }
691
- function renderNavigationIndexPrompt(navigationIndex) {
692
- const system = navigationIndex.system;
693
- const artifacts = navigationIndex.artifacts ?? {};
694
- const ids = Object.keys(artifacts);
695
- const sections = ["## Project Navigation Index"];
696
- const systemLabel = system?.name ? `${system.name}${system.id ? ` (${system.id})` : ""}` : system?.id ?? "unknown";
697
- sections.push(
698
- `System: ${systemLabel}
699
- Artifacts: ${ids.length}`
700
- );
701
- if (ids.length > 0) {
702
- const lines = [];
703
- for (const id of ids) {
704
- const node = artifacts[id] ?? {};
705
- const props = node.properties ?? {};
706
- const tags = [props.type, props.authority].filter((v) => typeof v === "string" && v.length > 0).join(", ");
707
- const editPolicy = typeof props.manual_edit === "string" ? `, edit:${props.manual_edit}` : "";
708
- lines.push(`- ${id}${tags || editPolicy ? ` [${tags}${editPolicy}]` : ""}`);
709
- const patterns = node.files?.path_patterns;
710
- if (Array.isArray(patterns) && patterns.length > 0) {
711
- lines.push(` files: ${patterns.join(", ")}`);
712
- }
713
- const derived = node.relations?.derived_artifacts;
714
- if (Array.isArray(derived) && derived.length > 0) {
715
- lines.push(` derived \u2192 ${derived.join(", ")}`);
716
- }
717
- const owners = node.agents?.owners;
718
- if (Array.isArray(owners) && owners.length > 0) {
719
- lines.push(` owners: ${owners.join(", ")}`);
720
- }
721
- }
722
- sections.push(lines.join("\n"));
723
- }
724
- return sections.join("\n\n");
725
- }
726
- function collectAnalyzerToolIds(registry) {
727
- if (!registry) return [];
728
- return registry.getAll().map((def) => def.toolId).filter((id) => id.startsWith("analyzer."));
729
- }
730
- function shouldInjectAnalyzerExplorationMandate(context) {
731
- return isNavigationIndex(context.variables?.navigationIndex);
732
- }
733
- function renderAnalyzerExplorationMandatePrompt(toolIds) {
734
- const tools = toolIds.length > 0 ? toolIds.map((id) => `- \`${id}\``).join("\n") : "- `analyzer.generateContextPack`\n- `analyzer.analyzeImpact`\n- `analyzer.buildCallGraph`";
735
- return [
736
- "## Codebase Exploration Protocol (Level 1)",
737
- "",
738
- "A Project Navigation Index is provided in the user prompt. When you need to",
739
- "investigate the codebase (locate affected files, trace dependencies, or scope",
740
- "changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:",
741
- "",
742
- "1. Use the navigation index to pick candidate artifacts and path patterns.",
743
- "2. Call `analyzer.generateContextPack` with your `changed[]` paths and a token budget.",
744
- "3. Call `analyzer.analyzeImpact` with the same `changed[]` paths.",
745
- "4. Use Read/Grep/Glob only for gaps the analyzer output did not cover.",
746
- "",
747
- "Available analyzer tools:",
748
- tools
749
- ].join("\n");
750
- }
751
- function buildSplitTaskPrompt(agent, task, context, options) {
752
- const system = [];
753
- system.push(renderAgentSystemPrompt(agent));
754
- if (options?.analyzerExploration?.toolIds.length && shouldInjectAnalyzerExplorationMandate(context)) {
755
- system.push(
756
- renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds)
757
- );
758
- }
759
- system.push(`## Task: ${task.id}
760
-
761
- ${task.description}`);
762
- if (task.completion_criteria.length > 0) {
763
- system.push(
764
- `## Completion Criteria
765
-
766
- ${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
767
- );
768
- }
769
- const handoffId = task.result_handoff;
770
- const schema = options?.handoffSchemas?.[handoffId];
771
- let outputSection = `## Required Output Format
772
-
773
- Return your result as a YAML block matching the "${handoffId}" schema.`;
774
- if (schema) {
775
- const fieldTable = zodSchemaToPromptDescription(schema);
776
- if (fieldTable) {
777
- outputSection += `
778
-
779
- ${fieldTable}`;
780
- }
781
- const yamlExample = zodSchemaToYamlExample(schema);
782
- if (yamlExample) {
783
- outputSection += `
784
-
785
- Example:
786
-
787
- \`\`\`yaml
788
- ${yamlExample}
789
- \`\`\``;
790
- }
791
- } else {
792
- outputSection += ` Include all required fields.`;
793
- }
794
- system.push(outputSection);
795
- if (options?.retry) {
796
- const r = options.retry;
797
- let recoverySection = `## Recovery Instructions
798
-
799
- If the task fails due to: "${r.condition}"
800
- \u2192 Apply the recovery approach from task "${r.fix_task}"`;
801
- if (r.revalidate_task) {
802
- recoverySection += `
803
- \u2192 Then revalidate using task "${r.revalidate_task}"`;
804
- }
805
- system.push(recoverySection);
806
- }
807
- const userSections = [];
808
- if (context.handoff_input) {
809
- const hi = context.handoff_input;
810
- const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
811
- userSections.push(`## User Request
812
-
813
- ${context.user_request}`);
814
- userSections.push(`## Handoff Input (${hi.type})
815
-
816
- \`\`\`yaml
817
- ${payloadStr}\`\`\``);
818
- } else {
819
- userSections.push(`## User Request
820
-
821
- ${context.user_request}`);
822
- }
823
- if (context.prior_context) {
824
- userSections.push(`## Prior Context
825
-
826
- ${context.prior_context}`);
827
- }
828
- if (context.relevant_paths && context.relevant_paths.length > 0) {
829
- userSections.push(
830
- `## Relevant Files
831
-
832
- ${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
833
- );
834
- }
835
- if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
836
- userSections.push(
837
- `## Acceptance Criteria
838
-
839
- ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
840
- );
841
- }
842
- if (context.variables && Object.keys(context.variables).length > 0) {
843
- const contextPack = context.variables.analyzerContextPack;
844
- if (isContextPack(contextPack)) {
845
- userSections.push(renderContextPackPrompt(contextPack));
846
- }
847
- const navigationIndex = context.variables.navigationIndex;
848
- if (isNavigationIndex(navigationIndex)) {
849
- userSections.push(renderNavigationIndexPrompt(navigationIndex));
850
- }
851
- const otherVars = Object.entries(context.variables).filter(
852
- ([k]) => k !== "analyzerContextPack" && k !== "navigationIndex"
853
- );
854
- if (otherVars.length > 0) {
855
- const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
856
- userSections.push(`## Context Variables
857
-
858
- ${varLines}`);
859
- }
860
- }
861
- return {
862
- system,
863
- user: userSections.join("\n\n---\n\n")
864
- };
865
- }
866
- function joinSplitPrompt(split) {
867
- return [...split.system, split.user].join("\n\n---\n\n");
868
- }
869
- function buildTaskPrompt(agent, task, context, options) {
870
- return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
871
- }
872
- function extractStructuredResult(raw) {
873
- const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
874
- if (yamlMatch) {
875
- try {
876
- return yaml.parse(yamlMatch[1]);
877
- } catch {
878
- }
879
- }
880
- const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
881
- if (jsonMatch) {
882
- try {
883
- return JSON.parse(jsonMatch[1]);
884
- } catch {
885
- }
886
- }
887
- try {
888
- return JSON.parse(raw);
889
- } catch {
890
- }
891
- return null;
892
- }
893
- function validateOutput(fullOutput, task, schemas) {
894
- if (!fullOutput.trim()) {
895
- return { status: "error", message: "Agent returned empty output" };
896
- }
897
- const parsed = extractStructuredResult(fullOutput);
898
- if (!parsed) {
899
- return {
900
- status: "validation_error",
901
- errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
902
- raw: fullOutput
903
- };
904
- }
905
- const schema = schemas[task.result_handoff];
906
- if (!schema) {
907
- return { status: "success", data: parsed, raw: fullOutput };
908
- }
909
- const validation = schema.safeParse(parsed);
910
- if (!validation.success) {
911
- return { status: "validation_error", errors: validation.error, raw: fullOutput };
912
- }
913
- const data = validation.data;
914
- if (data.escalation_needed === true) {
915
- return {
916
- status: "escalation",
917
- reason: data.escalation_reasons ?? "Agent requested escalation",
918
- raw: fullOutput
919
- };
920
- }
921
- return { status: "success", data: validation.data, raw: fullOutput };
922
- }
923
- function attachMemoryRef(outcome, adapter) {
924
- if (outcome.status !== "success") return outcome;
925
- const ref = adapter.getLastMemoryRef?.();
926
- if (!ref) return outcome;
927
- return { ...outcome, memoryRef: ref };
928
- }
929
- function buildRetryFollowUp(task, lastOutcome, options) {
930
- const sections = [];
931
- sections.push(
932
- "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."
933
- );
934
- if (lastOutcome.status === "validation_error") {
935
- sections.push(`Validation errors:
936
- ${lastOutcome.errors.message}`);
937
- } else if (lastOutcome.status === "error") {
938
- sections.push(`Error: ${lastOutcome.message}`);
939
- }
940
- const handoffId = task.result_handoff;
941
- const schema = options?.handoffSchemas?.[handoffId];
942
- let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
943
- if (schema) {
944
- const fieldTable = zodSchemaToPromptDescription(schema);
945
- if (fieldTable) {
946
- formatSection += `
947
-
948
- ${fieldTable}`;
949
- }
950
- const yamlExample = zodSchemaToYamlExample(schema);
951
- if (yamlExample) {
952
- formatSection += `
953
-
954
- Example:
955
-
956
- \`\`\`yaml
957
- ${yamlExample}
958
- \`\`\``;
959
- }
960
- } else {
961
- formatSection += ` Include all required fields.`;
962
- }
963
- sections.push(formatSection);
964
- return sections.join("\n\n");
965
- }
966
- function defaultDecideRetryStrategy(outcome, _counts) {
967
- if (outcome.status === "validation_error") {
968
- return "follow_up";
969
- }
970
- if (outcome.status === "error") {
971
- if (outcome.message === "Agent returned empty output") return "retry";
972
- return "abort";
973
- }
974
- return "abort";
975
- }
976
- function summarizeToolInput(input) {
977
- if (!input) return "";
978
- const path = input.file_path ?? input.path ?? input.filename ?? input.file;
979
- if (typeof path === "string") return ` \u2014 ${path}`;
980
- const cmd = input.command ?? input.cmd;
981
- if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
982
- const query = input.query ?? input.search ?? input.pattern;
983
- if (typeof query === "string") return ` \u2014 "${query}"`;
984
- return "";
985
- }
986
- function timestamp() {
987
- return (/* @__PURE__ */ new Date()).toISOString();
988
- }
989
- function formatProgressPrefix(event, taskId, agentId) {
990
- const ts = timestamp();
991
- const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
992
- const agent = agentId ?? "-";
993
- return `[${ts},${sid},${agent},${taskId}]`;
994
- }
995
- function formatProgressEvent(event, taskId, agentId) {
996
- const prefix = formatProgressPrefix(event, taskId, agentId);
997
- switch (event.type) {
998
- case "tool_use":
999
- return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
1000
- `;
1001
- case "tool_result":
1002
- return "";
1003
- case "text": {
1004
- if (!event.message) return "";
1005
- const trimmed = event.message.trim();
1006
- if (!trimmed) return "";
1007
- const firstLine = trimmed.split("\n")[0];
1008
- const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
1009
- return `${prefix} \u{1F4AD} ${preview}
1010
- `;
1011
- }
1012
- case "status":
1013
- return event.message ? `${prefix} \u25CF ${event.message}
1014
- ` : "";
1015
- default:
1016
- return "";
1017
- }
1018
- }
1019
- async function runTask(adapter, taskId, context, options) {
1020
- const taskReg = options?.taskRegistry ?? {};
1021
- const agentReg = options?.agentRegistry ?? {};
1022
- const schemas = options?.handoffSchemas ?? {};
1023
- const task = taskReg[taskId];
1024
- if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
1025
- const agentContract = agentReg[task.target_agent];
1026
- if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
1027
- const taskEnvelope = createExecutionEnvelope({
1028
- taskInstanceId: taskId,
1029
- componentId: agentContract.id,
1030
- fromAgent: agentContract.id,
1031
- parentRunId: options?.parentSpanId,
1032
- // correlates to agent.session run_id
1033
- adapter: options?.envelopeAdapter,
1034
- model: options?.envelopeModel
1035
- });
1036
- const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
1037
- if (modifiedContext === null) {
1038
- return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
1039
- }
1040
- const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
1041
- const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);
1042
- const promptOpts = {
1043
- handoffSchemas: schemas,
1044
- retry: options?.retry,
1045
- ...analyzerToolIds.length > 0 && shouldInjectAnalyzerExplorationMandate(enrichedContext) ? { analyzerExploration: { toolIds: analyzerToolIds } } : {}
1046
- };
1047
- const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
1048
- let prompt;
1049
- let splitPrompt;
1050
- const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
1051
- if (pluginPrompt) {
1052
- prompt = pluginPrompt;
1053
- } else {
1054
- const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
1055
- splitPrompt = split;
1056
- prompt = joinSplitPrompt(split);
1057
- }
1058
- const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
1059
- if (enhancedPrompt !== prompt) {
1060
- splitPrompt = void 0;
1061
- prompt = enhancedPrompt;
1062
- }
1063
- const isReadonly = agentContract.mode === "read-only";
1064
- const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
1065
- const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
1066
- entryAgentId: agentContract.id,
1067
- allowedAgentIds: agentContract.can_invoke_agents
1068
- }) : [];
1069
- const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
1070
- const maxFollowUps = options?.maxFollowUps ?? 2;
1071
- const maxRetries = options?.maxRetries ?? 0;
1072
- const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
1073
- const taskExecStart = Date.now();
1074
- const effectiveSessionId = options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;
1075
- let processTaskSpanId;
1076
- const emittedEditPaths = /* @__PURE__ */ new Set();
1077
- const onProgress = options?.progressOutput || options?.observer ? (event) => {
1078
- if (options?.progressOutput) {
1079
- const line = formatProgressEvent(event, taskId, agentContract.id);
1080
- if (line) options.progressOutput.write(line);
1081
- }
1082
- if (options?.observer && event.type === "tool_use" && isFileEditTool(event.tool_name)) {
1083
- const input = event.input ?? {};
1084
- const p = input.file_path ?? input.path ?? input.filename ?? input.file;
1085
- if (typeof p === "string" && p.length > 0 && !emittedEditPaths.has(p)) {
1086
- emittedEditPaths.add(p);
1087
- emitProcessEdit({
1088
- filePath: p,
1089
- sessionId: effectiveSessionId,
1090
- observer: options.observer
1091
- });
1092
- }
1093
- }
1094
- } : void 0;
1095
- let followUpsUsed = 0;
1096
- let retriesUsed = 0;
1097
- let memoryRef = enrichedContext.memoryRef;
1098
- if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
1099
- console.warn(
1100
- `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
1101
- );
1102
- memoryRef = void 0;
1103
- }
1104
- const subagentSpanId = emitSubagentOpen(
1105
- options?.observer,
1106
- taskEnvelope,
1107
- options?.parentSpanId,
1108
- taskId,
1109
- agentContract.role_name,
1110
- effectiveSessionId
1111
- );
1112
- processTaskSpanId = emitProcessTaskOpen({
1113
- taskId,
1114
- targetAgent: task.target_agent,
1115
- sessionId: effectiveSessionId,
1116
- parentSpanId: subagentSpanId ?? options?.parentSpanId,
1117
- observer: options?.observer
1118
- });
1119
- let closeStatus = "error";
1120
- let closeCause;
1121
- let spanClosed = false;
1122
- const closeSubagentSpan = () => {
1123
- if (spanClosed) return;
1124
- spanClosed = true;
1125
- const durationMs = Date.now() - taskExecStart;
1126
- const lastTokenUsage = adapter.getLastTokenUsage?.();
1127
- taskEnvelope.execution_metadata = {
1128
- ...taskEnvelope.execution_metadata ?? {},
1129
- duration_ms: durationMs,
1130
- ...lastTokenUsage ? {
1131
- token_usage: {
1132
- input_tokens: lastTokenUsage.inputTokens,
1133
- output_tokens: lastTokenUsage.outputTokens,
1134
- ...lastTokenUsage.totalTokens !== void 0 ? { total_tokens: lastTokenUsage.totalTokens } : {},
1135
- ...lastTokenUsage.cacheReadTokens !== void 0 ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {},
1136
- ...lastTokenUsage.cacheCreationTokens !== void 0 ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}
1137
- }
1138
- } : {}
1139
- };
1140
- emitSubagentClose(
1141
- options?.observer,
1142
- subagentSpanId ?? taskEnvelope.run_id,
1143
- taskEnvelope,
1144
- durationMs,
1145
- closeStatus,
1146
- agentContract.role_name,
1147
- closeCause,
1148
- effectiveSessionId
1149
- );
1150
- if (processTaskSpanId) {
1151
- emitProcessTaskClose(processTaskSpanId, {
1152
- status: closeStatus,
1153
- durationMs,
1154
- observer: options?.observer
1155
- });
1156
- }
1157
- };
1158
- try {
1159
- let fullOutput;
1160
- try {
1161
- if (adapter.sendExecution) {
1162
- fullOutput = await adapter.sendExecution({
1163
- agentId: agentContract.id,
1164
- taskId,
1165
- prompt,
1166
- handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
1167
- schema: schemas[task.result_handoff] ? {
1168
- handoffType: task.result_handoff,
1169
- zodSchema: schemas[task.result_handoff],
1170
- promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
1171
- } : void 0,
1172
- context: enrichedContext,
1173
- memoryRef,
1174
- splitPrompt,
1175
- agents,
1176
- options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 }
1177
- });
1178
- } else {
1179
- fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });
1180
- }
1181
- } catch (err) {
1182
- closeStatus = "error";
1183
- closeCause = `SDK error: ${err.message}`;
1184
- return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
1185
- }
1186
- let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1187
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1188
- while (outcome.status === "validation_error" || outcome.status === "error") {
1189
- const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
1190
- if (decision === "abort") break;
1191
- let effectiveDecision = decision;
1192
- if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
1193
- effectiveDecision = "retry";
1194
- }
1195
- if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
1196
- break;
1197
- }
1198
- if (effectiveDecision === "follow_up") {
1199
- followUpsUsed++;
1200
- const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
1201
- try {
1202
- if (adapter.followUp) {
1203
- fullOutput = await adapter.followUp(followUpPrompt);
1204
- } else {
1205
- const retryContext = {
1206
- ...modifiedContext,
1207
- prior_context: (modifiedContext.prior_context ?? "") + `
1208
-
1209
- --- FollowUp ${followUpsUsed} ---
1210
- ${followUpPrompt}`
1211
- };
1212
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
1213
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1214
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1215
- }
1216
- } catch (err) {
1217
- outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
1218
- continue;
1219
- }
1220
- } else {
1221
- retriesUsed++;
1222
- const retryContext = {
1223
- ...modifiedContext,
1224
- prior_context: (modifiedContext.prior_context ?? "") + `
1225
-
1226
- --- Full Retry ${retriesUsed} ---
1227
- Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
1228
- Please re-execute the entire task.`
1229
- };
1230
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
1231
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1232
- try {
1233
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1234
- } catch (err) {
1235
- outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
1236
- continue;
1237
- }
1238
- }
1239
- outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1240
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1241
- }
1242
- closeStatus = outcome.status;
1243
- const finalTokenUsage = adapter.getLastTokenUsage?.() ?? void 0;
1244
- return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };
1245
- } catch (err) {
1246
- closeStatus = "error";
1247
- closeCause = err.message;
1248
- throw err;
1249
- } finally {
1250
- closeSubagentSpan();
1251
- }
1252
- }
1253
-
1254
74
  // src/lib/toolchain-checker.ts
1255
75
  import { execFile } from "child_process";
1256
76
  import { readFile } from "fs/promises";
1257
77
  import { existsSync } from "fs";
1258
78
  import { resolve } from "path";
1259
79
  import { promisify } from "util";
1260
- import { z as z2 } from "zod";
80
+ import { z } from "zod";
1261
81
  import { parseToolchainFile } from "@aaac/toolchain";
1262
82
  var execFileAsync = promisify(execFile);
1263
83
  var SUBPROCESS_TIMEOUT_MS = 3e4;
1264
84
  var MANIFEST_FILENAME = ".toolchain-manifest.json";
1265
- var ToolchainManifestSchema = z2.object({
1266
- schema: z2.string(),
1267
- toolchain_id: z2.string(),
1268
- generated_at: z2.string(),
1269
- source_hash: z2.string(),
1270
- output_hash: z2.string(),
1271
- source_globs: z2.array(z2.string()).optional(),
1272
- output_globs: z2.array(z2.string()).optional(),
1273
- files: z2.array(
1274
- z2.object({
1275
- path: z2.string(),
1276
- hash: z2.string()
85
+ var ToolchainManifestSchema = z.object({
86
+ schema: z.string(),
87
+ toolchain_id: z.string(),
88
+ generated_at: z.string(),
89
+ source_hash: z.string(),
90
+ output_hash: z.string(),
91
+ source_globs: z.array(z.string()).optional(),
92
+ output_globs: z.array(z.string()).optional(),
93
+ files: z.array(
94
+ z.object({
95
+ path: z.string(),
96
+ hash: z.string()
1277
97
  })
1278
98
  ).optional()
1279
99
  });
@@ -2019,209 +839,8 @@ function emitStepEvent(options, workflowId, stepIndex, step, result) {
2019
839
  }
2020
840
 
2021
841
  // src/lib/bound-resolver.ts
2022
- import { readFile as readFile3 } from "fs/promises";
2023
- import YAML2 from "yaml";
2024
-
2025
- // src/lib/dsl-context.ts
2026
842
  import { readFile as readFile2 } from "fs/promises";
2027
843
  import YAML from "yaml";
2028
- var DslValidationError = class extends Error {
2029
- missing;
2030
- constructor(missing) {
2031
- super(
2032
- "Required entities missing after DSL merge:\n" + missing.map((m) => ` - ${m}`).join("\n")
2033
- );
2034
- this.name = "DslValidationError";
2035
- this.missing = missing;
2036
- }
2037
- };
2038
- function buildAgentRegistry(agents) {
2039
- const registry = {};
2040
- for (const [id, agent] of Object.entries(agents)) {
2041
- const rawMode = agent.mode ?? "read-only";
2042
- const mode = rawMode === "read-write" ? "read-write" : "read-only";
2043
- registry[id] = {
2044
- id,
2045
- role_name: agent.role_name ?? id,
2046
- purpose: agent.purpose ?? "",
2047
- mode,
2048
- responsibilities: agent.responsibilities ?? [],
2049
- constraints: agent.constraints ?? [],
2050
- rules: agent.rules ?? [],
2051
- can_invoke_agents: agent.can_invoke_agents ?? void 0,
2052
- can_execute_tools: agent.can_execute_tools ?? void 0
2053
- };
2054
- }
2055
- return registry;
2056
- }
2057
- function buildTaskRegistry(tasks) {
2058
- const registry = {};
2059
- for (const [id, task] of Object.entries(tasks)) {
2060
- registry[id] = {
2061
- id,
2062
- description: task.description ?? "",
2063
- target_agent: task.target_agent ?? "",
2064
- result_handoff: task.result_handoff ?? "",
2065
- completion_criteria: task.completion_criteria ?? [],
2066
- model_class: task.model_class
2067
- };
2068
- }
2069
- return registry;
2070
- }
2071
- function buildWorkflowStep(step) {
2072
- if (step.type === "gate") {
2073
- return {
2074
- type: "gate",
2075
- gate_kind: step.gate_kind ?? "",
2076
- description: step.description ?? "",
2077
- depends_on: step.depends_on
2078
- };
2079
- }
2080
- if (step.type === "evaluate") {
2081
- return {
2082
- type: "evaluate",
2083
- task: step.task ?? "",
2084
- from_agent: step.from_agent ?? "",
2085
- evaluator_agent: step.evaluator_agent,
2086
- description: step.description,
2087
- loop_to: step.loop_to ?? "",
2088
- max_iterations: step.max_iterations ?? 1,
2089
- inject_as: step.inject_as,
2090
- on_exhausted: step.on_exhausted,
2091
- depends_on: step.depends_on
2092
- };
2093
- }
2094
- return {
2095
- type: "delegate",
2096
- task: step.task ?? "",
2097
- from_agent: step.from_agent ?? "",
2098
- description: step.description ?? "",
2099
- optional: step.optional ?? false,
2100
- max_retries: step.max_retries ?? 0,
2101
- max_follow_ups: step.max_follow_ups,
2102
- depends_on: step.depends_on,
2103
- instruction: step.instruction,
2104
- receives: step.receives,
2105
- retry: step.retry
2106
- };
2107
- }
2108
- function buildWorkflowRegistry(workflows) {
2109
- const registry = {};
2110
- for (const [id, wf] of Object.entries(workflows)) {
2111
- const steps = (wf.steps ?? []).map(buildWorkflowStep);
2112
- registry[id] = { id, description: wf.description ?? "", steps };
2113
- }
2114
- return registry;
2115
- }
2116
- function buildHandoffSchemas(handoffTypes) {
2117
- const schemas = {};
2118
- for (const [id, ht] of Object.entries(handoffTypes)) {
2119
- const schema = ht.schema;
2120
- if (schema) {
2121
- schemas[id] = jsonSchemaToZod(schema);
2122
- }
2123
- }
2124
- return schemas;
2125
- }
2126
- function buildGuardrailRulesFromDsl(dsl) {
2127
- const raw = dsl._guardrailRules;
2128
- if (!raw) return void 0;
2129
- return {
2130
- commandRules: raw.commandRules ?? [],
2131
- fileRules: raw.fileRules ?? [],
2132
- contentRules: raw.contentRules ?? []
2133
- };
2134
- }
2135
- function buildRegistriesFromDsl(dsl) {
2136
- const agents = dsl.agents ?? {};
2137
- const tasks = dsl.tasks ?? {};
2138
- const workflows = dsl.workflow ?? {};
2139
- const handoffTypes = dsl.handoff_types ?? {};
2140
- return {
2141
- agentRegistry: buildAgentRegistry(agents),
2142
- taskRegistry: buildTaskRegistry(tasks),
2143
- workflowRegistry: buildWorkflowRegistry(workflows),
2144
- handoffSchemas: buildHandoffSchemas(handoffTypes)
2145
- };
2146
- }
2147
- function validateRequiredEntities(dsl, required) {
2148
- const missing = [];
2149
- const workflows = dsl.workflow ?? {};
2150
- const tasks = dsl.tasks ?? {};
2151
- const handoffTypes = dsl.handoff_types ?? {};
2152
- if (required.workflows) {
2153
- for (const wfId of required.workflows) {
2154
- if (!(wfId in workflows)) {
2155
- missing.push(`workflow "${wfId}" is required by the CLI but not found in the resolved DSL`);
2156
- }
2157
- }
2158
- }
2159
- if (required.tasks) {
2160
- for (const taskId of required.tasks) {
2161
- if (!(taskId in tasks)) {
2162
- missing.push(`task "${taskId}" is required by the CLI but not found in the resolved DSL`);
2163
- continue;
2164
- }
2165
- const task = tasks[taskId];
2166
- const invHandoff = task.invocation_handoff;
2167
- const resHandoff = task.result_handoff;
2168
- if (invHandoff && !(invHandoff in handoffTypes)) {
2169
- missing.push(`handoff_type "${invHandoff}" (invocation_handoff of task "${taskId}") not found`);
2170
- }
2171
- if (resHandoff && !(resHandoff in handoffTypes)) {
2172
- missing.push(`handoff_type "${resHandoff}" (result_handoff of task "${taskId}") not found`);
2173
- }
2174
- }
2175
- }
2176
- if (required.workflows) {
2177
- for (const wfId of required.workflows) {
2178
- if (!(wfId in workflows)) continue;
2179
- const wf = workflows[wfId];
2180
- const steps = wf.steps ?? [];
2181
- for (const step of steps) {
2182
- if (step.type !== "delegate") continue;
2183
- const taskId = step.task;
2184
- if (taskId && taskId in tasks) {
2185
- const task = tasks[taskId];
2186
- const resHandoff = task.result_handoff;
2187
- if (resHandoff && !(resHandoff in handoffTypes)) {
2188
- missing.push(`handoff_type "${resHandoff}" (result of task "${taskId}" in workflow "${wfId}") not found`);
2189
- }
2190
- }
2191
- }
2192
- }
2193
- }
2194
- if (missing.length > 0) {
2195
- throw new DslValidationError(missing);
2196
- }
2197
- }
2198
- async function loadDslContext(options) {
2199
- let dsl;
2200
- if (options.projectDslPath) {
2201
- const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
2202
- const raw = await readFile2(options.projectDslPath, "utf8");
2203
- const projectData = YAML.parse(raw);
2204
- if (projectData.extends === "/$embedded/") {
2205
- const { extends: _extends, ...projectOverrides } = projectData;
2206
- const merged = mergeDsl(options.embeddedDsl, projectOverrides);
2207
- dsl = expandDefaults(merged);
2208
- } else {
2209
- const projectResult = await resolveDsl(options.projectDslPath);
2210
- const merged = mergeDsl(options.embeddedDsl, projectResult.data);
2211
- dsl = expandDefaults(merged);
2212
- }
2213
- } else {
2214
- dsl = options.embeddedDsl;
2215
- }
2216
- if (options.requiredEntities) {
2217
- validateRequiredEntities(dsl, options.requiredEntities);
2218
- }
2219
- const registries = buildRegistriesFromDsl(dsl);
2220
- const guardrailRules = buildGuardrailRulesFromDsl(dsl);
2221
- return { registries, dsl, guardrailRules };
2222
- }
2223
-
2224
- // src/lib/bound-resolver.ts
2225
844
  function getEffectiveGuardrailIds(dsl, agentId) {
2226
845
  const ids = /* @__PURE__ */ new Set();
2227
846
  const agents = dsl.agents ?? {};
@@ -2397,8 +1016,8 @@ var BoundResolver = class {
2397
1016
  };
2398
1017
  if (opts.bindingPaths && opts.bindingPaths.length > 0) {
2399
1018
  for (const bindingPath of opts.bindingPaths) {
2400
- const raw = await readFile3(bindingPath, "utf8");
2401
- const binding = YAML2.parse(raw);
1019
+ const raw = await readFile2(bindingPath, "utf8");
1020
+ const binding = YAML.parse(raw);
2402
1021
  guardrailCtx = buildGuardrailContext(
2403
1022
  dsl,
2404
1023
  binding,
@@ -2575,15 +1194,15 @@ async function loadPluginModule(modulePath) {
2575
1194
  async function loadPluginsFromPaths(paths, baseDir) {
2576
1195
  const result = { loaded: 0, files: [], errors: [] };
2577
1196
  for (const p of paths) {
2578
- const absPath = resolve2(baseDir, p);
2579
- if (!existsSync2(absPath)) {
2580
- result.errors.push({ file: p, error: `File not found: ${absPath}` });
1197
+ const absPath2 = resolve2(baseDir, p);
1198
+ if (!existsSync2(absPath2)) {
1199
+ result.errors.push({ file: p, error: `File not found: ${absPath2}` });
2581
1200
  continue;
2582
1201
  }
2583
1202
  try {
2584
- const count = await loadPluginModule(absPath);
1203
+ const count = await loadPluginModule(absPath2);
2585
1204
  result.loaded += count;
2586
- result.files.push(absPath);
1205
+ result.files.push(absPath2);
2587
1206
  } catch (err) {
2588
1207
  result.errors.push({
2589
1208
  file: p,
@@ -2725,7 +1344,7 @@ var InMemoryStore = class {
2725
1344
  };
2726
1345
 
2727
1346
  // src/lib/file-memory-store.ts
2728
- import { mkdir, readFile as readFile4, unlink, writeFile } from "fs/promises";
1347
+ import { mkdir, readFile as readFile3, unlink, writeFile } from "fs/promises";
2729
1348
  import { join as join3 } from "path";
2730
1349
  function resolveFilePath2(baseDir, ref) {
2731
1350
  const runId = ref.parent_run_id ?? "unknown";
@@ -2744,7 +1363,7 @@ var FileMemoryStore = class {
2744
1363
  async load(ref) {
2745
1364
  const filePath = resolveFilePath2(this.baseDir, ref);
2746
1365
  try {
2747
- const raw = await readFile4(filePath, "utf-8");
1366
+ const raw = await readFile3(filePath, "utf-8");
2748
1367
  return JSON.parse(raw);
2749
1368
  } catch (error) {
2750
1369
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2767,7 +1386,7 @@ var FileMemoryStore = class {
2767
1386
  };
2768
1387
 
2769
1388
  // src/lib/agent-log-writer.ts
2770
- import { mkdir as mkdir2, readFile as readFile5, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
1389
+ import { mkdir as mkdir2, readFile as readFile4, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
2771
1390
  import { join as join4 } from "path";
2772
1391
  var AgentLogWriter = class {
2773
1392
  baseDir;
@@ -2791,7 +1410,7 @@ var AgentLogWriter = class {
2791
1410
  async readRunLog(runId) {
2792
1411
  const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
2793
1412
  try {
2794
- const raw = await readFile5(filePath, "utf-8");
1413
+ const raw = await readFile4(filePath, "utf-8");
2795
1414
  return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
2796
1415
  } catch (error) {
2797
1416
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2809,7 +1428,7 @@ var AgentLogWriter = class {
2809
1428
  async readHandoff(runId, step) {
2810
1429
  const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
2811
1430
  try {
2812
- const raw = await readFile5(filePath, "utf-8");
1431
+ const raw = await readFile4(filePath, "utf-8");
2813
1432
  return JSON.parse(raw);
2814
1433
  } catch (error) {
2815
1434
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -3009,59 +1628,6 @@ Install it with: npm install ${pkg2}`
3009
1628
 
3010
1629
  // src/lib/execute.ts
3011
1630
  import { resolve as resolve3 } from "path";
3012
-
3013
- // src/lib/navigation-context.ts
3014
- async function buildNavigationContext(options) {
3015
- const diagnostics = [];
3016
- let dsl;
3017
- if (options.embeddedDsl != null) {
3018
- if (options.projectDslPath) {
3019
- const ctx = await loadDslContext({
3020
- embeddedDsl: options.embeddedDsl,
3021
- projectDslPath: options.projectDslPath
3022
- });
3023
- dsl = ctx.dsl;
3024
- } else {
3025
- dsl = options.embeddedDsl;
3026
- }
3027
- } else if (options.projectDslPath) {
3028
- const { resolve: resolve5 } = await import("agent-contracts");
3029
- const result = await resolve5(options.projectDslPath);
3030
- dsl = result.data;
3031
- } else {
3032
- throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
3033
- }
3034
- if (options.artifactBinding) {
3035
- const { resolveBound } = await import("agent-contracts");
3036
- const boundResult = await resolveBound(dsl, {
3037
- artifactBinding: options.artifactBinding,
3038
- paths: options.paths
3039
- });
3040
- dsl = boundResult.data;
3041
- for (const d of boundResult.diagnostics) {
3042
- diagnostics.push({
3043
- path: d.rule,
3044
- message: d.message,
3045
- severity: d.severity
3046
- });
3047
- }
3048
- }
3049
- const { validateSchema, buildNavigationIndex } = await import("agent-contracts");
3050
- const validation = validateSchema(dsl);
3051
- for (const d of validation.diagnostics) {
3052
- diagnostics.push({
3053
- path: d.path,
3054
- message: d.message,
3055
- severity: d.severity ?? "error"
3056
- });
3057
- }
3058
- const navigationIndex = buildNavigationIndex(
3059
- validation.data ?? dsl
3060
- );
3061
- return { dsl, navigationIndex, diagnostics };
3062
- }
3063
-
3064
- // src/lib/execute.ts
3065
1631
  async function resolveExecutionContext(options, requiredEntities) {
3066
1632
  const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
3067
1633
  if (useBoundResolver) {
@@ -3260,7 +1826,7 @@ var DEFAULT_MEMORY_COMPAT = "aaac/0.1";
3260
1826
  function getMemoryRefConfig(op) {
3261
1827
  return op.memoryRef;
3262
1828
  }
3263
- function attachMemoryRef2(result, memoryRef) {
1829
+ function attachMemoryRef(result, memoryRef) {
3264
1830
  if (result !== null && typeof result === "object" && !Array.isArray(result)) {
3265
1831
  return { ...result, _memoryRef: memoryRef };
3266
1832
  }
@@ -3326,7 +1892,7 @@ function createRuntimeBinding(component, handlers) {
3326
1892
  memoryRef: newMemoryRef
3327
1893
  };
3328
1894
  await ctx.memoryStore.save(newMemoryRef, entry);
3329
- finalResult = attachMemoryRef2(result, newMemoryRef);
1895
+ finalResult = attachMemoryRef(result, newMemoryRef);
3330
1896
  }
3331
1897
  ctx.observer?.onOperationEnd?.(operationName, finalResult);
3332
1898
  if (ctx.logWriter) {
@@ -3379,9 +1945,9 @@ async function dispatchOperation(operationName, op, options, input, ctx, handler
3379
1945
 
3380
1946
  // src/lib/project-runtime.ts
3381
1947
  import { existsSync as existsSync3 } from "fs";
3382
- import { readFile as readFile6 } from "fs/promises";
1948
+ import { readFile as readFile5 } from "fs/promises";
3383
1949
  import { resolve as resolve4, dirname as dirname2 } from "path";
3384
- import YAML3 from "yaml";
1950
+ import YAML2 from "yaml";
3385
1951
  import { createPipeline } from "@aaac/observability";
3386
1952
  var PROJECT_CONFIG_FILENAME = "project.yaml";
3387
1953
  var DEFAULT_ADAPTER = "claude";
@@ -3410,7 +1976,7 @@ async function createProjectRuntime(options) {
3410
1976
  }
3411
1977
  const config = await loadProjectConfig(configPath);
3412
1978
  const env = options.env ?? process.env;
3413
- const rawManifest = YAML3.parse(await readFile6(configPath, "utf8"));
1979
+ const rawManifest = YAML2.parse(await readFile5(configPath, "utf8"));
3414
1980
  const overlayExplicit = typeof rawManifest?.agents === "string" || typeof rawManifest?.dsl === "string";
3415
1981
  if (overlayExplicit && !existsSync3(config.dslPath)) {
3416
1982
  throw new Error(
@@ -3615,8 +2181,8 @@ async function resolveArtifacts(options) {
3615
2181
  }
3616
2182
 
3617
2183
  // src/lib/guard-commands.ts
3618
- import { readFile as readFile7, readdir as readdir3 } from "fs/promises";
3619
- import YAML4 from "yaml";
2184
+ import { readFile as readFile6, readdir as readdir3 } from "fs/promises";
2185
+ import YAML3 from "yaml";
3620
2186
  async function evaluateGuardrail(opts) {
3621
2187
  let hookInput;
3622
2188
  try {
@@ -3636,13 +2202,13 @@ async function evaluateGuardrail(opts) {
3636
2202
  for (const bindingPath of opts.bindingPaths) {
3637
2203
  let raw;
3638
2204
  try {
3639
- raw = await readFile7(bindingPath, "utf8");
2205
+ raw = await readFile6(bindingPath, "utf8");
3640
2206
  } catch (err) {
3641
2207
  const code = err.code;
3642
2208
  if (code === "ENOENT") continue;
3643
2209
  throw err;
3644
2210
  }
3645
- const binding = YAML4.parse(raw);
2211
+ const binding = YAML3.parse(raw);
3646
2212
  guardrailCtx = buildGuardrailContext(
3647
2213
  opts.dsl,
3648
2214
  binding,
@@ -3685,13 +2251,13 @@ async function listGuardrails(opts) {
3685
2251
  for (const bindingPath of opts.bindingPaths) {
3686
2252
  let raw;
3687
2253
  try {
3688
- raw = await readFile7(bindingPath, "utf8");
2254
+ raw = await readFile6(bindingPath, "utf8");
3689
2255
  } catch (err) {
3690
2256
  const code = err.code;
3691
2257
  if (code === "ENOENT") continue;
3692
2258
  throw err;
3693
2259
  }
3694
- const binding = YAML4.parse(raw);
2260
+ const binding = YAML3.parse(raw);
3695
2261
  guardrailCtx = buildGuardrailContext(
3696
2262
  opts.dsl,
3697
2263
  binding,
@@ -3744,7 +2310,7 @@ async function guardStatus(opts = {}) {
3744
2310
  const filePath = `${runsDir}/${file}`;
3745
2311
  let raw;
3746
2312
  try {
3747
- raw = await readFile7(filePath, "utf8");
2313
+ raw = await readFile6(filePath, "utf8");
3748
2314
  } catch {
3749
2315
  continue;
3750
2316
  }
@@ -3766,8 +2332,159 @@ async function guardStatus(opts = {}) {
3766
2332
  };
3767
2333
  }
3768
2334
 
2335
+ // src/lib/claude-materialize/config.ts
2336
+ import { z as z2 } from "zod";
2337
+ var ClaudeConfigSchema = z2.object({
2338
+ /** Root directory for Claude artifacts (relative to the project root). */
2339
+ output_dir: z2.string().default(".claude"),
2340
+ /** Path to agent-contracts.yaml (relative to the project root). */
2341
+ config_path: z2.string().default("./agent-contracts.yaml"),
2342
+ /**
2343
+ * Command wired into guardrail hooks (e.g. "dev-team guard evaluate").
2344
+ * Reserved for future hook integration; validated for config parity.
2345
+ */
2346
+ guard_command: z2.string().optional(),
2347
+ /** Override component id; defaults to `dsl.system.id`. */
2348
+ component_id: z2.string().optional()
2349
+ }).strip();
2350
+ function parseClaudeConfig(raw) {
2351
+ return ClaudeConfigSchema.parse(raw ?? {});
2352
+ }
2353
+
2354
+ // src/lib/claude-materialize/materialize.ts
2355
+ import { existsSync as existsSync4 } from "fs";
2356
+ import { mkdir as mkdir3, readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
2357
+ import { dirname as dirname3, join as join5, resolve as resolve5 } from "path";
2358
+ import {
2359
+ claudeGenerator
2360
+ } from "@aaac/contracts";
2361
+ var CLAUDE_BLOCK_BEGIN = "<!-- aaac:claude-native:begin -->";
2362
+ var CLAUDE_BLOCK_END = "<!-- aaac:claude-native:end -->";
2363
+ function buildComponentIR(dsl, config) {
2364
+ const system = dsl.system;
2365
+ const componentId = config.component_id ?? system?.id ?? "component";
2366
+ return {
2367
+ schema: "aaac/0.1",
2368
+ info: {
2369
+ id: componentId,
2370
+ version: system?.version ?? "1.0.0"
2371
+ },
2372
+ implementation: config.config_path,
2373
+ projections: ["claude"],
2374
+ operations: {}
2375
+ };
2376
+ }
2377
+ function relPath(file) {
2378
+ if (file.targetDir && file.targetDir !== ".") {
2379
+ return join5(file.targetDir, file.path);
2380
+ }
2381
+ return file.path;
2382
+ }
2383
+ function absPath(root, file) {
2384
+ return join5(root, relPath(file));
2385
+ }
2386
+ async function readIfExists(path) {
2387
+ if (!existsSync4(path)) return void 0;
2388
+ return readFile7(path, "utf8");
2389
+ }
2390
+ function renderFiles(dsl, config) {
2391
+ const ir = buildComponentIR(dsl, config);
2392
+ return claudeGenerator.generate(ir, { outputDir: "", componentPath: "" });
2393
+ }
2394
+ function mergeClaudeMdBlock(existing, block) {
2395
+ const normalizedBlock = block.trimStart();
2396
+ if (existing === void 0) {
2397
+ return { content: normalizedBlock, action: "created" };
2398
+ }
2399
+ const beginIdx = existing.indexOf(CLAUDE_BLOCK_BEGIN);
2400
+ const endIdx = existing.indexOf(CLAUDE_BLOCK_END);
2401
+ if (beginIdx === -1 || endIdx === -1) {
2402
+ const needsSeparator = existing.length > 0 && !existing.endsWith("\n");
2403
+ const content2 = existing + (needsSeparator ? "\n" : "") + normalizedBlock;
2404
+ return { content: content2, action: "updated" };
2405
+ }
2406
+ const before = existing.slice(0, beginIdx);
2407
+ let after = existing.slice(endIdx + CLAUDE_BLOCK_END.length);
2408
+ if (after === "\n") {
2409
+ after = "";
2410
+ }
2411
+ const content = before + normalizedBlock + after;
2412
+ if (content === existing) {
2413
+ return { content: existing, action: "unchanged" };
2414
+ }
2415
+ return { content, action: "updated" };
2416
+ }
2417
+ function expectedClaudeMdContent(existing, block) {
2418
+ return mergeClaudeMdBlock(existing, block).content;
2419
+ }
2420
+ function actionForOverwriteTrue(existing, next) {
2421
+ if (existing === void 0) return "created";
2422
+ return existing === next ? "unchanged" : "updated";
2423
+ }
2424
+ function resolveContent(file, existing) {
2425
+ if (file.path === "CLAUDE.md" && file.targetDir === "." && !file.overwrite) {
2426
+ return mergeClaudeMdBlock(existing, file.content);
2427
+ }
2428
+ if (!file.overwrite) {
2429
+ if (existing !== void 0) {
2430
+ return { content: existing, action: "unchanged" };
2431
+ }
2432
+ if (!file.content) {
2433
+ return { content: "", action: "unchanged" };
2434
+ }
2435
+ return { content: file.content, action: "created" };
2436
+ }
2437
+ const action = actionForOverwriteTrue(existing, file.content);
2438
+ return { content: file.content, action };
2439
+ }
2440
+ function checkContent(file, existing) {
2441
+ if (file.path === "CLAUDE.md" && file.targetDir === "." && !file.overwrite) {
2442
+ if (existing === void 0) return "missing";
2443
+ const expected = expectedClaudeMdContent(existing, file.content);
2444
+ return existing === expected ? null : "changed";
2445
+ }
2446
+ if (!file.overwrite) {
2447
+ if (existing === void 0 && file.content) return "missing";
2448
+ return null;
2449
+ }
2450
+ if (existing === void 0) return "missing";
2451
+ if (existing !== file.content) return "changed";
2452
+ return null;
2453
+ }
2454
+ async function syncClaude(opts) {
2455
+ const config = parseClaudeConfig(opts.config);
2456
+ const root = resolve5(opts.projectRoot);
2457
+ const result = { files: [] };
2458
+ for (const file of renderFiles(opts.dsl, config)) {
2459
+ const rel = relPath(file);
2460
+ const abs = absPath(root, file);
2461
+ const existing = await readIfExists(abs);
2462
+ const { content, action } = resolveContent(file, existing);
2463
+ if (action !== "unchanged" && !opts.dryRun) {
2464
+ await mkdir3(dirname3(abs), { recursive: true });
2465
+ await writeFile3(abs, content, "utf8");
2466
+ }
2467
+ result.files.push({ path: rel, action });
2468
+ }
2469
+ return result;
2470
+ }
2471
+ async function checkClaude(opts) {
2472
+ const config = parseClaudeConfig(opts.config);
2473
+ const root = resolve5(opts.projectRoot);
2474
+ const drift = [];
2475
+ for (const file of renderFiles(opts.dsl, config)) {
2476
+ const rel = relPath(file);
2477
+ const existing = await readIfExists(absPath(root, file));
2478
+ const reason = checkContent(file, existing);
2479
+ if (reason) {
2480
+ drift.push({ path: rel, reason });
2481
+ }
2482
+ }
2483
+ return { inSync: drift.length === 0, drift };
2484
+ }
2485
+
3769
2486
  // src/lib/prompt-executor.ts
3770
- import * as YAML5 from "yaml";
2487
+ import * as YAML4 from "yaml";
3771
2488
  function unwrapInputSchema(input) {
3772
2489
  if (!input) {
3773
2490
  return { type: "object", properties: {} };
@@ -3826,7 +2543,7 @@ function parseRouterResponse(response, validNames) {
3826
2543
  const content = yamlMatch ? yamlMatch[1].trim() : response.trim();
3827
2544
  let parsed;
3828
2545
  try {
3829
- parsed = YAML5.parse(content);
2546
+ parsed = YAML4.parse(content);
3830
2547
  } catch {
3831
2548
  const jsonMatch = response.match(/\{[\s\S]*"operation"[\s\S]*\}/);
3832
2549
  if (jsonMatch) {
@@ -3905,6 +2622,7 @@ export {
3905
2622
  buildSdkFunctionTools,
3906
2623
  buildSplitTaskPrompt,
3907
2624
  buildTaskPrompt,
2625
+ checkClaude,
3908
2626
  collectAnalyzerToolIds,
3909
2627
  createAdapter,
3910
2628
  createAnalyzerBridge,
@@ -3962,6 +2680,7 @@ export {
3962
2680
  loadPluginsFromDirectory,
3963
2681
  loadPluginsFromPaths,
3964
2682
  operationsToTools,
2683
+ parseClaudeConfig,
3965
2684
  parseGateEvaluationResponse,
3966
2685
  parseRouterResponse,
3967
2686
  pluginRegistry,
@@ -3975,6 +2694,7 @@ export {
3975
2694
  runWorkflow,
3976
2695
  serializeObserverEmit,
3977
2696
  shouldInjectAnalyzerExplorationMandate,
2697
+ syncClaude,
3978
2698
  version,
3979
2699
  zodSchemaToPromptDescription,
3980
2700
  zodSchemaToYamlExample