@tangle-network/agent-runtime 10.0.19 → 10.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{activation-BudDVuT6.d.ts → activation-B0arteLE.d.ts} +2 -2
  3. package/dist/{activation-DLnZJab0.js → activation-D_J9qCzU.js} +2 -2
  4. package/dist/{activation-DLnZJab0.js.map → activation-D_J9qCzU.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{delegate-9b8qGlXp.js → delegate-AfWnrUWf.js} +2 -2
  8. package/dist/{delegate-9b8qGlXp.js.map → delegate-AfWnrUWf.js.map} +1 -1
  9. package/dist/{driver-control-acknowledgers-b5MsXxR5.js → driver-control-acknowledgers-CgeEYeHA.js} +8 -8
  10. package/dist/{driver-control-acknowledgers-b5MsXxR5.js.map → driver-control-acknowledgers-CgeEYeHA.js.map} +1 -1
  11. package/dist/durable-writer-thread.js +4 -4
  12. package/dist/durable.d.ts +1 -1
  13. package/dist/durable.js +13 -14
  14. package/dist/durable.js.map +1 -1
  15. package/dist/{graph--n31XKWJ.js → graph-hVouinKw.js} +8 -8
  16. package/dist/{graph--n31XKWJ.js.map → graph-hVouinKw.js.map} +1 -1
  17. package/dist/{graph-registry-aMRd94PD.js → graph-registry-DI8o9iCB.js} +1 -1
  18. package/dist/{graph-registry-SgsCxCTZ.js → graph-registry-qyaNDATw.js} +2 -3
  19. package/dist/{graph-registry-SgsCxCTZ.js.map → graph-registry-qyaNDATw.js.map} +1 -1
  20. package/dist/{improve-sIZhpXqE.js → improve-BjKhfQ_b.js} +6 -6
  21. package/dist/{improve-sIZhpXqE.js.map → improve-BjKhfQ_b.js.map} +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +10 -10
  24. package/dist/intelligence.d.ts +2 -2
  25. package/dist/intelligence.js +4 -4
  26. package/dist/{continuation-CDdjAkpk.js → jsonl-file-B2ESMrTh.js} +396 -4
  27. package/dist/jsonl-file-B2ESMrTh.js.map +1 -0
  28. package/dist/kernel.d.ts +1 -1
  29. package/dist/kernel.js +17 -18
  30. package/dist/{loop-runner-Bn7lFuQZ.d.ts → loop-runner-BFC781pC.d.ts} +2 -2
  31. package/dist/{loop-runner-Dt7I2oMa.js → loop-runner-BVTcuWZk.js} +2 -2
  32. package/dist/{loop-runner-Dt7I2oMa.js.map → loop-runner-BVTcuWZk.js.map} +1 -1
  33. package/dist/loop-runner-bin.d.ts +1 -1
  34. package/dist/loop-runner-bin.js +1 -1
  35. package/dist/mcp/bin.js +3 -3
  36. package/dist/mcp/index.d.ts +1 -1
  37. package/dist/mcp/index.js +6 -6
  38. package/dist/mcp/memory-bin.js +1 -1
  39. package/dist/profiles.d.ts +1 -1
  40. package/dist/{provision-supervisor-DfDAdtqb.js → provision-supervisor-KXJqdixT.js} +6 -6
  41. package/dist/{provision-supervisor-DfDAdtqb.js.map → provision-supervisor-KXJqdixT.js.map} +1 -1
  42. package/dist/{result-blob-store-Dke805sV.js → result-blob-store-CJjp44Mz.js} +3 -3
  43. package/dist/{result-blob-store-Dke805sV.js.map → result-blob-store-CJjp44Mz.js.map} +1 -1
  44. package/dist/{run-cancellation-B0SgcidY.js → run-cancellation-BNBmsY3a.js} +2 -2
  45. package/dist/{run-cancellation-B0SgcidY.js.map → run-cancellation-BNBmsY3a.js.map} +1 -1
  46. package/dist/{run-lock-BOg7BaXF.js → run-lock-Dcr79Wql.js} +2 -2
  47. package/dist/{run-lock-BOg7BaXF.js.map → run-lock-Dcr79Wql.js.map} +1 -1
  48. package/dist/{run-reopen-B7TN2aQQ.js → run-reopen-Cr2SHmYa.js} +6 -6
  49. package/dist/{run-reopen-B7TN2aQQ.js.map → run-reopen-Cr2SHmYa.js.map} +1 -1
  50. package/dist/{run-state-BNBUy2uK.js → run-state-Bko0BF0_.js} +7 -7
  51. package/dist/{run-state-BNBUy2uK.js.map → run-state-Bko0BF0_.js.map} +1 -1
  52. package/dist/{runtime-DXeWY00j.js → runtime-CFjS-eQV.js} +19 -20
  53. package/dist/{runtime-DXeWY00j.js.map → runtime-CFjS-eQV.js.map} +1 -1
  54. package/dist/{search-executor-BoQHI2Tz.js → search-executor-DnWnh4kj.js} +4 -4
  55. package/dist/{search-executor-BoQHI2Tz.js.map → search-executor-DnWnh4kj.js.map} +1 -1
  56. package/dist/{server-Xkgobp5y.js → server-D87su_-4.js} +4 -4
  57. package/dist/{server-Xkgobp5y.js.map → server-D87su_-4.js.map} +1 -1
  58. package/dist/{settle-record-B5OpVDnC.js → settle-record-BlIw2MU1.js} +3 -3
  59. package/dist/{settle-record-B5OpVDnC.js.map → settle-record-BlIw2MU1.js.map} +1 -1
  60. package/dist/{structural-rollout-BSF5tzUm.js → structural-rollout-BLflx9cs.js} +4 -4
  61. package/dist/{structural-rollout-BSF5tzUm.js.map → structural-rollout-BLflx9cs.js.map} +1 -1
  62. package/dist/{supervise-Drc1Pj1d.js → supervise-CQfJyuLL.js} +13 -13
  63. package/dist/supervise-CQfJyuLL.js.map +1 -0
  64. package/dist/{supervise-identity-Cz-Hzg9s.js → supervise-identity-CtxWEk1I.js} +3 -3
  65. package/dist/{supervise-identity-Cz-Hzg9s.js.map → supervise-identity-CtxWEk1I.js.map} +1 -1
  66. package/dist/{supervision-discovery-DdRd1lsz.js → supervision-discovery-DKxqbnHf.js} +4 -4
  67. package/dist/{supervision-discovery-DdRd1lsz.js.map → supervision-discovery-DKxqbnHf.js.map} +1 -1
  68. package/dist/{supervisor-CwUD7dsm.js → supervisor-DL4hO7UW.js} +12 -593
  69. package/dist/supervisor-DL4hO7UW.js.map +1 -0
  70. package/dist/{supervisor-accounting-CPDPG8mH.js → supervisor-accounting-DlDUl58C.js} +600 -8
  71. package/dist/supervisor-accounting-DlDUl58C.js.map +1 -0
  72. package/dist/{supervisor-root-contract-Uw2q3nvG.js → supervisor-root-contract-BCbu1A4n.js} +3 -3
  73. package/dist/{supervisor-root-contract-Uw2q3nvG.js.map → supervisor-root-contract-BCbu1A4n.js.map} +1 -1
  74. package/dist/testing.d.ts +1 -1
  75. package/dist/testing.js +11 -11
  76. package/dist/{failure-cause-C96rzF-d.js → tool-server-n4XYpCok.js} +181 -2
  77. package/dist/tool-server-n4XYpCok.js.map +1 -0
  78. package/dist/{top-web-5ThvdyD0.js → top-web-B-sHmI3g.js} +8 -8
  79. package/dist/{top-web-5ThvdyD0.js.map → top-web-B-sHmI3g.js.map} +1 -1
  80. package/dist/tui/bin.js +3 -3
  81. package/dist/tui/index.d.ts +1 -1
  82. package/dist/tui/index.js +2 -2
  83. package/dist/{types-BLhsL4qy.d.ts → types-YXZL7Wxi.d.ts} +5 -3
  84. package/package.json +1 -1
  85. package/dist/continuation-CDdjAkpk.js.map +0 -1
  86. package/dist/failure-cause-C96rzF-d.js.map +0 -1
  87. package/dist/jsonl-file-B8xfYz9M.js +0 -397
  88. package/dist/jsonl-file-B8xfYz9M.js.map +0 -1
  89. package/dist/supervise-Drc1Pj1d.js.map +0 -1
  90. package/dist/supervisor-CwUD7dsm.js.map +0 -1
  91. package/dist/supervisor-accounting-CPDPG8mH.js.map +0 -1
  92. package/dist/tool-server-BhsyVDj2.js +0 -174
  93. package/dist/tool-server-BhsyVDj2.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, l as RetainedInteractiveBindingError, m as ValidationError, r as BackendTransportError, u as RetainedRunAdmissionError } from "./errors-DG8yufqX.js";
2
- import { _ as runAbortable, c as withJsonlFileLock, d as journalFileStamp, f as sha256, h as deadlineSignal, l as appendCommittedJsonLine, o as readCommittedJsonLines, p as RunCancellationReason, r as prepareJsonlAppend, t as isNoEntError, v as signalAbortError } from "./jsonl-file-B8xfYz9M.js";
3
- import { c as checkInIdleMs, d as teardownExecutor, n as CHILD_DEADLINE_REASON, o as armDeadlineTimer, s as boundedChildDeadlineAt, u as singleFlightTeardown } from "./deadline-CySmJ_0S.js";
1
+ import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError, r as BackendTransportError, t as AgentEvalError$1, u as RetainedRunAdmissionError } from "./errors-DG8yufqX.js";
2
+ import { C as linkAbort, S as deadlineSignal, T as signalAbortError, b as RunCancellationReason, c as withJsonlFileLock, d as journalFileStamp, h as checkVerdictOf, l as appendCommittedJsonLine, o as readCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError, w as runAbortable, y as sha256 } from "./jsonl-file-B2ESMrTh.js";
3
+ import { c as checkInIdleMs, d as teardownExecutor, f as teardownSurfaces, n as CHILD_DEADLINE_REASON, o as armDeadlineTimer, s as boundedChildDeadlineAt, u as singleFlightTeardown } from "./deadline-CySmJ_0S.js";
4
4
  import { A as withBudgetResources, C as unreportedSpend, D as addResourceSpend, T as zeroSpend, a as cloneSpend, c as errorMessage, f as isAsyncIterable, i as chargedTokens, k as resourceTelemetry, n as addSpend, o as cloneTokenUsage, t as abortError, v as sleep } from "./util-qsH5cC9S.js";
5
- import { $ as createBudgetPool, F as contentAddress, J as BudgetReconcileFault, L as executorFailure, P as traceRootWriter, Q as completedLeafBacking, R as executorFailureInfra, X as budgetLeases, Y as budgetLeaseUpdates, Z as budgetRecoverySeeds, a as settlementFailureCause, at as assertValidBudget, d as executorEvidenceWriter, et as refreshBudgetLease, g as refusedBeforeItRan, gt as parseCanonicalTransportEvent, h as prepareRetainedExecutor, ht as extractTransportEventIdentity, it as spendFromUsageTotals, jt as recordValue, l as RetainedExecutionPendingError, m as leafContinuationExecutionId, n as runtimeFailureCause, nt as newUsageTotals, o as BUDGET_CONTINUATION_TASK, ot as assertValidSpend, t as reportedFailureCause, tt as meterUsageEvent, y as retainedExecutorSeamKey, z as executorFailureReason } from "./failure-cause-C96rzF-d.js";
6
- import { a as errMessage, f as defaultRedactor, i as causeChain, l as errorText, m as resolveRedactor, n as detachedSnapshot, r as shareParsedStrings } from "./snapshot-BKLziJ5K.js";
5
+ import { $ as budgetLeases, A as printedStatus, B as executorFailure, E as UNAVAILABLE_STATUSES, G as turnFailureOf, H as executorFailureReason, K as turnFailurePolicy, L as traceRootWriter, P as unavailableSignalOfFailure, Pt as recordValue, Q as budgetLeaseUpdates, R as contentAddress, S as retainedExecutorSeamKey, T as UNAVAILABLE_CODES, V as executorFailureInfra, X as isCredentialRefusal, Y as credentialCommandExit, Z as BudgetReconcileFault, _ as leafContinuationExecutionId, at as newUsageTotals, c as BUDGET_CONTINUATION_TASK, ct as assertValidBudget, d as RetainedExecutionPendingError, et as budgetRecoverySeeds, f as TRANSPORT_ERROR_CODES, g as isSpentCreateKeyRefusal, h as isSchemaRejection, i as runtimeFailureCause, it as meterUsageEvent, l as DISPATCH_EXECUTION_CHANGED_CODE, lt as assertValidSpend, m as isProvisioningRefusal, nt as createBudgetPool, p as executorEvidenceWriter, r as reportedFailureCause, rt as refreshBudgetLease, s as settlementFailureCause, st as spendFromUsageTotals, t as PROTOCOL_VERSION, tt as completedLeafBacking, u as DISPATCH_NOT_ADMITTED_CODE, v as prepareRetainedExecutor, vt as extractTransportEventIdentity, x as retainedExecutorContext, y as refusedBeforeItRan, yt as parseCanonicalTransportEvent } from "./tool-server-n4XYpCok.js";
6
+ import { a as errMessage, f as defaultRedactor, i as causeChain, l as errorText, m as resolveRedactor, n as detachedSnapshot, o as errorHttpStatus, r as shareParsedStrings, s as errorProperty } from "./snapshot-BKLziJ5K.js";
7
7
  import { p as canonicalObservedModelParts, t as assertExecutableAgentProfile } from "./model-policy-DFuhCC0-.js";
8
8
  import { b as verifiedArtifactChunks, g as workspaceLimits, h as safeArchivePath, i as readAgentCandidateWorkspaceArtifactFiles } from "./workspace-streams-C7PGLAUd.js";
9
9
  import { a as assertNoSymlinkDescendant, b as captureRunWriteContext, c as publishExclusiveFenced, d as writeAtomicDurableFileAsync, i as appendRunLinesFenced, n as appendDurableFile, o as publishExclusiveDurableFile, r as appendRunLines, s as publishExclusiveDurableFileAsync, u as writeAtomicDurableFile, v as runFencedAlways, x as fenceRunWrite, y as runFencedAsync } from "./durable-file-pao7FijS.js";
@@ -806,6 +806,317 @@ function providerAttemptEvidence(model) {
806
806
  models
807
807
  });
808
808
  }
809
+ // src/runtime/supervise/completion-gate.ts
810
+ /**
811
+ * Wrap an `Executor` so its settlement `valid` reflects the deliverable check, not the
812
+ * inner verdict. Handles both `execute` shapes (one-shot `Promise<ExecutorResult>` and
813
+ * streaming `AsyncIterable<UsageEvent>` + `resultArtifact()`); the check runs once the inner
814
+ * executor has produced its output. The inner `score` is preserved; only `valid` is gated.
815
+ */
816
+ function gateOnDeliverable(inner, deliverable) {
817
+ return wrapCompletionGate(inner, (result) => checkDeliverable(deliverable, result));
818
+ }
819
+ /** Build a worker with the same check on durable acceptance and normal completion. @internal */
820
+ function gateFactoryOnDeliverable(factory, deliverable) {
821
+ return (spec, ctx) => {
822
+ const profile = detachedSnapshot(spec.profile, "completion check profile");
823
+ const node = ctx.node === void 0 ? void 0 : detachedSnapshot(ctx.node, "completion check node");
824
+ const retention = retainedExecutorContext(ctx);
825
+ const verdicts = /* @__PURE__ */ new WeakMap();
826
+ const check = (result) => {
827
+ let verdict = verdicts.get(result);
828
+ if (verdict === void 0) {
829
+ verdict = checkDeliverable(deliverable, result, Object.freeze({
830
+ profile,
831
+ node,
832
+ signal: ctx.signal,
833
+ originalVerdict: result.verdict === void 0 ? void 0 : detachedSnapshot(result.verdict, "completion check original verdict")
834
+ }));
835
+ verdicts.set(result, verdict);
836
+ }
837
+ return verdict;
838
+ };
839
+ if (retention === void 0) return wrapCompletionGate(factory(spec, ctx), check);
840
+ const checkedRetention = (source) => ({
841
+ ...source,
842
+ onResult: async (result) => source.onResult({
843
+ ...result,
844
+ verdict: await check(result)
845
+ }),
846
+ ...source.continueInvocation === void 0 ? {} : { continueInvocation: async (task) => checkedRetention(await source.continueInvocation(task)) }
847
+ });
848
+ return wrapCompletionGate(factory(spec, {
849
+ ...ctx,
850
+ seams: {
851
+ ...ctx.seams,
852
+ [retainedExecutorSeamKey]: checkedRetention(retention)
853
+ }
854
+ }), check);
855
+ };
856
+ }
857
+ async function checkDeliverable(deliverable, result, context) {
858
+ let delivered;
859
+ try {
860
+ delivered = checkVerdictOf(await deliverable.check(result.out, context)).pass;
861
+ } catch {
862
+ delivered = false;
863
+ }
864
+ return {
865
+ valid: delivered,
866
+ score: result.verdict?.score ?? (delivered ? 1 : 0)
867
+ };
868
+ }
869
+ function wrapCompletionGate(inner, check) {
870
+ let gated;
871
+ /**
872
+ * Ask the delivery question once, from whatever the inner executor managed to produce.
873
+ *
874
+ * Fail-closed on the artifact being unavailable: an executor that never produced one delivered
875
+ * nothing, and leaving `gated` unset keeps the existing invalid-by-default reading.
876
+ */
877
+ const settleVerdict = async () => {
878
+ let art;
879
+ try {
880
+ art = inner.resultArtifact();
881
+ } catch {
882
+ return;
883
+ }
884
+ gated = await check(art);
885
+ };
886
+ const gateExecution = (r) => {
887
+ if (isAsyncIterable(r)) return (async function* () {
888
+ try {
889
+ for await (const ev of r) yield ev;
890
+ } finally {
891
+ await settleVerdict();
892
+ }
893
+ })();
894
+ return (async () => {
895
+ let res;
896
+ try {
897
+ res = await r;
898
+ } catch (error) {
899
+ await settleVerdict();
900
+ throw error;
901
+ }
902
+ gated = await check(res);
903
+ return {
904
+ ...res,
905
+ verdict: gated
906
+ };
907
+ })();
908
+ };
909
+ return inheritRuntimeOwnedExecutorAttestation(inner, {
910
+ runtime: inner.runtime,
911
+ ...inner.budgetExempt !== void 0 ? { budgetExempt: inner.budgetExempt } : {},
912
+ ...inner.deliver ? { deliver: (m) => inner.deliver?.(m) } : {},
913
+ ...inner.cancel ? { cancel: (request) => inner.cancel(request) } : {},
914
+ ...inner.interactive ? { interactive: () => inner.interactive() } : {},
915
+ ...inner.interactiveReady ? { interactiveReady: () => inner.interactiveReady() } : {},
916
+ ...inner.progress ? { progress: () => inner.progress?.() } : {},
917
+ ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
918
+ ...inner.metered ? { metered: () => inner.metered?.() } : {},
919
+ ...inner.accounting ? { accounting: () => inner.accounting?.() } : {},
920
+ ...inner.resultAccepted ? { resultAccepted: () => inner.resultAccepted?.() === true } : {},
921
+ ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
922
+ ...inner.harnessTranscriptSettled ? { harnessTranscriptSettled: () => inner.harnessTranscriptSettled?.() ?? Promise.resolve() } : {},
923
+ execute: (task, signal) => gateExecution(inner.execute(task, signal)),
924
+ ...inner.recover ? { recover: (task, signal) => gateExecution(inner.recover(task, signal)) } : {},
925
+ teardown: (grace) => inner.teardown(grace),
926
+ ...teardownSurfaces(inner),
927
+ resultArtifact() {
928
+ const art = inner.resultArtifact();
929
+ return {
930
+ ...art,
931
+ verdict: gated ?? art.verdict
932
+ };
933
+ }
934
+ });
935
+ }
936
+ /**
937
+ * Transform a Runtime executor's terminal artifact without losing its private
938
+ * profile-materialization attestation or altering its measured spend. This is
939
+ * the composition point for deterministic post-processing and grading; callers
940
+ * must not rebuild an Executor around a model transport merely to change `out`.
941
+ */
942
+ function mapExecutorResult(inner, map) {
943
+ let mapped;
944
+ const settle = async (result, task) => {
945
+ const transformed = await map(result, task);
946
+ mapped = {
947
+ outRef: transformed.outRef,
948
+ out: transformed.out,
949
+ ...transformed.verdict ? { verdict: transformed.verdict } : {},
950
+ spent: result.spent
951
+ };
952
+ return mapped;
953
+ };
954
+ const mapExecution = (execution, task) => {
955
+ if (isAsyncIterable(execution)) return (async function* () {
956
+ for await (const event of execution) yield event;
957
+ await settle(inner.resultArtifact(), task);
958
+ })();
959
+ return (async () => settle(await execution, task))();
960
+ };
961
+ return inheritRuntimeOwnedExecutorAttestation(inner, {
962
+ runtime: inner.runtime,
963
+ ...inner.budgetExempt !== void 0 ? { budgetExempt: inner.budgetExempt } : {},
964
+ ...inner.deliver ? { deliver: (message) => inner.deliver?.(message) } : {},
965
+ ...inner.cancel ? { cancel: (request) => inner.cancel(request) } : {},
966
+ ...inner.interactive ? { interactive: () => inner.interactive() } : {},
967
+ ...inner.interactiveReady ? { interactiveReady: () => inner.interactiveReady() } : {},
968
+ ...inner.progress ? { progress: () => inner.progress?.() } : {},
969
+ ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
970
+ ...inner.accounting ? { accounting: () => inner.accounting?.() } : {},
971
+ ...inner.metered ? { metered: () => inner.metered?.() } : {},
972
+ ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
973
+ ...inner.harnessTranscriptSettled ? { harnessTranscriptSettled: () => inner.harnessTranscriptSettled?.() ?? Promise.resolve() } : {},
974
+ execute: (task, signal) => mapExecution(inner.execute(task, signal), task),
975
+ ...inner.recover ? { recover: (task, signal) => mapExecution(inner.recover(task, signal), task) } : {},
976
+ teardown: (grace) => inner.teardown(grace),
977
+ ...teardownSurfaces(inner),
978
+ resultArtifact() {
979
+ if (!mapped) throw new Error("mapExecutorResult: resultArtifact() read before execute()");
980
+ return mapped;
981
+ }
982
+ });
983
+ }
984
+ /**
985
+ * The check could not run: its box did not start, its judge's provider refused, its program
986
+ * crashed. It is not a verdict on the result. Inside a run the loop pauses, as it does for an
987
+ * unavailable upstream, and the refusal tells the director its result was not judged.
988
+ */
989
+ var CheckUnavailableError = class extends Error {
990
+ constructor(message, options) {
991
+ super(message, options);
992
+ this.name = "CheckUnavailableError";
993
+ }
994
+ };
995
+ /**
996
+ * Read an agent-eval `JudgeScore` from a check program into a verdict.
997
+ *
998
+ * Each dimension is a checked item. `notes` lines that start with `FAIL ` are the failures; the
999
+ * remaining lines are the check's review. The verdict passes when `composite >= threshold` and the
1000
+ * score is not marked `failed`; a `failed` score means the judge itself did not run, which is
1001
+ * {@link CheckUnavailableError}, not a verdict.
1002
+ */
1003
+ function verdictFromJudgeScore(score, threshold) {
1004
+ if (score.failed === true) throw new CheckUnavailableError(`the check's judge did not run: ${score.notes}`);
1005
+ const lines = score.notes.split("\n").map((line) => line.trimEnd());
1006
+ const failures = lines.filter((line) => line.startsWith("FAIL "));
1007
+ const review = lines.filter((line) => !line.startsWith("FAIL ") && line.trim() !== "").join("\n");
1008
+ return checkVerdictOf({
1009
+ pass: score.composite >= threshold,
1010
+ items: score.dimensions,
1011
+ composite: score.composite,
1012
+ threshold,
1013
+ failures,
1014
+ ...review === "" ? {} : { review }
1015
+ });
1016
+ }
1017
+ // src/runtime/supervise/coordination-preflight.ts
1018
+ const MAX_RESPONSE_BYTES = 1048576;
1019
+ var CoordinationPreflightError = class extends ConfigError {
1020
+ constructor(reason) {
1021
+ super(`coordination public endpoint preflight failed: ${reason}`);
1022
+ }
1023
+ };
1024
+ /**
1025
+ * The route timed out, lost its socket, or answered 408, 429 or 5xx: it cannot serve now, so a
1026
+ * manager waits for it as for any unavailable upstream. magnetar-rust-sandbox-20261101b's :s2:s2
1027
+ * and :s1:s1 settled down on `timed out` while drew-gtr-pro, which serves the route, ran at load 25.
1028
+ */
1029
+ var CoordinationUnreachableError = class extends Error {
1030
+ name = "CoordinationUnreachableError";
1031
+ };
1032
+ const unreachable = (reason) => new CoordinationUnreachableError(`coordination public endpoint preflight failed: ${reason}`);
1033
+ function record(value) {
1034
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1035
+ }
1036
+ /** Check the operator's route before it becomes a provider attachment. This does not prove cloud egress. */
1037
+ async function preflightPublicCoordination(input) {
1038
+ const deadline = new AbortController();
1039
+ const linked = linkAbort(input.signal, deadline.signal);
1040
+ const timer = setTimeout(() => deadline.abort(), input.requestTimeoutMs);
1041
+ timer.unref();
1042
+ const rpc = async (method, params) => {
1043
+ const response = await fetch(input.url, {
1044
+ method: "POST",
1045
+ headers: {
1046
+ ...input.headers,
1047
+ "content-type": "application/json",
1048
+ accept: "application/json"
1049
+ },
1050
+ body: JSON.stringify({
1051
+ jsonrpc: "2.0",
1052
+ id: method,
1053
+ method,
1054
+ ...params ? { params } : {}
1055
+ }),
1056
+ redirect: "manual",
1057
+ signal: linked.signal
1058
+ });
1059
+ if (response.status !== 200) {
1060
+ response.body?.cancel().catch(() => void 0);
1061
+ const { status } = response;
1062
+ if (status === 408 || status === 429 || status >= 500) throw unreachable(`HTTP ${status}`);
1063
+ throw new CoordinationPreflightError(`HTTP ${status}`);
1064
+ }
1065
+ const reader = response.body?.getReader();
1066
+ if (!reader) throw new CoordinationPreflightError("invalid MCP response");
1067
+ let size = 0;
1068
+ const chunks = [];
1069
+ try {
1070
+ for (;;) {
1071
+ const part = await reader.read();
1072
+ if (part.done) break;
1073
+ size += part.value.byteLength;
1074
+ if (size > MAX_RESPONSE_BYTES) {
1075
+ reader.cancel().catch(() => void 0);
1076
+ throw new CoordinationPreflightError("response too large");
1077
+ }
1078
+ chunks.push(part.value);
1079
+ }
1080
+ } finally {
1081
+ reader.releaseLock();
1082
+ }
1083
+ let body;
1084
+ try {
1085
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
1086
+ } catch {
1087
+ throw new CoordinationPreflightError("invalid MCP response");
1088
+ }
1089
+ if (!record(body) || body.jsonrpc !== "2.0" || body.id !== method || body.error || !record(body.result)) throw new CoordinationPreflightError("invalid MCP response");
1090
+ return body.result;
1091
+ };
1092
+ try {
1093
+ await runAbortable(async () => {
1094
+ const initialized = await rpc("initialize", {
1095
+ protocolVersion: PROTOCOL_VERSION,
1096
+ capabilities: {},
1097
+ clientInfo: {
1098
+ name: "agent-runtime-coordination-preflight",
1099
+ version: "1"
1100
+ }
1101
+ });
1102
+ if (initialized.protocolVersion !== "2024-11-05" || !record(initialized.serverInfo) || initialized.serverInfo.name !== "coordination" || !record(initialized.capabilities) || !record(initialized.capabilities.tools)) throw new CoordinationPreflightError("invalid MCP initialization");
1103
+ const listing = await rpc("tools/list");
1104
+ if (!Array.isArray(listing.tools) || listing.tools.some((tool) => !record(tool) || typeof tool.name !== "string")) throw new CoordinationPreflightError("invalid MCP tool list");
1105
+ const names = listing.tools.map((tool) => tool.name).sort();
1106
+ if (JSON.stringify(names) !== JSON.stringify([...input.toolNames].sort())) throw new CoordinationPreflightError("coordination tool grants differ");
1107
+ }, linked.signal, "coordination public endpoint preflight cancelled");
1108
+ } catch (error) {
1109
+ if (input.signal.aborted) throw new CoordinationPreflightError("cancelled");
1110
+ if (deadline.signal.aborted) throw unreachable("timed out");
1111
+ if (error instanceof CoordinationPreflightError) throw error;
1112
+ if (error instanceof CoordinationUnreachableError) throw error;
1113
+ if (causeChain(error).some((cause) => TRANSPORT_ERROR_CODES.has(String(Object(cause).code)))) throw unreachable("transport unavailable");
1114
+ throw new CoordinationPreflightError("transport unavailable");
1115
+ } finally {
1116
+ clearTimeout(timer);
1117
+ linked.release();
1118
+ }
1119
+ }
809
1120
  // src/runtime/supervise/retained-owner-evidence.ts
810
1121
  /** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */
811
1122
  /** One grouping for release and the evidence gate before another owner invocation. */
@@ -1339,6 +1650,285 @@ function checkedSeatSelection(stage, selected) {
1339
1650
  if (selected.backend.backend !== "provider") throw new ValidationError("selectSeat: selection must use a provider backend");
1340
1651
  return selected;
1341
1652
  }
1653
+ // src/runtime/supervise/driver-attempt-evidence.ts
1654
+ /** Sandbox's `PartialFailureError` on `error` or a cause, read by name: packages that hold their own
1655
+ * copy of the class would miss an `instanceof`. */
1656
+ const causedByPartialFailure = (error) => causeChain(error).some((cause) => cause instanceof Error && errorProperty(cause, "name") === "PartialFailureError");
1657
+ /**
1658
+ * Abandon only `unobservable` or `nested-recovery`, or a spent create key. Transport and capacity
1659
+ * stay; a refused request and a contract violation do not start a second execution.
1660
+ */
1661
+ function abandonablePending(error) {
1662
+ return error instanceof RetainedExecutionPendingError && (error.pendingCause === "unobservable" || error.pendingCause === "nested-recovery" || spentCreateKey(error)) ? error : void 0;
1663
+ }
1664
+ /**
1665
+ * Sandbox refused this invocation's create key because no box exists for it, nor ever will
1666
+ * ({@link isSpentCreateKeyRefusal}). Nothing ran, and only the key is refused: a new invocation,
1667
+ * under a new key, is not. claim-designated-summands-20261116a (spawn journal rows 145-153)
1668
+ * replayed a key whose box the provider had deleted and settled failed on the refusal.
1669
+ */
1670
+ function spentCreateKey(error) {
1671
+ return error instanceof RetainedExecutionPendingError && error.phase === "admission" && error.pendingCause === "request-rejected" && causeChain(error.cause).some(isSpentCreateKeyRefusal);
1672
+ }
1673
+ /** Deterministic bridge refusals remain terminal even when transport omits HTTP status. */
1674
+ const DETERMINISTIC_BRIDGE_CODES = /* @__PURE__ */ new Set([
1675
+ "parse_error",
1676
+ "not_configured",
1677
+ "capability_denied",
1678
+ "MODEL_NOT_FOUND",
1679
+ "SEAT_NOT_LOGGED_IN"
1680
+ ]);
1681
+ /** Content-filter text under `AGENT_EXECUTION_FAILED` stays transient; a streak of it stops for the parent to reword. */
1682
+ const CONTENT_FILTER_REASON = "refused by the model provider's content filter";
1683
+ const isContentFilterRefusal = (error) => causeChain(error).some((cause) => cause instanceof Error && /\bcontent was flagged for possible\b/iu.test(errorProperty(cause, "message") ?? ""));
1684
+ /** A completed failed turn enters retry with its producer classification and legacy metadata intact. */
1685
+ var HarnessTurnFailedError = class extends Error {
1686
+ runtime;
1687
+ /** The failure as the harness reported it, before this error's framing. */
1688
+ reported;
1689
+ errorCode;
1690
+ statusCode;
1691
+ /** The shared HTTP error reader also uses this status for persisted diagnostics. */
1692
+ status;
1693
+ failure;
1694
+ /** The producer's quota reset, which `reportedResetAt` holds a capacity pause to. */
1695
+ resetAt;
1696
+ constructor(runtime, failure) {
1697
+ super(`${runtime} harness turn ended with a failed outcome` + (failure.errorCode === void 0 ? "" : ` (${failure.errorCode})`) + `: ${failure.error}`);
1698
+ this.name = "HarnessTurnFailedError";
1699
+ this.runtime = runtime;
1700
+ this.reported = failure.error;
1701
+ if (failure.failure !== void 0) this.failure = failure.failure;
1702
+ if (failure.errorCode !== void 0) this.errorCode = failure.errorCode;
1703
+ if (failure.resetAt !== void 0) this.resetAt = failure.resetAt;
1704
+ if (failure.statusCode !== void 0) {
1705
+ this.statusCode = failure.statusCode;
1706
+ this.status = failure.statusCode;
1707
+ }
1708
+ }
1709
+ };
1710
+ /** Provider schemas and JSON bounds reject the request deterministically. */
1711
+ function isProviderSchemaRejection(error) {
1712
+ try {
1713
+ return error.name === "ValidationError" || isSchemaRejection(error);
1714
+ } catch {
1715
+ return false;
1716
+ }
1717
+ }
1718
+ /** Sandbox started nothing for the dispatch: another execution owns the session or turn. */
1719
+ function isDispatchNotAdmitted(error) {
1720
+ try {
1721
+ return Reflect.get(error, "code") === DISPATCH_NOT_ADMITTED_CODE;
1722
+ } catch {
1723
+ return false;
1724
+ }
1725
+ }
1726
+ /** Sandbox confirmed the dispatch but named a different execution: deterministic on every retry. */
1727
+ function isDispatchExecutionChanged(value) {
1728
+ try {
1729
+ return Reflect.get(value, "code") === DISPATCH_EXECUTION_CHANGED_CODE;
1730
+ } catch {
1731
+ return false;
1732
+ }
1733
+ }
1734
+ /** Read Runtime admission evidence before producer hints and legacy transport metadata. */
1735
+ function upstreamUnavailableSignal(error) {
1736
+ if (undispatchedCredentialExit(error) !== void 0) return "credential-unavailable";
1737
+ if (error instanceof CheckUnavailableError) return "check-unavailable";
1738
+ if (error instanceof CoordinationUnreachableError) return "coordination-unreachable";
1739
+ const typed = turnFailureOf(error);
1740
+ if (typed) return turnFailurePolicy(typed).classification === "unavailable" ? subscriptionUsageLimitSignal({
1741
+ error: "",
1742
+ errorCode: typed.code
1743
+ }) ?? typed.code : void 0;
1744
+ const refusal = retainedAdmissionCause(error) ?? reconciliationCapacityRefusal(error);
1745
+ if (refusal !== void 0) return upstreamUnavailableSignal(refusal);
1746
+ if (!(error instanceof Error)) return void 0;
1747
+ if (isCredentialRefusal(error)) return void 0;
1748
+ if (isProviderSchemaRejection(error)) return void 0;
1749
+ const transport = error instanceof BackendTransportError;
1750
+ if (error instanceof AgentEvalError$1 && !transport) return void 0;
1751
+ const harness = error instanceof HarnessTurnFailedError;
1752
+ const failure = {
1753
+ error: errorProperty(error, "message") ?? "",
1754
+ errorCode: harness ? error.errorCode : transport ? error.upstreamCode : ownCode(error),
1755
+ statusCode: errorHttpStatus(error)
1756
+ };
1757
+ return (harness ? subscriptionUsageLimitSignal(failure) : void 0) ?? unavailableSignalOfFailure(failure);
1758
+ }
1759
+ function materializationTimedOut(error) {
1760
+ return causeChain(error).some((cause) => cause instanceof Error && errorProperty(cause, "name") === "RetainedMaterializationTimeoutError");
1761
+ }
1762
+ /** Capacity encountered while reconciling an admitted execution pauses that same execution. */
1763
+ function reconciliationCapacityRefusal(error) {
1764
+ if (!(error instanceof RetainedExecutionPendingError) || error.phase !== "execution") return void 0;
1765
+ if (error.pendingCause !== "unobservable" && error.pendingCause !== "transport") return void 0;
1766
+ return causeChain(error.cause).find((cause) => cause instanceof Error && (UNAVAILABLE_CODES.has(ownCode(cause)?.toLowerCase() ?? "") || errorHttpStatus(cause) === 429));
1767
+ }
1768
+ /** An error's own `code` field, read without trusting its getter: agent-provider-tangle's
1769
+ * `TangleCredentialCapacityError` carries the router's code even with no HTTP status. */
1770
+ function ownCode(error) {
1771
+ try {
1772
+ const code = Reflect.get(error, "code");
1773
+ return typeof code === "string" ? code : void 0;
1774
+ } catch {
1775
+ return;
1776
+ }
1777
+ }
1778
+ /** Runtime cancellation/contracts dominate producer policy; untyped foreign failures retain legacy rules. */
1779
+ function classifyDriverFailure(error, signal, stopSignal) {
1780
+ if (signal?.aborted) return "terminal";
1781
+ if (materializationTimedOut(error)) return "terminal";
1782
+ if (error instanceof CheckUnavailableError || error instanceof CoordinationUnreachableError) return "unavailable";
1783
+ if (error instanceof RetainedExecutionPendingError && (error.pendingCause === "provider-contract" || causeChain(error.cause).some((cause) => {
1784
+ try {
1785
+ return cause instanceof Error && !UNAVAILABLE_CODES.has(ownCode(cause)?.toLowerCase() ?? "") && (Reflect.get(cause, "retryable") === false || [401, 403].includes(errorHttpStatus(cause) ?? 0));
1786
+ } catch {
1787
+ return false;
1788
+ }
1789
+ }))) return "terminal";
1790
+ if (undispatchedCredentialExit(error) !== void 0) return "unavailable";
1791
+ const admission = retainedAdmissionCause(error);
1792
+ if (admission !== void 0 && isDispatchNotAdmitted(admission)) return "terminal";
1793
+ if (causeChain(error).some(isDispatchExecutionChanged)) return "terminal";
1794
+ if (admission !== void 0) return classifyDriverFailure(admission, signal, stopSignal);
1795
+ if (error instanceof Error && errorProperty(error, "name") === "AbortError") return stopSignal?.aborted === true ? "terminal" : "transient";
1796
+ if (error instanceof Error && isProviderSchemaRejection(error)) return "terminal";
1797
+ if (isCredentialRefusal(error)) return "terminal";
1798
+ if (causeChain(error).some(isProvisioningRefusal)) return "terminal";
1799
+ if (error instanceof AgentEvalError$1 && !(error instanceof BackendTransportError)) return "terminal";
1800
+ const typed = turnFailureOf(error);
1801
+ if (typed) return turnFailurePolicy(typed).classification;
1802
+ if (error instanceof HarnessTurnFailedError) {
1803
+ if (error.errorCode !== void 0 && DETERMINISTIC_BRIDGE_CODES.has(error.errorCode)) return "terminal";
1804
+ if (upstreamUnavailableSignal(error) !== void 0) return "unavailable";
1805
+ return foreignHttpStatusVerdict(error) ?? "transient";
1806
+ }
1807
+ if (error instanceof BackendTransportError) {
1808
+ if (error.upstreamCode !== void 0 && DETERMINISTIC_BRIDGE_CODES.has(error.upstreamCode)) return "terminal";
1809
+ if (upstreamUnavailableSignal(error) !== void 0) return "unavailable";
1810
+ const status = error.status;
1811
+ return status === void 0 || status === 408 || status >= 500 ? "transient" : "terminal";
1812
+ }
1813
+ if (upstreamUnavailableSignal(error) !== void 0) return "unavailable";
1814
+ return foreignHttpStatusVerdict(error) ?? "transient";
1815
+ }
1816
+ /** The credential command's exit code when it failed before Runtime journaled a dispatch: no
1817
+ * provider execution id exists, so nothing ran ({@link credentialCommandExit}). */
1818
+ function undispatchedCredentialExit(error) {
1819
+ return error instanceof RetainedExecutionPendingError && error.phase === "admission" && error.pendingCause === "unobservable" ? credentialCommandExit(error.cause) : void 0;
1820
+ }
1821
+ /** Admission refusals keep the original HTTP rules without interpreting failures after execution starts. */
1822
+ function retainedAdmissionCause(error) {
1823
+ if (!(error instanceof RetainedExecutionPendingError) || error.phase !== "admission" || error.pendingCause !== "request-rejected" && error.pendingCause !== "transport") return void 0;
1824
+ const queue = [];
1825
+ try {
1826
+ queue.push(error.cause);
1827
+ } catch {
1828
+ return;
1829
+ }
1830
+ const seen = /* @__PURE__ */ new Set();
1831
+ for (let steps = 0; queue.length > 0 && steps < 12; steps += 1) {
1832
+ const value = queue.shift();
1833
+ try {
1834
+ if (!(value instanceof Error) || seen.has(value)) continue;
1835
+ seen.add(value);
1836
+ if (value instanceof RetainedExecutionPendingError) {
1837
+ if (value.phase !== "admission" || value.pendingCause !== "request-rejected" && value.pendingCause !== "transport") return void 0;
1838
+ queue.push(value.cause);
1839
+ continue;
1840
+ }
1841
+ if (errorProperty(value, "name") === "RetainedRunProviderContractError") return void 0;
1842
+ const status = errorHttpStatus(value);
1843
+ if (status !== void 0 && status >= 400) return error.pendingCause === "request-rejected" || UNAVAILABLE_STATUSES.has(status) ? value : void 0;
1844
+ if (error.pendingCause === "request-rejected" && (value instanceof AgentEvalError$1 || isProviderSchemaRejection(value) || isDispatchNotAdmitted(value) || isCredentialRefusal(value) || UNAVAILABLE_CODES.has(ownCode(value)?.toLowerCase() ?? ""))) return value;
1845
+ const members = Reflect.get(value, "errors");
1846
+ if (Array.isArray(members)) queue.push(...members.slice(0, 12 - steps));
1847
+ queue.push(value.cause);
1848
+ } catch {
1849
+ return;
1850
+ }
1851
+ }
1852
+ }
1853
+ /** 408 and 5xx are transient. Any other 4xx fails identically, including a sandbox `CONFIG_ERROR`. Capacity was already classified. */
1854
+ function foreignHttpStatusVerdict(error) {
1855
+ if (!(error instanceof Error)) return void 0;
1856
+ const status = errorHttpStatus(error);
1857
+ if (status === void 0 || status < 400) return void 0;
1858
+ if (status === 408 || status >= 500) return "transient";
1859
+ return "terminal";
1860
+ }
1861
+ /** Transport errno codes and undici codes: the connection, not the request, failed. */
1862
+ const TRANSPORT_CODES = /* @__PURE__ */ new Set([
1863
+ "ECONNRESET",
1864
+ "ECONNREFUSED",
1865
+ "ECONNABORTED",
1866
+ "ETIMEDOUT",
1867
+ "EPIPE",
1868
+ "EAI_AGAIN",
1869
+ "ENETUNREACH",
1870
+ "EHOSTUNREACH"
1871
+ ]);
1872
+ const TRANSPORT_NAMES = /* @__PURE__ */ new Set([
1873
+ "TimeoutError",
1874
+ "NetworkError",
1875
+ "AbortError",
1876
+ "RetainedStreamError"
1877
+ ]);
1878
+ /** Producer infra earns the outage window; producer work earns only the bounded deterministic streak. */
1879
+ function transientFailureKind(error) {
1880
+ const typed = turnFailureOf(error);
1881
+ if (typed) return turnFailurePolicy(typed).failureKind;
1882
+ if (causedByPartialFailure(error)) return "deterministic";
1883
+ return causeChain(error).some((cause) => {
1884
+ if (!(cause instanceof Error)) return false;
1885
+ if (cause instanceof HarnessTurnFailedError && executorFailureInfra({
1886
+ error: cause.reported,
1887
+ ...cause.errorCode === void 0 ? {} : { errorCode: cause.errorCode }
1888
+ })) return true;
1889
+ const status = cause instanceof HarnessTurnFailedError ? cause.statusCode ?? printedStatus(cause.message) : errorHttpStatus(cause);
1890
+ const code = ownCode(cause) ?? "";
1891
+ return status !== void 0 && (status === 408 || status >= 500) || TRANSPORT_CODES.has(code) || code.startsWith("UND_ERR_") || cause instanceof BackendTransportError || TRANSPORT_NAMES.has(errorProperty(cause, "name") ?? "");
1892
+ }) ? "infra" : "deterministic";
1893
+ }
1894
+ /** The error a give-up throws: the original cause, re-described with the attempt history so
1895
+ * `driver-failed` carries a diagnosable message instead of one backend's last words. */
1896
+ var DriverAttemptsExhaustedError = class extends RuntimeRunStateError {
1897
+ attempts;
1898
+ stop;
1899
+ constructor(cause, attempts, stop) {
1900
+ const last = attempts[attempts.length - 1];
1901
+ const causeText = cause instanceof Error ? `${errorProperty(cause, "name")}: ${errMessage(cause)}` : errMessage(cause);
1902
+ const firstFailure = attempts.find((attempt) => attempt.error !== void 0)?.error;
1903
+ const pauses = attempts.filter((attempt) => attempt.classification === "unavailable");
1904
+ const pausedMs = pauses.reduce((sum, attempt) => sum + (attempt.retryInMs ?? 0), 0);
1905
+ super(`supervisor driver failed after ${attempts.length} attempt(s) — stopped by ${stop}` + (stop === "repeated-failure" && isContentFilterRefusal(cause) ? `: ${CONTENT_FILTER_REASON}; ` : "; ") + (pauses.length === 0 ? "" : `${pauses.length} attempt(s) met an unavailable upstream and paused ${Math.round(pausedMs / 1e3)} s in total; `) + (firstFailure !== void 0 && firstFailure !== last?.error ? `first failure: ${errorText(firstFailure)}; ` : "") + `last cause: ${causeText}` + (last?.classification ? ` (classified ${last.classification})` : ""), { cause });
1906
+ this.attempts = Object.freeze([...attempts]);
1907
+ this.stop = stop;
1908
+ }
1909
+ };
1910
+ /** Count a loop's attempt records into its {@link DriverLoopRecord}. */
1911
+ function summarizeDriverAttempts(records) {
1912
+ let barren = 0;
1913
+ for (const record of records) if (record.madeProgress) barren = 0;
1914
+ else if (record.beforeModelEvent !== true && record.error === void 0 && record.reentry !== void 0 && record.reentry !== "wake" && record.contract === "unmet") barren += 1;
1915
+ const last = records.at(-1);
1916
+ const stopPauses = records.filter((record) => record.replacesStop !== void 0);
1917
+ const refused = records.filter((record) => record.classification === "unavailable" && record.replacesStop === void 0);
1918
+ return {
1919
+ attempts: new Set(records.map((record) => record.attempt)).size,
1920
+ reprompts: records.filter((record) => record.reprompted === true).length,
1921
+ failureRetries: records.filter((record) => record.error !== void 0 && record.retryInMs !== void 0 && record.classification !== "unavailable" && record.replacesStop === void 0).length,
1922
+ stopPauses: stopPauses.length,
1923
+ unavailablePauses: refused.filter((record) => record.retryInMs !== void 0).length,
1924
+ unavailableMs: refused.reduce((sum, record) => sum + (record.madeProgress ? 0 : record.durationMs) + (record.retryInMs ?? 0), 0),
1925
+ barrenReentries: barren,
1926
+ wakes: records.filter((record) => record.reentry === "wake").length,
1927
+ waitedMs: records.reduce((sum, record) => sum + (record.waitedMs ?? 0), 0),
1928
+ ended: last?.stop ?? "unrecorded",
1929
+ ...last?.repromptRefusedBy === void 0 ? {} : { repromptRefusedBy: last.repromptRefusedBy }
1930
+ };
1931
+ }
1342
1932
  // src/runtime/supervise/node-status.ts
1343
1933
  /** Which {@link NodeStatus} values mean the node is finished. */
1344
1934
  const terminalNodeStatuses = /* @__PURE__ */ new Set([
@@ -7032,7 +7622,9 @@ async function abandonScopeRetainedOwnerInvocation(scope, failure, failures) {
7032
7622
  now: args.now
7033
7623
  });
7034
7624
  scope.signal.throwIfAborted();
7035
- if (!(stop?.effect === "cancelled" || stop?.effect === "not_live")) return false;
7625
+ const stopped = stop?.effect === "cancelled" || stop?.effect === "not_live";
7626
+ const keySpent = dispatched === void 0 && spentCreateKey(failure);
7627
+ if (!stopped && !keySpent) return false;
7036
7628
  await args.journal.appendEvent(args.rootId, {
7037
7629
  kind: "execution-abandoned",
7038
7630
  id: args.nodeId,
@@ -14303,6 +14895,6 @@ function unknownChannels(spend) {
14303
14895
  function isNonEmptySpend(s) {
14304
14896
  return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false || Object.values(s.resources ?? {}).some((resource) => resource.amount > 0 || !resource.known);
14305
14897
  }
14306
- export { appendTeardownConfirmation as $, generateSpanId as $n, runtimeOwnedScopeOwnerRuntime as $r, reconcileScopeRetainedOwnerEnvironment as $t, workerSteerRequestsDir as A, startRetainedRunInEnvironment as An, attestRuntimeOwnedDeferredExecutor as Ar, RELEASE_DESTROY_MS as At, isTraceAnalysisStore as B, environmentGone as Bn, newExecutionAttemptId as Br, recordScopeOwnerHarnessTranscript as Bt, readWorkerSteerRequests as C, verifyWorkspaceMarker as Cn, isTerminalNodeStatus as Cr, unconfirmedTeardowns as Ct, workerCancelRequestsFile as D, reconnectRetainedRun as Dn, authoredSeatStages as Dr, scopeRetainedOwnerResourceReader as Dt, supervisorRunsRoot as E, mintRetainedIdentity as En, SeatPauseError as Er, releaseScopeRetainedOwnerForSeatPause as Et, createWorkerSlots as F, FileObserverJournal as Fn, authoredProfileDigest as Fr, scopeRetainedOwnerResult as Ft, attachWorker as G, mergeTraceEnv as Gn, recordRuntimeOwnedProviderIdentityConflict as Gr, coordinationMcpAlias as Gt, workerTraceAnalysisStore as H, workerTraceEnv as Hn, recordRuntimeOwnedDriveHarnessProviderEvidence as Hr, restoreScopeOwnerAcceptedExecution as Ht, openSlotGroup as I, createFileObserverHooks as In, finalizeRuntimeOwnedPendingExecutor as Ir, beginScopeOwnerAttempt as It, recoverRetainedInteractiveRun as J, buildLoopSpanNodes as Jn, runtimeOwnedExecutorExecutionBinding as Jr, runtimeGraphMetadataKey as Jt, readWorkerInteractiveBinding as K, readTraceContextFromEnv as Kn, recordRuntimeOwnedProviderModel as Kr, coordinationProfileToolPrefix as Kt, resolveWorkerSlots as L, observerRecordDigest as Ln, inheritRuntimeOwnedExecutorAttestation as Lr, finalizeScopeOwnerMaterialization as Lt, writeWorkerSteer as M, acceptedInteractiveControl as Mn, attestRuntimeOwnedPendingExecutor as Mr, consumeScopeRetainedOwnerResult as Mt, writeWorkerSteerAcknowledgement as N, offerInteractiveControl as Nn, attestRuntimeOwnedScopeOwner as Nr, prepareScopeRetainedOwnerTask as Nt, workerCancellationsDir as O, recoverRetainedRun as On, seatExecutionProfile as Or, environmentReader as Ot, writeWorkerSteerAsync as P, prepareInteractiveDelegation as Pn, authoredAgentIdentity as Pr, scopeRetainedOwnerPriorSpend as Pt, spawnJournalRecordEvents as Q, flatOtelSpan as Qn, runtimeOwnedScopeOwnerControl as Qr, assertRetainedOwnerCoordinationRekey as Qt, prepareScopeResume as R, verifyObserverRecords as Rn, knownExecutionBindingReceipt as Rr, holdScopeOwnerTranscript as Rt, readWorkerSteerAcknowledgement as S, stopRetainedNativeExecution as Sn, isLiveNodeStatus as Sr, startScopeRecoveries as St, supervisorRunDir as T, assertRetainedRunReplayMaterial as Tn, SeatChain as Tr, prepareScopeRetainedOwnerSeatSwitch as Tt, nestedScopeSeamKey as U, workerTraceHeaders as Un, recordRuntimeOwnedProviderAttemptStart as Ur, scopeOwnerExecutionObservation as Ut, parseWorkerToolTraceArtifact as V, WORKER_TRACE_PROPAGATION as Vn, providerAttemptEvidence as Vr, recordScopeOwnerMaterialization as Vt, interactiveAdmissionSeamKey as W, createPropagatingTraceEmitter as Wn, recordRuntimeOwnedProviderDispatchNotStarted as Wr, scopeOwnerExecutorNodeContext as Wt, FileSpawnJournal as X, createOpenInferenceFileExporter as Xn, runtimeOwnedExecutorProviderEvidence as Xr, scopeRetainedOwnerSettled as Xt, startRetainedInteractiveRun as Y, buildRuntimeEventOtelSpans as Yn, runtimeOwnedExecutorMaterialization as Yr, beginScopeRetainedOwnerDrive as Yt, appendSpawnEvents as Z, createOtelExporter as Zn, runtimeOwnedPendingExecutorMaterialization as Zr, scopeRetainedOwnerTurnEnded as Zt, fileEscalateQuestion as _, providerMessageText as _i, executorObservation as _n, retainHarnessTranscript as _r, registerNestedTeardownScope as _t, closeStreamFile as a, runtimeCheckFactory as ai, owners as an, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as ar, queueOf as at, readWorkerCancelRequests as b, NATIVE_STOP_UNCONFIRMED as bn, describeToolArgs as br, retryUnconfirmedTeardowns as bt, openStreamFileFenced as c, RetainedRunProviderContractError as ci, scopeRetainedOwnerJournalRoot as cn, harnessTranscriptArtifact as cr, closeRetainedSlots as ct, syncStreamFileFenced as d, exactSession as di, materializeTreeView as dn, persistHarnessTranscript as dr, meterRuntimeOwnedAccounting as dt, unknownExecutionBindingReceipt as ei, scopeRetainedOwnerRestorePoint as en, loopEventToOtelSpan as er, reenteredWorkers as et, writeStreamLinesFenced as f, freezeControlRef as fi, attestNestedDriverTreeOwner as fn, readHarnessTranscript as fr, meterRuntimeOwnedProviderAttempt as ft, claimWorkerSteerDelivery as g, promptOptionsFromAgentTurnInput as gi, insideCursorNamespace as gn, resolveHarnessTranscriptCapture as gr, recordScopeOwnerPause as gt, cancelWorker as h, promptFromAgentTurnInput as hi, SpawnEventIndex as hn, readBoundHarnessSessions$1 as hr, recordScopeOwnerDriverAttempt as ht, ROOT_STREAM_FILE as i, isRuntimeFlowBrain as ii, bindScopeRetainedOwnerProvider as in, sanitizeRuntimeStreamEvent as ir, freeSlots as it, writeWorkerCancellation as j, retainedCreateMaterial as jn, attestRuntimeOwnedExecutor as jr, abandonScopeRetainedOwnerInvocation as jt, workerInboxFileFromEventDir as k, startRetainedRun as kn, subscriptionUsageLimitSignal as kr, resolveSpawnResourcePaths as kt, readRootStream as l, assertEventBinding as li, loadSpawnForest as ln, harnessTranscriptFromLines as lr, closeScopeAdmission as lt, appendWorkerControlEventAsync as m, sameControlCoordinates as mi, nestedDriverTreeRoot as mn, HARNESS_TRANSCRIPT_READ_LIMITS as mr, recordScopeOwnerBarrenPause as mt, terminalAccounting as n, executableAgentProfileSnapshot as ni, scopeRetainedOwnerCheckpointing as nn, createRuntimeStreamEventCollector as nr, assertRecursiveReservationPolicy as nt, createRootStreamSink as o, runtimeFlowAgent as oi, scopeOwnerLiabilities as on, captureBoundHarnessTranscript as or, rollingDispatch as ot, appendWorkerControlEvent as p, retainedSessionReplaced as pi, driverRuntime as pn, settleHarnessTranscript as pr, pauseScopeSeatAdmission as pt, reconnectRetainedInteractiveRun as q, buildLoopOtelSpans as qn, runtimeOwnedDriveHarnessProviderEvidence as qr, providerVisibleProfile as qt, createScope as r, executableAgentSpecSnapshot as ri, bindScopeRetainedOwnerEnvironmentId as rn, sanitizeKnowledgeReadinessReport as rr, deriveNodeExecutionIdentity as rt, nodeStreamFile as s, runtimeFlowBrain as si, scopeRetainedOwnerContext as sn, captureHarnessTranscript as sr, boundRetainedReleases as st, isNonEmptySpend as t, unknownMaterializationReceipt as ti, noteScopeRetainedOwnerCoordination as tn, createRuntimeEventCollector as tr, settledToIteration as tt, readRootStreamReceipt as u, awaitAbortable$1 as ui, ownedTreeRootSpawn as un, harnessTranscriptUnavailable as ur, hasRetriableTeardowns as ut, legacySupervisorRunDir as v, executorObservationSeamKey as vn, DEFAULT_STALL_AFTER_MS as vr, releaseHeldEnvironments as vt, safeWorkerFile as w, RetainedMaterializationTimeoutError as wn, SEAT_RECHECK_MS as wr, waitForScopeChildren as wt, readWorkerCancellation as x, describeRetainedNativeStops as xn, readWorkerProgress as xr, settleManagerWork as xt, legacySupervisorRunsRoot as y, observeModelRequest as yn, createActivityLog as yr, releaseRetainedEnvironments as yt, replaySpawnTree as z, destroyInteractiveEnvironment as zn, knownMaterializationReceipt as zr, noteScopeOwnerPlannedExecution as zt };
14898
+ export { appendTeardownConfirmation as $, generateSpanId as $n, knownExecutionBindingReceipt as $r, reconcileScopeRetainedOwnerEnvironment as $t, workerSteerRequestsDir as A, promptFromAgentTurnInput as Ai, startRetainedRunInEnvironment as An, transientFailureKind as Ar, RELEASE_DESTROY_MS as At, isTraceAnalysisStore as B, environmentGone as Bn, CheckUnavailableError as Br, recordScopeOwnerHarnessTranscript as Bt, readWorkerSteerRequests as C, RetainedRunProviderContractError as Ci, verifyWorkspaceMarker as Cn, isTerminalNodeStatus as Cr, unconfirmedTeardowns as Ct, workerCancelRequestsFile as D, freezeControlRef as Di, reconnectRetainedRun as Dn, classifyDriverFailure as Dr, scopeRetainedOwnerResourceReader as Dt, supervisorRunsRoot as E, exactSession as Ei, mintRetainedIdentity as En, abandonablePending as Er, releaseScopeRetainedOwnerForSeatPause as Et, createWorkerSlots as F, FileObserverJournal as Fn, SeatPauseError as Fr, scopeRetainedOwnerResult as Ft, attachWorker as G, mergeTraceEnv as Gn, attestRuntimeOwnedDeferredExecutor as Gr, coordinationMcpAlias as Gt, workerTraceAnalysisStore as H, workerTraceEnv as Hn, gateOnDeliverable as Hr, restoreScopeOwnerAcceptedExecution as Ht, openSlotGroup as I, createFileObserverHooks as In, authoredSeatStages as Ir, beginScopeOwnerAttempt as It, recoverRetainedInteractiveRun as J, buildLoopSpanNodes as Jn, attestRuntimeOwnedScopeOwner as Jr, runtimeGraphMetadataKey as Jt, readWorkerInteractiveBinding as K, readTraceContextFromEnv as Kn, attestRuntimeOwnedExecutor as Kr, coordinationProfileToolPrefix as Kt, resolveWorkerSlots as L, observerRecordDigest as Ln, seatExecutionProfile as Lr, finalizeScopeOwnerMaterialization as Lt, writeWorkerSteer as M, providerMessageText as Mi, acceptedInteractiveControl as Mn, upstreamUnavailableSignal as Mr, consumeScopeRetainedOwnerResult as Mt, writeWorkerSteerAcknowledgement as N, offerInteractiveControl as Nn, SEAT_RECHECK_MS as Nr, prepareScopeRetainedOwnerTask as Nt, workerCancellationsDir as O, retainedSessionReplaced as Oi, recoverRetainedRun as On, spentCreateKey as Or, environmentReader as Ot, writeWorkerSteerAsync as P, prepareInteractiveDelegation as Pn, SeatChain as Pr, scopeRetainedOwnerPriorSpend as Pt, spawnJournalRecordEvents as Q, flatOtelSpan as Qn, inheritRuntimeOwnedExecutorAttestation as Qr, assertRetainedOwnerCoordinationRekey as Qt, prepareScopeResume as R, verifyObserverRecords as Rn, subscriptionUsageLimitSignal as Rr, holdScopeOwnerTranscript as Rt, readWorkerSteerAcknowledgement as S, runtimeFlowBrain as Si, stopRetainedNativeExecution as Sn, isLiveNodeStatus as Sr, startScopeRecoveries as St, supervisorRunDir as T, awaitAbortable$1 as Ti, assertRetainedRunReplayMaterial as Tn, HarnessTurnFailedError as Tr, prepareScopeRetainedOwnerSeatSwitch as Tt, nestedScopeSeamKey as U, workerTraceHeaders as Un, mapExecutorResult as Ur, scopeOwnerExecutionObservation as Ut, parseWorkerToolTraceArtifact as V, WORKER_TRACE_PROPAGATION as Vn, gateFactoryOnDeliverable as Vr, recordScopeOwnerMaterialization as Vt, interactiveAdmissionSeamKey as W, createPropagatingTraceEmitter as Wn, verdictFromJudgeScore as Wr, scopeOwnerExecutorNodeContext as Wt, FileSpawnJournal as X, createOpenInferenceFileExporter as Xn, authoredProfileDigest as Xr, scopeRetainedOwnerSettled as Xt, startRetainedInteractiveRun as Y, buildRuntimeEventOtelSpans as Yn, authoredAgentIdentity as Yr, beginScopeRetainedOwnerDrive as Yt, appendSpawnEvents as Z, createOtelExporter as Zn, finalizeRuntimeOwnedPendingExecutor as Zr, scopeRetainedOwnerTurnEnded as Zt, fileEscalateQuestion as _, executableAgentProfileSnapshot as _i, executorObservation as _n, retainHarnessTranscript as _r, registerNestedTeardownScope as _t, closeStreamFile as a, recordRuntimeOwnedProviderDispatchNotStarted as ai, owners as an, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as ar, queueOf as at, readWorkerCancelRequests as b, runtimeCheckFactory as bi, NATIVE_STOP_UNCONFIRMED as bn, describeToolArgs as br, retryUnconfirmedTeardowns as bt, openStreamFileFenced as c, runtimeOwnedDriveHarnessProviderEvidence as ci, scopeRetainedOwnerJournalRoot as cn, harnessTranscriptArtifact as cr, closeRetainedSlots as ct, syncStreamFileFenced as d, runtimeOwnedExecutorProviderEvidence as di, materializeTreeView as dn, persistHarnessTranscript as dr, meterRuntimeOwnedAccounting as dt, knownMaterializationReceipt as ei, scopeRetainedOwnerRestorePoint as en, loopEventToOtelSpan as er, reenteredWorkers as et, writeStreamLinesFenced as f, runtimeOwnedPendingExecutorMaterialization as fi, attestNestedDriverTreeOwner as fn, readHarnessTranscript as fr, meterRuntimeOwnedProviderAttempt as ft, claimWorkerSteerDelivery as g, unknownMaterializationReceipt as gi, insideCursorNamespace as gn, resolveHarnessTranscriptCapture as gr, recordScopeOwnerPause as gt, cancelWorker as h, unknownExecutionBindingReceipt as hi, SpawnEventIndex as hn, readBoundHarnessSessions$1 as hr, recordScopeOwnerDriverAttempt as ht, ROOT_STREAM_FILE as i, recordRuntimeOwnedProviderAttemptStart as ii, bindScopeRetainedOwnerProvider as in, sanitizeRuntimeStreamEvent as ir, freeSlots as it, writeWorkerCancellation as j, promptOptionsFromAgentTurnInput as ji, retainedCreateMaterial as jn, undispatchedCredentialExit as jr, abandonScopeRetainedOwnerInvocation as jt, workerInboxFileFromEventDir as k, sameControlCoordinates as ki, startRetainedRun as kn, summarizeDriverAttempts as kr, resolveSpawnResourcePaths as kt, readRootStream as l, runtimeOwnedExecutorExecutionBinding as li, loadSpawnForest as ln, harnessTranscriptFromLines as lr, closeScopeAdmission as lt, appendWorkerControlEventAsync as m, runtimeOwnedScopeOwnerRuntime as mi, nestedDriverTreeRoot as mn, HARNESS_TRANSCRIPT_READ_LIMITS as mr, recordScopeOwnerBarrenPause as mt, terminalAccounting as n, providerAttemptEvidence as ni, scopeRetainedOwnerCheckpointing as nn, createRuntimeStreamEventCollector as nr, assertRecursiveReservationPolicy as nt, createRootStreamSink as o, recordRuntimeOwnedProviderIdentityConflict as oi, scopeOwnerLiabilities as on, captureBoundHarnessTranscript as or, rollingDispatch as ot, appendWorkerControlEvent as p, runtimeOwnedScopeOwnerControl as pi, driverRuntime as pn, settleHarnessTranscript as pr, pauseScopeSeatAdmission as pt, reconnectRetainedInteractiveRun as q, buildLoopOtelSpans as qn, attestRuntimeOwnedPendingExecutor as qr, providerVisibleProfile as qt, createScope as r, recordRuntimeOwnedDriveHarnessProviderEvidence as ri, bindScopeRetainedOwnerEnvironmentId as rn, sanitizeKnowledgeReadinessReport as rr, deriveNodeExecutionIdentity as rt, nodeStreamFile as s, recordRuntimeOwnedProviderModel as si, scopeRetainedOwnerContext as sn, captureHarnessTranscript as sr, boundRetainedReleases as st, isNonEmptySpend as t, newExecutionAttemptId as ti, noteScopeRetainedOwnerCoordination as tn, createRuntimeEventCollector as tr, settledToIteration as tt, readRootStreamReceipt as u, runtimeOwnedExecutorMaterialization as ui, ownedTreeRootSpawn as un, harnessTranscriptUnavailable as ur, hasRetriableTeardowns as ut, legacySupervisorRunDir as v, executableAgentSpecSnapshot as vi, executorObservationSeamKey as vn, DEFAULT_STALL_AFTER_MS as vr, releaseHeldEnvironments as vt, safeWorkerFile as w, assertEventBinding as wi, RetainedMaterializationTimeoutError as wn, DriverAttemptsExhaustedError as wr, waitForScopeChildren as wt, readWorkerCancellation as x, runtimeFlowAgent as xi, describeRetainedNativeStops as xn, readWorkerProgress as xr, settleManagerWork as xt, legacySupervisorRunsRoot as y, isRuntimeFlowBrain as yi, observeModelRequest as yn, createActivityLog as yr, releaseRetainedEnvironments as yt, replaySpawnTree as z, destroyInteractiveEnvironment as zn, preflightPublicCoordination as zr, noteScopeOwnerPlannedExecution as zt };
14307
14899
 
14308
- //# sourceMappingURL=supervisor-accounting-CPDPG8mH.js.map
14900
+ //# sourceMappingURL=supervisor-accounting-DlDUl58C.js.map