@aaac/runtime 0.1.18 → 0.1.19

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,7 @@
1
+ import {
2
+ buildGuardrailContext,
3
+ loadProjectConfig
4
+ } from "./chunk-RL4TCIDU.js";
1
5
  import {
2
6
  PluginRegistry,
3
7
  createGuardrailHooks,
@@ -11,10 +15,6 @@ import {
11
15
  import {
12
16
  buildSdkFunctionTools
13
17
  } from "./chunk-LONLL3K2.js";
14
- import {
15
- buildGuardrailContext,
16
- loadProjectConfig
17
- } from "./chunk-E2UR4TNM.js";
18
18
  import {
19
19
  jsonSchemaToZod
20
20
  } from "./chunk-ET6TGQRT.js";
@@ -151,7 +151,7 @@ function emitSessionOpen(observer, envelope, workflowId) {
151
151
  });
152
152
  return spanId;
153
153
  }
154
- function emitSessionClose(observer, spanId, envelope, durationMs, status) {
154
+ function emitSessionClose(observer, spanId, envelope, durationMs, status, errorMessage) {
155
155
  if (!observer) return;
156
156
  const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
157
157
  observer({
@@ -164,7 +164,8 @@ function emitSessionClose(observer, spanId, envelope, durationMs, status) {
164
164
  axis: "agent",
165
165
  "agent.session_id": envelope.run_id,
166
166
  "agent.session.duration_ms": durationMs,
167
- "agent.status": status
167
+ "agent.status": status,
168
+ "agent.error": errorMessage
168
169
  }),
169
170
  ...metaAttrs
170
171
  }
@@ -195,7 +196,7 @@ function emitSubagentOpen(observer, envelope, parentSpanId, taskId, agentRole) {
195
196
  });
196
197
  return spanId;
197
198
  }
198
- function emitSubagentClose(observer, spanId, envelope, durationMs, status, agentRole) {
199
+ function emitSubagentClose(observer, spanId, envelope, durationMs, status, agentRole, errorMessage) {
199
200
  if (!observer) return;
200
201
  const metaAttrs = envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};
201
202
  observer({
@@ -208,7 +209,8 @@ function emitSubagentClose(observer, spanId, envelope, durationMs, status, agent
208
209
  axis: "agent",
209
210
  "agent.role": agentRole,
210
211
  "agent.status": status,
211
- "agent.duration_ms": durationMs
212
+ "agent.duration_ms": durationMs,
213
+ "agent.error": errorMessage
212
214
  }),
213
215
  ...metaAttrs
214
216
  }
@@ -809,111 +811,264 @@ async function runTask(adapter, taskId, context, options) {
809
811
  taskId,
810
812
  agentContract.role_name
811
813
  );
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 };
814
+ let closeStatus = "error";
815
+ let closeCause;
816
+ let spanClosed = false;
817
+ const closeSubagentSpan = () => {
818
+ if (spanClosed) return;
819
+ spanClosed = true;
820
+ const durationMs = Date.now() - taskExecStart;
821
+ taskEnvelope.execution_metadata = {
822
+ ...taskEnvelope.execution_metadata ?? {},
823
+ duration_ms: durationMs
824
+ };
837
825
  emitSubagentClose(
838
826
  options?.observer,
839
827
  subagentSpanId ?? taskEnvelope.run_id,
840
828
  taskEnvelope,
841
- errDurationMs,
842
- "error",
843
- agentContract.role_name
829
+ durationMs,
830
+ closeStatus,
831
+ agentContract.role_name,
832
+ closeCause
844
833
  );
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 ?? "") + `
834
+ };
835
+ try {
836
+ let fullOutput;
837
+ try {
838
+ if (adapter.sendExecution) {
839
+ fullOutput = await adapter.sendExecution({
840
+ agentId: agentContract.id,
841
+ taskId,
842
+ prompt,
843
+ handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
844
+ schema: schemas[task.result_handoff] ? {
845
+ handoffType: task.result_handoff,
846
+ zodSchema: schemas[task.result_handoff],
847
+ promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
848
+ } : void 0,
849
+ context: enrichedContext,
850
+ memoryRef,
851
+ splitPrompt,
852
+ agents,
853
+ options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, maxFollowUps, attempt: 0 }
854
+ });
855
+ } else {
856
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools });
857
+ }
858
+ } catch (err) {
859
+ closeStatus = "error";
860
+ closeCause = `SDK error: ${err.message}`;
861
+ return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
862
+ }
863
+ let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
864
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
865
+ while (outcome.status === "validation_error" || outcome.status === "error") {
866
+ const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
867
+ if (decision === "abort") break;
868
+ let effectiveDecision = decision;
869
+ if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
870
+ effectiveDecision = "retry";
871
+ }
872
+ if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
873
+ break;
874
+ }
875
+ if (effectiveDecision === "follow_up") {
876
+ followUpsUsed++;
877
+ const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
878
+ try {
879
+ if (adapter.followUp) {
880
+ fullOutput = await adapter.followUp(followUpPrompt);
881
+ } else {
882
+ const retryContext = {
883
+ ...modifiedContext,
884
+ prior_context: (modifiedContext.prior_context ?? "") + `
869
885
 
870
886
  --- FollowUp ${followUpsUsed} ---
871
887
  ${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 });
888
+ };
889
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
890
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
891
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
892
+ }
893
+ } catch (err) {
894
+ outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
895
+ continue;
876
896
  }
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 ?? "") + `
897
+ } else {
898
+ retriesUsed++;
899
+ const retryContext = {
900
+ ...modifiedContext,
901
+ prior_context: (modifiedContext.prior_context ?? "") + `
886
902
 
887
903
  --- Full Retry ${retriesUsed} ---
888
904
  Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
889
905
  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;
906
+ };
907
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
908
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
909
+ try {
910
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
911
+ } catch (err) {
912
+ outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
913
+ continue;
914
+ }
898
915
  }
916
+ outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
917
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
899
918
  }
900
- outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
901
- outcome = await pluginRegistry.runAfterTask(taskId, outcome);
919
+ closeStatus = outcome.status;
920
+ return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed };
921
+ } catch (err) {
922
+ closeStatus = "error";
923
+ closeCause = err.message;
924
+ throw err;
925
+ } finally {
926
+ closeSubagentSpan();
927
+ }
928
+ }
929
+
930
+ // src/lib/toolchain-checker.ts
931
+ import { execFile } from "child_process";
932
+ import { readFile } from "fs/promises";
933
+ import { existsSync } from "fs";
934
+ import { resolve } from "path";
935
+ import { promisify } from "util";
936
+ import { z as z2 } from "zod";
937
+ import { parseToolchainFile } from "@aaac/toolchain";
938
+ var execFileAsync = promisify(execFile);
939
+ var SUBPROCESS_TIMEOUT_MS = 3e4;
940
+ var MANIFEST_FILENAME = ".toolchain-manifest.json";
941
+ var ToolchainManifestSchema = z2.object({
942
+ schema: z2.string(),
943
+ toolchain_id: z2.string(),
944
+ generated_at: z2.string(),
945
+ source_hash: z2.string(),
946
+ output_hash: z2.string(),
947
+ source_globs: z2.array(z2.string()).optional(),
948
+ output_globs: z2.array(z2.string()).optional(),
949
+ files: z2.array(
950
+ z2.object({
951
+ path: z2.string(),
952
+ hash: z2.string()
953
+ })
954
+ ).optional()
955
+ });
956
+ function resolveAction(checkType, checkTypeActions, defaultAction) {
957
+ if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
958
+ if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
959
+ return defaultAction ?? "warn";
960
+ }
961
+ async function tryManifestFastPath(toolchainId, cwd) {
962
+ const manifestPath = resolve(cwd, MANIFEST_FILENAME);
963
+ if (!existsSync(manifestPath)) return null;
964
+ try {
965
+ const raw = await readFile(manifestPath, "utf-8");
966
+ const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
967
+ if (parsed.toolchain_id !== toolchainId) return null;
968
+ return {
969
+ toolchainId,
970
+ checkType: "drift",
971
+ status: "pass",
972
+ action: "warn",
973
+ message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
974
+ durationMs: 0
975
+ };
976
+ } catch {
977
+ return null;
902
978
  }
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 };
979
+ }
980
+ async function executeCheck(command, cwd) {
981
+ try {
982
+ const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
983
+ cwd,
984
+ timeout: SUBPROCESS_TIMEOUT_MS
985
+ });
986
+ return { exitCode: 0, stdout, stderr };
987
+ } catch (err) {
988
+ const execErr = err;
989
+ if (execErr.killed) {
990
+ throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
991
+ }
992
+ const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
993
+ return {
994
+ exitCode,
995
+ stdout: execErr.stdout ?? "",
996
+ stderr: execErr.stderr ?? ""
997
+ };
998
+ }
999
+ }
1000
+ async function runToolchainChecks(options) {
1001
+ const {
1002
+ toolchainsPath,
1003
+ cwd: workingDir,
1004
+ checkTypes,
1005
+ toolchainFilter,
1006
+ checkTypeActions,
1007
+ defaultAction,
1008
+ observer,
1009
+ parentSpanId,
1010
+ componentId
1011
+ } = options;
1012
+ const cwd = workingDir ?? process.cwd();
1013
+ const contracts = await parseToolchainFile(toolchainsPath);
1014
+ const results = [];
1015
+ for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
1016
+ if (!toolchain.checks) continue;
1017
+ if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
1018
+ for (const [checkType, command] of Object.entries(toolchain.checks)) {
1019
+ if (checkTypes && !checkTypes.includes(checkType)) continue;
1020
+ const action = resolveAction(checkType, checkTypeActions, defaultAction);
1021
+ const start = performance.now();
1022
+ const spanId = emitToolchainOpen(
1023
+ observer,
1024
+ parentSpanId,
1025
+ toolchainId,
1026
+ checkType,
1027
+ [],
1028
+ componentId
1029
+ );
1030
+ let result;
1031
+ const fastResult = checkType === "drift" && options.artifactsPath ? await tryManifestFastPath(toolchainId, cwd) : null;
1032
+ if (fastResult) {
1033
+ fastResult.action = action;
1034
+ result = fastResult;
1035
+ } else {
1036
+ try {
1037
+ const { exitCode, stderr } = await executeCheck(command, cwd);
1038
+ const durationMs = Math.round(performance.now() - start);
1039
+ result = {
1040
+ toolchainId,
1041
+ checkType,
1042
+ status: exitCode === 0 ? "pass" : "fail",
1043
+ action,
1044
+ message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
1045
+ durationMs
1046
+ };
1047
+ } catch (err) {
1048
+ const durationMs = Math.round(performance.now() - start);
1049
+ result = {
1050
+ toolchainId,
1051
+ checkType,
1052
+ status: "error",
1053
+ action,
1054
+ message: err.message,
1055
+ durationMs
1056
+ };
1057
+ }
1058
+ }
1059
+ results.push(result);
1060
+ emitToolchainClose(
1061
+ observer,
1062
+ spanId ?? "",
1063
+ toolchainId,
1064
+ checkType,
1065
+ result.durationMs ?? Math.round(performance.now() - start),
1066
+ result.status === "pass" ? "success" : "failure",
1067
+ result.status === "pass" ? void 0 : result.message
1068
+ );
1069
+ }
1070
+ }
1071
+ return results;
917
1072
  }
918
1073
 
919
1074
  // src/lib/workflow-runner.ts
@@ -954,7 +1109,8 @@ function resolveInvocation(invocation) {
954
1109
  onStepComplete: invocation.hooks?.onStepComplete,
955
1110
  onOptionalStep: invocation.hooks?.onOptionalStep,
956
1111
  progressOutput: invocation.progressOutput,
957
- observer: invocation.observer
1112
+ observer: invocation.observer,
1113
+ toolchain: invocation.toolchain
958
1114
  }
959
1115
  };
960
1116
  }
@@ -1005,367 +1161,386 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
1005
1161
  const sessionEnvelope = createExecutionEnvelope({ componentId: workflowId });
1006
1162
  const sessionSpanId = emitSessionOpen(options.observer, sessionEnvelope, workflowId);
1007
1163
  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`);
1164
+ let wfResult;
1165
+ let sessionError;
1166
+ try {
1167
+ let extractPath2 = function(obj, path) {
1168
+ const cleanPath = path.startsWith("$.") ? path.slice(2) : path;
1169
+ const segments = cleanPath.split(".");
1170
+ let current = obj;
1171
+ for (const seg of segments) {
1172
+ if (current == null || typeof current !== "object") return void 0;
1173
+ current = current[seg];
1174
+ }
1175
+ return current;
1176
+ }, projectHandoffs2 = function(stepIndex, step) {
1177
+ if (!step.receives) return void 0;
1178
+ const projected = {};
1179
+ for (const [alias, spec] of Object.entries(step.receives)) {
1180
+ const fromTaskId = spec.from ?? alias;
1181
+ const depIdx = workflow.steps.findIndex((s, j) => j < stepIndex && stepId(j) === fromTaskId);
1182
+ if (depIdx === -1) continue;
1183
+ const output = stepOutputs[depIdx];
1184
+ if (output === void 0) continue;
1185
+ if (spec.path) {
1186
+ projected[alias] = extractPath2(output, spec.path);
1187
+ } else {
1188
+ projected[alias] = output;
1019
1189
  }
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
1190
  }
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);
1191
+ return Object.keys(projected).length > 0 ? projected : void 0;
1192
+ }, contextFor2 = function(stepIndex) {
1193
+ const deps = depsByIndex[stepIndex];
1194
+ if (deps.length === 0) return "";
1195
+ return deps.filter((d) => completed.has(d)).map((d) => stepContexts[d]).filter(Boolean).join("");
1196
+ };
1197
+ var extractPath = extractPath2, projectHandoffs = projectHandoffs2, contextFor = contextFor2;
1198
+ const stepId = (i) => {
1199
+ const s = workflow.steps[i];
1200
+ if (s.type === "delegate" || s.type === "evaluate") return s.task;
1201
+ return `gate:${s.gate_kind}`;
1202
+ };
1203
+ const depsByIndex = workflow.steps.map((step, i) => {
1204
+ if (step.depends_on !== void 0) {
1205
+ return step.depends_on.map((dep) => {
1206
+ const idx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === dep);
1207
+ if (idx === -1) {
1208
+ throw new Error(`depends_on "${dep}" in step ${i} (${stepId(i)}) not found among preceding steps`);
1209
+ }
1210
+ return idx;
1211
+ });
1084
1212
  }
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 } : {}
1213
+ return i === 0 ? [] : Array.from({ length: i }, (_, k) => k);
1214
+ });
1215
+ const completed = /* @__PURE__ */ new Set();
1216
+ const stepResults = new Array(workflow.steps.length);
1217
+ const stepContexts = new Array(workflow.steps.length).fill("");
1218
+ const stepOutputs = new Array(workflow.steps.length).fill(void 0);
1219
+ let abortResult;
1220
+ const evaluateExecCount = /* @__PURE__ */ new Map();
1221
+ const iterationSpanIds = /* @__PURE__ */ new Map();
1222
+ const loopInjectedVars = {};
1223
+ async function executeStep(i, stepAdapter) {
1224
+ const step = workflow.steps[i];
1225
+ const stepStart = Date.now();
1226
+ if (step.type === "gate") {
1227
+ return handleGateStep(step, Object.values(stepResults).filter(Boolean), options, i, stepAdapter);
1228
+ }
1229
+ if (step.type === "evaluate") {
1230
+ const evaluateStep = step;
1231
+ const iterationNumber = (evaluateExecCount.get(i) ?? 0) + 1;
1232
+ const iterationSpanId = emitIterationOpen(
1233
+ options.observer,
1234
+ sessionSpanId,
1235
+ evaluateStep.task,
1236
+ evaluateStep.loop_to,
1237
+ iterationNumber,
1238
+ evaluateStep.max_iterations
1239
+ );
1240
+ if (iterationSpanId) {
1241
+ iterationSpanIds.set(i, iterationSpanId);
1242
+ }
1243
+ const effectiveVariables = mergeVariables(options.variables, loopInjectedVars);
1244
+ const context2 = {
1245
+ user_request: evaluateStep.description ?? options.user_request,
1246
+ prior_context: contextFor2(i),
1247
+ ...effectiveVariables ? { variables: effectiveVariables } : {}
1248
+ };
1249
+ const taskResult2 = await runTask(stepAdapter, evaluateStep.task, context2, {
1250
+ maxFollowUps: options.maxFollowUps ?? 2,
1251
+ maxRetries: 0,
1252
+ // evaluate steps do not retry
1253
+ taskRegistry: registries?.taskRegistry,
1254
+ agentRegistry: registries?.agentRegistry,
1255
+ handoffSchemas: registries?.handoffSchemas,
1256
+ progressOutput: options.progressOutput,
1257
+ observer: options.observer,
1258
+ parentSpanId: iterationSpanId ?? sessionSpanId
1259
+ });
1260
+ return {
1261
+ step_index: i,
1262
+ task_id: evaluateStep.task,
1263
+ outcome: taskResult2.outcome,
1264
+ follow_ups_used: taskResult2.follow_ups_used,
1265
+ retries_used: taskResult2.retries_used,
1266
+ elapsed_ms: Date.now() - stepStart
1267
+ };
1268
+ }
1269
+ const delegateStep = step;
1270
+ if (step.optional) {
1271
+ const stepUserRequest2 = delegateStep.instruction ?? options.user_request;
1272
+ const ctxVars = mergeVariables(options.variables, loopInjectedVars);
1273
+ const ctx = {
1274
+ user_request: stepUserRequest2,
1275
+ prior_context: contextFor2(i),
1276
+ ...ctxVars ? { variables: ctxVars } : {}
1277
+ };
1278
+ const shouldRun = options.onOptionalStep ? await options.onOptionalStep(step, ctx) : false;
1279
+ if (!shouldRun) {
1280
+ return {
1281
+ step_index: i,
1282
+ task_id: step.task,
1283
+ outcome: { status: "skipped" },
1284
+ follow_ups_used: 0,
1285
+ retries_used: 0,
1286
+ elapsed_ms: Date.now() - stepStart
1287
+ };
1288
+ }
1289
+ }
1290
+ const stepUserRequest = delegateStep.instruction ?? options.user_request;
1291
+ let handoffInput;
1292
+ const projected = projectHandoffs2(i, delegateStep);
1293
+ if (projected) {
1294
+ handoffInput = {
1295
+ type: "step-projection",
1296
+ payload: projected
1297
+ };
1298
+ } else if (i === 0 && invocationHandoff) {
1299
+ handoffInput = invocationHandoff;
1300
+ }
1301
+ const useLegacyContext = !delegateStep.receives;
1302
+ const delegateVars = mergeVariables(options.variables, loopInjectedVars);
1303
+ const context = {
1304
+ user_request: stepUserRequest,
1305
+ ...useLegacyContext ? { prior_context: contextFor2(i) } : {},
1306
+ ...delegateVars ? { variables: delegateVars } : {},
1307
+ ...handoffInput ? { handoff_input: handoffInput } : {}
1090
1308
  };
1091
- const taskResult2 = await runTask(stepAdapter, evaluateStep.task, context2, {
1092
- maxFollowUps: options.maxFollowUps ?? 2,
1093
- maxRetries: 0,
1094
- // evaluate steps do not retry
1309
+ const taskResult = await runTask(stepAdapter, step.task, context, {
1310
+ maxFollowUps: options.maxFollowUps ?? step.max_follow_ups ?? 2,
1311
+ maxRetries: options.maxRetries ?? step.max_retries ?? 0,
1095
1312
  taskRegistry: registries?.taskRegistry,
1096
1313
  agentRegistry: registries?.agentRegistry,
1097
1314
  handoffSchemas: registries?.handoffSchemas,
1315
+ retry: step.retry,
1098
1316
  progressOutput: options.progressOutput,
1317
+ // ── Phase 1-2: Observer Bridge ────────────────────────────────────────
1318
+ // Thread observer and session span ID so task-runner can emit agent.subagent
1319
+ // spans correlated to this session (parent_run_id → parentSpanId).
1099
1320
  observer: options.observer,
1100
- parentSpanId: iterationSpanId ?? sessionSpanId
1321
+ parentSpanId: sessionSpanId
1101
1322
  });
1102
1323
  return {
1103
1324
  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,
1325
+ task_id: step.task,
1326
+ outcome: taskResult.outcome,
1327
+ follow_ups_used: taskResult.follow_ups_used,
1328
+ retries_used: taskResult.retries_used,
1108
1329
  elapsed_ms: Date.now() - stepStart
1109
1330
  };
1110
1331
  }
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
- };
1130
- }
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);
1332
+ while (completed.size < workflow.steps.length) {
1333
+ const ready = [];
1334
+ for (let i = 0; i < workflow.steps.length; i++) {
1335
+ if (completed.has(i)) continue;
1336
+ if (depsByIndex[i].every((d) => completed.has(d))) {
1337
+ ready.push(i);
1338
+ }
1180
1339
  }
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;
1340
+ if (ready.length === 0) {
1341
+ abortResult = {
1342
+ workflow_id: workflow.id,
1343
+ status: "error",
1344
+ steps: stepResults.filter(Boolean),
1345
+ total_elapsed_ms: Date.now() - workflowStart,
1346
+ error_message: "Dependency cycle detected: no steps are ready to execute"
1347
+ };
1348
+ break;
1204
1349
  }
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);
1350
+ const batchResults = await Promise.all(ready.map(async (i) => {
1351
+ const step = workflow.steps[i];
1352
+ const modelClass = step.type === "delegate" || step.type === "evaluate" ? registries?.taskRegistry?.[step.task]?.model_class : void 0;
1353
+ let stepAdapter;
1354
+ if (ready.length > 1 && adapterFactory) {
1355
+ const result = adapterFactory(modelClass);
1356
+ stepAdapter = result && typeof result.then === "function" ? await result : result;
1357
+ } else if (modelClass && adapterFactory) {
1358
+ const result = adapterFactory(modelClass);
1359
+ stepAdapter = result && typeof result.then === "function" ? await result : result;
1360
+ } else {
1361
+ stepAdapter = primaryAdapter;
1230
1362
  }
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)}`;
1363
+ return executeStep(i, stepAdapter);
1364
+ }));
1365
+ for (let b = 0; b < ready.length; b++) {
1366
+ const i = ready[b];
1367
+ const result = batchResults[b];
1368
+ const step = workflow.steps[i];
1369
+ if (step.type === "evaluate") {
1370
+ const evaluateStep = step;
1371
+ const data = result.outcome.status === "success" ? result.outcome.data : void 0;
1372
+ const verdict = typeof data?.verdict === "string" ? data.verdict : "fail";
1373
+ const execCount = (evaluateExecCount.get(i) ?? 0) + 1;
1374
+ const currentIterationSpanId = iterationSpanIds.get(i);
1375
+ if (currentIterationSpanId) {
1376
+ const willLoopBack = verdict !== "pass" && execCount < evaluateStep.max_iterations;
1377
+ const feedbackInjected = willLoopBack && !!evaluateStep.inject_as;
1378
+ emitIterationClose(
1379
+ options.observer,
1380
+ currentIterationSpanId,
1381
+ evaluateStep.task,
1382
+ execCount,
1383
+ verdict,
1384
+ result.elapsed_ms,
1385
+ feedbackInjected
1386
+ );
1387
+ iterationSpanIds.delete(i);
1248
1388
  }
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;
1254
- }
1255
- const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);
1256
- if (loopToIdx === -1) {
1389
+ if (verdict === "pass") {
1390
+ emitIterationMetric(
1391
+ options.observer,
1392
+ sessionSpanId,
1393
+ evaluateStep.task,
1394
+ execCount,
1395
+ "pass"
1396
+ );
1257
1397
  stepResults[i] = result;
1258
1398
  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] = "";
1399
+ emitStepEvent(options, workflow.id, i, step, result);
1400
+ if (data !== void 0) {
1401
+ stepOutputs[i] = data;
1402
+ stepContexts[i] = `
1403
+
1404
+ --- Step ${i + 1}: ${stepId(i)} ---
1405
+ ${JSON.stringify(data, null, 2)}`;
1271
1406
  }
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":
1407
+ } else if (execCount < evaluateStep.max_iterations) {
1408
+ evaluateExecCount.set(i, execCount);
1409
+ if (evaluateStep.inject_as) {
1410
+ const feedback = typeof data?.feedback === "string" ? data.feedback : data !== void 0 ? JSON.stringify(data) : "Evaluate step returned no feedback";
1411
+ loopInjectedVars[evaluateStep.inject_as] = feedback;
1412
+ }
1413
+ const loopToIdx = workflow.steps.findIndex((s, j) => j < i && stepId(j) === evaluateStep.loop_to);
1414
+ if (loopToIdx === -1) {
1415
+ stepResults[i] = result;
1416
+ completed.add(i);
1287
1417
  abortResult = {
1288
1418
  workflow_id: workflow.id,
1289
1419
  status: "error",
1290
1420
  steps: stepResults.filter(Boolean),
1291
1421
  total_elapsed_ms: Date.now() - workflowStart,
1292
- error_message: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1422
+ error_message: `Evaluate step "${evaluateStep.task}" references unknown loop_to "${evaluateStep.loop_to}"`
1293
1423
  };
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`
1306
- };
1307
- break;
1424
+ } else {
1425
+ for (let k = loopToIdx; k <= i; k++) {
1426
+ completed.delete(k);
1427
+ stepOutputs[k] = void 0;
1428
+ stepContexts[k] = "";
1429
+ }
1430
+ }
1431
+ } else {
1432
+ evaluateExecCount.set(i, execCount);
1433
+ stepResults[i] = result;
1434
+ completed.add(i);
1435
+ const exhaustedPolicy = evaluateStep.on_exhausted ?? "escalate";
1436
+ emitIterationMetric(
1437
+ options.observer,
1438
+ sessionSpanId,
1439
+ evaluateStep.task,
1440
+ execCount,
1441
+ `exhausted-${exhaustedPolicy}`
1442
+ );
1443
+ switch (exhaustedPolicy) {
1444
+ case "abort":
1445
+ abortResult = {
1446
+ workflow_id: workflow.id,
1447
+ status: "error",
1448
+ steps: stepResults.filter(Boolean),
1449
+ total_elapsed_ms: Date.now() - workflowStart,
1450
+ error_message: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1451
+ };
1452
+ break;
1453
+ case "fail_partial":
1454
+ emitStepEvent(options, workflow.id, i, step, result);
1455
+ break;
1456
+ case "escalate":
1457
+ default:
1458
+ abortResult = {
1459
+ workflow_id: workflow.id,
1460
+ status: "escalated",
1461
+ steps: stepResults.filter(Boolean),
1462
+ total_elapsed_ms: Date.now() - workflowStart,
1463
+ escalation_reason: `Evaluate step "${evaluateStep.task}" exhausted ${evaluateStep.max_iterations} iterations without passing`
1464
+ };
1465
+ break;
1466
+ }
1308
1467
  }
1468
+ continue;
1309
1469
  }
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] = `
1470
+ stepResults[i] = result;
1471
+ completed.add(i);
1472
+ emitStepEvent(options, workflow.id, i, step, result);
1473
+ if (result.outcome.status === "success") {
1474
+ const data = result.outcome.data;
1475
+ stepOutputs[i] = data;
1476
+ stepContexts[i] = `
1319
1477
 
1320
1478
  --- Step ${i + 1}: ${stepId(i)} ---
1321
1479
  ` + (typeof data === "string" ? data : JSON.stringify(data, null, 2));
1480
+ }
1481
+ if (result.outcome.status === "gate_rejected") {
1482
+ abortResult = {
1483
+ workflow_id: workflow.id,
1484
+ status: "gate_rejected",
1485
+ steps: stepResults.filter(Boolean),
1486
+ total_elapsed_ms: Date.now() - workflowStart
1487
+ };
1488
+ } else if (result.outcome.status === "escalation") {
1489
+ abortResult = {
1490
+ workflow_id: workflow.id,
1491
+ status: "escalated",
1492
+ steps: stepResults.filter(Boolean),
1493
+ total_elapsed_ms: Date.now() - workflowStart,
1494
+ escalation_reason: result.outcome.reason
1495
+ };
1496
+ } else if (result.outcome.status === "error" || result.outcome.status === "validation_error") {
1497
+ const taskId = step.type === "delegate" ? step.task : step.gate_kind;
1498
+ abortResult = {
1499
+ workflow_id: workflow.id,
1500
+ status: "escalated",
1501
+ steps: stepResults.filter(Boolean),
1502
+ total_elapsed_ms: Date.now() - workflowStart,
1503
+ escalation_reason: `Task "${taskId}" failed after ${result.follow_ups_used} follow-ups and ${result.retries_used} retries`
1504
+ };
1505
+ }
1322
1506
  }
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
- };
1507
+ if (abortResult) break;
1508
+ }
1509
+ wfResult = abortResult ?? {
1510
+ workflow_id: workflow.id,
1511
+ status: "completed",
1512
+ steps: stepResults.filter(Boolean),
1513
+ total_elapsed_ms: Date.now() - workflowStart
1514
+ };
1515
+ await pluginRegistry.runAfterWorkflow(workflow.id, wfResult);
1516
+ if (options.toolchain && options.observer) {
1517
+ try {
1518
+ await runToolchainChecks({
1519
+ ...options.toolchain,
1520
+ observer: options.observer,
1521
+ parentSpanId: sessionSpanId
1522
+ });
1523
+ } catch {
1347
1524
  }
1348
1525
  }
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
- );
1526
+ return wfResult;
1527
+ } catch (err) {
1528
+ sessionError = err;
1529
+ throw err;
1530
+ } finally {
1531
+ if (sessionSpanId) {
1532
+ const durationMs = wfResult?.total_elapsed_ms ?? Date.now() - workflowStart;
1533
+ sessionEnvelope.execution_metadata = { duration_ms: durationMs };
1534
+ emitSessionClose(
1535
+ options.observer,
1536
+ sessionSpanId,
1537
+ sessionEnvelope,
1538
+ durationMs,
1539
+ wfResult?.status ?? "error",
1540
+ sessionError?.message
1541
+ );
1542
+ }
1367
1543
  }
1368
- return wfResult;
1369
1544
  }
1370
1545
  function mergeVariables(base, injected) {
1371
1546
  const merged = { ...base, ...injected };
@@ -1563,11 +1738,11 @@ function emitProcessEdit(options) {
1563
1738
  }
1564
1739
 
1565
1740
  // src/lib/bound-resolver.ts
1566
- import { readFile as readFile2 } from "fs/promises";
1741
+ import { readFile as readFile3 } from "fs/promises";
1567
1742
  import YAML2 from "yaml";
1568
1743
 
1569
1744
  // src/lib/dsl-context.ts
1570
- import { readFile } from "fs/promises";
1745
+ import { readFile as readFile2 } from "fs/promises";
1571
1746
  import YAML from "yaml";
1572
1747
  var DslValidationError = class extends Error {
1573
1748
  missing;
@@ -1621,6 +1796,20 @@ function buildWorkflowStep(step) {
1621
1796
  depends_on: step.depends_on
1622
1797
  };
1623
1798
  }
1799
+ if (step.type === "evaluate") {
1800
+ return {
1801
+ type: "evaluate",
1802
+ task: step.task ?? "",
1803
+ from_agent: step.from_agent ?? "",
1804
+ evaluator_agent: step.evaluator_agent,
1805
+ description: step.description,
1806
+ loop_to: step.loop_to ?? "",
1807
+ max_iterations: step.max_iterations ?? 1,
1808
+ inject_as: step.inject_as,
1809
+ on_exhausted: step.on_exhausted,
1810
+ depends_on: step.depends_on
1811
+ };
1812
+ }
1624
1813
  return {
1625
1814
  type: "delegate",
1626
1815
  task: step.task ?? "",
@@ -1727,7 +1916,7 @@ async function loadDslContext(options) {
1727
1916
  let dsl;
1728
1917
  if (options.projectDslPath) {
1729
1918
  const { resolve: resolveDsl, mergeDsl, expandDefaults } = await import("agent-contracts");
1730
- const raw = await readFile(options.projectDslPath, "utf8");
1919
+ const raw = await readFile2(options.projectDslPath, "utf8");
1731
1920
  const projectData = YAML.parse(raw);
1732
1921
  if (projectData.extends === "/$embedded/") {
1733
1922
  const { extends: _extends, ...projectOverrides } = projectData;
@@ -1925,7 +2114,7 @@ var BoundResolver = class {
1925
2114
  };
1926
2115
  if (opts.bindingPaths && opts.bindingPaths.length > 0) {
1927
2116
  for (const bindingPath of opts.bindingPaths) {
1928
- const raw = await readFile2(bindingPath, "utf8");
2117
+ const raw = await readFile3(bindingPath, "utf8");
1929
2118
  const binding = YAML2.parse(raw);
1930
2119
  guardrailCtx = buildGuardrailContext(
1931
2120
  dsl,
@@ -2072,19 +2261,19 @@ var WorkflowBuilder = class {
2072
2261
  };
2073
2262
 
2074
2263
  // src/lib/plugin-loader.ts
2075
- import { existsSync } from "fs";
2264
+ import { existsSync as existsSync2 } from "fs";
2076
2265
  import { readdir } from "fs/promises";
2077
- import { resolve, join } from "path";
2266
+ import { resolve as resolve2, join } from "path";
2078
2267
  var PLUGIN_EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
2079
2268
  function isPluginLike(obj) {
2080
2269
  return typeof obj === "object" && obj !== null && typeof obj.id === "string";
2081
2270
  }
2082
2271
  async function scanDirectory(dir) {
2083
- if (!existsSync(dir)) return [];
2272
+ if (!existsSync2(dir)) return [];
2084
2273
  const entries = await readdir(dir, { withFileTypes: true });
2085
2274
  return entries.filter(
2086
2275
  (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));
2276
+ ).map((e) => resolve2(dir, e.name));
2088
2277
  }
2089
2278
  async function loadPluginModule(modulePath) {
2090
2279
  const mod = await import(new URL(`file://${modulePath}`).href);
@@ -2103,8 +2292,8 @@ async function loadPluginModule(modulePath) {
2103
2292
  async function loadPluginsFromPaths(paths, baseDir) {
2104
2293
  const result = { loaded: 0, files: [], errors: [] };
2105
2294
  for (const p of paths) {
2106
- const absPath = resolve(baseDir, p);
2107
- if (!existsSync(absPath)) {
2295
+ const absPath = resolve2(baseDir, p);
2296
+ if (!existsSync2(absPath)) {
2108
2297
  result.errors.push({ file: p, error: `File not found: ${absPath}` });
2109
2298
  continue;
2110
2299
  }
@@ -2253,7 +2442,7 @@ var InMemoryStore = class {
2253
2442
  };
2254
2443
 
2255
2444
  // src/lib/file-memory-store.ts
2256
- import { mkdir, readFile as readFile3, unlink, writeFile } from "fs/promises";
2445
+ import { mkdir, readFile as readFile4, unlink, writeFile } from "fs/promises";
2257
2446
  import { join as join3 } from "path";
2258
2447
  function resolveFilePath2(baseDir, ref) {
2259
2448
  const runId = ref.parent_run_id ?? "unknown";
@@ -2272,7 +2461,7 @@ var FileMemoryStore = class {
2272
2461
  async load(ref) {
2273
2462
  const filePath = resolveFilePath2(this.baseDir, ref);
2274
2463
  try {
2275
- const raw = await readFile3(filePath, "utf-8");
2464
+ const raw = await readFile4(filePath, "utf-8");
2276
2465
  return JSON.parse(raw);
2277
2466
  } catch (error) {
2278
2467
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2295,7 +2484,7 @@ var FileMemoryStore = class {
2295
2484
  };
2296
2485
 
2297
2486
  // 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";
2487
+ import { mkdir as mkdir2, readFile as readFile5, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
2299
2488
  import { join as join4 } from "path";
2300
2489
  var AgentLogWriter = class {
2301
2490
  baseDir;
@@ -2319,7 +2508,7 @@ var AgentLogWriter = class {
2319
2508
  async readRunLog(runId) {
2320
2509
  const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
2321
2510
  try {
2322
- const raw = await readFile4(filePath, "utf-8");
2511
+ const raw = await readFile5(filePath, "utf-8");
2323
2512
  return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
2324
2513
  } catch (error) {
2325
2514
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2337,7 +2526,7 @@ var AgentLogWriter = class {
2337
2526
  async readHandoff(runId, step) {
2338
2527
  const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
2339
2528
  try {
2340
- const raw = await readFile4(filePath, "utf-8");
2529
+ const raw = await readFile5(filePath, "utf-8");
2341
2530
  return JSON.parse(raw);
2342
2531
  } catch (error) {
2343
2532
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -2504,7 +2693,7 @@ Install it with: npm install ${pkg2}`
2504
2693
  }
2505
2694
 
2506
2695
  // src/lib/execute.ts
2507
- import { resolve as resolve2 } from "path";
2696
+ import { resolve as resolve3 } from "path";
2508
2697
  async function resolveExecutionContext(options, requiredEntities) {
2509
2698
  const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
2510
2699
  if (useBoundResolver) {
@@ -2572,7 +2761,7 @@ async function executeTask(taskId, options) {
2572
2761
  ...adapterOptions
2573
2762
  });
2574
2763
  const progressSink = createProgressSink(
2575
- options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
2764
+ options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
2576
2765
  );
2577
2766
  try {
2578
2767
  if (options.hooks?.beforeTask) {
@@ -2582,6 +2771,7 @@ async function executeTask(taskId, options) {
2582
2771
  maxFollowUps: options.maxFollowUps ?? 2,
2583
2772
  maxRetries: options.maxRetries ?? 0,
2584
2773
  progressOutput: progressSink,
2774
+ observer: options.observer,
2585
2775
  ...execCtx.registries
2586
2776
  });
2587
2777
  if (options.hooks?.afterTask) {
@@ -2601,7 +2791,7 @@ async function executeWorkflow(workflowId, options) {
2601
2791
  ...adapterOptions
2602
2792
  });
2603
2793
  const progressSink = createProgressSink(
2604
- options.logFile ? { stderr: true, file: resolve2(options.logFile), naming: "single" } : { stderr: true }
2794
+ options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
2605
2795
  );
2606
2796
  try {
2607
2797
  if (options.hooks?.beforeWorkflow) {
@@ -2612,6 +2802,8 @@ async function executeWorkflow(workflowId, options) {
2612
2802
  user_request: options.request,
2613
2803
  handoff: options.handoff,
2614
2804
  progressOutput: progressSink,
2805
+ observer: options.observer,
2806
+ toolchain: options.toolchain,
2615
2807
  runtime: {
2616
2808
  maxFollowUps: options.maxFollowUps ?? 2,
2617
2809
  maxRetries: options.maxRetries ?? 0
@@ -2758,17 +2950,18 @@ async function dispatchOperation(operationName, op, options, input, ctx, handler
2758
2950
  }
2759
2951
 
2760
2952
  // 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";
2953
+ import { existsSync as existsSync3 } from "fs";
2954
+ import { readFile as readFile6 } from "fs/promises";
2955
+ import { resolve as resolve4, dirname as dirname2 } from "path";
2764
2956
  import YAML3 from "yaml";
2957
+ import { createPipeline } from "@aaac/observability";
2765
2958
  var PROJECT_CONFIG_FILENAME = "project.yaml";
2766
2959
  var DEFAULT_ADAPTER = "claude";
2767
2960
  function findProjectConfig(startDir, filename = PROJECT_CONFIG_FILENAME) {
2768
- let dir = resolve3(startDir);
2961
+ let dir = resolve4(startDir);
2769
2962
  for (; ; ) {
2770
- const candidate = resolve3(dir, filename);
2771
- if (existsSync2(candidate)) return candidate;
2963
+ const candidate = resolve4(dir, filename);
2964
+ if (existsSync3(candidate)) return candidate;
2772
2965
  const parent = dirname2(dir);
2773
2966
  if (parent === dir) return void 0;
2774
2967
  dir = parent;
@@ -2780,8 +2973,8 @@ function serializeRequest(input) {
2780
2973
  }
2781
2974
  async function createProjectRuntime(options) {
2782
2975
  const cwd = options.cwd ?? process.cwd();
2783
- const configPath = options.configPath ? resolve3(cwd, options.configPath) : findProjectConfig(cwd);
2784
- if (!configPath || !existsSync2(configPath)) {
2976
+ const configPath = options.configPath ? resolve4(cwd, options.configPath) : findProjectConfig(cwd);
2977
+ if (!configPath || !existsSync3(configPath)) {
2785
2978
  const where = options.configPath ? `config path "${options.configPath}"` : `${PROJECT_CONFIG_FILENAME} from ${cwd} upward`;
2786
2979
  throw new Error(
2787
2980
  `No ${PROJECT_CONFIG_FILENAME} found (${where}). Pass --config <path> to a project manifest.`
@@ -2789,14 +2982,30 @@ async function createProjectRuntime(options) {
2789
2982
  }
2790
2983
  const config = await loadProjectConfig(configPath);
2791
2984
  const env = options.env ?? process.env;
2792
- const rawManifest = YAML3.parse(await readFile5(configPath, "utf8"));
2985
+ const rawManifest = YAML3.parse(await readFile6(configPath, "utf8"));
2793
2986
  const overlayExplicit = typeof rawManifest?.agents === "string" || typeof rawManifest?.dsl === "string";
2794
- if (overlayExplicit && !existsSync2(config.dslPath)) {
2987
+ if (overlayExplicit && !existsSync3(config.dslPath)) {
2795
2988
  throw new Error(
2796
2989
  `Project agents DSL not found: ${config.dslPath} (referenced by ${configPath}).`
2797
2990
  );
2798
2991
  }
2799
2992
  const projectDslPath = overlayExplicit ? config.dslPath : void 0;
2993
+ let observer;
2994
+ let observerSink;
2995
+ let observerClosed = false;
2996
+ if (config.observability && config.observability.enabled !== false) {
2997
+ const pipeline = createPipeline(
2998
+ config.observability.dbPath ? { dbPath: config.observability.dbPath } : {}
2999
+ );
3000
+ observer = pipeline.collector.emit.bind(pipeline.collector);
3001
+ observerSink = pipeline.sink;
3002
+ }
3003
+ function closeObserver() {
3004
+ if (observerSink && !observerClosed) {
3005
+ observerClosed = true;
3006
+ observerSink.close();
3007
+ }
3008
+ }
2800
3009
  function resolveAdapter2() {
2801
3010
  const explicit = options.adapter ?? env.AGENT_RUNTIME_ADAPTER;
2802
3011
  if (explicit) {
@@ -2822,22 +3031,40 @@ async function createProjectRuntime(options) {
2822
3031
  activeGuardrailPolicy: config.active_guardrail_policy,
2823
3032
  artifactBinding: config.artifactsPath ? { source: config.artifactsPath } : void 0,
2824
3033
  maxFollowUps: config.recovery.max_follow_ups,
2825
- maxRetries: config.recovery.max_retries
3034
+ maxRetries: config.recovery.max_retries,
3035
+ observer,
3036
+ // Toolchain.execution observation: only when BOTH in-process observability
3037
+ // is wired AND project.yaml declares `toolchains`. Observation is non-
3038
+ // destructive (records spans; never gates the workflow) and a no-op when
3039
+ // either is absent (AC4 regression safety). Consumed only by executeWorkflow.
3040
+ toolchain: observer && config.toolchainsPath ? {
3041
+ toolchainsPath: config.toolchainsPath,
3042
+ artifactsPath: config.artifactsPath,
3043
+ cwd
3044
+ } : void 0
2826
3045
  };
2827
3046
  }
2828
3047
  const runtime = {
2829
3048
  async runWorkflow(workflowId, _options, input, _ctx) {
2830
- return executeWorkflow(workflowId, {
2831
- ...sharedExecuteOptions(),
2832
- request: serializeRequest(input),
2833
- autoApproveGates: options.autoApproveGates ?? true
2834
- });
3049
+ try {
3050
+ return await executeWorkflow(workflowId, {
3051
+ ...sharedExecuteOptions(),
3052
+ request: serializeRequest(input),
3053
+ autoApproveGates: options.autoApproveGates ?? true
3054
+ });
3055
+ } finally {
3056
+ closeObserver();
3057
+ }
2835
3058
  },
2836
3059
  async runTask(taskId, _options, input, _ctx) {
2837
- return executeTask(taskId, {
2838
- ...sharedExecuteOptions(),
2839
- request: serializeRequest(input)
2840
- });
3060
+ try {
3061
+ return await executeTask(taskId, {
3062
+ ...sharedExecuteOptions(),
3063
+ request: serializeRequest(input)
3064
+ });
3065
+ } finally {
3066
+ closeObserver();
3067
+ }
2841
3068
  }
2842
3069
  };
2843
3070
  return {
@@ -3003,7 +3230,7 @@ async function resolveArtifacts(options) {
3003
3230
  }
3004
3231
 
3005
3232
  // src/lib/guard-commands.ts
3006
- import { readFile as readFile6, readdir as readdir3 } from "fs/promises";
3233
+ import { readFile as readFile7, readdir as readdir3 } from "fs/promises";
3007
3234
  import YAML4 from "yaml";
3008
3235
  async function evaluateGuardrail(opts) {
3009
3236
  let hookInput;
@@ -3024,7 +3251,7 @@ async function evaluateGuardrail(opts) {
3024
3251
  for (const bindingPath of opts.bindingPaths) {
3025
3252
  let raw;
3026
3253
  try {
3027
- raw = await readFile6(bindingPath, "utf8");
3254
+ raw = await readFile7(bindingPath, "utf8");
3028
3255
  } catch (err) {
3029
3256
  const code = err.code;
3030
3257
  if (code === "ENOENT") continue;
@@ -3073,7 +3300,7 @@ async function listGuardrails(opts) {
3073
3300
  for (const bindingPath of opts.bindingPaths) {
3074
3301
  let raw;
3075
3302
  try {
3076
- raw = await readFile6(bindingPath, "utf8");
3303
+ raw = await readFile7(bindingPath, "utf8");
3077
3304
  } catch (err) {
3078
3305
  const code = err.code;
3079
3306
  if (code === "ENOENT") continue;
@@ -3132,7 +3359,7 @@ async function guardStatus(opts = {}) {
3132
3359
  const filePath = `${runsDir}/${file}`;
3133
3360
  let raw;
3134
3361
  try {
3135
- raw = await readFile6(filePath, "utf8");
3362
+ raw = await readFile7(filePath, "utf8");
3136
3363
  } catch {
3137
3364
  continue;
3138
3365
  }
@@ -3267,130 +3494,6 @@ async function executePrompt(message, ir, binding, ctx, opts) {
3267
3494
  return { selectedOperation, mappedInput, output };
3268
3495
  }
3269
3496
 
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
3497
  // src/index.ts
3395
3498
  var require2 = createRequire(import.meta.url);
3396
3499
  var pkg = require2("../package.json");