@aaac/runtime 0.1.18 → 0.1.20

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
@@ -14,7 +14,7 @@ import {
14
14
  import {
15
15
  buildGuardrailContext,
16
16
  loadProjectConfig
17
- } from "./chunk-E2UR4TNM.js";
17
+ } from "./chunk-RL4TCIDU.js";
18
18
  import {
19
19
  jsonSchemaToZod
20
20
  } from "./chunk-ET6TGQRT.js";
@@ -91,6 +91,290 @@ function buildCandidateAgents(agentRegistry, opts) {
91
91
  return candidates;
92
92
  }
93
93
 
94
+ // src/lib/analyzer-bridge.ts
95
+ var ANALYZER_PKG = "artifact-contracts-analyzer";
96
+ async function loadAnalyzerModule() {
97
+ const mod = await import(
98
+ /* webpackIgnore: true */
99
+ ANALYZER_PKG
100
+ );
101
+ return mod;
102
+ }
103
+ function createAnalyzerBridge(options) {
104
+ const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;
105
+ let cachedGraph = null;
106
+ let cachedFileContents = null;
107
+ let graphBuildPromise = null;
108
+ async function ensureGraph() {
109
+ if (cachedGraph) return cachedGraph;
110
+ if (graphBuildPromise) {
111
+ await graphBuildPromise;
112
+ return cachedGraph;
113
+ }
114
+ graphBuildPromise = doBuildGraph();
115
+ await graphBuildPromise;
116
+ return cachedGraph;
117
+ }
118
+ async function doBuildGraph() {
119
+ let mod;
120
+ try {
121
+ mod = await loadAnalyzerModule();
122
+ } catch (error) {
123
+ const msg = error instanceof Error ? error.message : String(error);
124
+ throw new Error(
125
+ `artifact-contracts-analyzer is not available. Install it to use analyzer features: ${msg}`
126
+ );
127
+ }
128
+ const patterns = artifactPatterns ?? /* @__PURE__ */ new Map();
129
+ const registry = mod.createDefaultRegistry();
130
+ const astResult = await mod.buildAstGraph({
131
+ projectRoot,
132
+ artifactPatterns: patterns,
133
+ registry
134
+ });
135
+ cachedFileContents = astResult.fileContents;
136
+ cachedGraph = await mod.buildDependencyGraph({
137
+ ast: astResult.graph,
138
+ projectRoot,
139
+ artifactPatterns: patterns,
140
+ manifests: manifests ?? []
141
+ });
142
+ }
143
+ const bridge = {
144
+ async buildGraph() {
145
+ await ensureGraph();
146
+ },
147
+ async getGraph() {
148
+ return ensureGraph();
149
+ },
150
+ async analyzeImpact(changed, opts) {
151
+ let mod;
152
+ try {
153
+ mod = await loadAnalyzerModule();
154
+ } catch {
155
+ return {
156
+ error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.",
157
+ changed
158
+ };
159
+ }
160
+ const graph = await ensureGraph();
161
+ return mod.analyzeImpact({
162
+ graph,
163
+ changed,
164
+ direction: opts?.direction ?? "downstream",
165
+ ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
166
+ ...opts?.limit !== void 0 ? { limit: opts.limit } : {},
167
+ ...navigationIndex ? { navigationIndex } : {}
168
+ });
169
+ },
170
+ async generateContextPack(changed, opts) {
171
+ let mod;
172
+ try {
173
+ mod = await loadAnalyzerModule();
174
+ } catch {
175
+ return {
176
+ entries: [],
177
+ metadata: {
178
+ totalTokens: 0,
179
+ budgetTokens: opts?.budgetTokens ?? 5e4,
180
+ filesIncluded: 0,
181
+ filesExcluded: 0,
182
+ filesReferenced: 0,
183
+ artifactsCovered: [],
184
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
185
+ }
186
+ };
187
+ }
188
+ const graph = await ensureGraph();
189
+ return mod.generateContextPack({
190
+ graph,
191
+ changed,
192
+ projectRoot,
193
+ ...opts?.budgetTokens !== void 0 ? { budgetTokens: opts.budgetTokens } : {},
194
+ ...opts?.granularity ? { granularity: opts.granularity } : {},
195
+ ...navigationIndex ? { navigationIndex } : {},
196
+ ...cachedFileContents ? { fileContents: cachedFileContents } : {}
197
+ });
198
+ },
199
+ async buildCallGraph(entry, opts) {
200
+ let mod;
201
+ try {
202
+ mod = await loadAnalyzerModule();
203
+ } catch {
204
+ return {
205
+ error: "artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.",
206
+ entry
207
+ };
208
+ }
209
+ const graph = await ensureGraph();
210
+ return mod.buildCallGraph({
211
+ graph,
212
+ entry,
213
+ ...opts?.maxDepth !== void 0 ? { maxDepth: opts.maxDepth } : {},
214
+ ...opts?.direction ? { direction: opts.direction } : {}
215
+ });
216
+ },
217
+ invalidateCache() {
218
+ cachedGraph = null;
219
+ cachedFileContents = null;
220
+ graphBuildPromise = null;
221
+ },
222
+ buildAnalyzerTools() {
223
+ return [
224
+ {
225
+ name: "analyzer.analyzeImpact",
226
+ description: "Analyze the impact of changed files across the dependency graph",
227
+ inputSchema: {
228
+ type: "object",
229
+ properties: {
230
+ changed: {
231
+ type: "array",
232
+ items: { type: "string" },
233
+ description: "File paths that changed"
234
+ },
235
+ direction: {
236
+ type: "string",
237
+ enum: ["downstream", "upstream"],
238
+ description: "Traversal direction. downstream = what breaks if this changes"
239
+ },
240
+ maxDepth: {
241
+ type: "number",
242
+ description: "Maximum BFS depth to explore"
243
+ },
244
+ limit: {
245
+ type: "number",
246
+ description: "Cap the number of affected entries returned"
247
+ }
248
+ },
249
+ required: ["changed"]
250
+ },
251
+ handler: async (args) => {
252
+ const changed = args.changed;
253
+ const result = await bridge.analyzeImpact(changed, {
254
+ direction: args.direction,
255
+ maxDepth: args.maxDepth,
256
+ limit: args.limit
257
+ });
258
+ return JSON.stringify(result);
259
+ }
260
+ },
261
+ {
262
+ name: "analyzer.generateContextPack",
263
+ description: "Generate a token-budget-constrained context pack for changed files",
264
+ inputSchema: {
265
+ type: "object",
266
+ properties: {
267
+ changed: {
268
+ type: "array",
269
+ items: { type: "string" },
270
+ description: "File paths that changed"
271
+ },
272
+ budgetTokens: {
273
+ type: "number",
274
+ description: "Token budget for the context pack"
275
+ },
276
+ granularity: {
277
+ type: "string",
278
+ enum: ["file", "symbol"],
279
+ description: "Context granularity level"
280
+ }
281
+ },
282
+ required: ["changed"]
283
+ },
284
+ handler: async (args) => {
285
+ const changed = args.changed;
286
+ const result = await bridge.generateContextPack(changed, {
287
+ budgetTokens: args.budgetTokens,
288
+ granularity: args.granularity
289
+ });
290
+ return JSON.stringify(result);
291
+ }
292
+ },
293
+ {
294
+ name: "analyzer.buildCallGraph",
295
+ description: "Build a call graph rooted at a symbol",
296
+ inputSchema: {
297
+ type: "object",
298
+ properties: {
299
+ entry: {
300
+ type: "string",
301
+ description: "Entry symbolId (filePath#name) to root the call graph at"
302
+ },
303
+ maxDepth: {
304
+ type: "number",
305
+ description: "Maximum traversal depth"
306
+ },
307
+ direction: {
308
+ type: "string",
309
+ enum: ["forward", "reverse"],
310
+ description: "Traversal direction: forward (callees) or reverse (callers)"
311
+ }
312
+ },
313
+ required: ["entry"]
314
+ },
315
+ handler: async (args) => {
316
+ const entry = args.entry;
317
+ const result = await bridge.buildCallGraph(entry, {
318
+ maxDepth: args.maxDepth,
319
+ direction: args.direction
320
+ });
321
+ return JSON.stringify(result);
322
+ }
323
+ }
324
+ ];
325
+ }
326
+ };
327
+ return bridge;
328
+ }
329
+ function isContextPack(value) {
330
+ if (typeof value !== "object" || value === null) return false;
331
+ const obj = value;
332
+ if (!Array.isArray(obj.entries)) return false;
333
+ if (typeof obj.metadata !== "object" || obj.metadata === null) return false;
334
+ const meta = obj.metadata;
335
+ return typeof meta.totalTokens === "number" && typeof meta.budgetTokens === "number";
336
+ }
337
+ function renderContextPackPrompt(pack) {
338
+ const m = pack.metadata;
339
+ const sections = [];
340
+ sections.push("## Source Code Context");
341
+ sections.push(
342
+ `### Budget
343
+ - Tokens used: ${m.totalTokens} / ${m.budgetTokens}
344
+ - Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`
345
+ );
346
+ if (m.artifactsCovered.length > 0) {
347
+ sections.push(
348
+ `### Affected Artifacts
349
+ ${m.artifactsCovered.map((a) => `- ${a}`).join("\n")}`
350
+ );
351
+ }
352
+ if (pack.entries.length > 0) {
353
+ const fileBlocks = [];
354
+ for (const entry of pack.entries) {
355
+ const ext = entry.path.split(".").pop() ?? "";
356
+ const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;
357
+ const reason = `> ${entry.reason}`;
358
+ if (entry.content) {
359
+ fileBlocks.push(
360
+ `${header}
361
+ ${reason}
362
+
363
+ \`\`\`${ext}
364
+ ${entry.content}
365
+ \`\`\``
366
+ );
367
+ } else {
368
+ fileBlocks.push(`${header}
369
+ ${reason}`);
370
+ }
371
+ }
372
+ sections.push(`### Files
373
+ ${fileBlocks.join("\n\n")}`);
374
+ }
375
+ return sections.join("\n\n");
376
+ }
377
+
94
378
  // src/lib/observability-bridge.ts
95
379
  import { generateId } from "@aaac/observability";
96
380
  function createExecutionEnvelope(params = {}) {
@@ -151,7 +435,7 @@ function emitSessionOpen(observer, envelope, workflowId) {
151
435
  });
152
436
  return spanId;
153
437
  }
154
- function emitSessionClose(observer, spanId, envelope, durationMs, status) {
438
+ function emitSessionClose(observer, spanId, envelope, durationMs, status, errorMessage) {
155
439
  if (!observer) return;
156
440
  const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
157
441
  observer({
@@ -164,7 +448,8 @@ function emitSessionClose(observer, spanId, envelope, durationMs, status) {
164
448
  axis: "agent",
165
449
  "agent.session_id": envelope.run_id,
166
450
  "agent.session.duration_ms": durationMs,
167
- "agent.status": status
451
+ "agent.status": status,
452
+ "agent.error": errorMessage
168
453
  }),
169
454
  ...metaAttrs
170
455
  }
@@ -195,7 +480,7 @@ function emitSubagentOpen(observer, envelope, parentSpanId, taskId, agentRole) {
195
480
  });
196
481
  return spanId;
197
482
  }
198
- function emitSubagentClose(observer, spanId, envelope, durationMs, status, agentRole) {
483
+ function emitSubagentClose(observer, spanId, envelope, durationMs, status, agentRole, errorMessage) {
199
484
  if (!observer) return;
200
485
  const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
201
486
  observer({
@@ -208,7 +493,8 @@ function emitSubagentClose(observer, spanId, envelope, durationMs, status, agent
208
493
  axis: "agent",
209
494
  "agent.role": agentRole,
210
495
  "agent.status": status,
211
- "agent.duration_ms": durationMs
496
+ "agent.duration_ms": durationMs,
497
+ "agent.error": errorMessage
212
498
  }),
213
499
  ...metaAttrs
214
500
  }
@@ -578,10 +864,19 @@ ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
578
864
  );
579
865
  }
580
866
  if (context.variables && Object.keys(context.variables).length > 0) {
581
- const varLines = Object.entries(context.variables).map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
582
- userSections.push(`## Context Variables
867
+ const contextPack = context.variables.analyzerContextPack;
868
+ if (isContextPack(contextPack)) {
869
+ userSections.push(renderContextPackPrompt(contextPack));
870
+ }
871
+ const otherVars = Object.entries(context.variables).filter(
872
+ ([k]) => k !== "analyzerContextPack"
873
+ );
874
+ if (otherVars.length > 0) {
875
+ const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
876
+ userSections.push(`## Context Variables
583
877
 
584
878
  ${varLines}`);
879
+ }
585
880
  }
586
881
  return {
587
882
  system,
@@ -809,111 +1104,264 @@ async function runTask(adapter, taskId, context, options) {
809
1104
  taskId,
810
1105
  agentContract.role_name
811
1106
  );
812
- let fullOutput;
813
- try {
814
- if (adapter.sendExecution) {
815
- fullOutput = await adapter.sendExecution({
816
- agentId: agentContract.id,
817
- taskId,
818
- prompt,
819
- handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
820
- schema: schemas[task.result_handoff] ? {
821
- handoffType: task.result_handoff,
822
- zodSchema: schemas[task.result_handoff],
823
- promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
824
- } : void 0,
825
- context: enrichedContext,
826
- memoryRef,
827
- splitPrompt,
828
- agents,
829
- options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, maxFollowUps, attempt: 0 }
830
- });
831
- } else {
832
- fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools });
833
- }
834
- } catch (err) {
835
- const errDurationMs = Date.now() - taskExecStart;
836
- taskEnvelope.execution_metadata = { duration_ms: errDurationMs };
1107
+ let closeStatus = "error";
1108
+ let closeCause;
1109
+ let spanClosed = false;
1110
+ const closeSubagentSpan = () => {
1111
+ if (spanClosed) return;
1112
+ spanClosed = true;
1113
+ const durationMs = Date.now() - taskExecStart;
1114
+ taskEnvelope.execution_metadata = {
1115
+ ...taskEnvelope.execution_metadata ?? {},
1116
+ duration_ms: durationMs
1117
+ };
837
1118
  emitSubagentClose(
838
1119
  options?.observer,
839
1120
  subagentSpanId ?? taskEnvelope.run_id,
840
1121
  taskEnvelope,
841
- errDurationMs,
842
- "error",
843
- agentContract.role_name
1122
+ durationMs,
1123
+ closeStatus,
1124
+ agentContract.role_name,
1125
+ closeCause
844
1126
  );
845
- return { outcome: { status: "error", message: `SDK error: ${err.message}` }, follow_ups_used: 0, retries_used: 0 };
846
- }
847
- let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
848
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
849
- while (outcome.status === "validation_error" || outcome.status === "error") {
850
- const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
851
- if (decision === "abort") break;
852
- let effectiveDecision = decision;
853
- if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
854
- effectiveDecision = "retry";
855
- }
856
- if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
857
- break;
858
- }
859
- if (effectiveDecision === "follow_up") {
860
- followUpsUsed++;
861
- const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
862
- try {
863
- if (adapter.followUp) {
864
- fullOutput = await adapter.followUp(followUpPrompt);
865
- } else {
866
- const retryContext = {
867
- ...modifiedContext,
868
- prior_context: (modifiedContext.prior_context ?? "") + `
1127
+ };
1128
+ try {
1129
+ let fullOutput;
1130
+ try {
1131
+ if (adapter.sendExecution) {
1132
+ fullOutput = await adapter.sendExecution({
1133
+ agentId: agentContract.id,
1134
+ taskId,
1135
+ prompt,
1136
+ handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
1137
+ schema: schemas[task.result_handoff] ? {
1138
+ handoffType: task.result_handoff,
1139
+ zodSchema: schemas[task.result_handoff],
1140
+ promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
1141
+ } : void 0,
1142
+ context: enrichedContext,
1143
+ memoryRef,
1144
+ splitPrompt,
1145
+ agents,
1146
+ options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, maxFollowUps, attempt: 0 }
1147
+ });
1148
+ } else {
1149
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools });
1150
+ }
1151
+ } catch (err) {
1152
+ closeStatus = "error";
1153
+ closeCause = `SDK error: ${err.message}`;
1154
+ return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
1155
+ }
1156
+ let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1157
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1158
+ while (outcome.status === "validation_error" || outcome.status === "error") {
1159
+ const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
1160
+ if (decision === "abort") break;
1161
+ let effectiveDecision = decision;
1162
+ if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
1163
+ effectiveDecision = "retry";
1164
+ }
1165
+ if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
1166
+ break;
1167
+ }
1168
+ if (effectiveDecision === "follow_up") {
1169
+ followUpsUsed++;
1170
+ const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
1171
+ try {
1172
+ if (adapter.followUp) {
1173
+ fullOutput = await adapter.followUp(followUpPrompt);
1174
+ } else {
1175
+ const retryContext = {
1176
+ ...modifiedContext,
1177
+ prior_context: (modifiedContext.prior_context ?? "") + `
869
1178
 
870
1179
  --- FollowUp ${followUpsUsed} ---
871
1180
  ${followUpPrompt}`
872
- };
873
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
874
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
875
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1181
+ };
1182
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
1183
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1184
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1185
+ }
1186
+ } catch (err) {
1187
+ outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
1188
+ continue;
876
1189
  }
877
- } catch (err) {
878
- outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
879
- continue;
880
- }
881
- } else {
882
- retriesUsed++;
883
- const retryContext = {
884
- ...modifiedContext,
885
- prior_context: (modifiedContext.prior_context ?? "") + `
1190
+ } else {
1191
+ retriesUsed++;
1192
+ const retryContext = {
1193
+ ...modifiedContext,
1194
+ prior_context: (modifiedContext.prior_context ?? "") + `
886
1195
 
887
1196
  --- Full Retry ${retriesUsed} ---
888
1197
  Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
889
1198
  Please re-execute the entire task.`
890
- };
891
- let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
892
- retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
893
- try {
894
- fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
895
- } catch (err) {
896
- outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
897
- continue;
1199
+ };
1200
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
1201
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
1202
+ try {
1203
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
1204
+ } catch (err) {
1205
+ outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
1206
+ continue;
1207
+ }
898
1208
  }
1209
+ outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
1210
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
899
1211
  }
900
- outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
901
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
1212
+ closeStatus = outcome.status;
1213
+ return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
1214
+ } catch (err) {
1215
+ closeStatus = "error";
1216
+ closeCause = err.message;
1217
+ throw err;
1218
+ } finally {
1219
+ closeSubagentSpan();
902
1220
  }
903
- const totalDurationMs = Date.now() - taskExecStart;
904
- taskEnvelope.execution_metadata = {
905
- ...taskEnvelope.execution_metadata ?? {},
906
- duration_ms: totalDurationMs
907
- };
908
- emitSubagentClose(
909
- options?.observer,
910
- subagentSpanId ?? taskEnvelope.run_id,
911
- taskEnvelope,
912
- totalDurationMs,
913
- outcome.status,
914
- agentContract.role_name
915
- );
916
- return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
1221
+ }
1222
+
1223
+ // src/lib/toolchain-checker.ts
1224
+ import { execFile } from "child_process";
1225
+ import { readFile } from "fs/promises";
1226
+ import { existsSync } from "fs";
1227
+ import { resolve } from "path";
1228
+ import { promisify } from "util";
1229
+ import { z as z2 } from "zod";
1230
+ import { parseToolchainFile } from "@aaac/toolchain";
1231
+ var execFileAsync = promisify(execFile);
1232
+ var SUBPROCESS_TIMEOUT_MS = 3e4;
1233
+ var MANIFEST_FILENAME = ".toolchain-manifest.json";
1234
+ var ToolchainManifestSchema = z2.object({
1235
+ schema: z2.string(),
1236
+ toolchain_id: z2.string(),
1237
+ generated_at: z2.string(),
1238
+ source_hash: z2.string(),
1239
+ output_hash: z2.string(),
1240
+ source_globs: z2.array(z2.string()).optional(),
1241
+ output_globs: z2.array(z2.string()).optional(),
1242
+ files: z2.array(
1243
+ z2.object({
1244
+ path: z2.string(),
1245
+ hash: z2.string()
1246
+ })
1247
+ ).optional()
1248
+ });
1249
+ function resolveAction(checkType, checkTypeActions, defaultAction) {
1250
+ if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
1251
+ if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
1252
+ return defaultAction ?? "warn";
1253
+ }
1254
+ async function tryManifestFastPath(toolchainId, cwd) {
1255
+ const manifestPath = resolve(cwd, MANIFEST_FILENAME);
1256
+ if (!existsSync(manifestPath)) return null;
1257
+ try {
1258
+ const raw = await readFile(manifestPath, "utf-8");
1259
+ const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
1260
+ if (parsed.toolchain_id !== toolchainId) return null;
1261
+ return {
1262
+ toolchainId,
1263
+ checkType: "drift",
1264
+ status: "pass",
1265
+ action: "warn",
1266
+ message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
1267
+ durationMs: 0
1268
+ };
1269
+ } catch {
1270
+ return null;
1271
+ }
1272
+ }
1273
+ async function executeCheck(command, cwd) {
1274
+ try {
1275
+ const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
1276
+ cwd,
1277
+ timeout: SUBPROCESS_TIMEOUT_MS
1278
+ });
1279
+ return { exitCode: 0, stdout, stderr };
1280
+ } catch (err) {
1281
+ const execErr = err;
1282
+ if (execErr.killed) {
1283
+ throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
1284
+ }
1285
+ const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
1286
+ return {
1287
+ exitCode,
1288
+ stdout: execErr.stdout ?? "",
1289
+ stderr: execErr.stderr ?? ""
1290
+ };
1291
+ }
1292
+ }
1293
+ async function runToolchainChecks(options) {
1294
+ const {
1295
+ toolchainsPath,
1296
+ cwd: workingDir,
1297
+ checkTypes,
1298
+ toolchainFilter,
1299
+ checkTypeActions,
1300
+ defaultAction,
1301
+ observer,
1302
+ parentSpanId,
1303
+ componentId
1304
+ } = options;
1305
+ const cwd = workingDir ?? process.cwd();
1306
+ const contracts = await parseToolchainFile(toolchainsPath);
1307
+ const results = [];
1308
+ for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
1309
+ if (!toolchain.checks) continue;
1310
+ if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
1311
+ for (const [checkType, command] of Object.entries(toolchain.checks)) {
1312
+ if (checkTypes && !checkTypes.includes(checkType)) continue;
1313
+ const action = resolveAction(checkType, checkTypeActions, defaultAction);
1314
+ const start = performance.now();
1315
+ const spanId = emitToolchainOpen(
1316
+ observer,
1317
+ parentSpanId,
1318
+ toolchainId,
1319
+ checkType,
1320
+ [],
1321
+ componentId
1322
+ );
1323
+ let result;
1324
+ const fastResult = checkType === "drift" && options.artifactsPath ? await tryManifestFastPath(toolchainId, cwd) : null;
1325
+ if (fastResult) {
1326
+ fastResult.action = action;
1327
+ result = fastResult;
1328
+ } else {
1329
+ try {
1330
+ const { exitCode, stderr } = await executeCheck(command, cwd);
1331
+ const durationMs = Math.round(performance.now() - start);
1332
+ result = {
1333
+ toolchainId,
1334
+ checkType,
1335
+ status: exitCode === 0 ? "pass" : "fail",
1336
+ action,
1337
+ message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
1338
+ durationMs
1339
+ };
1340
+ } catch (err) {
1341
+ const durationMs = Math.round(performance.now() - start);
1342
+ result = {
1343
+ toolchainId,
1344
+ checkType,
1345
+ status: "error",
1346
+ action,
1347
+ message: err.message,
1348
+ durationMs
1349
+ };
1350
+ }
1351
+ }
1352
+ results.push(result);
1353
+ emitToolchainClose(
1354
+ observer,
1355
+ spanId ?? "",
1356
+ toolchainId,
1357
+ checkType,
1358
+ result.durationMs ?? Math.round(performance.now() - start),
1359
+ result.status === "pass" ? "success" : "failure",
1360
+ result.status === "pass" ? void 0 : result.message
1361
+ );
1362
+ }
1363
+ }
1364
+ return results;
917
1365
  }
918
1366
 
919
1367
  // src/lib/workflow-runner.ts
@@ -954,7 +1402,8 @@ function resolveInvocation(invocation) {
954
1402
  onStepComplete: invocation.hooks?.onStepComplete,
955
1403
  onOptionalStep: invocation.hooks?.onOptionalStep,
956
1404
  progressOutput: invocation.progressOutput,
957
- observer: invocation.observer
1405
+ observer: invocation.observer,
1406
+ toolchain: invocation.toolchain
958
1407
  }
959
1408
  };
960
1409
  }
@@ -1005,367 +1454,386 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
1005
1454
  const sessionEnvelope = createExecutionEnvelope({ componentId: workflowId });
1006
1455
  const sessionSpanId = emitSessionOpen(options.observer, sessionEnvelope, workflowId);
1007
1456
  const workflowStart = Date.now();
1008
- const stepId = (i) => {
1009
- const s = workflow.steps[i];
1010
- if (s.type === "delegate" || s.type === "evaluate") return s.task;
1011
- return `gate:${s.gate_kind}`;
1012
- };
1013
- const depsByIndex = workflow.steps.map((step, i) => {
1014
- if (step.depends_on !== void 0) {
1015
- return step.depends_on.map((dep) => {
1016
- const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);
1017
- if (idx === -1) {
1018
- throw new Error(`depends_on "${dep}" in step ${i} (${stepId(i)}) not found among preceding steps`);
1457
+ let wfResult;
1458
+ let sessionError;
1459
+ try {
1460
+ let extractPath2 = function(obj, path) {
1461
+ const cleanPath = path.startsWith("$.") ? path.slice(2) : path;
1462
+ const segments = cleanPath.split(".");
1463
+ let current = obj;
1464
+ for (const seg of segments) {
1465
+ if (current == null || typeof current !== "object") return void 0;
1466
+ current = current[seg];
1467
+ }
1468
+ return current;
1469
+ }, projectHandoffs2 = function(stepIndex, step) {
1470
+ if (!step.receives) return void 0;
1471
+ const projected = {};
1472
+ for (const [alias, spec] of Object.entries(step.receives)) {
1473
+ const fromTaskId = spec.from ?? alias;
1474
+ const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);
1475
+ if (depIdx === -1) continue;
1476
+ const output = stepOutputs[depIdx];
1477
+ if (output === void 0) continue;
1478
+ if (spec.path) {
1479
+ projected[alias] = extractPath2(output, spec.path);
1480
+ } else {
1481
+ projected[alias] = output;
1019
1482
  }
1020
- return idx;
1021
- });
1022
- }
1023
- return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);
1024
- });
1025
- const completed = /* @__PURE__ */ new Set();
1026
- const stepResults = new Array(workflow.steps.length);
1027
- const stepContexts = new Array(workflow.steps.length).fill("");
1028
- const stepOutputs = new Array(workflow.steps.length).fill(void 0);
1029
- let abortResult;
1030
- const evaluateExecCount = /* @__PURE__ */ new Map();
1031
- const iterationSpanIds = /* @__PURE__ */ new Map();
1032
- const loopInjectedVars = {};
1033
- function extractPath(obj, path) {
1034
- const cleanPath = path.startsWith("$.") ? path.slice(2) : path;
1035
- const segments = cleanPath.split(".");
1036
- let current = obj;
1037
- for (const seg of segments) {
1038
- if (current == null || typeof current !== "object") return void 0;
1039
- current = current[seg];
1040
- }
1041
- return current;
1042
- }
1043
- function projectHandoffs(stepIndex, step) {
1044
- if (!step.receives) return void 0;
1045
- const projected = {};
1046
- for (const [alias, spec] of Object.entries(step.receives)) {
1047
- const fromTaskId = spec.from ?? alias;
1048
- const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);
1049
- if (depIdx === -1) continue;
1050
- const output = stepOutputs[depIdx];
1051
- if (output === void 0) continue;
1052
- if (spec.path) {
1053
- projected[alias] = extractPath(output, spec.path);
1054
- } else {
1055
- projected[alias] = output;
1056
1483
  }
1057
- }
1058
- return Object.keys(projected).length > 0 ? projected : void 0;
1059
- }
1060
- function contextFor(stepIndex) {
1061
- const deps = depsByIndex[stepIndex];
1062
- if (deps.length === 0) return "";
1063
- return deps.filter((d) => completed.has(d)).map((d) => stepContexts[d]).filter(Boolean).join("");
1064
- }
1065
- async function executeStep(i, stepAdapter) {
1066
- const step = workflow.steps[i];
1067
- const stepStart = Date.now();
1068
- if (step.type === "gate") {
1069
- return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);
1070
- }
1071
- if (step.type === "evaluate") {
1072
- const evaluateStep = step;
1073
- const iterationNumber = (evaluateExecCount.get(i) ?? 0) + 1;
1074
- const iterationSpanId = emitIterationOpen(
1075
- options.observer,
1076
- sessionSpanId,
1077
- evaluateStep.task,
1078
- evaluateStep.loop_to,
1079
- iterationNumber,
1080
- evaluateStep.max_iterations
1081
- );
1082
- if (iterationSpanId) {
1083
- iterationSpanIds.set(i, iterationSpanId);
1084
- }
1085
- const effectiveVariables = mergeVariables(options.variables, loopInjectedVars);
1086
- const context2 = {
1087
- user_request: evaluateStep.description ?? options.user_request,
1088
- prior_context: contextFor(i),
1089
- ...effectiveVariables ? { variables: effectiveVariables } : {}
1484
+ return Object.keys(projected).length > 0 ? projected : void 0;
1485
+ }, contextFor2 = function(stepIndex) {
1486
+ const deps = depsByIndex[stepIndex];
1487
+ if (deps.length === 0) return "";
1488
+ return deps.filter((d) => completed.has(d)).map((d) => stepContexts[d]).filter(Boolean).join("");
1489
+ };
1490
+ var extractPath = extractPath2, projectHandoffs = projectHandoffs2, contextFor = contextFor2;
1491
+ const stepId = (i) => {
1492
+ const s = workflow.steps[i];
1493
+ if (s.type === "delegate" || s.type === "evaluate") return s.task;
1494
+ return `gate:${s.gate_kind}`;
1495
+ };
1496
+ const depsByIndex = workflow.steps.map((step, i) => {
1497
+ if (step.depends_on !== void 0) {
1498
+ return step.depends_on.map((dep) => {
1499
+ const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);
1500
+ if (idx === -1) {
1501
+ throw new Error(`depends_on "${dep}" in step ${i} (${stepId(i)}) not found among preceding steps`);
1502
+ }
1503
+ return idx;
1504
+ });
1505
+ }
1506
+ return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);
1507
+ });
1508
+ const completed = /* @__PURE__ */ new Set();
1509
+ const stepResults = new Array(workflow.steps.length);
1510
+ const stepContexts = new Array(workflow.steps.length).fill("");
1511
+ const stepOutputs = new Array(workflow.steps.length).fill(void 0);
1512
+ let abortResult;
1513
+ const evaluateExecCount = /* @__PURE__ */ new Map();
1514
+ const iterationSpanIds = /* @__PURE__ */ new Map();
1515
+ const loopInjectedVars = {};
1516
+ async function executeStep(i, stepAdapter) {
1517
+ const step = workflow.steps[i];
1518
+ const stepStart = Date.now();
1519
+ if (step.type === "gate") {
1520
+ return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);
1521
+ }
1522
+ if (step.type === "evaluate") {
1523
+ const evaluateStep = step;
1524
+ const iterationNumber = (evaluateExecCount.get(i) ?? 0) + 1;
1525
+ const iterationSpanId = emitIterationOpen(
1526
+ options.observer,
1527
+ sessionSpanId,
1528
+ evaluateStep.task,
1529
+ evaluateStep.loop_to,
1530
+ iterationNumber,
1531
+ evaluateStep.max_iterations
1532
+ );
1533
+ if (iterationSpanId) {
1534
+ iterationSpanIds.set(i, iterationSpanId);
1535
+ }
1536
+ const effectiveVariables = mergeVariables(options.variables, loopInjectedVars);
1537
+ const context2 = {
1538
+ user_request: evaluateStep.description ?? options.user_request,
1539
+ prior_context: contextFor2(i),
1540
+ ...effectiveVariables ? { variables: effectiveVariables } : {}
1541
+ };
1542
+ const taskResult2 = await runTask(stepAdapter, evaluateStep.task, context2, {
1543
+ maxFollowUps: options.maxFollowUps ?? 2,
1544
+ maxRetries: 0,
1545
+ // evaluate steps do not retry
1546
+ taskRegistry: registries?.taskRegistry,
1547
+ agentRegistry: registries?.agentRegistry,
1548
+ handoffSchemas: registries?.handoffSchemas,
1549
+ progressOutput: options.progressOutput,
1550
+ observer: options.observer,
1551
+ parentSpanId: iterationSpanId ?? sessionSpanId
1552
+ });
1553
+ return {
1554
+ step_index: i,
1555
+ task_id: evaluateStep.task,
1556
+ outcome: taskResult2.outcome,
1557
+ follow_ups_used: taskResult2.follow_ups_used,
1558
+ retries_used: taskResult2.retries_used,
1559
+ elapsed_ms: Date.now() - stepStart
1560
+ };
1561
+ }
1562
+ const delegateStep = step;
1563
+ if (step.optional) {
1564
+ const stepUserRequest2 = delegateStep.instruction ?? options.user_request;
1565
+ const ctxVars = mergeVariables(options.variables, loopInjectedVars);
1566
+ const ctx = {
1567
+ user_request: stepUserRequest2,
1568
+ prior_context: contextFor2(i),
1569
+ ...ctxVars ? { variables: ctxVars } : {}
1570
+ };
1571
+ const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
1572
+ if (!shouldRun) {
1573
+ return {
1574
+ step_index: i,
1575
+ task_id: step.task,
1576
+ outcome: { status: "skipped" },
1577
+ follow_ups_used: 0,
1578
+ retries_used: 0,
1579
+ elapsed_ms: Date.now() - stepStart
1580
+ };
1581
+ }
1582
+ }
1583
+ const stepUserRequest = delegateStep.instruction ?? options.user_request;
1584
+ let handoffInput;
1585
+ const projected = projectHandoffs2(i, delegateStep);
1586
+ if (projected) {
1587
+ handoffInput = {
1588
+ type: "step-projection",
1589
+ payload: projected
1590
+ };
1591
+ } else if (i === 0 && invocationHandoff) {
1592
+ handoffInput = invocationHandoff;
1593
+ }
1594
+ const useLegacyContext = !delegateStep.receives;
1595
+ const delegateVars = mergeVariables(options.variables, loopInjectedVars);
1596
+ const context = {
1597
+ user_request: stepUserRequest,
1598
+ ...useLegacyContext ? { prior_context: contextFor2(i) } : {},
1599
+ ...delegateVars ? { variables: delegateVars } : {},
1600
+ ...handoffInput ? { handoff_input: handoffInput } : {}
1090
1601
  };
1091
- const taskResult2 = await runTask(stepAdapter, evaluateStep.task, context2, {
1092
- maxFollowUps: options.maxFollowUps ?? 2,
1093
- maxRetries: 0,
1094
- // evaluate steps do not retry
1602
+ const taskResult = await runTask(stepAdapter, step.task, context, {
1603
+ maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,
1604
+ maxRetries: options.maxRetries ?? step.max_retries ?? 0,
1095
1605
  taskRegistry: registries?.taskRegistry,
1096
1606
  agentRegistry: registries?.agentRegistry,
1097
1607
  handoffSchemas: registries?.handoffSchemas,
1608
+ retry: step.retry,
1098
1609
  progressOutput: options.progressOutput,
1610
+ // ── Phase 1-2: Observer Bridge ────────────────────────────────────────
1611
+ // Thread observer and session span ID so task-runner can emit agent.subagent
1612
+ // spans correlated to this session (parent_run_id → parentSpanId).
1099
1613
  observer: options.observer,
1100
- parentSpanId: iterationSpanId ?? sessionSpanId
1614
+ parentSpanId: sessionSpanId
1101
1615
  });
1102
1616
  return {
1103
1617
  step_index: i,
1104
- task_id: evaluateStep.task,
1105
- outcome: taskResult2.outcome,
1106
- follow_ups_used: taskResult2.follow_ups_used,
1107
- retries_used: taskResult2.retries_used,
1618
+ task_id: step.task,
1619
+ outcome: taskResult.outcome,
1620
+ follow_ups_used: taskResult.follow_ups_used,
1621
+ retries_used: taskResult.retries_used,
1108
1622
  elapsed_ms: Date.now() - stepStart
1109
1623
  };
1110
1624
  }
1111
- const delegateStep = step;
1112
- if (step.optional) {
1113
- const stepUserRequest2 = delegateStep.instruction ?? options.user_request;
1114
- const ctxVars = mergeVariables(options.variables, loopInjectedVars);
1115
- const ctx = {
1116
- user_request: stepUserRequest2,
1117
- prior_context: contextFor(i),
1118
- ...ctxVars ? { variables: ctxVars } : {}
1119
- };
1120
- const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
1121
- if (!shouldRun) {
1122
- return {
1123
- step_index: i,
1124
- task_id: step.task,
1125
- outcome: { status: "skipped" },
1126
- follow_ups_used: 0,
1127
- retries_used: 0,
1128
- elapsed_ms: Date.now() - stepStart
1129
- };
1625
+ while (completed.size < workflow.steps.length) {
1626
+ const ready = [];
1627
+ for (let i = 0; i < workflow.steps.length; i++) {
1628
+ if (completed.has(i)) continue;
1629
+ if (depsByIndex[i].every((d) => completed.has(d))) {
1630
+ ready.push(i);
1631
+ }
1130
1632
  }
1131
- }
1132
- const stepUserRequest = delegateStep.instruction ?? options.user_request;
1133
- let handoffInput;
1134
- const projected = projectHandoffs(i, delegateStep);
1135
- if (projected) {
1136
- handoffInput = {
1137
- type: "step-projection",
1138
- payload: projected
1139
- };
1140
- } else if (i === 0 && invocationHandoff) {
1141
- handoffInput = invocationHandoff;
1142
- }
1143
- const useLegacyContext = !delegateStep.receives;
1144
- const delegateVars = mergeVariables(options.variables, loopInjectedVars);
1145
- const context = {
1146
- user_request: stepUserRequest,
1147
- ...useLegacyContext ? { prior_context: contextFor(i) } : {},
1148
- ...delegateVars ? { variables: delegateVars } : {},
1149
- ...handoffInput ? { handoff_input: handoffInput } : {}
1150
- };
1151
- const taskResult = await runTask(stepAdapter, step.task, context, {
1152
- maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,
1153
- maxRetries: options.maxRetries ?? step.max_retries ?? 0,
1154
- taskRegistry: registries?.taskRegistry,
1155
- agentRegistry: registries?.agentRegistry,
1156
- handoffSchemas: registries?.handoffSchemas,
1157
- retry: step.retry,
1158
- progressOutput: options.progressOutput,
1159
- // ── Phase 1-2: Observer Bridge ────────────────────────────────────────
1160
- // Thread observer and session span ID so task-runner can emit agent.subagent
1161
- // spans correlated to this session (parent_run_id → parentSpanId).
1162
- observer: options.observer,
1163
- parentSpanId: sessionSpanId
1164
- });
1165
- return {
1166
- step_index: i,
1167
- task_id: step.task,
1168
- outcome: taskResult.outcome,
1169
- follow_ups_used: taskResult.follow_ups_used,
1170
- retries_used: taskResult.retries_used,
1171
- elapsed_ms: Date.now() - stepStart
1172
- };
1173
- }
1174
- while (completed.size < workflow.steps.length) {
1175
- const ready = [];
1176
- for (let i = 0; i < workflow.steps.length; i++) {
1177
- if (completed.has(i)) continue;
1178
- if (depsByIndex[i].every((d) => completed.has(d))) {
1179
- ready.push(i);
1180
- }
1181
- }
1182
- if (ready.length === 0) {
1183
- abortResult = {
1184
- workflow_id: workflow.id,
1185
- status: "error",
1186
- steps: stepResults.filter(Boolean),
1187
- total_elapsed_ms: Date.now() - workflowStart,
1188
- error_message: "Dependency cycle detected: no steps are ready to execute"
1189
- };
1190
- break;
1191
- }
1192
- const batchResults = await Promise.all(ready.map(async (i) => {
1193
- const step = workflow.steps[i];
1194
- const modelClass = step.type === "delegate" || step.type === "evaluate" ? registries?.taskRegistry?.[step.task]?.model_class : void 0;
1195
- let stepAdapter;
1196
- if (ready.length > 1 && adapterFactory) {
1197
- const result = adapterFactory(modelClass);
1198
- stepAdapter = result && typeof result.then === "function" ? await result : result;
1199
- } else if (modelClass && adapterFactory) {
1200
- const result = adapterFactory(modelClass);
1201
- stepAdapter = result && typeof result.then === "function" ? await result : result;
1202
- } else {
1203
- stepAdapter = primaryAdapter;
1633
+ if (ready.length === 0) {
1634
+ abortResult = {
1635
+ workflow_id: workflow.id,
1636
+ status: "error",
1637
+ steps: stepResults.filter(Boolean),
1638
+ total_elapsed_ms: Date.now() - workflowStart,
1639
+ error_message: "Dependency cycle detected: no steps are ready to execute"
1640
+ };
1641
+ break;
1204
1642
  }
1205
- return executeStep(i, stepAdapter);
1206
- }));
1207
- for (let b = 0; b < ready.length; b++) {
1208
- const i = ready[b];
1209
- const result = batchResults[b];
1210
- const step = workflow.steps[i];
1211
- if (step.type === "evaluate") {
1212
- const evaluateStep = step;
1213
- const data = result.outcome.status === "success" ? result.outcome.data : void 0;
1214
- const verdict = typeof data?.verdict === "string" ? data.verdict : "fail";
1215
- const execCount = (evaluateExecCount.get(i) ?? 0) + 1;
1216
- const currentIterationSpanId = iterationSpanIds.get(i);
1217
- if (currentIterationSpanId) {
1218
- const willLoopBack = verdict !== "pass" && execCount < evaluateStep.max_iterations;
1219
- const feedbackInjected = willLoopBack && !!evaluateStep.inject_as;
1220
- emitIterationClose(
1221
- options.observer,
1222
- currentIterationSpanId,
1223
- evaluateStep.task,
1224
- execCount,
1225
- verdict,
1226
- result.elapsed_ms,
1227
- feedbackInjected
1228
- );
1229
- iterationSpanIds.delete(i);
1643
+ const batchResults = await Promise.all(ready.map(async (i) => {
1644
+ const step = workflow.steps[i];
1645
+ const modelClass = step.type === "delegate" || step.type === "evaluate" ? registries?.taskRegistry?.[step.task]?.model_class : void 0;
1646
+ let stepAdapter;
1647
+ if (ready.length > 1 && adapterFactory) {
1648
+ const result = adapterFactory(modelClass);
1649
+ stepAdapter = result && typeof result.then === "function" ? await result : result;
1650
+ } else if (modelClass && adapterFactory) {
1651
+ const result = adapterFactory(modelClass);
1652
+ stepAdapter = result && typeof result.then === "function" ? await result : result;
1653
+ } else {
1654
+ stepAdapter = primaryAdapter;
1230
1655
  }
1231
- if (verdict === "pass") {
1232
- emitIterationMetric(
1233
- options.observer,
1234
- sessionSpanId,
1235
- evaluateStep.task,
1236
- execCount,
1237
- "pass"
1238
- );
1239
- stepResults[i] = result;
1240
- completed.add(i);
1241
- emitStepEvent(options, workflow.id, i, step, result);
1242
- if (data !== void 0) {
1243
- stepOutputs[i] = data;
1244
- stepContexts[i] = `
1245
-
1246
- --- Step ${i + 1}: ${stepId(i)} ---
1247
- ${JSON.stringify(data, null, 2)}`;
1248
- }
1249
- } else if (execCount < evaluateStep.max_iterations) {
1250
- evaluateExecCount.set(i, execCount);
1251
- if (evaluateStep.inject_as) {
1252
- const feedback = typeof data?.feedback === "string" ? data.feedback : data !== void 0 ? JSON.stringify(data) : "Evaluate step returned no feedback";
1253
- loopInjectedVars[evaluateStep.inject_as] = feedback;
1656
+ return executeStep(i, stepAdapter);
1657
+ }));
1658
+ for (let b = 0; b < ready.length; b++) {
1659
+ const i = ready[b];
1660
+ const result = batchResults[b];
1661
+ const step = workflow.steps[i];
1662
+ if (step.type === "evaluate") {
1663
+ const evaluateStep = step;
1664
+ const data = result.outcome.status === "success" ? result.outcome.data : void 0;
1665
+ const verdict = typeof data?.verdict === "string" ? data.verdict : "fail";
1666
+ const execCount = (evaluateExecCount.get(i) ?? 0) + 1;
1667
+ const currentIterationSpanId = iterationSpanIds.get(i);
1668
+ if (currentIterationSpanId) {
1669
+ const willLoopBack = verdict !== "pass" && execCount < evaluateStep.max_iterations;
1670
+ const feedbackInjected = willLoopBack && !!evaluateStep.inject_as;
1671
+ emitIterationClose(
1672
+ options.observer,
1673
+ currentIterationSpanId,
1674
+ evaluateStep.task,
1675
+ execCount,
1676
+ verdict,
1677
+ result.elapsed_ms,
1678
+ feedbackInjected
1679
+ );
1680
+ iterationSpanIds.delete(i);
1254
1681
  }
1255
- const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);
1256
- if (loopToIdx === -1) {
1682
+ if (verdict === "pass") {
1683
+ emitIterationMetric(
1684
+ options.observer,
1685
+ sessionSpanId,
1686
+ evaluateStep.task,
1687
+ execCount,
1688
+ "pass"
1689
+ );
1257
1690
  stepResults[i] = result;
1258
1691
  completed.add(i);
1259
- abortResult = {
1260
- workflow_id: workflow.id,
1261
- status: "error",
1262
- steps: stepResults.filter(Boolean),
1263
- total_elapsed_ms: Date.now() - workflowStart,
1264
- error_message: `Evaluate step "${evaluateStep.task}" references unknown loop_to "${evaluateStep.loop_to}"`
1265
- };
1266
- } else {
1267
- for (let k = loopToIdx; k <= i; k++) {
1268
- completed.delete(k);
1269
- stepOutputs[k] = void 0;
1270
- stepContexts[k] = "";
1692
+ emitStepEvent(options, workflow.id, i, step, result);
1693
+ if (data !== void 0) {
1694
+ stepOutputs[i] = data;
1695
+ stepContexts[i] = `
1696
+
1697
+ --- Step ${i + 1}: ${stepId(i)} ---
1698
+ ${JSON.stringify(data, null, 2)}`;
1271
1699
  }
1272
- }
1273
- } else {
1274
- evaluateExecCount.set(i, execCount);
1275
- stepResults[i] = result;
1276
- completed.add(i);
1277
- const exhaustedPolicy = evaluateStep.on_exhausted ?? "escalate";
1278
- emitIterationMetric(
1279
- options.observer,
1280
- sessionSpanId,
1281
- evaluateStep.task,
1282
- execCount,
1283
- `exhausted-${exhaustedPolicy}`
1284
- );
1285
- switch (exhaustedPolicy) {
1286
- case "abort":
1700
+ } else if (execCount < evaluateStep.max_iterations) {
1701
+ evaluateExecCount.set(i, execCount);
1702
+ if (evaluateStep.inject_as) {
1703
+ const feedback = typeof data?.feedback === "string" ? data.feedback : data !== void 0 ? JSON.stringify(data) : "Evaluate step returned no feedback";
1704
+ loopInjectedVars[evaluateStep.inject_as] = feedback;
1705
+ }
1706
+ const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);
1707
+ if (loopToIdx === -1) {
1708
+ stepResults[i] = result;
1709
+ completed.add(i);
1287
1710
  abortResult = {
1288
1711
  workflow_id: workflow.id,
1289
1712
  status: "error",
1290
1713
  steps: stepResults.filter(Boolean),
1291
1714
  total_elapsed_ms: Date.now() - workflowStart,
1292
- error_message: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1293
- };
1294
- break;
1295
- case "fail_partial":
1296
- emitStepEvent(options, workflow.id, i, step, result);
1297
- break;
1298
- case "escalate":
1299
- default:
1300
- abortResult = {
1301
- workflow_id: workflow.id,
1302
- status: "escalated",
1303
- steps: stepResults.filter(Boolean),
1304
- total_elapsed_ms: Date.now() - workflowStart,
1305
- escalation_reason: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1715
+ error_message: `Evaluate step "${evaluateStep.task}" references unknown loop_to "${evaluateStep.loop_to}"`
1306
1716
  };
1307
- break;
1717
+ } else {
1718
+ for (let k = loopToIdx; k <= i; k++) {
1719
+ completed.delete(k);
1720
+ stepOutputs[k] = void 0;
1721
+ stepContexts[k] = "";
1722
+ }
1723
+ }
1724
+ } else {
1725
+ evaluateExecCount.set(i, execCount);
1726
+ stepResults[i] = result;
1727
+ completed.add(i);
1728
+ const exhaustedPolicy = evaluateStep.on_exhausted ?? "escalate";
1729
+ emitIterationMetric(
1730
+ options.observer,
1731
+ sessionSpanId,
1732
+ evaluateStep.task,
1733
+ execCount,
1734
+ `exhausted-${exhaustedPolicy}`
1735
+ );
1736
+ switch (exhaustedPolicy) {
1737
+ case "abort":
1738
+ abortResult = {
1739
+ workflow_id: workflow.id,
1740
+ status: "error",
1741
+ steps: stepResults.filter(Boolean),
1742
+ total_elapsed_ms: Date.now() - workflowStart,
1743
+ error_message: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1744
+ };
1745
+ break;
1746
+ case "fail_partial":
1747
+ emitStepEvent(options, workflow.id, i, step, result);
1748
+ break;
1749
+ case "escalate":
1750
+ default:
1751
+ abortResult = {
1752
+ workflow_id: workflow.id,
1753
+ status: "escalated",
1754
+ steps: stepResults.filter(Boolean),
1755
+ total_elapsed_ms: Date.now() - workflowStart,
1756
+ escalation_reason: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1757
+ };
1758
+ break;
1759
+ }
1308
1760
  }
1761
+ continue;
1309
1762
  }
1310
- continue;
1311
- }
1312
- stepResults[i] = result;
1313
- completed.add(i);
1314
- emitStepEvent(options, workflow.id, i, step, result);
1315
- if (result.outcome.status === "success") {
1316
- const data = result.outcome.data;
1317
- stepOutputs[i] = data;
1318
- stepContexts[i] = `
1763
+ stepResults[i] = result;
1764
+ completed.add(i);
1765
+ emitStepEvent(options, workflow.id, i, step, result);
1766
+ if (result.outcome.status === "success") {
1767
+ const data = result.outcome.data;
1768
+ stepOutputs[i] = data;
1769
+ stepContexts[i] = `
1319
1770
 
1320
1771
  --- Step ${i + 1}: ${stepId(i)} ---
1321
1772
  ` + (typeof data === "string" ? data : JSON.stringify(data, null, 2));
1773
+ }
1774
+ if (result.outcome.status === "gate_rejected") {
1775
+ abortResult = {
1776
+ workflow_id: workflow.id,
1777
+ status: "gate_rejected",
1778
+ steps: stepResults.filter(Boolean),
1779
+ total_elapsed_ms: Date.now() - workflowStart
1780
+ };
1781
+ } else if (result.outcome.status === "escalation") {
1782
+ abortResult = {
1783
+ workflow_id: workflow.id,
1784
+ status: "escalated",
1785
+ steps: stepResults.filter(Boolean),
1786
+ total_elapsed_ms: Date.now() - workflowStart,
1787
+ escalation_reason: result.outcome.reason
1788
+ };
1789
+ } else if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
1790
+ const taskId = step.type === "delegate" ? step.task : step.gate_kind;
1791
+ abortResult = {
1792
+ workflow_id: workflow.id,
1793
+ status: "escalated",
1794
+ steps: stepResults.filter(Boolean),
1795
+ total_elapsed_ms: Date.now() - workflowStart,
1796
+ escalation_reason: `Task "${taskId}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
1797
+ };
1798
+ }
1322
1799
  }
1323
- if (result.outcome.status === "gate_rejected") {
1324
- abortResult = {
1325
- workflow_id: workflow.id,
1326
- status: "gate_rejected",
1327
- steps: stepResults.filter(Boolean),
1328
- total_elapsed_ms: Date.now() - workflowStart
1329
- };
1330
- } else if (result.outcome.status === "escalation") {
1331
- abortResult = {
1332
- workflow_id: workflow.id,
1333
- status: "escalated",
1334
- steps: stepResults.filter(Boolean),
1335
- total_elapsed_ms: Date.now() - workflowStart,
1336
- escalation_reason: result.outcome.reason
1337
- };
1338
- } else if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
1339
- const taskId = step.type === "delegate" ? step.task : step.gate_kind;
1340
- abortResult = {
1341
- workflow_id: workflow.id,
1342
- status: "escalated",
1343
- steps: stepResults.filter(Boolean),
1344
- total_elapsed_ms: Date.now() - workflowStart,
1345
- escalation_reason: `Task "${taskId}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
1346
- };
1800
+ if (abortResult) break;
1801
+ }
1802
+ wfResult = abortResult ?? {
1803
+ workflow_id: workflow.id,
1804
+ status: "completed",
1805
+ steps: stepResults.filter(Boolean),
1806
+ total_elapsed_ms: Date.now() - workflowStart
1807
+ };
1808
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
1809
+ if (options.toolchain && options.observer) {
1810
+ try {
1811
+ await runToolchainChecks({
1812
+ ...options.toolchain,
1813
+ observer: options.observer,
1814
+ parentSpanId: sessionSpanId
1815
+ });
1816
+ } catch {
1347
1817
  }
1348
1818
  }
1349
- if (abortResult) break;
1350
- }
1351
- const wfResult = abortResult ?? {
1352
- workflow_id: workflow.id,
1353
- status: "completed",
1354
- steps: stepResults.filter(Boolean),
1355
- total_elapsed_ms: Date.now() - workflowStart
1356
- };
1357
- await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
1358
- if (sessionSpanId) {
1359
- sessionEnvelope.execution_metadata = { duration_ms: wfResult.total_elapsed_ms };
1360
- emitSessionClose(
1361
- options.observer,
1362
- sessionSpanId,
1363
- sessionEnvelope,
1364
- wfResult.total_elapsed_ms,
1365
- wfResult.status
1366
- );
1819
+ return wfResult;
1820
+ } catch (err) {
1821
+ sessionError = err;
1822
+ throw err;
1823
+ } finally {
1824
+ if (sessionSpanId) {
1825
+ const durationMs = wfResult?.total_elapsed_ms ?? Date.now() - workflowStart;
1826
+ sessionEnvelope.execution_metadata = { duration_ms: durationMs };
1827
+ emitSessionClose(
1828
+ options.observer,
1829
+ sessionSpanId,
1830
+ sessionEnvelope,
1831
+ durationMs,
1832
+ wfResult?.status ?? "error",
1833
+ sessionError?.message
1834
+ );
1835
+ }
1367
1836
  }
1368
- return wfResult;
1369
1837
  }
1370
1838
  function mergeVariables(base, injected) {
1371
1839
  const merged = { ...base, ...injected };
@@ -1563,11 +2031,11 @@ function emitProcessEdit(options) {
1563
2031
  }
1564
2032
 
1565
2033
  // src/lib/bound-resolver.ts
1566
- import { readFile as readFile2 } from "fs/promises";
2034
+ import { readFile as readFile3 } from "fs/promises";
1567
2035
  import YAML2 from "yaml";
1568
2036
 
1569
2037
  // src/lib/dsl-context.ts
1570
- import { readFile } from "fs/promises";
2038
+ import { readFile as readFile2 } from "fs/promises";
1571
2039
  import YAML from "yaml";
1572
2040
  var DslValidationError = class extends Error {
1573
2041
  missing;
@@ -1621,6 +2089,20 @@ function buildWorkflowStep(step) {
1621
2089
  depends_on: step.depends_on
1622
2090
  };
1623
2091
  }
2092
+ if (step.type === "evaluate") {
2093
+ return {
2094
+ type: "evaluate",
2095
+ task: step.task ?? "",
2096
+ from_agent: step.from_agent ?? "",
2097
+ evaluator_agent: step.evaluator_agent,
2098
+ description: step.description,
2099
+ loop_to: step.loop_to ?? "",
2100
+ max_iterations: step.max_iterations ?? 1,
2101
+ inject_as: step.inject_as,
2102
+ on_exhausted: step.on_exhausted,
2103
+ depends_on: step.depends_on
2104
+ };
2105
+ }
1624
2106
  return {
1625
2107
  type: "delegate",
1626
2108
  task: step.task ?? "",
@@ -1727,7 +2209,7 @@ async function loadDslContext(options) {
1727
2209
  let dsl;
1728
2210
  if (options.projectDslPath) {
1729
2211
  const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
1730
- const raw = await readFile(options.projectDslPath, "utf8");
2212
+ const raw = await readFile2(options.projectDslPath, "utf8");
1731
2213
  const projectData = YAML.parse(raw);
1732
2214
  if (projectData.extends === "/$embedded/") {
1733
2215
  const { extends: _extends, ...projectOverrides } = projectData;
@@ -1925,7 +2407,7 @@ var BoundResolver = class {
1925
2407
  };
1926
2408
  if (opts.bindingPaths && opts.bindingPaths.length > 0) {
1927
2409
  for (const bindingPath of opts.bindingPaths) {
1928
- const raw = await readFile2(bindingPath, "utf8");
2410
+ const raw = await readFile3(bindingPath, "utf8");
1929
2411
  const binding = YAML2.parse(raw);
1930
2412
  guardrailCtx = buildGuardrailContext(
1931
2413
  dsl,
@@ -2072,19 +2554,19 @@ var WorkflowBuilder = class {
2072
2554
  };
2073
2555
 
2074
2556
  // src/lib/plugin-loader.ts
2075
- import { existsSync } from "fs";
2557
+ import { existsSync as existsSync2 } from "fs";
2076
2558
  import { readdir } from "fs/promises";
2077
- import { resolve, join } from "path";
2559
+ import { resolve as resolve2, join } from "path";
2078
2560
  var PLUGIN_EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
2079
2561
  function isPluginLike(obj) {
2080
2562
  return typeof obj === "object" && obj !== null && typeof obj.id === "string";
2081
2563
  }
2082
2564
  async function scanDirectory(dir) {
2083
- if (!existsSync(dir)) return [];
2565
+ if (!existsSync2(dir)) return [];
2084
2566
  const entries = await readdir(dir, { withFileTypes: true });
2085
2567
  return entries.filter(
2086
2568
  (e) => e.isFile() && PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) && !e.name.startsWith("_") && !e.name.endsWith(".d.ts") && !e.name.endsWith(".test.ts") && !e.name.endsWith(".spec.ts")
2087
- ).map((e) => resolve(dir, e.name));
2569
+ ).map((e) => resolve2(dir, e.name));
2088
2570
  }
2089
2571
  async function loadPluginModule(modulePath) {
2090
2572
  const mod = await import(new URL(`file://${modulePath}`).href);
@@ -2103,8 +2585,8 @@ async function loadPluginModule(modulePath) {
2103
2585
  async function loadPluginsFromPaths(paths, baseDir) {
2104
2586
  const result = { loaded: 0, files: [], errors: [] };
2105
2587
  for (const p of paths) {
2106
- const absPath = resolve(baseDir, p);
2107
- if (!existsSync(absPath)) {
2588
+ const absPath = resolve2(baseDir, p);
2589
+ if (!existsSync2(absPath)) {
2108
2590
  result.errors.push({ file: p, error: `File not found: ${absPath}` });
2109
2591
  continue;
2110
2592
  }
@@ -2253,7 +2735,7 @@ var InMemoryStore = class {
2253
2735
  };
2254
2736
 
2255
2737
  // src/lib/file-memory-store.ts
2256
- import { mkdir, readFile as readFile3, unlink, writeFile } from "fs/promises";
2738
+ import { mkdir, readFile as readFile4, unlink, writeFile } from "fs/promises";
2257
2739
  import { join as join3 } from "path";
2258
2740
  function resolveFilePath2(baseDir, ref) {
2259
2741
  const runId = ref.parent_run_id ?? "unknown";
@@ -2272,7 +2754,7 @@ var FileMemoryStore = class {
2272
2754
  async load(ref) {
2273
2755
  const filePath = resolveFilePath2(this.baseDir, ref);
2274
2756
  try {
2275
- const raw = await readFile3(filePath, "utf-8");
2757
+ const raw = await readFile4(filePath, "utf-8");
2276
2758
  return JSON.parse(raw);
2277
2759
  } catch (error) {
2278
2760
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2295,7 +2777,7 @@ var FileMemoryStore = class {
2295
2777
  };
2296
2778
 
2297
2779
  // src/lib/agent-log-writer.ts
2298
- import { mkdir as mkdir2, readFile as readFile4, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
2780
+ import { mkdir as mkdir2, readFile as readFile5, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
2299
2781
  import { join as join4 } from "path";
2300
2782
  var AgentLogWriter = class {
2301
2783
  baseDir;
@@ -2319,7 +2801,7 @@ var AgentLogWriter = class {
2319
2801
  async readRunLog(runId) {
2320
2802
  const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
2321
2803
  try {
2322
- const raw = await readFile4(filePath, "utf-8");
2804
+ const raw = await readFile5(filePath, "utf-8");
2323
2805
  return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
2324
2806
  } catch (error) {
2325
2807
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2337,7 +2819,7 @@ var AgentLogWriter = class {
2337
2819
  async readHandoff(runId, step) {
2338
2820
  const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
2339
2821
  try {
2340
- const raw = await readFile4(filePath, "utf-8");
2822
+ const raw = await readFile5(filePath, "utf-8");
2341
2823
  return JSON.parse(raw);
2342
2824
  } catch (error) {
2343
2825
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2504,7 +2986,7 @@ Install it with: npm install ${pkg2}`
2504
2986
  }
2505
2987
 
2506
2988
  // src/lib/execute.ts
2507
- import { resolve as resolve2 } from "path";
2989
+ import { resolve as resolve3 } from "path";
2508
2990
  async function resolveExecutionContext(options, requiredEntities) {
2509
2991
  const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
2510
2992
  if (useBoundResolver) {
@@ -2572,7 +3054,7 @@ async function executeTask(taskId, options) {
2572
3054
  ...adapterOptions
2573
3055
  });
2574
3056
  const progressSink = createProgressSink(
2575
- options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
3057
+ options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
2576
3058
  );
2577
3059
  try {
2578
3060
  if (options.hooks?.beforeTask) {
@@ -2582,6 +3064,7 @@ async function executeTask(taskId, options) {
2582
3064
  maxFollowUps: options.maxFollowUps ?? 2,
2583
3065
  maxRetries: options.maxRetries ?? 0,
2584
3066
  progressOutput: progressSink,
3067
+ observer: options.observer,
2585
3068
  ...execCtx.registries
2586
3069
  });
2587
3070
  if (options.hooks?.afterTask) {
@@ -2601,7 +3084,7 @@ async function executeWorkflow(workflowId, options) {
2601
3084
  ...adapterOptions
2602
3085
  });
2603
3086
  const progressSink = createProgressSink(
2604
- options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
3087
+ options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
2605
3088
  );
2606
3089
  try {
2607
3090
  if (options.hooks?.beforeWorkflow) {
@@ -2612,6 +3095,8 @@ async function executeWorkflow(workflowId, options) {
2612
3095
  user_request: options.request,
2613
3096
  handoff: options.handoff,
2614
3097
  progressOutput: progressSink,
3098
+ observer: options.observer,
3099
+ toolchain: options.toolchain,
2615
3100
  runtime: {
2616
3101
  maxFollowUps: options.maxFollowUps ?? 2,
2617
3102
  maxRetries: options.maxRetries ?? 0
@@ -2758,17 +3243,18 @@ async function dispatchOperation(operationName, op, options, input, ctx, handler
2758
3243
  }
2759
3244
 
2760
3245
  // src/lib/project-runtime.ts
2761
- import { existsSync as existsSync2 } from "fs";
2762
- import { readFile as readFile5 } from "fs/promises";
2763
- import { resolve as resolve3, dirname as dirname2 } from "path";
3246
+ import { existsSync as existsSync3 } from "fs";
3247
+ import { readFile as readFile6 } from "fs/promises";
3248
+ import { resolve as resolve4, dirname as dirname2 } from "path";
2764
3249
  import YAML3 from "yaml";
3250
+ import { createPipeline } from "@aaac/observability";
2765
3251
  var PROJECT_CONFIG_FILENAME = "project.yaml";
2766
3252
  var DEFAULT_ADAPTER = "claude";
2767
3253
  function findProjectConfig(startDir, filename = PROJECT_CONFIG_FILENAME) {
2768
- let dir = resolve3(startDir);
3254
+ let dir = resolve4(startDir);
2769
3255
  for (; ; ) {
2770
- const candidate = resolve3(dir, filename);
2771
- if (existsSync2(candidate)) return candidate;
3256
+ const candidate = resolve4(dir, filename);
3257
+ if (existsSync3(candidate)) return candidate;
2772
3258
  const parent = dirname2(dir);
2773
3259
  if (parent === dir) return void 0;
2774
3260
  dir = parent;
@@ -2780,8 +3266,8 @@ function serializeRequest(input) {
2780
3266
  }
2781
3267
  async function createProjectRuntime(options) {
2782
3268
  const cwd = options.cwd ?? process.cwd();
2783
- const configPath = options.configPath ? resolve3(cwd, options.configPath) : findProjectConfig(cwd);
2784
- if (!configPath || !existsSync2(configPath)) {
3269
+ const configPath = options.configPath ? resolve4(cwd, options.configPath) : findProjectConfig(cwd);
3270
+ if (!configPath || !existsSync3(configPath)) {
2785
3271
  const where = options.configPath ? `config path "${options.configPath}"` : `${PROJECT_CONFIG_FILENAME} from ${cwd} upward`;
2786
3272
  throw new Error(
2787
3273
  `No ${PROJECT_CONFIG_FILENAME} found (${where}). Pass --config <path> to a project manifest.`
@@ -2789,14 +3275,30 @@ async function createProjectRuntime(options) {
2789
3275
  }
2790
3276
  const config = await loadProjectConfig(configPath);
2791
3277
  const env = options.env ?? process.env;
2792
- const rawManifest = YAML3.parse(await readFile5(configPath, "utf8"));
3278
+ const rawManifest = YAML3.parse(await readFile6(configPath, "utf8"));
2793
3279
  const overlayExplicit = typeof rawManifest?.agents === "string" || typeof rawManifest?.dsl === "string";
2794
- if (overlayExplicit && !existsSync2(config.dslPath)) {
3280
+ if (overlayExplicit && !existsSync3(config.dslPath)) {
2795
3281
  throw new Error(
2796
3282
  `Project agents DSL not found: ${config.dslPath} (referenced by ${configPath}).`
2797
3283
  );
2798
3284
  }
2799
3285
  const projectDslPath = overlayExplicit ? config.dslPath : void 0;
3286
+ let observer;
3287
+ let observerSink;
3288
+ let observerClosed = false;
3289
+ if (config.observability && config.observability.enabled !== false) {
3290
+ const pipeline = createPipeline(
3291
+ config.observability.dbPath ? { dbPath: config.observability.dbPath } : {}
3292
+ );
3293
+ observer = pipeline.collector.emit.bind(pipeline.collector);
3294
+ observerSink = pipeline.sink;
3295
+ }
3296
+ function closeObserver() {
3297
+ if (observerSink && !observerClosed) {
3298
+ observerClosed = true;
3299
+ observerSink.close();
3300
+ }
3301
+ }
2800
3302
  function resolveAdapter2() {
2801
3303
  const explicit = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;
2802
3304
  if (explicit) {
@@ -2822,22 +3324,40 @@ async function createProjectRuntime(options) {
2822
3324
  activeGuardrailPolicy: config.active_guardrail_policy,
2823
3325
  artifactBinding: config.artifactsPath ? { source: config.artifactsPath } : void 0,
2824
3326
  maxFollowUps: config.recovery.max_follow_ups,
2825
- maxRetries: config.recovery.max_retries
3327
+ maxRetries: config.recovery.max_retries,
3328
+ observer,
3329
+ // Toolchain.execution observation: only when BOTH in-process observability
3330
+ // is wired AND project.yaml declares `toolchains`. Observation is non-
3331
+ // destructive (records spans; never gates the workflow) and a no-op when
3332
+ // either is absent (AC4 regression safety). Consumed only by executeWorkflow.
3333
+ toolchain: observer && config.toolchainsPath ? {
3334
+ toolchainsPath: config.toolchainsPath,
3335
+ artifactsPath: config.artifactsPath,
3336
+ cwd
3337
+ } : void 0
2826
3338
  };
2827
3339
  }
2828
3340
  const runtime = {
2829
3341
  async runWorkflow(workflowId, _options, input, _ctx) {
2830
- return executeWorkflow(workflowId, {
2831
- ...sharedExecuteOptions(),
2832
- request: serializeRequest(input),
2833
- autoApproveGates: options.autoApproveGates ?? true
2834
- });
3342
+ try {
3343
+ return await executeWorkflow(workflowId, {
3344
+ ...sharedExecuteOptions(),
3345
+ request: serializeRequest(input),
3346
+ autoApproveGates: options.autoApproveGates ?? true
3347
+ });
3348
+ } finally {
3349
+ closeObserver();
3350
+ }
2835
3351
  },
2836
3352
  async runTask(taskId, _options, input, _ctx) {
2837
- return executeTask(taskId, {
2838
- ...sharedExecuteOptions(),
2839
- request: serializeRequest(input)
2840
- });
3353
+ try {
3354
+ return await executeTask(taskId, {
3355
+ ...sharedExecuteOptions(),
3356
+ request: serializeRequest(input)
3357
+ });
3358
+ } finally {
3359
+ closeObserver();
3360
+ }
2841
3361
  }
2842
3362
  };
2843
3363
  return {
@@ -3003,7 +3523,7 @@ async function resolveArtifacts(options) {
3003
3523
  }
3004
3524
 
3005
3525
  // src/lib/guard-commands.ts
3006
- import { readFile as readFile6, readdir as readdir3 } from "fs/promises";
3526
+ import { readFile as readFile7, readdir as readdir3 } from "fs/promises";
3007
3527
  import YAML4 from "yaml";
3008
3528
  async function evaluateGuardrail(opts) {
3009
3529
  let hookInput;
@@ -3024,7 +3544,7 @@ async function evaluateGuardrail(opts) {
3024
3544
  for (const bindingPath of opts.bindingPaths) {
3025
3545
  let raw;
3026
3546
  try {
3027
- raw = await readFile6(bindingPath, "utf8");
3547
+ raw = await readFile7(bindingPath, "utf8");
3028
3548
  } catch (err) {
3029
3549
  const code = err.code;
3030
3550
  if (code === "ENOENT") continue;
@@ -3073,7 +3593,7 @@ async function listGuardrails(opts) {
3073
3593
  for (const bindingPath of opts.bindingPaths) {
3074
3594
  let raw;
3075
3595
  try {
3076
- raw = await readFile6(bindingPath, "utf8");
3596
+ raw = await readFile7(bindingPath, "utf8");
3077
3597
  } catch (err) {
3078
3598
  const code = err.code;
3079
3599
  if (code === "ENOENT") continue;
@@ -3132,7 +3652,7 @@ async function guardStatus(opts = {}) {
3132
3652
  const filePath = `${runsDir}/${file}`;
3133
3653
  let raw;
3134
3654
  try {
3135
- raw = await readFile6(filePath, "utf8");
3655
+ raw = await readFile7(filePath, "utf8");
3136
3656
  } catch {
3137
3657
  continue;
3138
3658
  }
@@ -3267,130 +3787,6 @@ async function executePrompt(message, ir, binding, ctx, opts) {
3267
3787
  return { selectedOperation, mappedInput, output };
3268
3788
  }
3269
3789
 
3270
- // src/lib/toolchain-checker.ts
3271
- import { execFile } from "child_process";
3272
- import { readFile as readFile7 } from "fs/promises";
3273
- import { existsSync as existsSync3 } from "fs";
3274
- import { resolve as resolve4 } from "path";
3275
- import { promisify } from "util";
3276
- import { z as z2 } from "zod";
3277
- import { parseToolchainFile } from "@aaac/toolchain";
3278
- var execFileAsync = promisify(execFile);
3279
- var SUBPROCESS_TIMEOUT_MS = 3e4;
3280
- var MANIFEST_FILENAME = ".toolchain-manifest.json";
3281
- var ToolchainManifestSchema = z2.object({
3282
- schema: z2.string(),
3283
- toolchain_id: z2.string(),
3284
- generated_at: z2.string(),
3285
- source_hash: z2.string(),
3286
- output_hash: z2.string(),
3287
- source_globs: z2.array(z2.string()).optional(),
3288
- output_globs: z2.array(z2.string()).optional(),
3289
- files: z2.array(
3290
- z2.object({
3291
- path: z2.string(),
3292
- hash: z2.string()
3293
- })
3294
- ).optional()
3295
- });
3296
- function resolveAction(checkType, checkTypeActions, defaultAction) {
3297
- if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
3298
- if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
3299
- return defaultAction ?? "warn";
3300
- }
3301
- async function tryManifestFastPath(toolchainId, cwd) {
3302
- const manifestPath = resolve4(cwd, MANIFEST_FILENAME);
3303
- if (!existsSync3(manifestPath)) return null;
3304
- try {
3305
- const raw = await readFile7(manifestPath, "utf-8");
3306
- const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
3307
- if (parsed.toolchain_id !== toolchainId) return null;
3308
- return {
3309
- toolchainId,
3310
- checkType: "drift",
3311
- status: "pass",
3312
- action: "warn",
3313
- message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
3314
- durationMs: 0
3315
- };
3316
- } catch {
3317
- return null;
3318
- }
3319
- }
3320
- async function executeCheck(command, cwd) {
3321
- try {
3322
- const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
3323
- cwd,
3324
- timeout: SUBPROCESS_TIMEOUT_MS
3325
- });
3326
- return { exitCode: 0, stdout, stderr };
3327
- } catch (err) {
3328
- const execErr = err;
3329
- if (execErr.killed) {
3330
- throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
3331
- }
3332
- const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
3333
- return {
3334
- exitCode,
3335
- stdout: execErr.stdout ?? "",
3336
- stderr: execErr.stderr ?? ""
3337
- };
3338
- }
3339
- }
3340
- async function runToolchainChecks(options) {
3341
- const {
3342
- toolchainsPath,
3343
- cwd: workingDir,
3344
- checkTypes,
3345
- toolchainFilter,
3346
- checkTypeActions,
3347
- defaultAction
3348
- } = options;
3349
- const cwd = workingDir ?? process.cwd();
3350
- const contracts = await parseToolchainFile(toolchainsPath);
3351
- const results = [];
3352
- for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
3353
- if (!toolchain.checks) continue;
3354
- if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
3355
- for (const [checkType, command] of Object.entries(toolchain.checks)) {
3356
- if (checkTypes && !checkTypes.includes(checkType)) continue;
3357
- const action = resolveAction(checkType, checkTypeActions, defaultAction);
3358
- const start = performance.now();
3359
- if (checkType === "drift" && options.artifactsPath) {
3360
- const fastResult = await tryManifestFastPath(toolchainId, cwd);
3361
- if (fastResult) {
3362
- fastResult.action = action;
3363
- results.push(fastResult);
3364
- continue;
3365
- }
3366
- }
3367
- try {
3368
- const { exitCode, stderr } = await executeCheck(command, cwd);
3369
- const durationMs = Math.round(performance.now() - start);
3370
- results.push({
3371
- toolchainId,
3372
- checkType,
3373
- status: exitCode === 0 ? "pass" : "fail",
3374
- action,
3375
- message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
3376
- durationMs
3377
- });
3378
- } catch (err) {
3379
- const durationMs = Math.round(performance.now() - start);
3380
- results.push({
3381
- toolchainId,
3382
- checkType,
3383
- status: "error",
3384
- action,
3385
- message: err.message,
3386
- durationMs
3387
- });
3388
- }
3389
- }
3390
- }
3391
- return results;
3392
- }
3393
-
3394
3790
  // src/index.ts
3395
3791
  var require2 = createRequire(import.meta.url);
3396
3792
  var pkg = require2("../package.json");
@@ -3416,6 +3812,7 @@ export {
3416
3812
  buildSplitTaskPrompt,
3417
3813
  buildTaskPrompt,
3418
3814
  createAdapter,
3815
+ createAnalyzerBridge,
3419
3816
  createComponentScope,
3420
3817
  createExecutionEnvelope,
3421
3818
  createGuardrailHooks,
@@ -3455,6 +3852,7 @@ export {
3455
3852
  guardStatus,
3456
3853
  guardrailContextToRuleData,
3457
3854
  hasBlockingViolation,
3855
+ isContextPack,
3458
3856
  jsonSchemaToZod,
3459
3857
  listGuardrails,
3460
3858
  loadDslContext,
@@ -3466,6 +3864,7 @@ export {
3466
3864
  parseRouterResponse,
3467
3865
  pluginRegistry,
3468
3866
  renderAgentSystemPrompt,
3867
+ renderContextPackPrompt,
3469
3868
  resolveArtifacts,
3470
3869
  runTask,
3471
3870
  runToolchainChecks,