@tangle-network/agent-runtime 10.0.17 → 10.0.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/{activation-BSyIPZNw.d.ts → activation-BudDVuT6.d.ts} +2 -2
  3. package/dist/{activation-CxTZHC70.js → activation-DLnZJab0.js} +2 -2
  4. package/dist/{activation-CxTZHC70.js.map → activation-DLnZJab0.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{delegate-DGeAiukN.js → delegate-9b8qGlXp.js} +2 -2
  8. package/dist/{delegate-DGeAiukN.js.map → delegate-9b8qGlXp.js.map} +1 -1
  9. package/dist/{driver-control-acknowledgers-Q4c0RMoG.js → driver-control-acknowledgers-b5MsXxR5.js} +7 -7
  10. package/dist/{driver-control-acknowledgers-Q4c0RMoG.js.map → driver-control-acknowledgers-b5MsXxR5.js.map} +1 -1
  11. package/dist/durable-writer-thread.js +2 -2
  12. package/dist/durable.d.ts +1 -1
  13. package/dist/durable.js +15 -15
  14. package/dist/durable.js.map +1 -1
  15. package/dist/{failure-cause-DeSINrKC.js → failure-cause-C96rzF-d.js} +12 -2
  16. package/dist/{failure-cause-DeSINrKC.js.map → failure-cause-C96rzF-d.js.map} +1 -1
  17. package/dist/{graph-qm8N8-Jg.js → graph--n31XKWJ.js} +6 -6
  18. package/dist/{graph-qm8N8-Jg.js.map → graph--n31XKWJ.js.map} +1 -1
  19. package/dist/{improve-BIgddUb2.js → improve-sIZhpXqE.js} +5 -5
  20. package/dist/{improve-BIgddUb2.js.map → improve-sIZhpXqE.js.map} +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +10 -10
  23. package/dist/intelligence.d.ts +2 -2
  24. package/dist/intelligence.js +4 -4
  25. package/dist/kernel.d.ts +1 -1
  26. package/dist/kernel.js +15 -15
  27. package/dist/{loop-runner-CG8rMjSU.d.ts → loop-runner-Bn7lFuQZ.d.ts} +2 -2
  28. package/dist/{loop-runner-CARBEmJ-.js → loop-runner-Dt7I2oMa.js} +2 -2
  29. package/dist/{loop-runner-CARBEmJ-.js.map → loop-runner-Dt7I2oMa.js.map} +1 -1
  30. package/dist/loop-runner-bin.d.ts +1 -1
  31. package/dist/loop-runner-bin.js +1 -1
  32. package/dist/mcp/bin.js +3 -3
  33. package/dist/mcp/index.d.ts +1 -1
  34. package/dist/mcp/index.js +6 -6
  35. package/dist/mcp/memory-bin.js +1 -1
  36. package/dist/profiles.d.ts +1 -1
  37. package/dist/{provision-supervisor-bnP_5YKO.js → provision-supervisor-DfDAdtqb.js} +5 -5
  38. package/dist/{provision-supervisor-bnP_5YKO.js.map → provision-supervisor-DfDAdtqb.js.map} +1 -1
  39. package/dist/{result-blob-store-hfSuzvWt.js → result-blob-store-Dke805sV.js} +2 -2
  40. package/dist/{result-blob-store-hfSuzvWt.js.map → result-blob-store-Dke805sV.js.map} +1 -1
  41. package/dist/{run-cancellation-3JALg48v.js → run-cancellation-B0SgcidY.js} +2 -2
  42. package/dist/{run-cancellation-3JALg48v.js.map → run-cancellation-B0SgcidY.js.map} +1 -1
  43. package/dist/{run-reopen-CrlP610D.js → run-reopen-B7TN2aQQ.js} +6 -6
  44. package/dist/{run-reopen-CrlP610D.js.map → run-reopen-B7TN2aQQ.js.map} +1 -1
  45. package/dist/{run-state-CdmftIyV.js → run-state-BNBUy2uK.js} +5 -5
  46. package/dist/{run-state-CdmftIyV.js.map → run-state-BNBUy2uK.js.map} +1 -1
  47. package/dist/{runtime-BJfxfru1.js → runtime-DXeWY00j.js} +15 -15
  48. package/dist/{runtime-BJfxfru1.js.map → runtime-DXeWY00j.js.map} +1 -1
  49. package/dist/{search-executor-B0XqNpI1.js → search-executor-BoQHI2Tz.js} +4 -4
  50. package/dist/{search-executor-B0XqNpI1.js.map → search-executor-BoQHI2Tz.js.map} +1 -1
  51. package/dist/{server-BL1KHd0N.js → server-Xkgobp5y.js} +4 -4
  52. package/dist/{server-BL1KHd0N.js.map → server-Xkgobp5y.js.map} +1 -1
  53. package/dist/{settle-record-CWixHcZl.js → settle-record-B5OpVDnC.js} +2 -2
  54. package/dist/{settle-record-CWixHcZl.js.map → settle-record-B5OpVDnC.js.map} +1 -1
  55. package/dist/{structural-rollout-PkvuJbEk.js → structural-rollout-BSF5tzUm.js} +4 -4
  56. package/dist/{structural-rollout-PkvuJbEk.js.map → structural-rollout-BSF5tzUm.js.map} +1 -1
  57. package/dist/{supervise-CPMm88sh.js → supervise-Drc1Pj1d.js} +67 -39
  58. package/dist/supervise-Drc1Pj1d.js.map +1 -0
  59. package/dist/{supervise-identity-BAOmWwLn.js → supervise-identity-Cz-Hzg9s.js} +2 -2
  60. package/dist/{supervise-identity-BAOmWwLn.js.map → supervise-identity-Cz-Hzg9s.js.map} +1 -1
  61. package/dist/{supervision-discovery-B6fyGpHe.js → supervision-discovery-DdRd1lsz.js} +3 -3
  62. package/dist/{supervision-discovery-B6fyGpHe.js.map → supervision-discovery-DdRd1lsz.js.map} +1 -1
  63. package/dist/{supervisor-BOYyb8eL.js → supervisor-CwUD7dsm.js} +6 -6
  64. package/dist/{supervisor-BOYyb8eL.js.map → supervisor-CwUD7dsm.js.map} +1 -1
  65. package/dist/{supervisor-accounting-BmY9xWOW.js → supervisor-accounting-CPDPG8mH.js} +1785 -1728
  66. package/dist/supervisor-accounting-CPDPG8mH.js.map +1 -0
  67. package/dist/{supervisor-root-contract-DIMbL04L.js → supervisor-root-contract-Uw2q3nvG.js} +3 -3
  68. package/dist/{supervisor-root-contract-DIMbL04L.js.map → supervisor-root-contract-Uw2q3nvG.js.map} +1 -1
  69. package/dist/testing.d.ts +1 -1
  70. package/dist/testing.js +11 -11
  71. package/dist/{tool-server--58hhIKE.js → tool-server-BhsyVDj2.js} +2 -2
  72. package/dist/{tool-server--58hhIKE.js.map → tool-server-BhsyVDj2.js.map} +1 -1
  73. package/dist/{top-web-CPzT4hJX.js → top-web-5ThvdyD0.js} +7 -7
  74. package/dist/{top-web-CPzT4hJX.js.map → top-web-5ThvdyD0.js.map} +1 -1
  75. package/dist/tui/bin.js +3 -3
  76. package/dist/tui/index.d.ts +1 -1
  77. package/dist/tui/index.js +2 -2
  78. package/dist/{types-C477vlPv.d.ts → types-BLhsL4qy.d.ts} +44 -35
  79. package/package.json +2 -2
  80. package/dist/supervise-CPMm88sh.js.map +0 -1
  81. package/dist/supervisor-accounting-BmY9xWOW.js.map +0 -1
@@ -2,7 +2,7 @@ import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBinding
2
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
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";
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 refreshBudgetLease, At as recordValue, I as executorFailure, J as budgetLeaseUpdates, L as executorFailureInfra, N as traceRootWriter, P as contentAddress, Q as createBudgetPool, R as executorFailureReason, X as budgetRecoverySeeds, Y as budgetLeases, Z as completedLeafBacking, a as settlementFailureCause, at as assertValidSpend, d as executorEvidenceWriter, et as meterUsageEvent, h as prepareRetainedExecutor, ht as parseCanonicalTransportEvent, it as assertValidBudget, l as RetainedExecutionPendingError, m as leafContinuationExecutionId, mt as extractTransportEventIdentity, n as runtimeFailureCause, o as BUDGET_CONTINUATION_TASK, q as BudgetReconcileFault, rt as spendFromUsageTotals, t as reportedFailureCause, tt as newUsageTotals, v as retainedExecutorSeamKey } from "./failure-cause-DeSINrKC.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
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";
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";
@@ -806,323 +806,623 @@ function providerAttemptEvidence(model) {
806
806
  models
807
807
  });
808
808
  }
809
- // src/runtime/supervise/seat-chain.ts
810
- /** How often a pause with no known reset asks again, the account cache's cadence. */
811
- const SEAT_RECHECK_MS = 12e4;
812
- /** No seat can start before `resumeAt`: the chain is exhausted, or `detail` says why not. */
813
- var SeatPauseError = class extends Error {
814
- resumeAt;
815
- detail;
816
- constructor(resumeAt, detail) {
817
- super(`${detail ?? "authored subscription seat chain exhausted"}; resume at ${resumeAt}`);
818
- this.name = "SeatPauseError";
819
- this.resumeAt = resumeAt;
820
- this.detail = detail;
821
- }
822
- };
823
- /** One logical node's durable chain. The spawn journal is the sole transition authority. */
824
- var SeatChain = class {
825
- profile;
826
- nodeId;
827
- rootId;
828
- journal;
829
- select;
830
- now;
831
- onSegment;
832
- beforeStart;
833
- observedThrough = -1;
834
- constructor(profile, nodeId, rootId, journal, select, now = Date.now, onSegment, beforeStart) {
835
- this.profile = profile;
836
- this.nodeId = nodeId;
837
- this.rootId = rootId;
838
- this.journal = journal;
839
- this.select = select;
840
- this.now = now;
841
- this.onSegment = onSegment;
842
- this.beforeStart = beforeStart;
809
+ // src/runtime/supervise/retained-owner-evidence.ts
810
+ /** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */
811
+ /** One grouping for release and the evidence gate before another owner invocation. */
812
+ function ownerWorkspaceAttempts(events, nodeId) {
813
+ const attempts = [];
814
+ let current;
815
+ const flush = () => {
816
+ if (current !== void 0) attempts.push(current);
817
+ current = void 0;
818
+ };
819
+ const fresh = (executionId, workspaceRetention) => ({
820
+ workspaceRetention,
821
+ admissions: [],
822
+ ...executionId === void 0 ? {} : { executionId },
823
+ environmentIds: /* @__PURE__ */ new Set(),
824
+ controlByEnvironment: /* @__PURE__ */ new Map(),
825
+ evidence: []
826
+ });
827
+ for (const event of events) {
828
+ if (!("id" in event) || event.id !== nodeId) continue;
829
+ if (event.kind === "execution-input") {
830
+ flush();
831
+ current = fresh(`${nodeId}:input:${event.seq}`, event.workspaceRetention);
832
+ } else if (event.kind === "execution-admitted" && event.admission.phase === "environment") {
833
+ if (current?.result !== void 0) flush();
834
+ current ??= fresh();
835
+ current.environmentIds.add(event.admission.environmentId);
836
+ current.admissions.push(event.admission);
837
+ } else if (event.kind === "execution-admitted" && event.admission.phase === "dispatched") {
838
+ current?.admissions.push(event.admission);
839
+ current?.controlByEnvironment.set(event.admission.controlRef.environmentId, event.admission.controlRef);
840
+ } else if (event.kind === "execution-admitted") {
841
+ current?.admissions.push(event.admission);
842
+ if (current && event.admission.phase === "intent" && event.admission.outputFilePolicyDigest) current.outputFilePolicyDigest = current.outputFilePolicyDigest === void 0 || current.outputFilePolicyDigest === event.admission.outputFilePolicyDigest ? event.admission.outputFilePolicyDigest : "conflicting-file-policies";
843
+ } else if (event.kind === "execution-bound") {
844
+ if (current !== void 0 && current.result === void 0) current.binding = event.binding;
845
+ } else if (event.kind === "execution-result") {
846
+ current ??= fresh();
847
+ current.result = event;
848
+ } else if (event.kind === "execution-evidence") current?.evidence.push(event);
843
849
  }
844
- async next(afterUsageLimit = false, afterRecheck = false) {
845
- const stages = authoredSeatStages(this.profile);
846
- if (!stages) throw new ValidationError("SeatChain requires authored AgentProfile.seats");
847
- const allEvents = await this.journal.loadTree(this.rootId) ?? [];
848
- const events = allEvents.filter((event) => event.kind === "seat-segment" && event.id === this.nodeId);
849
- const destroyed = new Set(allEvents.filter((event) => event.kind === "environment-teardown" && event.id === this.nodeId && event.destroyed).map((event) => event.environmentId));
850
- let admittedEnvironmentId;
851
- for (const event of allEvents) if (event.kind === "execution-admitted" && event.id === this.nodeId && event.admission.phase === "environment") admittedEnvironmentId = event.admission.environmentId;
852
- const retainedEnvironmentId = admittedEnvironmentId !== void 0 && !destroyed.has(admittedEnvironmentId) ? admittedEnvironmentId : void 0;
853
- await this.reconcile(events);
854
- const starts = events.filter((event) => event.phase === "started");
855
- const last = starts.at(-1);
856
- const closed = last && events.find((event) => event.phase === "ended" && event.segmentIndex === last.segmentIndex);
857
- if (last && !closed && afterUsageLimit) await this.end(last, "usage-limit");
858
- const resume = last && !closed && !afterUsageLimit;
859
- const segmentIndex = resume ? last.segmentIndex : (last?.segmentIndex ?? -1) + 1;
860
- const firstStageIndex = afterRecheck ? 0 : last?.stageIndex ?? 0;
861
- let earliestReset;
862
- for (let stageIndex = firstStageIndex; stageIndex < stages.length; stageIndex += 1) {
863
- const stage = stages[stageIndex];
864
- const rebind = last && stageIndex === last.stageIndex && !afterUsageLimit && closed?.reason !== "usage-limit";
865
- const excludedSeatIds = (afterRecheck ? [] : starts).filter((event) => event.stageIndex === stageIndex && (!rebind || event.seat !== last.seat)).map((event) => event.seat);
866
- const prior = last === void 0 ? void 0 : {
867
- seat: last.seat,
868
- harness: last.harness,
869
- provider: last.provider,
870
- model: last.model
871
- };
872
- const preceding = resume ? starts.at(-2) : last;
873
- const requiresNativeTurnGrant = Boolean(preceding && preceding.provider === stage.provider && preceding.harness === stage.harness && (!rebind || preceding.seat !== last.seat));
874
- const selection = checkedSeatSelection(stage, await this.select({
875
- profile: this.profile,
876
- nodeId: this.nodeId,
877
- stage,
878
- stageIndex,
879
- segmentIndex,
880
- excludedSeatIds,
881
- requiresNativeTurnGrant,
882
- ...retainedEnvironmentId === void 0 ? {} : { retainedEnvironmentId },
883
- ...prior === void 0 ? {} : { previous: prior },
884
- ...rebind ? { resumeSeatId: last.seat } : {}
885
- }));
886
- if ("resumeAt" in selection) {
887
- const reset = Date.parse(selection.resumeAt);
888
- earliestReset = earliestReset === void 0 ? reset : Math.min(earliestReset, reset);
889
- if (resume) break;
890
- continue;
891
- }
892
- if (rebind && selection.seat !== last.seat) throw new ValidationError("selectSeat: resume changed the committed seat");
893
- if (excludedSeatIds.includes(selection.seat)) throw new ValidationError("selectSeat: selected an exhausted seat");
894
- if (preceding && preceding.seat !== selection.seat && preceding.provider === stage.provider && preceding.harness === stage.harness && selection.nativeTurnGrant !== true) throw new ValidationError("selectSeat: same-environment seat requires a verified native turn grant");
895
- const active = {
896
- seat: selection.seat,
897
- stageIndex,
898
- segmentIndex,
899
- stage,
900
- backend: selection.backend,
901
- ...selection.nativeTurnGrant === true ? { nativeTurnGrant: true } : {},
902
- ...preceding === void 0 ? {} : { previous: {
903
- seat: preceding.seat,
904
- harness: preceding.harness,
905
- provider: preceding.provider,
906
- model: preceding.model
907
- } }
908
- };
909
- if (!resume) {
910
- await this.beforeStart?.(active, prior);
911
- const at = new Date(this.now()).toISOString();
912
- await this.journal.appendEvent(this.rootId, {
913
- kind: "seat-segment",
914
- id: this.nodeId,
915
- segmentIndex,
916
- stageIndex,
917
- phase: "started",
918
- seat: selection.seat,
919
- harness: stage.harness,
920
- provider: stage.provider,
921
- model: stage.model,
922
- seq: segmentIndex,
923
- at
924
- });
925
- await this.onSegment?.({
926
- seat: selection.seat,
927
- harness: stage.harness,
928
- provider: stage.provider,
929
- model: stage.model,
930
- startedAt: at
931
- }, "started");
932
- this.observedThrough = events.length;
933
- return active;
934
- }
935
- return active;
850
+ flush();
851
+ return attempts;
852
+ }
853
+ /** Group owner admissions by input. A source with no verified workspace receipt is preserved, including one a later resume can still use. */
854
+ const UNVERIFIED_SOURCE = "provider workspace retention: source preserved because the owner execution has no verified workspace receipt";
855
+ async function ownerWorkspaceRetentionFailures(events, owner) {
856
+ const attempts = ownerWorkspaceAttempts(events, owner.nodeId);
857
+ const failures = /* @__PURE__ */ new Map();
858
+ for (const index of attempts.keys()) {
859
+ const attempt = withLaterEvidence(attempts, index);
860
+ if (attempt.workspaceRetention !== true && attempt.outputFilePolicyDigest === void 0) continue;
861
+ if (attempt.environmentIds.size === 0) continue;
862
+ if (attempt.environmentIds.size > 1) {
863
+ for (const environmentId of attempt.environmentIds) failures.set(environmentId, UNVERIFIED_SOURCE);
864
+ continue;
936
865
  }
937
- const recheckAt = Math.max(earliestReset ?? 0, this.now() + SEAT_RECHECK_MS);
938
- throw new SeatPauseError(new Date(recheckAt).toISOString());
866
+ const environmentId = [...attempt.environmentIds][0];
867
+ const reason = await ownerAttemptHasCapture(attempt, environmentId, owner.blobs, owner);
868
+ if (reason !== void 0) failures.set(environmentId, reason);
939
869
  }
940
- async close(reason) {
941
- const events = (await this.journal.loadTree(this.rootId) ?? []).filter((event) => event.kind === "seat-segment" && event.id === this.nodeId);
942
- await this.reconcile(events);
943
- const last = events.filter((event) => event.phase === "started").at(-1);
944
- if (last && !events.some((event) => event.phase === "ended" && event.segmentIndex === last.segmentIndex)) await this.end(last, reason);
870
+ return failures;
871
+ }
872
+ /**
873
+ * The attempt with the evidence journaled after it. A release's capture of a preserved source is
874
+ * journaled after later invocations began; every receipt names its exact execution, environment
875
+ * and control reference, so a receipt of another attempt never verifies this one.
876
+ */
877
+ function withLaterEvidence(attempts, index) {
878
+ const attempt = attempts[index];
879
+ const later = attempts.slice(index + 1).flatMap((next) => next.evidence);
880
+ return later.length === 0 ? attempt : {
881
+ ...attempt,
882
+ evidence: [...attempt.evidence, ...later]
883
+ };
884
+ }
885
+ /** Undefined when a receipt authorizes destroying the source. Otherwise why it stays. */
886
+ async function ownerAttemptHasCapture(attempt, environmentId, blobs, owner, allowPartialProcessCapture = false) {
887
+ const controlRef = attempt.controlByEnvironment.get(environmentId);
888
+ if (attempt.outputFilePolicyDigest !== void 0) {
889
+ const output = attempt.result === void 0 ? void 0 : recordValue(await storedOutput(blobs, attempt.result.outRef));
890
+ const publication = AgentRetainedFilePublicationSchema.safeParse(output?.publication);
891
+ const node = owner === void 0 ? void 0 : ownerCaptureIdentity(attempt, owner).node;
892
+ if (!output || output.kind !== "retained-file-output" || output.version !== 1 || output.invocationId !== attempt.executionId || output.policyDigest !== attempt.outputFilePolicyDigest || !Object.hasOwn(output, "submission") || !recordValue(output.node) || output.submissionRef !== contentAddress(output.submission) || !node || contentAddress(output.node) !== contentAddress(node) || !publication.success || !controlRef || !sameControlCoordinates(publication.data.controlRef, controlRef) || canonicalCandidateDigest(publication.data.policy) !== attempt.outputFilePolicyDigest) return UNVERIFIED_SOURCE;
893
+ if (attempt.workspaceRetention !== true) return void 0;
945
894
  }
946
- async end(start, reason) {
947
- const at = new Date(this.now()).toISOString();
948
- await this.journal.appendEvent(this.rootId, {
949
- ...start,
950
- phase: "ended",
951
- reason,
952
- at
953
- });
954
- await this.onSegment?.({
955
- seat: start.seat,
956
- harness: start.harness,
957
- provider: start.provider,
958
- model: start.model,
959
- startedAt: start.at,
960
- endedAt: at,
961
- reason
962
- }, "ended");
963
- this.observedThrough += 1;
895
+ const receipts = [...attempt.result === void 0 || attempt.result.outputFormat === "json" ? [] : [attempt.result.outRef], ...attempt.evidence.map((event) => event.outRef)];
896
+ const identity = owner === void 0 ? void 0 : ownerCaptureIdentity(attempt, owner);
897
+ let verified = false;
898
+ let nativeHold;
899
+ for (const outRef of receipts) {
900
+ const output = await storedOutput(blobs, outRef);
901
+ const snapshot = output !== null && typeof output === "object" ? output.workspaceSnapshot : void 0;
902
+ const capture = output !== null && typeof output === "object" ? output.workspaceCapture : void 0;
903
+ const receipt = capture !== null && typeof capture === "object" ? capture : void 0;
904
+ const matches = receipt !== void 0 && receipt.environmentId === environmentId && receipt.executionId === attempt.executionId;
905
+ const durable = hasDurableWorkspaceCapture(output, snapshot, environmentId, attempt.executionId, controlRef, identity, allowPartialProcessCapture);
906
+ if (matches && receipt !== void 0) {
907
+ const hold = nativeSessionCopyHoldReason(receipt);
908
+ if (hold !== void 0) {
909
+ nativeHold = hold;
910
+ verified = false;
911
+ } else if (durable) {
912
+ nativeHold = void 0;
913
+ verified = true;
914
+ }
915
+ } else if (nativeHold === void 0 && durable) verified = true;
964
916
  }
965
- /** A crash may land between the authoritative journal append and observer delivery. On
966
- * reconstruction, deliver every unobserved boundary again; the observer projection folds
967
- * repeated boundaries by seat and start time, so a callback never decides execution identity. */
968
- async reconcile(events) {
969
- const starts = /* @__PURE__ */ new Map();
970
- for (let index = 0; index < events.length; index += 1) {
971
- const event = events[index];
972
- if (event.phase === "started") starts.set(event.segmentIndex, event);
973
- if (index <= this.observedThrough) continue;
974
- const start = event.phase === "started" ? event : starts.get(event.segmentIndex);
975
- if (!start) throw new ValidationError("seat segment ended without a committed start");
976
- await this.onSegment?.({
977
- seat: start.seat,
978
- harness: start.harness,
979
- provider: start.provider,
980
- model: start.model,
981
- startedAt: start.at,
982
- ...event.phase === "ended" ? {
983
- endedAt: event.at,
984
- reason: event.reason
985
- } : {}
986
- }, event.phase);
987
- this.observedThrough = index;
988
- }
989
- }
990
- };
991
- /** Preserve the authored profile for identity; only the provider-facing copy changes stages. */
992
- function seatExecutionProfile(profile, stage) {
993
- const { seats: _seats, ...withoutSeats } = profile;
917
+ if (nativeHold !== void 0) return nativeHold;
918
+ return verified ? void 0 : UNVERIFIED_SOURCE;
919
+ }
920
+ function ownerCaptureIdentity(attempt, owner) {
921
+ const intent = attempt.admissions.find((admission) => admission.phase === "intent");
922
+ const node = attempt.binding === void 0 ? void 0 : {
923
+ rootId: owner.executionRootId ?? owner.rootId,
924
+ parentId: owner.nodeId,
925
+ nodeId: owner.nodeId,
926
+ ...owner.depth === void 0 ? {} : { depth: owner.depth },
927
+ attemptId: attempt.binding.attemptId
928
+ };
994
929
  return {
995
- ...withoutSeats,
996
- harness: stage.harness,
997
- ...stage.tools === void 0 ? {} : { tools: stage.tools },
998
- ...stage.permissions === void 0 ? {} : { permissions: stage.permissions },
999
- model: {
1000
- ...profile.model,
1001
- default: stage.model,
1002
- provider: stage.provider,
1003
- ...stage.reasoningEffort === void 0 ? {} : { reasoningEffort: stage.reasoningEffort },
1004
- ...stage.credentialSource === void 0 ? {} : { metadata: {
1005
- ...profile.model?.metadata,
1006
- credentialSource: stage.credentialSource
1007
- } }
1008
- }
930
+ profileDigest: intent?.requestedProfileDigest,
931
+ node
1009
932
  };
1010
933
  }
1011
- function authoredSeatStages(profile) {
1012
- const seats = profile.seats;
1013
- if (seats === void 0) return void 0;
1014
- if (!Array.isArray(seats) || seats.length === 0) throw new ValidationError("AgentProfile.seats must be a nonempty ordered chain");
1015
- return seats;
934
+ /** Recover evidence before reuse. Failed unverified turns keep their invocation; accepted turns owe evidence. */
935
+ async function reconcileOwnerWorkspaceBeforeReuse(state, signal, reconnecting = false) {
936
+ const { args } = state;
937
+ const indebted = /* @__PURE__ */ new Set();
938
+ const events = await args.journal.loadTree(args.rootId) ?? [];
939
+ const attempts = ownerWorkspaceAttempts(events, args.nodeId);
940
+ const latest = attempts.at(-1);
941
+ const unusable = unusableEnvironmentIds(events.filter((event) => event.id === args.nodeId));
942
+ if (latest === void 0) return indebted;
943
+ const reusing = new Set(latest.environmentIds);
944
+ if (latest.result === void 0 && state.priorSession !== void 0) reusing.add(state.priorSession.environmentId);
945
+ for (const attempt of attempts) {
946
+ if ((attempt.workspaceRetention !== true || attempt.result === void 0) && attempt.outputFilePolicyDigest === void 0) continue;
947
+ if (reconnecting && attempt === latest && attempt.result === void 0) continue;
948
+ for (const environmentId of attempt.environmentIds) {
949
+ if (!reusing.has(environmentId) || unusable.has(environmentId)) continue;
950
+ if (await ownerAttemptHasCapture(attempt, environmentId, args.blobs, args, true) === void 0) continue;
951
+ if (attempt.outputFilePolicyDigest !== void 0) throw new RetainedExecutionPendingError(/* @__PURE__ */ new Error(UNVERIFIED_SOURCE), "unobservable");
952
+ if (attempt.result === void 0) continue;
953
+ signal.throwIfAborted();
954
+ const failure = capturePendingMessage(attempt.executionId ?? args.nodeId, /* @__PURE__ */ new Error("client capture writers are retired; a persisted verified receipt is required"));
955
+ if (executorFailureReason(attempt.result) === void 0) await owePendingEvidence(state, events, attempt, environmentId, failure);
956
+ else {
957
+ await state.context.onEvidence({
958
+ executionId: attempt.executionId,
959
+ environmentId,
960
+ controlRef: attempt.controlByEnvironment.get(environmentId),
961
+ ...ownerCaptureIdentity(attempt, args),
962
+ workspaceCaptureFailure: failure
963
+ });
964
+ throw new RetainedExecutionPendingError(new Error(failure), "unobservable");
965
+ }
966
+ indebted.add(environmentId);
967
+ state.forceNewSession = true;
968
+ }
969
+ }
970
+ return indebted;
1016
971
  }
1017
- const USAGE_LIMIT_CODES = /* @__PURE__ */ new Set([
1018
- "provider_quota_exhausted",
1019
- "subscription_usage_limit",
1020
- "usage_limit_reached",
1021
- "usage_limit_exceeded",
1022
- "weekly_limit_reached",
1023
- "session_limit_reached"
1024
- ]);
1025
- /** Normalize a native harness refusal into a typed limit. A plain HTTP 429 is insufficient. */
1026
- function subscriptionUsageLimitSignal(failure) {
1027
- if (failure.errorCode && USAGE_LIMIT_CODES.has(failure.errorCode.toLowerCase())) return "subscription-usage-limit";
1028
- if (/\bYou've hit your (?:usage|weekly|session|monthly spend) limit\b/iu.test(failure.error)) return "subscription-usage-limit";
1029
- if (/\bUsage limit reached for \d+ hours?\b|已达到\s*\d+\s*小时的使用上限/iu.test(failure.error)) return "subscription-usage-limit";
972
+ function capturePendingMessage(executionId, cause) {
973
+ return `retained workspace capture pending for ${executionId}; source environment preserved: ${cause instanceof Error ? cause.message : String(cause)}`;
1030
974
  }
1031
- /** An ineligible or misconfigured account must never turn an authored stage into another model. */
1032
- function checkedSeatSelection(stage, selected) {
1033
- if ("resumeAt" in selected) {
1034
- if (!Number.isFinite(Date.parse(selected.resumeAt))) throw new ValidationError("selectSeat: resumeAt must be an ISO timestamp");
1035
- return selected;
975
+ /** Preserve a historical capture obligation without blocking work in a fresh environment. */
976
+ async function owePendingEvidence(state, events, attempt, environmentId, failure) {
977
+ const { args } = state;
978
+ if (!events.some((event) => event.kind === "evidence-pending" && event.id === args.nodeId && event.environmentId === environmentId)) {
979
+ const at = new Date(args.now()).toISOString();
980
+ await args.journal.appendEvent(args.rootId, {
981
+ kind: "evidence-pending",
982
+ id: args.nodeId,
983
+ environmentId,
984
+ ...attempt.executionId === void 0 ? {} : { executionId: attempt.executionId },
985
+ error: failure,
986
+ since: at,
987
+ seq: state.nextSequence(),
988
+ at
989
+ });
1036
990
  }
1037
- if (!selected.seat.trim()) throw new ValidationError("selectSeat: seat must be nonempty");
1038
- if (stage.selector.kind === "seat" && stage.selector.id !== selected.seat) throw new ValidationError("selectSeat: selection does not match the authored seat");
1039
- if (selected.backend.backend !== "provider") throw new ValidationError("selectSeat: selection must use a provider backend");
1040
- return selected;
1041
991
  }
1042
- // src/runtime/supervise/node-status.ts
1043
- /** Which {@link NodeStatus} values mean the node is finished. */
1044
- const terminalNodeStatuses = /* @__PURE__ */ new Set([
1045
- "done",
1046
- "failed",
1047
- "cancelled"
1048
- ]);
992
+ /** A stored output whose bytes match its content reference, or undefined. */
993
+ async function storedOutput(blobs, outRef) {
994
+ try {
995
+ const output = await blobs.get(outRef);
996
+ return output === void 0 || contentAddress(output) !== outRef ? void 0 : output;
997
+ } catch {
998
+ return;
999
+ }
1000
+ }
1001
+ /** A stored result authorizes cleanup only for the exact source and complete capture. */
1002
+ function hasDurableWorkspaceCapture(output, snapshot, environmentId, executionId, controlRef, identity, allowPartialProcessCapture = false) {
1003
+ const parsed = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(snapshot);
1004
+ if (!parsed.success || !("locator" in parsed.data.manifest) || !("locator" in parsed.data.archive)) return false;
1005
+ if (output === null || typeof output !== "object") return false;
1006
+ const capture = output.workspaceCapture;
1007
+ if (capture === null || typeof capture !== "object") return false;
1008
+ const receipt = capture;
1009
+ if (identity !== void 0 && (identity.profileDigest === void 0 || receipt.profileDigest !== identity.profileDigest || (identity.node === void 0 ? receipt.node !== void 0 : receipt.node === void 0 || contentAddress(receipt.node) !== contentAddress(identity.node)))) return false;
1010
+ const capturedControl = AgentExactRunControlRefSchema.safeParse(receipt.controlRef);
1011
+ if (executionId === void 0 || controlRef === void 0 || !capturedControl.success || !sameControlCoordinates(capturedControl.data, controlRef) || receipt.environmentId !== environmentId || receipt.executionId !== executionId || !captureAuthorizesDestroy(receipt, allowPartialProcessCapture)) return false;
1012
+ const linked = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(receipt.snapshot);
1013
+ return linked.success && linked.data.digest === parsed.data.digest && JSON.stringify(linked.data.manifest) === JSON.stringify(parsed.data.manifest) && JSON.stringify(linked.data.archive) === JSON.stringify(parsed.data.archive);
1014
+ }
1015
+ const NATIVE_STORE_GAP = /(?:^|\s)((?:over_bound|store_file_):[^\s;]+)/g;
1016
+ const COVERAGE_GAP_PREFIX = "provider workspace retention coverage incomplete: ";
1017
+ const PROCESS_GAP = [
1018
+ /^process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
1019
+ /^Sandbox session [\w-]+ declared partial raw capture$/,
1020
+ /^Sandbox session [\w-]+ attempt [\w-]+\/\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
1021
+ /^Sandbox session [\w-]+ has no original process source: [\w-]+$/,
1022
+ /^Sandbox session [\w-]+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
1023
+ /^Raw native session capture for Sandbox session [\w-]+ is unavailable: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
1024
+ /^Session [\w-]+ process streams incomplete$/,
1025
+ /^Attempt [\w-]+\/\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/
1026
+ ];
1027
+ const EVENT_GAP = /(?:^|:\s)events_incomplete(?::[\w.-]+)?$/;
1028
+ /** Keep the box when the final native copy is incomplete. Process I/O or event-log gaps do not. */
1029
+ function nativeSessionCopyHoldReason(receipt) {
1030
+ const provenance = receipt.provenance;
1031
+ if (provenance === null || typeof provenance !== "object") return void 0;
1032
+ const reported = provenance;
1033
+ const sessions = Array.isArray(reported.sessions) ? reported.sessions : [];
1034
+ let incomplete = false;
1035
+ const tokens = /* @__PURE__ */ new Set();
1036
+ const take = (value) => {
1037
+ const text = Array.isArray(value) ? value.filter((item) => typeof item === "string").join("; ") : typeof value === "string" ? value : "";
1038
+ for (const match of text.matchAll(NATIVE_STORE_GAP)) tokens.add(match[1]);
1039
+ };
1040
+ for (const session of sessions) {
1041
+ if (session === null || typeof session !== "object") continue;
1042
+ const row = session;
1043
+ const store = row.nativeStore;
1044
+ if (store !== null && typeof store === "object" && store.complete === false) incomplete = true;
1045
+ take(row.nativeReason);
1046
+ if (store !== null && typeof store === "object") take(store.missingReasons);
1047
+ }
1048
+ take(reported.missing);
1049
+ if (!incomplete && tokens.size === 0) return void 0;
1050
+ return `native session copy incomplete: ${tokens.size > 0 ? [...tokens].join("; ") : "nativeStore incomplete"}`;
1051
+ }
1052
+ function captureAuthorizesDestroy(receipt, allowPartialProcessCapture) {
1053
+ if (nativeSessionCopyHoldReason(receipt) !== void 0) return false;
1054
+ if (receipt.coverageComplete === true) return true;
1055
+ return hasOnlyRawProcessCaptureGap(receipt, !allowPartialProcessCapture);
1056
+ }
1057
+ function captureGapTexts(receipt) {
1058
+ const reason = receipt.incompleteReason;
1059
+ const named = typeof reason === "string" && reason.startsWith(COVERAGE_GAP_PREFIX) ? reason.slice(50).split("; ") : [];
1060
+ const provenance = receipt.provenance;
1061
+ const missing = provenance !== null && typeof provenance === "object" && Array.isArray(provenance.missing) ? provenance.missing.filter((item) => typeof item === "string") : [];
1062
+ return [...named, ...missing].map((gap) => gap.trim()).filter((gap) => gap.length > 0);
1063
+ }
1049
1064
  /**
1050
- * True once a node has reached a terminal status.
1051
- *
1052
- * The single owner of this rule. Written per call site it drifts silently: a status added to
1053
- * `NodeStatus` is classified by whichever sites the author remembered, and the ones they missed
1054
- * keep a dead node in the live set — a stop rule that never fires, mail delivered to a worker that
1055
- * cannot read it, or a cancel answered `not_live` for a node that is still running.
1065
+ * A process I/O gap does not invalidate a verified workspace. `includeEvents` is the release
1066
+ * rule: an event-log gap alone also authorizes destroy. Any other gap keeps the source.
1056
1067
  */
1057
- function isTerminalNodeStatus(status) {
1058
- return terminalNodeStatuses.has(status);
1068
+ function hasOnlyRawProcessCaptureGap(receipt, includeEvents = false) {
1069
+ const provenance = receipt.provenance;
1070
+ if (provenance === null || typeof provenance !== "object") return false;
1071
+ const reported = provenance;
1072
+ const workspace = reported.workspace;
1073
+ if (reported.status !== "reported" || workspace === null || typeof workspace !== "object" || workspace.complete !== true) return false;
1074
+ const sessions = reported.sessions;
1075
+ if (!Array.isArray(sessions) || !sessions.some((session) => session !== null && typeof session === "object" && (session.processStreams?.complete === false || includeEvents && session.nativeEvents?.complete === false))) return false;
1076
+ const gaps = captureGapTexts(receipt);
1077
+ return gaps.length > 0 && gaps.every((gap) => PROCESS_GAP.some((pattern) => pattern.test(gap)) || includeEvents && EVENT_GAP.test(gap));
1059
1078
  }
1060
- /** True while a node has not yet reached a terminal status. The complement of
1061
- * {@link isTerminalNodeStatus}, so the two can never disagree. */
1062
- function isLiveNodeStatus(status) {
1063
- return !terminalNodeStatuses.has(status);
1079
+ /** Environments that cannot execute another turn, whether absent or terminal at the provider. */
1080
+ function unusableEnvironmentIds(owned) {
1081
+ return new Set(owned.flatMap((event) => event.kind === "environment-terminal" || event.kind === "environment-teardown" && (event.destroyed || event.retired === true) ? [event.environmentId] : []));
1064
1082
  }
1065
- // src/runtime/supervise/progress.ts
1066
1083
  /**
1067
- *
1068
- * The LIVE read-model of a still-RUNNING worker — what a driver can see BEFORE the worker settles.
1069
- *
1070
- * Until this existed, `observe_agent` on a running worker returned `{status:'running', spent:{0,0},
1071
- * outRef:null, output:null}`: nothing a brain could act on, so a brain that wanted to steer had no
1072
- * evidence to steer FROM. This is the other half of the steering wire (the first half is
1073
- * `Executor.deliver`): a supervisor cannot correct a worker it cannot watch.
1074
- *
1075
- * Two layers, both pull-based — no timer, no background task, so it is safe to leave on:
1076
- *
1077
- * - The SCOPE layer, available for EVERY executor with no executor cooperation at all: usage
1078
- * events are timestamped as they arrive, so `lastActivityAt` / `idleMs` / `stalled` /
1079
- * `tokens` / `turns` are derived from the stream the conserved pool already meters.
1080
- * - The EXECUTOR layer, optional enrichment via `Executor.progress()`: the tool/file activity
1081
- * the harness exposes, its own turn count, and how many steers are queued but unread.
1082
- *
1083
- * `stalled` is a DERIVED read, computed at observation time against `stallAfterMs` — never a
1084
- * background watchdog. A worker that has produced no metered activity for longer than the
1085
- * threshold reads `stalled: true`; nothing is killed, nothing is retried. The driver decides.
1086
- *
1087
- * @experimental
1084
+ * After {@link reconcileOwnerWorkspaceBeforeReuse}: an unfinished input an older coordinator
1085
+ * admitted into a source now owed evidence, but never dispatched there, is abandoned. Replaying
1086
+ * it would mutate the source, so the next drive is a new invocation in another environment. A
1087
+ * dispatch lost before its admission was journaled cannot be ruled out, so the outcome is
1088
+ * uncertain.
1088
1089
  */
1089
- /** How long a worker may produce no metered activity before a `progress()` read calls it stalled.
1090
- * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a
1091
- * false stall that provokes a steer is worse than a late one. */
1092
- const DEFAULT_STALL_AFTER_MS = 18e4;
1093
- /** A short, already-truncated descriptor of a tool call's target — the file/command a driver
1094
- * needs to tell "editing the right module" from "re-reading the same file for the fifth time",
1095
- * without pulling the worker's transcript across the wire. Shared by every executor that fills an
1096
- * `ActivityLog` (pi RPC, sandbox session parts, cli-bridge tool-call deltas) so one harness's
1097
- * argument naming never reads differently from another's in the same driver's window. */
1098
- function describeToolArgs(argsValue) {
1099
- if (!argsValue || typeof argsValue !== "object") return void 0;
1100
- const a = argsValue;
1101
- for (const key of [
1102
- "filePath",
1103
- "file_path",
1104
- "path",
1105
- "file",
1106
- "command",
1107
- "cmd",
1108
- "pattern"
1109
- ]) {
1110
- const v = a[key];
1111
- if (typeof v === "string" && v.length > 0) return v.length > 120 ? `${v.slice(0, 117)}...` : v;
1112
- }
1090
+ async function abandonInputAdmittedIntoDebt(state, indebted) {
1091
+ const { args } = state;
1092
+ const pending = state.admissions.find((admission) => admission.phase === "environment" && indebted.has(admission.environmentId));
1093
+ if (pending === void 0 || state.admissions.some((admission) => admission.phase === "dispatched")) return;
1094
+ await args.journal.appendEvent(args.rootId, {
1095
+ kind: "execution-abandoned",
1096
+ id: args.nodeId,
1097
+ inputSeq: state.inputSequence,
1098
+ pendingCause: "unobservable",
1099
+ failures: 1,
1100
+ detail: `admitted into ${pending.environmentId}, whose workspace capture is pending; never dispatched there`,
1101
+ outcome: "uncertain",
1102
+ seq: state.nextSequence(),
1103
+ at: new Date(args.now()).toISOString()
1104
+ });
1105
+ delete state.inputSequence;
1106
+ delete state.taskRef;
1107
+ state.admissions.length = 0;
1113
1108
  }
1114
- /** Create a bounded activity ring. `limit` caps memory for a worker that runs thousands of tools. */
1115
- function createActivityLog(limit = 12) {
1116
- const notes = [];
1117
- const cap = Math.max(1, Math.floor(limit));
1109
+ // src/runtime/supervise/seat-chain.ts
1110
+ /** How often a pause with no known reset asks again, the account cache's cadence. */
1111
+ const SEAT_RECHECK_MS = 12e4;
1112
+ /** No seat can start before `resumeAt`: the chain is exhausted, or `detail` says why not. */
1113
+ var SeatPauseError = class extends Error {
1114
+ resumeAt;
1115
+ detail;
1116
+ constructor(resumeAt, detail) {
1117
+ super(`${detail ?? "authored subscription seat chain exhausted"}; resume at ${resumeAt}`);
1118
+ this.name = "SeatPauseError";
1119
+ this.resumeAt = resumeAt;
1120
+ this.detail = detail;
1121
+ }
1122
+ };
1123
+ /** One logical node's durable chain. The spawn journal is the sole transition authority. */
1124
+ var SeatChain = class {
1125
+ profile;
1126
+ nodeId;
1127
+ rootId;
1128
+ journal;
1129
+ select;
1130
+ now;
1131
+ onSegment;
1132
+ beforeStart;
1133
+ observedThrough = -1;
1134
+ constructor(profile, nodeId, rootId, journal, select, now = Date.now, onSegment, beforeStart) {
1135
+ this.profile = profile;
1136
+ this.nodeId = nodeId;
1137
+ this.rootId = rootId;
1138
+ this.journal = journal;
1139
+ this.select = select;
1140
+ this.now = now;
1141
+ this.onSegment = onSegment;
1142
+ this.beforeStart = beforeStart;
1143
+ }
1144
+ async next(afterUsageLimit = false, afterRecheck = false) {
1145
+ const stages = authoredSeatStages(this.profile);
1146
+ if (!stages) throw new ValidationError("SeatChain requires authored AgentProfile.seats");
1147
+ const allEvents = await this.journal.loadTree(this.rootId) ?? [];
1148
+ const events = allEvents.filter((event) => event.kind === "seat-segment" && event.id === this.nodeId);
1149
+ const unusable = unusableEnvironmentIds(allEvents.filter((event) => event.id === this.nodeId));
1150
+ let admittedEnvironmentId;
1151
+ for (const event of allEvents) if (event.kind === "execution-admitted" && event.id === this.nodeId && event.admission.phase === "environment") admittedEnvironmentId = event.admission.environmentId;
1152
+ const retainedEnvironmentId = admittedEnvironmentId !== void 0 && !unusable.has(admittedEnvironmentId) ? admittedEnvironmentId : void 0;
1153
+ await this.reconcile(events);
1154
+ const starts = events.filter((event) => event.phase === "started");
1155
+ const last = starts.at(-1);
1156
+ const closed = last && events.find((event) => event.phase === "ended" && event.segmentIndex === last.segmentIndex);
1157
+ if (last && !closed && afterUsageLimit) await this.end(last, "usage-limit");
1158
+ const resume = last && !closed && !afterUsageLimit;
1159
+ const segmentIndex = resume ? last.segmentIndex : (last?.segmentIndex ?? -1) + 1;
1160
+ const firstStageIndex = afterRecheck ? 0 : last?.stageIndex ?? 0;
1161
+ let earliestReset;
1162
+ for (let stageIndex = firstStageIndex; stageIndex < stages.length; stageIndex += 1) {
1163
+ const stage = stages[stageIndex];
1164
+ const rebind = last && stageIndex === last.stageIndex && !afterUsageLimit && closed?.reason !== "usage-limit";
1165
+ const excludedSeatIds = (afterRecheck ? [] : starts).filter((event) => event.stageIndex === stageIndex && (!rebind || event.seat !== last.seat)).map((event) => event.seat);
1166
+ const prior = last === void 0 ? void 0 : {
1167
+ seat: last.seat,
1168
+ harness: last.harness,
1169
+ provider: last.provider,
1170
+ model: last.model
1171
+ };
1172
+ const preceding = resume ? starts.at(-2) : last;
1173
+ const requiresNativeTurnGrant = Boolean(retainedEnvironmentId !== void 0 && preceding && preceding.provider === stage.provider && preceding.harness === stage.harness && (!rebind || preceding.seat !== last.seat));
1174
+ const selection = checkedSeatSelection(stage, await this.select({
1175
+ profile: this.profile,
1176
+ nodeId: this.nodeId,
1177
+ stage,
1178
+ stageIndex,
1179
+ segmentIndex,
1180
+ excludedSeatIds,
1181
+ requiresNativeTurnGrant,
1182
+ ...retainedEnvironmentId === void 0 ? {} : { retainedEnvironmentId },
1183
+ ...prior === void 0 ? {} : { previous: prior },
1184
+ ...rebind ? { resumeSeatId: last.seat } : {}
1185
+ }));
1186
+ if ("resumeAt" in selection) {
1187
+ const reset = Date.parse(selection.resumeAt);
1188
+ earliestReset = earliestReset === void 0 ? reset : Math.min(earliestReset, reset);
1189
+ if (resume) break;
1190
+ continue;
1191
+ }
1192
+ if (rebind && selection.seat !== last.seat) throw new ValidationError("selectSeat: resume changed the committed seat");
1193
+ if (excludedSeatIds.includes(selection.seat)) throw new ValidationError("selectSeat: selected an exhausted seat");
1194
+ if (requiresNativeTurnGrant && preceding && preceding.seat !== selection.seat && selection.nativeTurnGrant !== true) throw new ValidationError("selectSeat: same-environment seat requires a verified native turn grant");
1195
+ const active = {
1196
+ seat: selection.seat,
1197
+ stageIndex,
1198
+ segmentIndex,
1199
+ stage,
1200
+ backend: selection.backend,
1201
+ ...selection.nativeTurnGrant === true ? { nativeTurnGrant: true } : {},
1202
+ ...preceding === void 0 ? {} : { previous: {
1203
+ seat: preceding.seat,
1204
+ harness: preceding.harness,
1205
+ provider: preceding.provider,
1206
+ model: preceding.model
1207
+ } }
1208
+ };
1209
+ if (!resume) {
1210
+ await this.beforeStart?.(active, prior);
1211
+ const at = new Date(this.now()).toISOString();
1212
+ await this.journal.appendEvent(this.rootId, {
1213
+ kind: "seat-segment",
1214
+ id: this.nodeId,
1215
+ segmentIndex,
1216
+ stageIndex,
1217
+ phase: "started",
1218
+ seat: selection.seat,
1219
+ harness: stage.harness,
1220
+ provider: stage.provider,
1221
+ model: stage.model,
1222
+ seq: segmentIndex,
1223
+ at
1224
+ });
1225
+ await this.onSegment?.({
1226
+ seat: selection.seat,
1227
+ harness: stage.harness,
1228
+ provider: stage.provider,
1229
+ model: stage.model,
1230
+ startedAt: at
1231
+ }, "started");
1232
+ this.observedThrough = events.length;
1233
+ return active;
1234
+ }
1235
+ return active;
1236
+ }
1237
+ const recheckAt = Math.max(earliestReset ?? 0, this.now() + SEAT_RECHECK_MS);
1238
+ throw new SeatPauseError(new Date(recheckAt).toISOString());
1239
+ }
1240
+ async close(reason) {
1241
+ const events = (await this.journal.loadTree(this.rootId) ?? []).filter((event) => event.kind === "seat-segment" && event.id === this.nodeId);
1242
+ await this.reconcile(events);
1243
+ const last = events.filter((event) => event.phase === "started").at(-1);
1244
+ if (last && !events.some((event) => event.phase === "ended" && event.segmentIndex === last.segmentIndex)) await this.end(last, reason);
1245
+ }
1246
+ async end(start, reason) {
1247
+ const at = new Date(this.now()).toISOString();
1248
+ await this.journal.appendEvent(this.rootId, {
1249
+ ...start,
1250
+ phase: "ended",
1251
+ reason,
1252
+ at
1253
+ });
1254
+ await this.onSegment?.({
1255
+ seat: start.seat,
1256
+ harness: start.harness,
1257
+ provider: start.provider,
1258
+ model: start.model,
1259
+ startedAt: start.at,
1260
+ endedAt: at,
1261
+ reason
1262
+ }, "ended");
1263
+ this.observedThrough += 1;
1264
+ }
1265
+ /** A crash may land between the authoritative journal append and observer delivery. On
1266
+ * reconstruction, deliver every unobserved boundary again; the observer projection folds
1267
+ * repeated boundaries by seat and start time, so a callback never decides execution identity. */
1268
+ async reconcile(events) {
1269
+ const starts = /* @__PURE__ */ new Map();
1270
+ for (let index = 0; index < events.length; index += 1) {
1271
+ const event = events[index];
1272
+ if (event.phase === "started") starts.set(event.segmentIndex, event);
1273
+ if (index <= this.observedThrough) continue;
1274
+ const start = event.phase === "started" ? event : starts.get(event.segmentIndex);
1275
+ if (!start) throw new ValidationError("seat segment ended without a committed start");
1276
+ await this.onSegment?.({
1277
+ seat: start.seat,
1278
+ harness: start.harness,
1279
+ provider: start.provider,
1280
+ model: start.model,
1281
+ startedAt: start.at,
1282
+ ...event.phase === "ended" ? {
1283
+ endedAt: event.at,
1284
+ reason: event.reason
1285
+ } : {}
1286
+ }, event.phase);
1287
+ this.observedThrough = index;
1288
+ }
1289
+ }
1290
+ };
1291
+ /** Preserve the authored profile for identity; only the provider-facing copy changes stages. */
1292
+ function seatExecutionProfile(profile, stage) {
1293
+ const { seats: _seats, ...withoutSeats } = profile;
1118
1294
  return {
1119
- push(note) {
1120
- notes.push(note);
1121
- if (notes.length > cap) notes.splice(0, notes.length - cap);
1122
- },
1123
- read: () => [...notes],
1124
- last: () => notes[notes.length - 1],
1125
- size: () => notes.length
1295
+ ...withoutSeats,
1296
+ harness: stage.harness,
1297
+ ...stage.tools === void 0 ? {} : { tools: stage.tools },
1298
+ ...stage.permissions === void 0 ? {} : { permissions: stage.permissions },
1299
+ model: {
1300
+ ...profile.model,
1301
+ default: stage.model,
1302
+ provider: stage.provider,
1303
+ ...stage.reasoningEffort === void 0 ? {} : { reasoningEffort: stage.reasoningEffort },
1304
+ ...stage.credentialSource === void 0 ? {} : { metadata: {
1305
+ ...profile.model?.metadata,
1306
+ credentialSource: stage.credentialSource
1307
+ } }
1308
+ }
1309
+ };
1310
+ }
1311
+ function authoredSeatStages(profile) {
1312
+ const seats = profile.seats;
1313
+ if (seats === void 0) return void 0;
1314
+ if (!Array.isArray(seats) || seats.length === 0) throw new ValidationError("AgentProfile.seats must be a nonempty ordered chain");
1315
+ return seats;
1316
+ }
1317
+ const USAGE_LIMIT_CODES = /* @__PURE__ */ new Set([
1318
+ "provider_quota_exhausted",
1319
+ "subscription_usage_limit",
1320
+ "usage_limit_reached",
1321
+ "usage_limit_exceeded",
1322
+ "weekly_limit_reached",
1323
+ "session_limit_reached"
1324
+ ]);
1325
+ /** Normalize a native harness refusal into a typed limit. A plain HTTP 429 is insufficient. */
1326
+ function subscriptionUsageLimitSignal(failure) {
1327
+ if (failure.errorCode && USAGE_LIMIT_CODES.has(failure.errorCode.toLowerCase())) return "subscription-usage-limit";
1328
+ if (/\bYou've hit your (?:usage|weekly|session|monthly spend) limit\b/iu.test(failure.error)) return "subscription-usage-limit";
1329
+ if (/\bUsage limit reached for \d+ hours?\b|已达到\s*\d+\s*小时的使用上限/iu.test(failure.error)) return "subscription-usage-limit";
1330
+ }
1331
+ /** An ineligible or misconfigured account must never turn an authored stage into another model. */
1332
+ function checkedSeatSelection(stage, selected) {
1333
+ if ("resumeAt" in selected) {
1334
+ if (!Number.isFinite(Date.parse(selected.resumeAt))) throw new ValidationError("selectSeat: resumeAt must be an ISO timestamp");
1335
+ return selected;
1336
+ }
1337
+ if (!selected.seat.trim()) throw new ValidationError("selectSeat: seat must be nonempty");
1338
+ if (stage.selector.kind === "seat" && stage.selector.id !== selected.seat) throw new ValidationError("selectSeat: selection does not match the authored seat");
1339
+ if (selected.backend.backend !== "provider") throw new ValidationError("selectSeat: selection must use a provider backend");
1340
+ return selected;
1341
+ }
1342
+ // src/runtime/supervise/node-status.ts
1343
+ /** Which {@link NodeStatus} values mean the node is finished. */
1344
+ const terminalNodeStatuses = /* @__PURE__ */ new Set([
1345
+ "done",
1346
+ "failed",
1347
+ "cancelled"
1348
+ ]);
1349
+ /**
1350
+ * True once a node has reached a terminal status.
1351
+ *
1352
+ * The single owner of this rule. Written per call site it drifts silently: a status added to
1353
+ * `NodeStatus` is classified by whichever sites the author remembered, and the ones they missed
1354
+ * keep a dead node in the live set — a stop rule that never fires, mail delivered to a worker that
1355
+ * cannot read it, or a cancel answered `not_live` for a node that is still running.
1356
+ */
1357
+ function isTerminalNodeStatus(status) {
1358
+ return terminalNodeStatuses.has(status);
1359
+ }
1360
+ /** True while a node has not yet reached a terminal status. The complement of
1361
+ * {@link isTerminalNodeStatus}, so the two can never disagree. */
1362
+ function isLiveNodeStatus(status) {
1363
+ return !terminalNodeStatuses.has(status);
1364
+ }
1365
+ // src/runtime/supervise/progress.ts
1366
+ /**
1367
+ *
1368
+ * The LIVE read-model of a still-RUNNING worker — what a driver can see BEFORE the worker settles.
1369
+ *
1370
+ * Until this existed, `observe_agent` on a running worker returned `{status:'running', spent:{0,0},
1371
+ * outRef:null, output:null}`: nothing a brain could act on, so a brain that wanted to steer had no
1372
+ * evidence to steer FROM. This is the other half of the steering wire (the first half is
1373
+ * `Executor.deliver`): a supervisor cannot correct a worker it cannot watch.
1374
+ *
1375
+ * Two layers, both pull-based — no timer, no background task, so it is safe to leave on:
1376
+ *
1377
+ * - The SCOPE layer, available for EVERY executor with no executor cooperation at all: usage
1378
+ * events are timestamped as they arrive, so `lastActivityAt` / `idleMs` / `stalled` /
1379
+ * `tokens` / `turns` are derived from the stream the conserved pool already meters.
1380
+ * - The EXECUTOR layer, optional enrichment via `Executor.progress()`: the tool/file activity
1381
+ * the harness exposes, its own turn count, and how many steers are queued but unread.
1382
+ *
1383
+ * `stalled` is a DERIVED read, computed at observation time against `stallAfterMs` — never a
1384
+ * background watchdog. A worker that has produced no metered activity for longer than the
1385
+ * threshold reads `stalled: true`; nothing is killed, nothing is retried. The driver decides.
1386
+ *
1387
+ * @experimental
1388
+ */
1389
+ /** How long a worker may produce no metered activity before a `progress()` read calls it stalled.
1390
+ * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a
1391
+ * false stall that provokes a steer is worse than a late one. */
1392
+ const DEFAULT_STALL_AFTER_MS = 18e4;
1393
+ /** A short, already-truncated descriptor of a tool call's target — the file/command a driver
1394
+ * needs to tell "editing the right module" from "re-reading the same file for the fifth time",
1395
+ * without pulling the worker's transcript across the wire. Shared by every executor that fills an
1396
+ * `ActivityLog` (pi RPC, sandbox session parts, cli-bridge tool-call deltas) so one harness's
1397
+ * argument naming never reads differently from another's in the same driver's window. */
1398
+ function describeToolArgs(argsValue) {
1399
+ if (!argsValue || typeof argsValue !== "object") return void 0;
1400
+ const a = argsValue;
1401
+ for (const key of [
1402
+ "filePath",
1403
+ "file_path",
1404
+ "path",
1405
+ "file",
1406
+ "command",
1407
+ "cmd",
1408
+ "pattern"
1409
+ ]) {
1410
+ const v = a[key];
1411
+ if (typeof v === "string" && v.length > 0) return v.length > 120 ? `${v.slice(0, 117)}...` : v;
1412
+ }
1413
+ }
1414
+ /** Create a bounded activity ring. `limit` caps memory for a worker that runs thousands of tools. */
1415
+ function createActivityLog(limit = 12) {
1416
+ const notes = [];
1417
+ const cap = Math.max(1, Math.floor(limit));
1418
+ return {
1419
+ push(note) {
1420
+ notes.push(note);
1421
+ if (notes.length > cap) notes.splice(0, notes.length - cap);
1422
+ },
1423
+ read: () => [...notes],
1424
+ last: () => notes[notes.length - 1],
1425
+ size: () => notes.length
1126
1426
  };
1127
1427
  }
1128
1428
  /** Fold the scope-derived facts and the executor's optional enrichment into one read. Pure: the
@@ -4662,1503 +4962,1203 @@ function retainedRunIntent(options, identity, contextTransfer, turnFields) {
4662
4962
  create: retainedCreateMaterial(options.environment),
4663
4963
  turn: retainedTurnMaterial(options.turn, contextTransfer, turnFields)
4664
4964
  });
4665
- return {
4666
- phase: "intent",
4667
- ...material,
4668
- runId: `retained-intent-run:${requestDigest.slice(7)}`,
4669
- requestDigest
4670
- };
4671
- }
4672
- function retainedContextTransfer(value) {
4673
- if (value === void 0) return void 0;
4674
- const parsed = ContextTransferRequestSchema.safeParse(value);
4675
- if (!parsed.success) throw new Error("retained context transfer request is invalid or uses an incompatible wire contract; preserve the original record and explicitly reconstruct and review an Interface 5 transfer request before retrying", { cause: parsed.error });
4676
- return detachedSnapshot(parsed.data, "retained context transfer request");
4677
- }
4678
- function assertExactRetainedRunIntent(received, expected, legacyExpected) {
4679
- const receivedDigest = canonicalCandidateDigest(parseRetainedRunIntent(received, expected));
4680
- if (receivedDigest === canonicalCandidateDigest(expected)) return;
4681
- if (legacyExpected && receivedDigest === canonicalCandidateDigest(legacyExpected())) return;
4682
- throw new Error("retained run intent conflicts with replay material");
4683
- }
4684
- function parseRetainedRunIntent(value, expected) {
4685
- const stable = detachedSnapshot(value, "retained run intent");
4686
- if (stable === null || typeof stable !== "object" || Array.isArray(stable)) throw new Error("retained run intent is malformed");
4687
- const record = stable;
4688
- if (Object.keys(record).some((key) => !Object.hasOwn(expected, key))) throw new Error("retained run intent contains unsupported material");
4689
- if (record.phase !== "intent") throw new Error("retained run intent has an invalid phase");
4690
- for (const [key, value] of Object.entries(record)) if (key !== "phase" && (typeof value !== "string" || value.length === 0)) throw new Error(`retained run intent field "${key}" is invalid`);
4691
- assertDigest$2(record.requestedProfileDigest, "retained run intent profile digest");
4692
- assertDigest$2(record.requestDigest, "retained run intent request digest");
4693
- if (record.outputFilePolicyDigest !== void 0) assertDigest$2(record.outputFilePolicyDigest, "retained run intent file policy digest");
4694
- return stable;
4695
- }
4696
- function assertDigest$2(value, label) {
4697
- if (typeof value !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(value)) throw new Error(`${label} is invalid`);
4698
- }
4699
- /** Rebuild a retained-run client without retaining any object from the starter. @stable */
4700
- async function reconnectRetainedRun(options) {
4701
- const controlRef = AgentExactRunControlRefSchema.parse(options.controlRef);
4702
- if (controlRef.provider !== options.provider.name) throw new Error(`run provider "${controlRef.provider}" does not match "${options.provider.name}"`);
4703
- const providerCapabilities = await assertRetainedCapabilities(options.provider);
4704
- if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
4705
- const environment = await options.provider.get(controlRef.environmentId);
4706
- if (!environment) return null;
4707
- const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
4708
- const exact = exactSession(environment, controlRef);
4709
- return createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now);
4710
- }
4711
- async function assertRetainedCapabilities(provider) {
4712
- const capabilities = AgentEnvironmentCapabilitiesSchema.parse(await provider.capabilities());
4713
- assertRetainedCapabilityRequirements(provider.name, capabilities);
4714
- return capabilities;
4715
- }
4716
- /** A measured environment capability document wins; an absent one uses the provider document. */
4717
- function retainedCapabilitiesForEnvironment(providerName, providerCapabilities, environment) {
4718
- if (environment.capabilities === void 0) return providerCapabilities;
4719
- const measured = AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities);
4720
- assertRetainedCapabilityRequirements(providerName, measured);
4721
- return measured;
4722
- }
4723
- function assertRetainedCapabilityRequirements(providerName, capabilities) {
4724
- if (capabilities.retainedControl === void 0) throw new Error(`provider "${providerName}" cannot control a retry-safe retained run`);
4725
- }
4726
- // src/runtime/supervise/workspace-checkpoint.ts
4727
- /** Workspace-relative path of the marker Runtime writes before every checkpoint. */
4728
- const WORKSPACE_CHECKPOINT_MARKER_PATH = ".agent-runtime-checkpoint";
4729
- /** Bound on one checkpoint: environment lookup, marker write, and the provider operation. */
4730
- const WORKSPACE_CHECKPOINT_TIMEOUT_MS = 12e4;
4731
- /** Bound on the deletes one checkpoint rotation runs. A turn capture cuts them short; the release deletes the rest. */
4732
- const WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS = 12e4;
4733
- /** Write the marker. False when the environment cannot take it, so no restore can be verified. */
4734
- async function writeWorkspaceMarker(environment, marker, signal) {
4735
- if (typeof environment.write !== "function") return false;
4736
- try {
4737
- await environment.write(marker.path, marker.content, { signal });
4738
- return true;
4739
- } catch {
4740
- return false;
4741
- }
4742
- }
4743
- /** Read the marker back from a restored environment and compare it byte for byte. */
4744
- async function verifyWorkspaceMarker(environment, marker, signal) {
4745
- if (marker === void 0) return {
4746
- verified: false,
4747
- detail: "the checkpoint has no marker: the source could not take one"
4748
- };
4749
- if (typeof environment.read !== "function") return {
4750
- verified: false,
4751
- detail: "the restored environment does not expose read"
4752
- };
4753
- try {
4754
- return await environment.read(marker.path, { signal }) === marker.content ? { verified: true } : {
4755
- verified: false,
4756
- detail: "the marker in the restored environment differs from the checkpoint"
4757
- };
4758
- } catch (error) {
4759
- return {
4760
- verified: false,
4761
- detail: `the marker could not be read: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500)
4762
- };
4763
- }
4764
- }
4765
- // src/runtime/retained-native-stop.ts
4766
- /** One request per run: every caller that stops the same execution replays one provider operation,
4767
- * so the operation id and its reason never disagree across a teardown and a release. */
4768
- const NATIVE_STOP_REASON = "Runtime stopped the native harness: its execution is no longer observed";
4769
- /** How often a stop the provider accepted asynchronously reads the run's status. */
4770
- const STOP_STATUS_POLL_MS = 1e3;
4771
- /**
4772
- * Stop the native harness process of a retained execution that Runtime no longer observes.
4773
- *
4774
- * A retained execution outlives its local stream by design, so an aborted observer can reconnect.
4775
- * Keeping its environment preserves the files; it must not keep the harness running. Measured on
4776
- * Discovery: after `disco cancel` the kept root box ran `claude --print` for two
4777
- * more minutes, untraced and charged to the subscription, until an operator stopped the box; on
4778
- * 2026-10-03 a cancelled run kept 18 boxes whose `claude` processes ran until an operator stopped
4779
- * them. The provider's exact cancellation stops the process; the box and its files stay.
4780
- *
4781
- * The operation id is derived from the run reference, so a repeated stop replays the first one.
4782
- * Never rejects: the answer is evidence for the teardown receipt.
4783
- */
4784
- async function stopRetainedNativeExecution(options) {
4785
- const now = options.now ?? Date.now;
4786
- const executionId = options.controlRef.executionId;
4787
- const operationId = `runtime-native-stop-${canonicalCandidateDigest({
4788
- kind: "runtime-native-stop.v1",
4789
- run: options.controlRef
4790
- }).slice(7)}`;
4791
- let effect = "unknown";
4792
- const stop = async () => {
4793
- const handle = options.handle ?? await reconnectRetainedRun({
4794
- provider: options.provider,
4795
- controlRef: options.controlRef
4796
- });
4797
- if (handle === null) return "not_live";
4798
- const cancellation = await handle.cancel({
4799
- operationId,
4800
- reason: NATIVE_STOP_REASON,
4801
- signal: options.signal
4802
- });
4803
- effect = cancellation.status === "conflict" ? "unknown" : cancellation.effect;
4804
- while (effect === "cancel_requested") {
4805
- await sleep(STOP_STATUS_POLL_MS, options.signal);
4806
- const current = await handle.status({ signal: options.signal });
4807
- if (isTerminalSessionStatus(current.status)) effect = current.status === "cancelled" || current.status === "stopped" ? "cancelled" : "not_live";
4808
- }
4809
- return effect;
4810
- };
4811
- try {
4812
- effect = await awaitAbortable$1(stop(), options.signal);
4813
- return {
4814
- executionId,
4815
- effect,
4816
- at: new Date(now()).toISOString()
4817
- };
4818
- } catch (error) {
4819
- return {
4820
- executionId,
4821
- effect: effect === "cancel_requested" ? effect : "unknown",
4822
- at: new Date(now()).toISOString(),
4823
- error: errorText(error instanceof Error ? error.message : error).slice(0, 512)
4824
- };
4825
- }
4826
- }
4827
- /**
4828
- * The teardown-receipt text for stopped executions. A killed harness never reports the usage of
4829
- * its last turn, so the receipt says so instead of letting a reader take the settled spend as
4830
- * complete.
4831
- */
4832
- /** The phrase a stop description carries when the harness may still be running. */
4833
- const NATIVE_STOP_UNCONFIRMED = "it may still be running";
4834
- function describeRetainedNativeStops(stops) {
4835
- return stops.map((stop) => {
4836
- if (stop.effect === "cancelled") return `native execution ${stop.executionId} stopped at ${stop.at}; usage unknown: killed at ${stop.at}`;
4837
- if (stop.effect === "not_live") return `native execution ${stop.executionId} was not live at ${stop.at}`;
4838
- return `native execution ${stop.executionId} stop unconfirmed at ${stop.at} (effect ${stop.effect}${stop.error === void 0 ? "" : `: ${stop.error}`}); ${NATIVE_STOP_UNCONFIRMED}`;
4839
- }).join("; ");
4840
- }
4841
- // src/runtime/supervise/executor-observation.ts
4842
- const executorObservationSeamKey = "runtime.executionObservation";
4843
- function executorObservation(ctx) {
4844
- return ctx.seams[executorObservationSeamKey];
4845
- }
4846
- /** Promise and streaming executors share their owner's existing observation channel. */
4847
- function createExecutorObservation(hooks, node, onProgress) {
4848
- let sequence = 0;
4849
- return {
4850
- progress: onProgress,
4851
- event(target, payload) {
4852
- notifyRuntimeHookEvent(hooks, {
4853
- id: `${node.nodeId}:${node.attemptId}:${target}:${sequence++}`,
4854
- runId: node.rootId,
4855
- parentId: node.nodeId,
4856
- target,
4857
- phase: "after",
4858
- timestamp: Date.now(),
4859
- payload: defaultRedactor({
4860
- ...payload,
4861
- attemptId: node.attemptId
4862
- })
4863
- });
4864
- }
4865
- };
4866
- }
4867
- /** Observe completed HTTP work without copying customer payloads into trace metadata. */
4868
- async function observeModelRequest(observation, model, request) {
4869
- const startedAt = Date.now();
4870
- try {
4871
- const result = await request();
4872
- observation?.event("agent.model", {
4873
- model: result.model ?? model,
4874
- startedAt,
4875
- endedAt: Date.now(),
4876
- status: "ok",
4877
- ...result.usage && model !== "tangle/auto" ? {
4878
- tokensIn: result.usage.input,
4879
- tokensOut: result.usage.output
4880
- } : {},
4881
- ...result.billedCostUsd === void 0 || model === "tangle/auto" ? {} : { costUsd: result.billedCostUsd }
4882
- });
4883
- if (result.content) observation?.progress({
4884
- kind: "text_delta",
4885
- text: result.content
4886
- });
4887
- return result;
4888
- } catch (error) {
4889
- observation?.event("agent.model", {
4890
- model,
4891
- startedAt,
4892
- endedAt: Date.now(),
4893
- status: "error",
4894
- error: { type: error instanceof Error ? error.name : "Error" }
4895
- });
4896
- throw error;
4897
- }
4898
- }
4899
- /** Only a native call id can prove a tool duration; legacy results remain instant observations. */
4900
- function createToolProgressObserver(observation) {
4901
- const calls = /* @__PURE__ */ new Map();
4902
- return (event, at) => {
4903
- if (event.kind !== "tool_call" && event.kind !== "tool_result") return;
4904
- if (event.kind === "tool_call") {
4905
- if (event.toolCallId !== void 0 && !calls.has(event.toolCallId)) calls.set(event.toolCallId, at);
4906
- return;
4907
- }
4908
- const startedAt = event.toolCallId === void 0 ? void 0 : calls.get(event.toolCallId);
4909
- if (event.toolCallId !== void 0) calls.delete(event.toolCallId);
4910
- observation.event("agent.tool_call", {
4911
- toolName: event.toolName,
4912
- toolCallId: event.toolCallId,
4913
- startedAt: startedAt ?? at,
4914
- endedAt: at,
4915
- durationKnown: startedAt !== void 0,
4916
- status: event.status,
4917
- ...event.error ? { error: event.error } : {}
4918
- });
4919
- };
4920
- }
4921
- /** Call only after the exact dispatched admission's journal write has acknowledged. */
4922
- function notifyExecutionAdmitted(hooks, runId, nodeId, admission, now, attemptId) {
4923
- if (admission.phase !== "dispatched" || admission.controlRef.sessionId === void 0) return;
4924
- notifyRuntimeHookEvent(hooks, {
4925
- id: `${nodeId}:admitted:${admission.controlRef.executionId}`,
4926
- runId,
4927
- parentId: nodeId,
4928
- target: "agent.execution",
4929
- phase: "after",
4930
- timestamp: now(),
4931
- payload: {
4932
- nodeId,
4933
- ...attemptId === void 0 ? {} : { attemptId },
4934
- controlRef: { ...admission.controlRef },
4935
- sessionId: admission.controlRef.sessionId
4936
- }
4937
- });
4938
- }
4939
- // src/durable/spawn-journal/event-index.ts
4940
- /**
4941
- * A trace root is valid only beside the output it commits to, with a well-formed root, artifact
4942
- * reference and leaf count (at least the summary leaf). Records written before trace roots carry
4943
- * none and stay valid.
4944
- */
4945
- function assertTraceRoot(event, root) {
4946
- if (!("traceRoot" in event) || event.traceRoot === void 0) return;
4947
- const receipt = event.traceRoot;
4948
- const fields = receipt !== null && typeof receipt === "object" ? receipt : {};
4949
- if (typeof event.outRef !== "string" || typeof fields.root !== "string" || !/^sha256:[0-9a-f]{64}$/.test(fields.root) || typeof fields.ref !== "string" || !/^sha256:[0-9a-f]{64}$/.test(fields.ref) || typeof fields.leafCount !== "number" || !Number.isSafeInteger(fields.leafCount) || fields.leafCount < 1) throw new Error(`spawn journal corrupted: ${event.kind} for node '${event.id}' carries a malformed trace root in tree '${root}'`);
4950
- }
4951
- /** One validation implementation for memory, durable append, and cold replay. */
4952
- /** @internal shared with the SQL-backed store. */
4953
- var SpawnEventIndex = class {
4954
- root;
4955
- nodes = /* @__PURE__ */ new Map();
4956
- cursors = /* @__PURE__ */ new Set();
4957
- constructor(root) {
4958
- this.root = root;
4959
- }
4960
- assert(event) {
4961
- const node = this.nodes.get(event.id);
4962
- this.assertRetained(node, event);
4963
- assertTraceRoot(event, this.root);
4964
- if (event.kind === "reconciled" && event.reservation) {
4965
- if (!node?.budget) throw new Error("reservation evidence has no admitted node");
4966
- assertValidBudget(event.reservation, "reconciled reservation");
4967
- for (const [name, value] of Object.entries(event.reservation.resources ?? {})) if (node.budget.resources?.[name]?.unit !== value.unit) throw new Error(`reconciled reservation resource ${name}: original grant unit mismatch`);
4968
- for (const channel of [
4969
- "maxTokens",
4970
- "maxIterations",
4971
- "maxUsd"
4972
- ]) if (event.reservation[channel] !== void 0 && node.budget[channel] === void 0) throw new Error(`reconciled reservation adds an undeclared ${channel} channel`);
4973
- }
4974
- if (event.kind === "admission-queued" || event.kind === "admission-granted") {
4975
- if (!node?.spawned || node.closed || typeof event.attemptId !== "string" || event.attemptId.length === 0 || event.kind === "admission-granted" && node.grants?.has(`${event.attemptId}:${event.seq}`)) throw new Error(`spawn journal corrupted: invalid admission transition for '${event.id}'`);
4976
- if (!Number.isSafeInteger(event.seq) || event.seq < 0 || event.kind === "admission-queued" && (![
4977
- "budget",
4978
- "slot",
4979
- "seat"
4980
- ].includes(event.gate) || event.resumeAt !== void 0 && !Number.isFinite(Date.parse(event.resumeAt))) || !Number.isFinite(Date.parse(event.at)) || event.kind === "admission-granted" && (!Number.isFinite(Date.parse(event.deadlineArmedAt)) || event.deadlineAt !== void 0 && !Number.isFinite(Date.parse(event.deadlineAt)))) throw new Error(`spawn journal corrupted: invalid admission clock for '${event.id}'`);
4981
- if (event.kind === "admission-granted" && node.grantClock && (event.deadlineArmedAt !== node.grantClock.deadlineArmedAt || event.deadlineAt !== node.grantClock.deadlineAt)) throw new Error(`spawn journal corrupted: admission deadline changed for '${event.id}'`);
4982
- }
4983
- if (event.kind === "execution-evidence") {
4984
- if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef) || event.attemptId !== void 0 && (typeof event.attemptId !== "string" || !event.attemptId)) throw new Error("spawn journal corrupted: executor evidence has no spawned node, valid content reference or attempt");
4985
- }
4986
- if (event.kind === "materialized") {
4987
- if (node?.materialized) throw new Error(`spawn journal corrupted: duplicate materialization receipt for node '${event.id}' in tree '${this.root}'`);
4988
- if (!node?.spawned) throw new Error(`spawn journal corrupted: materialization for node '${event.id}' precedes its spawn in tree '${this.root}'`);
4989
- }
4990
- if (event.kind === "seat-materialized") {
4991
- if (!node?.materialized || node.authoredProfileDigest === void 0 || event.receipt.status !== "known" || event.receipt.authoredProfileDigest !== node.authoredProfileDigest || !Number.isSafeInteger(event.segmentIndex) || event.segmentIndex <= node.latestSeatMaterialization) throw new Error(`spawn journal corrupted: invalid seat materialization for node '${event.id}' in tree '${this.root}'`);
4992
- }
4993
- if (event.kind === "execution-bound") {
4994
- if (node?.bindings.has(event.binding.attemptId)) throw new Error(`spawn journal corrupted: duplicate execution binding for node '${event.id}' attempt '${event.binding.attemptId}' in tree '${this.root}'`);
4995
- if (!node?.materialized) throw new Error(`spawn journal corrupted: execution binding for node '${event.id}' precedes materialization in tree '${this.root}'`);
4996
- }
4997
- if (!outsideCursorNamespace(event) && this.cursors.has(event.seq)) throw new Error(`spawn journal corrupted: duplicate cursor seq ${event.seq} in tree '${this.root}'; the cursor order replay relies on is not unique`);
4998
- }
4999
- /** Called after validation; a file writer discards staged state if grouped publication fails. */
5000
- add(event) {
5001
- if (!outsideCursorNamespace(event)) this.cursors.add(event.seq);
5002
- if (event.kind !== "spawned" && event.kind !== "admission-granted" && event.kind !== "materialized" && event.kind !== "seat-materialized" && event.kind !== "execution-bound" && event.kind !== "execution-input" && event.kind !== "execution-admitted" && event.kind !== "execution-result" && event.kind !== "execution-abandoned" && event.kind !== "environment-teardown" && event.kind !== "environment-terminal" && !closesCursorSlot(event)) return;
5003
- let node = this.nodes.get(event.id);
5004
- if (!node) {
5005
- node = {
5006
- spawned: false,
5007
- closed: false,
5008
- materialized: false,
5009
- latestSeatMaterialization: 0,
5010
- bindings: /* @__PURE__ */ new Set(),
5011
- inputs: /* @__PURE__ */ new Set(),
5012
- input: false,
5013
- result: false,
5014
- abandoned: false,
5015
- admissions: /* @__PURE__ */ new Map(),
5016
- unusableEnvironments: /* @__PURE__ */ new Set()
5017
- };
5018
- this.nodes.set(event.id, node);
5019
- }
5020
- if (event.kind === "environment-teardown") {
5021
- if (event.destroyed) node.unusableEnvironments.add(event.environmentId);
5022
- return;
5023
- }
5024
- if (event.kind === "environment-terminal") {
5025
- node.unusableEnvironments.add(event.environmentId);
5026
- return;
5027
- }
5028
- if (event.kind === "execution-admitted" && event.admission.phase === "environment") node.lastEnvironmentId = event.admission.environmentId;
5029
- if (event.kind === "spawned") {
5030
- node.spawned = true;
5031
- node.budget = event.budget;
5032
- } else if (event.kind === "admission-granted") {
5033
- node.grants ??= /* @__PURE__ */ new Set();
5034
- node.grants.add(`${event.attemptId}:${event.seq}`);
5035
- node.grantClock ??= {
5036
- deadlineArmedAt: event.deadlineArmedAt,
5037
- deadlineAt: event.deadlineAt
5038
- };
5039
- } else if (event.kind === "materialized") {
5040
- node.materialized = true;
5041
- node.authoredProfileDigest = event.receipt.authoredProfileDigest;
5042
- } else if (event.kind === "seat-materialized") node.latestSeatMaterialization = event.segmentIndex;
5043
- else if (event.kind === "execution-bound") node.bindings.add(event.binding.attemptId);
5044
- else if (event.kind === "execution-input") {
5045
- node.inputs.add(event.seq);
5046
- node.input = true;
5047
- node.latestInput = event.seq;
5048
- node.result = false;
5049
- node.abandoned = false;
5050
- node.admissions.clear();
5051
- } else if (event.kind === "execution-admitted") node.admissions.set(event.admission.phase, event.admission);
5052
- else if (event.kind === "execution-result") node.result = true;
5053
- else if (event.kind === "execution-abandoned") node.abandoned = true;
5054
- if (closesCursorSlot(event)) node.closed = true;
5055
- }
5056
- assertRetained(node, event) {
5057
- if (event.kind !== "execution-input" && event.kind !== "execution-admitted" && event.kind !== "execution-result" && event.kind !== "execution-abandoned") return;
5058
- function fail(reason) {
5059
- throw new Error(`spawn journal corrupted: retained execution '${event.id}' ${reason}`);
5060
- }
5061
- if (!node?.spawned) fail("precedes its spawn");
5062
- if (node.closed) fail("follows its terminal settlement");
5063
- if (event.kind === "execution-input") {
5064
- if (!/^sha256:[0-9a-f]{64}$/.test(event.taskRef)) fail("has an invalid task reference");
5065
- if (node.inputs.has(event.seq)) fail("has duplicate input sequence");
5066
- const environment = node.admissions.get("environment");
5067
- const ranIn = environment?.phase === "environment" ? environment.environmentId : node.lastEnvironmentId;
5068
- const closed = node.abandoned || ranIn !== void 0 && node.unusableEnvironments.has(ranIn);
5069
- if (node.input && !node.result && !closed) fail("input replaces an unfinished invocation");
5070
- return;
5071
- }
5072
- if (event.kind === "execution-abandoned") {
5073
- if (!node.input || node.latestInput !== event.inputSeq) fail("abandons an invocation that is not its latest");
5074
- if (node.result) fail("abandons an invocation that has a result");
5075
- if (node.abandoned) fail("abandons an invocation twice");
5076
- if (!Number.isSafeInteger(event.failures) || event.failures < 1) fail("abandons without a failure count");
5077
- return;
5078
- }
5079
- if (node.abandoned) fail(`${event.kind} follows its abandonment`);
5080
- if (event.kind === "execution-result") {
5081
- if (node.result) fail("has duplicate result");
5082
- if (!node.admissions.has("dispatched")) fail("result precedes dispatch");
5083
- if (!/^sha256:[0-9a-f]{64}$/.test(event.outRef)) fail("has an invalid result reference");
5084
- if (event.outputFormat !== void 0 && event.outputFormat !== "json") fail("has an invalid output format");
5085
- assertValidSpend(event.spent, "retained execution result");
5086
- executorFailureReason(event);
5087
- return;
5088
- }
5089
- const admission = event.admission;
5090
- if (!admission || ![
5091
- "intent",
5092
- "environment",
5093
- "dispatched"
5094
- ].includes(admission.phase)) fail("has an invalid admission phase");
5095
- if (node.admissions.has(admission.phase)) fail("has duplicate admission phase");
5096
- if (node.result) fail("admission follows result");
5097
- if (!node.input) fail("admission precedes input");
5098
- if (admission.phase === "intent") {
5099
- if (node.admissions.size !== 0) fail("intent follows another admission");
5100
- return;
5101
- }
5102
- const intent = node.admissions.get("intent");
5103
- if (intent?.phase !== "intent") fail("admission precedes intent");
5104
- if (admission.idempotencyKey !== intent.idempotencyKey || admission.turnId !== intent.turnId) fail("changes its admitted request identity");
5105
- if (admission.phase === "environment") {
5106
- if (admission.provider !== intent.provider || admission.sessionId !== intent.sessionId || admission.executionId !== intent.executionId) fail("changes its admitted execution identity");
5107
- return;
5108
- }
5109
- const environment = node.admissions.get("environment");
5110
- if (environment?.phase !== "environment") fail("dispatch precedes environment");
5111
- const control = admission.controlRef;
5112
- if (!control || control.provider !== intent.provider || control.environmentId !== environment.environmentId || control.sessionId !== intent.sessionId || control.executionId !== intent.executionId) fail("dispatch changes its admitted execution identity");
5113
- }
5114
- };
5115
- /**
5116
- * The records that CLOSE a node's cursor slot: a settlement or a cancellation. The complement question to {@link outsideCursorNamespace}, and the one a resume needs —
5117
- * a kind missing here leaves a finished node looking live, so its budget is never reclaimed and
5118
- * its reservation is replayed as still in doubt.
5119
- */
5120
- function closesCursorSlot(ev) {
5121
- return ev.kind === "settled" || ev.kind === "cancelled";
5122
- }
5123
- const outsideKinds = /* @__PURE__ */ new Set([
5124
- "spawned",
5125
- "admission-queued",
5126
- "admission-granted",
5127
- "metered",
5128
- "materialized",
5129
- "execution-bound",
5130
- "execution-input",
5131
- "execution-admitted",
5132
- "execution-result",
5133
- "execution-abandoned",
5134
- "execution-evidence",
5135
- "evidence-pending",
5136
- "progress",
5137
- "reconciled",
5138
- "edge",
5139
- "teardown-unconfirmed",
5140
- "teardown-pending",
5141
- "teardown-confirmed",
5142
- "environment-teardown",
5143
- "environment-terminal",
5144
- "workspace-checkpoint-requested",
5145
- "workspace-checkpoint-refused",
5146
- "workspace-checkpoint",
5147
- "workspace-checkpoint-fork-requested",
5148
- "workspace-checkpoint-fork-ready",
5149
- "workspace-checkpoint-fork-teardown",
5150
- "workspace-checkpoint-capture",
5151
- "workspace-checkpoint-cleanup",
5152
- "workspace-restored",
5153
- "workspace-capture-started",
5154
- "workspace-capture",
5155
- "trace-unpropagated",
5156
- "seat-segment",
5157
- "seat-materialized",
5158
- "seat-paused",
5159
- "run-parked",
5160
- "root-segment",
5161
- "root-reentered",
5162
- "reopened",
5163
- "paused",
5164
- "barren-pause",
5165
- "driver-attempt",
5166
- "node-inputs-resolved",
5167
- "edge-verdict",
5168
- "join-state"
5169
- ]);
5170
- /** True for a node-CREATION or informational record. Narrows, so a caller keeps the union's arms. */
5171
- function outsideCursorNamespace(ev) {
5172
- return outsideKinds.has(ev.kind);
4965
+ return {
4966
+ phase: "intent",
4967
+ ...material,
4968
+ runId: `retained-intent-run:${requestDigest.slice(7)}`,
4969
+ requestDigest
4970
+ };
5173
4971
  }
5174
- /** True for a record inside the cursor namespace. Narrows to {@link CursorNamespaceEvent}. */
5175
- function insideCursorNamespace(ev) {
5176
- return !outsideKinds.has(ev.kind);
4972
+ function retainedContextTransfer(value) {
4973
+ if (value === void 0) return void 0;
4974
+ const parsed = ContextTransferRequestSchema.safeParse(value);
4975
+ if (!parsed.success) throw new Error("retained context transfer request is invalid or uses an incompatible wire contract; preserve the original record and explicitly reconstruct and review an Interface 5 transfer request before retrying", { cause: parsed.error });
4976
+ return detachedSnapshot(parsed.data, "retained context transfer request");
5177
4977
  }
5178
- // src/runtime/supervise/tree-key.ts
5179
- /** Runtime tag used only for a child that owns another supervised scope. */
5180
- const driverRuntime = "driver";
5181
- const nestedDriverTreeOwners = /* @__PURE__ */ new WeakSet();
5182
- /** Canonical journal key for the scope owned by one nested driver node. */
5183
- function nestedDriverTreeRoot(parentTreeRoot, driverNodeId) {
5184
- return `${parentTreeRoot}/${driverNodeId}`;
4978
+ function assertExactRetainedRunIntent(received, expected, legacyExpected) {
4979
+ const receivedDigest = canonicalCandidateDigest(parseRetainedRunIntent(received, expected));
4980
+ if (receivedDigest === canonicalCandidateDigest(expected)) return;
4981
+ if (legacyExpected && receivedDigest === canonicalCandidateDigest(legacyExpected())) return;
4982
+ throw new Error("retained run intent conflicts with replay material");
5185
4983
  }
5186
- /** Privately mark the exact recursive executor that will create a nested journal tree. */
5187
- function attestNestedDriverTreeOwner(owner) {
5188
- nestedDriverTreeOwners.add(owner);
5189
- return owner;
4984
+ function parseRetainedRunIntent(value, expected) {
4985
+ const stable = detachedSnapshot(value, "retained run intent");
4986
+ if (stable === null || typeof stable !== "object" || Array.isArray(stable)) throw new Error("retained run intent is malformed");
4987
+ const record = stable;
4988
+ if (Object.keys(record).some((key) => !Object.hasOwn(expected, key))) throw new Error("retained run intent contains unsupported material");
4989
+ if (record.phase !== "intent") throw new Error("retained run intent has an invalid phase");
4990
+ for (const [key, value] of Object.entries(record)) if (key !== "phase" && (typeof value !== "string" || value.length === 0)) throw new Error(`retained run intent field "${key}" is invalid`);
4991
+ assertDigest$2(record.requestedProfileDigest, "retained run intent profile digest");
4992
+ assertDigest$2(record.requestDigest, "retained run intent request digest");
4993
+ if (record.outputFilePolicyDigest !== void 0) assertDigest$2(record.outputFilePolicyDigest, "retained run intent file policy digest");
4994
+ return stable;
5190
4995
  }
5191
- /** Return the canonical owned tree only for an exact privately marked recursive executor. */
5192
- function runtimeOwnedNestedDriverTreeRoot(owner, parentTreeRoot, driverNodeId) {
5193
- return nestedDriverTreeOwners.has(owner) ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId) : void 0;
4996
+ function assertDigest$2(value, label) {
4997
+ if (typeof value !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(value)) throw new Error(`${label} is invalid`);
5194
4998
  }
5195
- // src/durable/spawn-journal/settlement-evidence.ts
5196
- /** Copy a terminal record's overspend at the journal boundary; absent stays absent. */
5197
- function budgetViolationOf(event) {
5198
- if (event.budgetViolation === void 0) return {};
5199
- return { budgetViolation: Object.freeze({ overspent: Object.freeze(event.budgetViolation.overspent.map((entry) => Object.freeze({
5200
- channel: entry.channel,
5201
- reserved: entry.reserved,
5202
- spent: entry.spent
5203
- }))) }) };
4999
+ /** Rebuild a retained-run client without retaining any object from the starter. @stable */
5000
+ async function reconnectRetainedRun(options) {
5001
+ const controlRef = AgentExactRunControlRefSchema.parse(options.controlRef);
5002
+ if (controlRef.provider !== options.provider.name) throw new Error(`run provider "${controlRef.provider}" does not match "${options.provider.name}"`);
5003
+ const providerCapabilities = await assertRetainedCapabilities(options.provider);
5004
+ if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
5005
+ const environment = await options.provider.get(controlRef.environmentId);
5006
+ if (!environment) return null;
5007
+ const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
5008
+ const exact = exactSession(environment, controlRef);
5009
+ return createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now);
5204
5010
  }
5205
- /** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */
5206
- function copyProviderModelEvidence(evidence) {
5207
- if (evidence === void 0) return void 0;
5208
- const attempts = snapshotProviderObservations(evidence.attempts);
5209
- const models = Object.freeze([...evidence.models]);
5210
- return Object.freeze(evidence.status === "unknown" ? {
5211
- status: "unknown",
5212
- attempts,
5213
- models,
5214
- reason: evidence.reason
5215
- } : {
5216
- status: "known",
5217
- attempts,
5218
- models
5219
- });
5011
+ async function assertRetainedCapabilities(provider) {
5012
+ const capabilities = AgentEnvironmentCapabilitiesSchema.parse(await provider.capabilities());
5013
+ assertRetainedCapabilityRequirements(provider.name, capabilities);
5014
+ return capabilities;
5220
5015
  }
5221
- function traceEvidenceFor(event) {
5222
- return event.trace ?? {
5223
- status: "unavailable",
5224
- reason: "legacy-settlement-without-trace-evidence"
5225
- };
5016
+ /** A measured environment capability document wins; an absent one uses the provider document. */
5017
+ function retainedCapabilitiesForEnvironment(providerName, providerCapabilities, environment) {
5018
+ if (environment.capabilities === void 0) return providerCapabilities;
5019
+ const measured = AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities);
5020
+ assertRetainedCapabilityRequirements(providerName, measured);
5021
+ return measured;
5226
5022
  }
5227
- // src/durable/spawn-journal/tree-view.ts
5228
- /**
5229
- * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds
5230
- * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each
5231
- * `metered` event's driver-inference spend onto its node in a separate additive pass so the view
5232
- * matches the recorded cursor. It does not recover live executors or driver state after restart.
5233
- */
5234
- function materializeTreeView(events) {
5235
- const nodes = /* @__PURE__ */ new Map();
5236
- let root;
5237
- const spawns = events.filter((ev) => ev.kind === "spawned").sort((a, b) => a.seq - b.seq);
5238
- const settlements = events.filter((ev) => insideCursorNamespace(ev)).sort((a, b) => a.seq - b.seq);
5239
- for (const ev of spawns) {
5240
- if (ev.parent === void 0 && root === void 0) root = ev.id;
5241
- nodes.set(ev.id, {
5242
- id: ev.id,
5243
- parent: ev.parent,
5244
- label: ev.label,
5245
- status: "pending",
5246
- runtime: ev.runtime,
5247
- budget: ev.budget,
5248
- ...ev.ownedTreeRoot === void 0 ? {} : { ownedTreeRoot: ev.ownedTreeRoot },
5249
- ...ev.assignmentId === void 0 ? {} : { assignmentId: ev.assignmentId },
5250
- ...ev.identity ? { identity: ev.identity } : {},
5251
- ...ev.modelSubstitution ? { modelSubstitution: ev.modelSubstitution } : {},
5252
- ...Number.isFinite(Date.parse(ev.at)) ? { spawnedAt: Date.parse(ev.at) } : {},
5253
- spent: zeroSpend()
5254
- });
5255
- }
5256
- for (const ev of settlements) {
5257
- const node = requireNode(nodes, ev.id);
5258
- const down = ev.kind === "cancelled" || ev.status === "down";
5259
- node.status = ev.kind === "cancelled" ? "cancelled" : down ? "failed" : "done";
5260
- if (ev.spent !== void 0) node.spent = cloneSpend(ev.spent);
5261
- node.providerModel = copyProviderModelEvidence(ev.providerModel);
5262
- node.outRef = ev.outRef;
5263
- node.failure = down ? ev.failure ?? settlementFailureCause({
5264
- reason: ev.reason ?? (ev.kind === "settled" ? ev.verdict?.notes : void 0) ?? "child down",
5265
- infra: ev.infra,
5266
- retainedPendingCause: ev.retainedPendingCause
5267
- }) : void 0;
5268
- node.trace = ev.kind === "cancelled" ? ev.trace ?? {
5269
- status: "unavailable",
5270
- reason: "execution-did-not-start"
5271
- } : traceEvidenceFor(ev);
5272
- node.budgetViolation = budgetViolationOf(ev).budgetViolation;
5273
- if (ev.retainedExecution !== void 0) node.retainedExecution = ev.retainedExecution;
5274
- if (ev.retainedPendingCause !== void 0) node.retainedPendingCause = ev.retainedPendingCause;
5275
- const settledAt = Date.parse(ev.at);
5276
- if (Number.isFinite(settledAt)) node.settledAt = settledAt;
5277
- }
5278
- for (const ev of events) {
5279
- if (ev.kind !== "materialized" && ev.kind !== "seat-materialized") continue;
5280
- const node = requireNode(nodes, ev.id);
5281
- node.materialization = ev.receipt;
5282
- node.runtime = ev.receipt.runtime;
5283
- }
5284
- for (const ev of events) {
5285
- if (ev.kind !== "execution-bound") continue;
5286
- const node = requireNode(nodes, ev.id);
5287
- node.executionBindings ??= [];
5288
- node.executionBindings.push(ev.binding);
5289
- }
5290
- for (const ev of events) {
5291
- if (ev.kind !== "reconciled" && ev.kind !== "admission-queued" && ev.kind !== "admission-granted") continue;
5292
- const node = requireNode(nodes, ev.id);
5293
- if (node.status === "pending" || node.status === "queued" || node.status === "acquiring") {
5294
- node.status = ev.kind === "reconciled" ? "pending" : ev.kind === "admission-queued" ? "queued" : "acquiring";
5295
- if (ev.kind === "reconciled") {
5296
- node.spent = cloneSpend(ev.spent);
5297
- node.failure = ev.failure;
5298
- }
5299
- }
5300
- }
5301
- for (const ev of events) {
5302
- if (ev.kind !== "metered") continue;
5303
- const node = requireNode(nodes, ev.id);
5304
- node.spent = addSpend(node.spent, ev.spend);
5305
- }
5306
- const snapshots = [...nodes.values()].map(freezeSnapshot);
5307
- return {
5308
- root: root ?? snapshots[0]?.id ?? "",
5309
- nodes: snapshots,
5310
- inFlight: snapshots.filter((n) => [
5311
- "queued",
5312
- "running",
5313
- "acquiring"
5314
- ].includes(n.status)).length
5315
- };
5023
+ function assertRetainedCapabilityRequirements(providerName, capabilities) {
5024
+ if (capabilities.retainedControl === void 0) throw new Error(`provider "${providerName}" cannot control a retry-safe retained run`);
5316
5025
  }
5317
- function requireNode(nodes, id) {
5318
- const node = nodes.get(id);
5319
- if (!node) throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`);
5320
- return node;
5026
+ // src/runtime/supervise/workspace-checkpoint.ts
5027
+ /** Workspace-relative path of the marker Runtime writes before every checkpoint. */
5028
+ const WORKSPACE_CHECKPOINT_MARKER_PATH = ".agent-runtime-checkpoint";
5029
+ /** Bound on one checkpoint: environment lookup, marker write, and the provider operation. */
5030
+ const WORKSPACE_CHECKPOINT_TIMEOUT_MS = 12e4;
5031
+ /** Bound on the deletes one checkpoint rotation runs. A turn capture cuts them short; the release deletes the rest. */
5032
+ const WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS = 12e4;
5033
+ /** Write the marker. False when the environment cannot take it, so no restore can be verified. */
5034
+ async function writeWorkspaceMarker(environment, marker, signal) {
5035
+ if (typeof environment.write !== "function") return false;
5036
+ try {
5037
+ await environment.write(marker.path, marker.content, { signal });
5038
+ return true;
5039
+ } catch {
5040
+ return false;
5041
+ }
5321
5042
  }
5322
- function freezeSnapshot(node) {
5323
- return {
5324
- id: node.id,
5325
- parent: node.parent,
5326
- label: node.label,
5327
- status: node.status,
5328
- ...node.failure === void 0 ? {} : { failure: node.failure },
5329
- runtime: node.runtime,
5330
- budget: node.budget,
5331
- ownedTreeRoot: node.ownedTreeRoot,
5332
- assignmentId: node.assignmentId,
5333
- identity: node.identity,
5334
- modelSubstitution: node.modelSubstitution,
5335
- materialization: node.materialization,
5336
- executionBindings: node.executionBindings === void 0 ? void 0 : Object.freeze([...node.executionBindings]),
5337
- spent: node.spent,
5338
- providerModel: node.providerModel,
5339
- outRef: node.outRef,
5340
- trace: node.trace,
5341
- ...node.budgetViolation === void 0 ? {} : { budgetViolation: node.budgetViolation },
5342
- ...node.retainedExecution === void 0 ? {} : { retainedExecution: node.retainedExecution },
5343
- ...node.retainedPendingCause === void 0 ? {} : { retainedPendingCause: node.retainedPendingCause },
5344
- settledAt: node.settledAt,
5345
- spawnedAt: node.spawnedAt
5043
+ /** Read the marker back from a restored environment and compare it byte for byte. */
5044
+ async function verifyWorkspaceMarker(environment, marker, signal) {
5045
+ if (marker === void 0) return {
5046
+ verified: false,
5047
+ detail: "the checkpoint has no marker: the source could not take one"
5048
+ };
5049
+ if (typeof environment.read !== "function") return {
5050
+ verified: false,
5051
+ detail: "the restored environment does not expose read"
5346
5052
  };
5053
+ try {
5054
+ return await environment.read(marker.path, { signal }) === marker.content ? { verified: true } : {
5055
+ verified: false,
5056
+ detail: "the marker in the restored environment differs from the checkpoint"
5057
+ };
5058
+ } catch (error) {
5059
+ return {
5060
+ verified: false,
5061
+ detail: `the marker could not be read: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500)
5062
+ };
5063
+ }
5347
5064
  }
5348
- // src/durable/spawn-journal/spawn-forest.ts
5065
+ // src/runtime/retained-native-stop.ts
5066
+ /** One request per run: every caller that stops the same execution replays one provider operation,
5067
+ * so the operation id and its reason never disagree across a teardown and a release. */
5068
+ const NATIVE_STOP_REASON = "Runtime stopped the native harness: its execution is no longer observed";
5069
+ /** How often a stop the provider accepted asynchronously reads the run's status. */
5070
+ const STOP_STATUS_POLL_MS = 1e3;
5349
5071
  /**
5350
- * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.
5072
+ * Stop the native harness process of a retained execution that Runtime no longer observes.
5351
5073
  *
5352
- * Nested driver tree keys are a Runtime implementation detail; callers should use this reader
5353
- * instead of deriving or scanning keys themselves. The reader follows only the explicit
5354
- * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime
5355
- * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are
5356
- * intentionally treated as leaves rather than guessing or scanning convention-derived keys.
5357
- * This preserves each tree's independent cursor namespace on flattened events.
5358
- * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node
5359
- * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work
5360
- * interpretation.
5074
+ * A retained execution outlives its local stream by design, so an aborted observer can reconnect.
5075
+ * Keeping its environment preserves the files; it must not keep the harness running. Measured on
5076
+ * Discovery: after `disco cancel` the kept root box ran `claude --print` for two
5077
+ * more minutes, untraced and charged to the subscription, until an operator stopped the box; on
5078
+ * 2026-10-03 a cancelled run kept 18 boxes whose `claude` processes ran until an operator stopped
5079
+ * them. The provider's exact cancellation stops the process; the box and its files stay.
5361
5080
  *
5362
- * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value
5363
- * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot
5364
- * change the result already observed.
5081
+ * The operation id is derived from the run reference, so a repeated stop replays the first one.
5082
+ * Never rejects: the answer is evidence for the teardown receipt.
5365
5083
  */
5366
- async function loadSpawnForest(journal, root) {
5367
- const rootEvents = await journal.loadTree(root);
5368
- if (rootEvents === void 0) throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`);
5369
- const trees = [];
5370
- const nodes = [];
5371
- const events = [];
5372
- const inDoubt = [];
5373
- const missingTrees = [];
5374
- const visited = /* @__PURE__ */ new Set();
5375
- const queue = [{
5376
- root,
5377
- events: rootEvents
5378
- }];
5379
- for (let cursor = 0; cursor < queue.length; cursor += 1) {
5380
- const current = queue[cursor];
5381
- if (visited.has(current.root)) throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`);
5382
- visited.add(current.root);
5383
- const stableEvents = detachedSnapshot(current.events, `loadSpawnForest tree ${JSON.stringify(current.root)}`);
5384
- const viewEvents = current.ownerSpawn === void 0 || stableEvents.some((event) => event.kind === "spawned" && event.id === current.ownerSpawn?.id) ? [...stableEvents] : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents];
5385
- const view = detachedSnapshot(materializeTreeView(viewEvents), `loadSpawnForest view ${JSON.stringify(current.root)}`);
5386
- trees.push({
5387
- root: current.root,
5388
- ...current.ownerNodeId === void 0 ? {} : { ownerNodeId: current.ownerNodeId },
5389
- ...current.parentTreeRoot === void 0 ? {} : { parentTreeRoot: current.parentTreeRoot },
5390
- events: stableEvents,
5391
- view
5084
+ async function stopRetainedNativeExecution(options) {
5085
+ const now = options.now ?? Date.now;
5086
+ const executionId = options.controlRef.executionId;
5087
+ const operationId = `runtime-native-stop-${canonicalCandidateDigest({
5088
+ kind: "runtime-native-stop.v1",
5089
+ run: options.controlRef
5090
+ }).slice(7)}`;
5091
+ let effect = "unknown";
5092
+ const stop = async () => {
5093
+ const handle = options.handle ?? await reconnectRetainedRun({
5094
+ provider: options.provider,
5095
+ controlRef: options.controlRef
5392
5096
  });
5393
- nodes.push(...view.nodes.filter((node) => current.ownerNodeId === void 0 || node.id !== current.ownerNodeId).map((node) => ({
5394
- treeRoot: current.root,
5395
- ...node
5396
- })));
5397
- events.push(...stableEvents.map((event) => ({
5398
- treeRoot: current.root,
5399
- event
5400
- })));
5401
- const terminal = /* @__PURE__ */ new Set();
5402
- for (const event of stableEvents) if (event.kind === "settled" || event.kind === "cancelled") terminal.add(event.id);
5403
- const spawns = stableEvents.filter((event) => event.kind === "spawned").sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id));
5404
- for (const spawn of spawns) {
5405
- if (spawn.parent !== void 0 && !terminal.has(spawn.id)) inDoubt.push({
5406
- treeRoot: current.root,
5407
- nodeId: spawn.id,
5408
- label: spawn.label,
5409
- runtime: spawn.runtime
5410
- });
5411
- if (spawn.ownedTreeRoot === void 0) continue;
5412
- const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id);
5413
- if (spawn.ownedTreeRoot !== expectedRoot) throw new Error(`loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`);
5414
- const nestedRoot = spawn.ownedTreeRoot;
5415
- const nestedEvents = await journal.loadTree(nestedRoot);
5416
- if (nestedEvents === void 0) {
5417
- missingTrees.push({
5418
- parentTreeRoot: current.root,
5419
- ownerNodeId: spawn.id,
5420
- root: nestedRoot
5421
- });
5422
- continue;
5423
- }
5424
- queue.push({
5425
- root: nestedRoot,
5426
- events: nestedEvents,
5427
- ownerNodeId: spawn.id,
5428
- parentTreeRoot: current.root,
5429
- ownerSpawn: spawn
5430
- });
5097
+ if (handle === null) return "not_live";
5098
+ const cancellation = await handle.cancel({
5099
+ operationId,
5100
+ reason: NATIVE_STOP_REASON,
5101
+ signal: options.signal
5102
+ });
5103
+ effect = cancellation.status === "conflict" ? "unknown" : cancellation.effect;
5104
+ while (effect === "cancel_requested") {
5105
+ await sleep(STOP_STATUS_POLL_MS, options.signal);
5106
+ const current = await handle.status({ signal: options.signal });
5107
+ if (isTerminalSessionStatus(current.status)) effect = current.status === "cancelled" || current.status === "stopped" ? "cancelled" : "not_live";
5431
5108
  }
5109
+ return effect;
5110
+ };
5111
+ try {
5112
+ effect = await awaitAbortable$1(stop(), options.signal);
5113
+ return {
5114
+ executionId,
5115
+ effect,
5116
+ at: new Date(now()).toISOString()
5117
+ };
5118
+ } catch (error) {
5119
+ return {
5120
+ executionId,
5121
+ effect: effect === "cancel_requested" ? effect : "unknown",
5122
+ at: new Date(now()).toISOString(),
5123
+ error: errorText(error instanceof Error ? error.message : error).slice(0, 512)
5124
+ };
5432
5125
  }
5433
- return detachedSnapshot({
5434
- root,
5435
- trees,
5436
- nodes,
5437
- events,
5438
- inDoubt,
5439
- missingTrees
5440
- }, "loadSpawnForest result");
5441
5126
  }
5442
- /** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to
5443
- * the parent tree. Supply a view-only parentless copy so strict materialization can fold root
5444
- * metering without weakening its missing-spawn corruption check for ordinary event lists. */
5445
- /** @internal Exact parentless root for a Runtime-owned subtree. */
5446
- function ownedTreeRootSpawn(spawn) {
5447
- const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn;
5448
- return root;
5127
+ /**
5128
+ * The teardown-receipt text for stopped executions. A killed harness never reports the usage of
5129
+ * its last turn, so the receipt says so instead of letting a reader take the settled spend as
5130
+ * complete.
5131
+ */
5132
+ /** The phrase a stop description carries when the harness may still be running. */
5133
+ const NATIVE_STOP_UNCONFIRMED = "it may still be running";
5134
+ function describeRetainedNativeStops(stops) {
5135
+ return stops.map((stop) => {
5136
+ if (stop.effect === "cancelled") return `native execution ${stop.executionId} stopped at ${stop.at}; usage unknown: killed at ${stop.at}`;
5137
+ if (stop.effect === "not_live") return `native execution ${stop.executionId} was not live at ${stop.at}`;
5138
+ return `native execution ${stop.executionId} stop unconfirmed at ${stop.at} (effect ${stop.effect}${stop.error === void 0 ? "" : `: ${stop.error}`}); ${NATIVE_STOP_UNCONFIRMED}`;
5139
+ }).join("; ");
5449
5140
  }
5450
- // src/runtime/supervise/retained-owner-state.ts
5451
- const owners = /* @__PURE__ */ new WeakMap();
5452
- /** Bound native custody, read from its canonical receipts without probing another provider. */
5453
- function scopeOwnerLiabilities(scope, events) {
5454
- const state = owners.get(scope);
5455
- if (!state) return {
5456
- environmentHeld: false,
5457
- invocationUnsettled: false,
5458
- measuredResources: /* @__PURE__ */ new Map()
5141
+ // src/runtime/supervise/executor-observation.ts
5142
+ const executorObservationSeamKey = "runtime.executionObservation";
5143
+ function executorObservation(ctx) {
5144
+ return ctx.seams[executorObservationSeamKey];
5145
+ }
5146
+ /** Promise and streaming executors share their owner's existing observation channel. */
5147
+ function createExecutorObservation(hooks, node, onProgress) {
5148
+ let sequence = 0;
5149
+ return {
5150
+ progress: onProgress,
5151
+ event(target, payload) {
5152
+ notifyRuntimeHookEvent(hooks, {
5153
+ id: `${node.nodeId}:${node.attemptId}:${target}:${sequence++}`,
5154
+ runId: node.rootId,
5155
+ parentId: node.nodeId,
5156
+ target,
5157
+ phase: "after",
5158
+ timestamp: Date.now(),
5159
+ payload: defaultRedactor({
5160
+ ...payload,
5161
+ attemptId: node.attemptId
5162
+ })
5163
+ });
5164
+ }
5459
5165
  };
5460
- const held = /* @__PURE__ */ new Set();
5461
- const destroyed = /* @__PURE__ */ new Set();
5462
- const forks = /* @__PURE__ */ new Set();
5463
- const key = (provider, id) => JSON.stringify([provider, id]);
5464
- const forkKey = (provider, id, environmentId) => JSON.stringify([
5465
- provider,
5466
- id,
5467
- environmentId ?? null
5468
- ]);
5469
- let invocationUnsettled = false;
5470
- let environment;
5471
- const measurements = /* @__PURE__ */ new Map();
5472
- for (const event of events) {
5473
- if (event.id !== state.args.nodeId) continue;
5474
- if (event.kind === "execution-admitted") {
5475
- invocationUnsettled = true;
5476
- if (event.admission.phase === "environment") {
5477
- environment = key(event.admission.provider, event.admission.environmentId);
5478
- held.add(environment);
5479
- destroyed.delete(environment);
5480
- measurements.delete(environment);
5481
- }
5482
- } else if (event.kind === "execution-result") {
5483
- invocationUnsettled = false;
5484
- if (environment !== void 0) measurements.set(environment, new Map(Object.entries(event.spent.resources ?? {}).flatMap(([name, value]) => value.known ? [[name, value.unit]] : [])));
5485
- } else if (event.kind === "environment-teardown" && event.destroyed) {
5486
- held.delete(key(event.provider, event.environmentId));
5487
- destroyed.add(key(event.provider, event.environmentId));
5488
- } else if (event.kind === "workspace-checkpoint-fork-requested") forks.add(forkKey(event.provider, event.idempotencyKey));
5489
- else if (event.kind === "workspace-checkpoint-fork-ready") {
5490
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5491
- forks.add(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5492
- } else if (event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed) {
5493
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5494
- forks.delete(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5166
+ }
5167
+ /** Observe completed HTTP work without copying customer payloads into trace metadata. */
5168
+ async function observeModelRequest(observation, model, request) {
5169
+ const startedAt = Date.now();
5170
+ try {
5171
+ const result = await request();
5172
+ observation?.event("agent.model", {
5173
+ model: result.model ?? model,
5174
+ startedAt,
5175
+ endedAt: Date.now(),
5176
+ status: "ok",
5177
+ ...result.usage && model !== "tangle/auto" ? {
5178
+ tokensIn: result.usage.input,
5179
+ tokensOut: result.usage.output
5180
+ } : {},
5181
+ ...result.billedCostUsd === void 0 || model === "tangle/auto" ? {} : { costUsd: result.billedCostUsd }
5182
+ });
5183
+ if (result.content) observation?.progress({
5184
+ kind: "text_delta",
5185
+ text: result.content
5186
+ });
5187
+ return result;
5188
+ } catch (error) {
5189
+ observation?.event("agent.model", {
5190
+ model,
5191
+ startedAt,
5192
+ endedAt: Date.now(),
5193
+ status: "error",
5194
+ error: { type: error instanceof Error ? error.name : "Error" }
5195
+ });
5196
+ throw error;
5197
+ }
5198
+ }
5199
+ /** Only a native call id can prove a tool duration; legacy results remain instant observations. */
5200
+ function createToolProgressObserver(observation) {
5201
+ const calls = /* @__PURE__ */ new Map();
5202
+ return (event, at) => {
5203
+ if (event.kind !== "tool_call" && event.kind !== "tool_result") return;
5204
+ if (event.kind === "tool_call") {
5205
+ if (event.toolCallId !== void 0 && !calls.has(event.toolCallId)) calls.set(event.toolCallId, at);
5206
+ return;
5495
5207
  }
5496
- }
5497
- const live = state.liveEnvironmentId?.();
5498
- if (live !== void 0 && (state.provider === void 0 || !destroyed.has(key(state.provider.name, live)))) held.add(key(state.provider?.name ?? "", live));
5499
- const measuredResources = new Map(measurements.get([...held][0] ?? "") ?? []);
5500
- for (const reference of held) for (const [name, unit] of measuredResources) if (measurements.get(reference)?.get(name) !== unit) measuredResources.delete(name);
5501
- if (forks.size > 0 || invocationUnsettled) measuredResources.clear();
5502
- return {
5503
- environmentHeld: held.size > 0 || forks.size > 0,
5504
- invocationUnsettled,
5505
- measuredResources
5208
+ const startedAt = event.toolCallId === void 0 ? void 0 : calls.get(event.toolCallId);
5209
+ if (event.toolCallId !== void 0) calls.delete(event.toolCallId);
5210
+ observation.event("agent.tool_call", {
5211
+ toolName: event.toolName,
5212
+ toolCallId: event.toolCallId,
5213
+ startedAt: startedAt ?? at,
5214
+ endedAt: at,
5215
+ durationKnown: startedAt !== void 0,
5216
+ status: event.status,
5217
+ ...event.error ? { error: event.error } : {}
5218
+ });
5506
5219
  };
5507
5220
  }
5508
- function scopeRetainedOwnerContext(scope) {
5509
- return owners.get(scope)?.context;
5510
- }
5511
- /** The journal tree that owns this manager turn, including nested driver children. */
5512
- function scopeRetainedOwnerJournalRoot(scope) {
5513
- return owners.get(scope)?.args.rootId;
5514
- }
5515
- /** Bind the provider that owns native stop, checkpoint and environment acknowledgements. */
5516
- function bindScopeRetainedOwnerProvider(scope, provider) {
5517
- const state = owners.get(scope);
5518
- if (state) state.provider = provider;
5519
- }
5520
- /** Bind the resolver for the owner's current environment id. Admissions alone miss a provider that never writes an environment admission. */
5521
- function bindScopeRetainedOwnerEnvironmentId(scope, liveEnvironmentId) {
5522
- const state = owners.get(scope);
5523
- if (state) state.liveEnvironmentId = liveEnvironmentId;
5524
- }
5525
- // src/runtime/supervise/retained-owner-checkpoint-requests.ts
5526
- /** Reconstruct authority for this source only; a replacement cannot own its snapshots. */
5527
- async function checkpointHandle(state, sourceEnvironmentId, signal) {
5528
- const cached = state.checkpointHandles?.get(sourceEnvironmentId);
5529
- if (cached !== void 0) return cached;
5530
- const provider = state.provider;
5531
- if (provider === void 0) return void 0;
5532
- try {
5533
- const branching = await runAbortable(async () => {
5534
- if (provider.workspaceBranching) return await provider.workspaceBranching.forEnvironment(sourceEnvironmentId, { signal }) ?? void 0;
5535
- const source = await provider.get?.(sourceEnvironmentId);
5536
- return source?.id === sourceEnvironmentId && source.provider === provider.name ? source.workspaceBranching : void 0;
5537
- }, signal, "retained owner checkpoint handle lookup timed out");
5538
- if (branching !== void 0) {
5539
- state.checkpointHandles ??= /* @__PURE__ */ new Map();
5540
- state.checkpointHandles.set(sourceEnvironmentId, branching);
5221
+ /** Call only after the exact dispatched admission's journal write has acknowledged. */
5222
+ function notifyExecutionAdmitted(hooks, runId, nodeId, admission, now, attemptId) {
5223
+ if (admission.phase !== "dispatched" || admission.controlRef.sessionId === void 0) return;
5224
+ notifyRuntimeHookEvent(hooks, {
5225
+ id: `${nodeId}:admitted:${admission.controlRef.executionId}`,
5226
+ runId,
5227
+ parentId: nodeId,
5228
+ target: "agent.execution",
5229
+ phase: "after",
5230
+ timestamp: now(),
5231
+ payload: {
5232
+ nodeId,
5233
+ ...attemptId === void 0 ? {} : { attemptId },
5234
+ controlRef: { ...admission.controlRef },
5235
+ sessionId: admission.controlRef.sessionId
5541
5236
  }
5542
- return branching;
5543
- } catch {
5544
- return;
5545
- }
5237
+ });
5546
5238
  }
5239
+ // src/durable/spawn-journal/event-index.ts
5547
5240
  /**
5548
- * An aborted observation cannot prove that the provider never created a snapshot, so a request
5549
- * whose lookup does not find it keeps its source. A `not_found` older than
5550
- * {@link WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS} never created one. A parent abort starts no lookup.
5241
+ * A trace root is valid only beside the output it commits to, with a well-formed root, artifact
5242
+ * reference and leaf count (at least the summary leaf). Records written before trace roots carry
5243
+ * none and stay valid.
5551
5244
  */
5552
- async function reconcileCheckpointRequests(state, events, parent) {
5553
- const operationKey = (operation) => JSON.stringify([operation.idempotencyKey, operation.requestDigest]);
5554
- const resolved = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint" && event.id === state.args.nodeId && event.provider === state.provider?.name ? [operationKey(event.checkpoint)] : []));
5555
- const pending = events.filter((event) => event.kind === "workspace-checkpoint-requested" && event.id === state.args.nodeId && event.provider === state.provider?.name && !resolved.has(operationKey(event.request)));
5556
- const unconfirmed = [];
5557
- for (const event of pending) {
5558
- if (parent?.aborted) {
5559
- unconfirmed.push({
5560
- event,
5561
- reason: "cancelled before checkpoint lookup"
5562
- });
5563
- continue;
5245
+ function assertTraceRoot(event, root) {
5246
+ if (!("traceRoot" in event) || event.traceRoot === void 0) return;
5247
+ const receipt = event.traceRoot;
5248
+ const fields = receipt !== null && typeof receipt === "object" ? receipt : {};
5249
+ if (typeof event.outRef !== "string" || typeof fields.root !== "string" || !/^sha256:[0-9a-f]{64}$/.test(fields.root) || typeof fields.ref !== "string" || !/^sha256:[0-9a-f]{64}$/.test(fields.ref) || typeof fields.leafCount !== "number" || !Number.isSafeInteger(fields.leafCount) || fields.leafCount < 1) throw new Error(`spawn journal corrupted: ${event.kind} for node '${event.id}' carries a malformed trace root in tree '${root}'`);
5250
+ }
5251
+ /** One validation implementation for memory, durable append, and cold replay. */
5252
+ /** @internal shared with the SQL-backed store. */
5253
+ var SpawnEventIndex = class {
5254
+ root;
5255
+ nodes = /* @__PURE__ */ new Map();
5256
+ cursors = /* @__PURE__ */ new Set();
5257
+ constructor(root) {
5258
+ this.root = root;
5259
+ }
5260
+ assert(event) {
5261
+ const node = this.nodes.get(event.id);
5262
+ this.assertRetained(node, event);
5263
+ assertTraceRoot(event, this.root);
5264
+ if (event.kind === "reconciled" && event.reservation) {
5265
+ if (!node?.budget) throw new Error("reservation evidence has no admitted node");
5266
+ assertValidBudget(event.reservation, "reconciled reservation");
5267
+ for (const [name, value] of Object.entries(event.reservation.resources ?? {})) if (node.budget.resources?.[name]?.unit !== value.unit) throw new Error(`reconciled reservation resource ${name}: original grant unit mismatch`);
5268
+ for (const channel of [
5269
+ "maxTokens",
5270
+ "maxIterations",
5271
+ "maxUsd"
5272
+ ]) if (event.reservation[channel] !== void 0 && node.budget[channel] === void 0) throw new Error(`reconciled reservation adds an undeclared ${channel} channel`);
5273
+ }
5274
+ if (event.kind === "admission-queued" || event.kind === "admission-granted") {
5275
+ if (!node?.spawned || node.closed || typeof event.attemptId !== "string" || event.attemptId.length === 0 || event.kind === "admission-granted" && node.grants?.has(`${event.attemptId}:${event.seq}`)) throw new Error(`spawn journal corrupted: invalid admission transition for '${event.id}'`);
5276
+ if (!Number.isSafeInteger(event.seq) || event.seq < 0 || event.kind === "admission-queued" && (![
5277
+ "budget",
5278
+ "slot",
5279
+ "seat"
5280
+ ].includes(event.gate) || event.resumeAt !== void 0 && !Number.isFinite(Date.parse(event.resumeAt))) || !Number.isFinite(Date.parse(event.at)) || event.kind === "admission-granted" && (!Number.isFinite(Date.parse(event.deadlineArmedAt)) || event.deadlineAt !== void 0 && !Number.isFinite(Date.parse(event.deadlineAt)))) throw new Error(`spawn journal corrupted: invalid admission clock for '${event.id}'`);
5281
+ if (event.kind === "admission-granted" && node.grantClock && (event.deadlineArmedAt !== node.grantClock.deadlineArmedAt || event.deadlineAt !== node.grantClock.deadlineAt)) throw new Error(`spawn journal corrupted: admission deadline changed for '${event.id}'`);
5282
+ }
5283
+ if (event.kind === "execution-evidence") {
5284
+ if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef) || event.attemptId !== void 0 && (typeof event.attemptId !== "string" || !event.attemptId)) throw new Error("spawn journal corrupted: executor evidence has no spawned node, valid content reference or attempt");
5285
+ }
5286
+ if (event.kind === "materialized") {
5287
+ if (node?.materialized) throw new Error(`spawn journal corrupted: duplicate materialization receipt for node '${event.id}' in tree '${this.root}'`);
5288
+ if (!node?.spawned) throw new Error(`spawn journal corrupted: materialization for node '${event.id}' precedes its spawn in tree '${this.root}'`);
5289
+ }
5290
+ if (event.kind === "seat-materialized") {
5291
+ if (!node?.materialized || node.authoredProfileDigest === void 0 || event.receipt.status !== "known" || event.receipt.authoredProfileDigest !== node.authoredProfileDigest || !Number.isSafeInteger(event.segmentIndex) || event.segmentIndex <= node.latestSeatMaterialization) throw new Error(`spawn journal corrupted: invalid seat materialization for node '${event.id}' in tree '${this.root}'`);
5292
+ }
5293
+ if (event.kind === "execution-bound") {
5294
+ if (node?.bindings.has(event.binding.attemptId)) throw new Error(`spawn journal corrupted: duplicate execution binding for node '${event.id}' attempt '${event.binding.attemptId}' in tree '${this.root}'`);
5295
+ if (!node?.materialized) throw new Error(`spawn journal corrupted: execution binding for node '${event.id}' precedes materialization in tree '${this.root}'`);
5296
+ }
5297
+ if (!outsideCursorNamespace(event) && this.cursors.has(event.seq)) throw new Error(`spawn journal corrupted: duplicate cursor seq ${event.seq} in tree '${this.root}'; the cursor order replay relies on is not unique`);
5298
+ }
5299
+ /** Called after validation; a file writer discards staged state if grouped publication fails. */
5300
+ add(event) {
5301
+ if (!outsideCursorNamespace(event)) this.cursors.add(event.seq);
5302
+ if (event.kind !== "spawned" && event.kind !== "admission-granted" && event.kind !== "materialized" && event.kind !== "seat-materialized" && event.kind !== "execution-bound" && event.kind !== "execution-input" && event.kind !== "execution-admitted" && event.kind !== "execution-result" && event.kind !== "execution-abandoned" && event.kind !== "environment-teardown" && event.kind !== "environment-terminal" && !closesCursorSlot(event)) return;
5303
+ let node = this.nodes.get(event.id);
5304
+ if (!node) {
5305
+ node = {
5306
+ spawned: false,
5307
+ closed: false,
5308
+ materialized: false,
5309
+ latestSeatMaterialization: 0,
5310
+ bindings: /* @__PURE__ */ new Set(),
5311
+ inputs: /* @__PURE__ */ new Set(),
5312
+ input: false,
5313
+ result: false,
5314
+ abandoned: false,
5315
+ admissions: /* @__PURE__ */ new Map(),
5316
+ unusableEnvironments: /* @__PURE__ */ new Set()
5317
+ };
5318
+ this.nodes.set(event.id, node);
5319
+ }
5320
+ if (event.kind === "environment-teardown") {
5321
+ if (event.destroyed || event.retired === true) node.unusableEnvironments.add(event.environmentId);
5322
+ return;
5323
+ }
5324
+ if (event.kind === "environment-terminal") {
5325
+ node.unusableEnvironments.add(event.environmentId);
5326
+ return;
5327
+ }
5328
+ if (event.kind === "execution-admitted" && event.admission.phase === "environment") node.lastEnvironmentId = event.admission.environmentId;
5329
+ if (event.kind === "spawned") {
5330
+ node.spawned = true;
5331
+ node.budget = event.budget;
5332
+ } else if (event.kind === "admission-granted") {
5333
+ node.grants ??= /* @__PURE__ */ new Set();
5334
+ node.grants.add(`${event.attemptId}:${event.seq}`);
5335
+ node.grantClock ??= {
5336
+ deadlineArmedAt: event.deadlineArmedAt,
5337
+ deadlineAt: event.deadlineAt
5338
+ };
5339
+ } else if (event.kind === "materialized") {
5340
+ node.materialized = true;
5341
+ node.authoredProfileDigest = event.receipt.authoredProfileDigest;
5342
+ } else if (event.kind === "seat-materialized") node.latestSeatMaterialization = event.segmentIndex;
5343
+ else if (event.kind === "execution-bound") node.bindings.add(event.binding.attemptId);
5344
+ else if (event.kind === "execution-input") {
5345
+ node.inputs.add(event.seq);
5346
+ node.input = true;
5347
+ node.latestInput = event.seq;
5348
+ node.result = false;
5349
+ node.abandoned = false;
5350
+ node.admissions.clear();
5351
+ } else if (event.kind === "execution-admitted") node.admissions.set(event.admission.phase, event.admission);
5352
+ else if (event.kind === "execution-result") node.result = true;
5353
+ else if (event.kind === "execution-abandoned") node.abandoned = true;
5354
+ if (closesCursorSlot(event)) node.closed = true;
5355
+ }
5356
+ assertRetained(node, event) {
5357
+ if (event.kind !== "execution-input" && event.kind !== "execution-admitted" && event.kind !== "execution-result" && event.kind !== "execution-abandoned") return;
5358
+ function fail(reason) {
5359
+ throw new Error(`spawn journal corrupted: retained execution '${event.id}' ${reason}`);
5360
+ }
5361
+ if (!node?.spawned) fail("precedes its spawn");
5362
+ if (node.closed) fail("follows its terminal settlement");
5363
+ if (event.kind === "execution-input") {
5364
+ if (!/^sha256:[0-9a-f]{64}$/.test(event.taskRef)) fail("has an invalid task reference");
5365
+ if (node.inputs.has(event.seq)) fail("has duplicate input sequence");
5366
+ const environment = node.admissions.get("environment");
5367
+ const ranIn = environment?.phase === "environment" ? environment.environmentId : node.lastEnvironmentId;
5368
+ const closed = node.abandoned || ranIn !== void 0 && node.unusableEnvironments.has(ranIn);
5369
+ if (node.input && !node.result && !closed) fail("input replaces an unfinished invocation");
5370
+ return;
5371
+ }
5372
+ if (event.kind === "execution-abandoned") {
5373
+ if (!node.input || node.latestInput !== event.inputSeq) fail("abandons an invocation that is not its latest");
5374
+ if (node.result) fail("abandons an invocation that has a result");
5375
+ if (node.abandoned) fail("abandons an invocation twice");
5376
+ if (!Number.isSafeInteger(event.failures) || event.failures < 1) fail("abandons without a failure count");
5377
+ return;
5378
+ }
5379
+ if (node.abandoned) fail(`${event.kind} follows its abandonment`);
5380
+ if (event.kind === "execution-result") {
5381
+ if (node.result) fail("has duplicate result");
5382
+ if (!node.admissions.has("dispatched")) fail("result precedes dispatch");
5383
+ if (!/^sha256:[0-9a-f]{64}$/.test(event.outRef)) fail("has an invalid result reference");
5384
+ if (event.outputFormat !== void 0 && event.outputFormat !== "json") fail("has an invalid output format");
5385
+ assertValidSpend(event.spent, "retained execution result");
5386
+ executorFailureReason(event);
5387
+ return;
5388
+ }
5389
+ const admission = event.admission;
5390
+ if (!admission || ![
5391
+ "intent",
5392
+ "environment",
5393
+ "dispatched"
5394
+ ].includes(admission.phase)) fail("has an invalid admission phase");
5395
+ if (node.admissions.has(admission.phase)) fail("has duplicate admission phase");
5396
+ if (node.result) fail("admission follows result");
5397
+ if (!node.input) fail("admission precedes input");
5398
+ if (admission.phase === "intent") {
5399
+ if (node.admissions.size !== 0) fail("intent follows another admission");
5400
+ return;
5564
5401
  }
5565
- const signal = deadlineSignal(parent, 3e4);
5566
- try {
5567
- const branching = await checkpointHandle(state, event.environmentId, signal);
5568
- if (branching === void 0) throw new Error("source-scoped checkpoint handle unavailable");
5569
- const result = await runAbortable(() => branching.lookupCheckpoint({
5570
- idempotencyKey: event.request.idempotencyKey,
5571
- requestDigest: event.request.requestDigest
5572
- }, { signal }), signal, "retained owner checkpoint lookup timed out");
5573
- if (result.status === "not_found") {
5574
- const requestedAt = Date.parse(event.at);
5575
- if (Number.isFinite(requestedAt) && state.args.now() - requestedAt >= 12e5) continue;
5576
- unconfirmed.push({
5577
- event,
5578
- reason: "lookup not_found while the request may be in flight"
5579
- });
5580
- continue;
5581
- }
5582
- if (result.status !== "found") {
5583
- unconfirmed.push({
5584
- event,
5585
- reason: `lookup ${result.status}${"message" in result && result.message ? `: ${result.message}` : ""}`
5586
- });
5587
- continue;
5588
- }
5589
- if (!workspaceCheckpointResultMatchesRequest(event.request, result)) {
5590
- unconfirmed.push({
5591
- event,
5592
- reason: "lookup found a checkpoint for another request"
5593
- });
5594
- continue;
5595
- }
5596
- const recovered = {
5597
- kind: "workspace-checkpoint",
5598
- id: event.id,
5599
- provider: event.provider,
5600
- environmentId: event.environmentId,
5601
- checkpoint: result.checkpoint,
5602
- ...event.marker === void 0 ? {} : { marker: event.marker },
5603
- seq: state.nextSequence(),
5604
- at: event.at
5605
- };
5606
- await state.args.journal.appendEvent(state.args.rootId, recovered);
5607
- events.push(recovered);
5608
- } catch (error) {
5609
- unconfirmed.push({
5610
- event,
5611
- reason: `lookup failed: ${errorText(error instanceof Error ? error.message : error)}`
5612
- });
5402
+ const intent = node.admissions.get("intent");
5403
+ if (intent?.phase !== "intent") fail("admission precedes intent");
5404
+ if (admission.idempotencyKey !== intent.idempotencyKey || admission.turnId !== intent.turnId) fail("changes its admitted request identity");
5405
+ if (admission.phase === "environment") {
5406
+ if (admission.provider !== intent.provider || admission.sessionId !== intent.sessionId || admission.executionId !== intent.executionId) fail("changes its admitted execution identity");
5407
+ return;
5613
5408
  }
5409
+ const environment = node.admissions.get("environment");
5410
+ if (environment?.phase !== "environment") fail("dispatch precedes environment");
5411
+ const control = admission.controlRef;
5412
+ if (!control || control.provider !== intent.provider || control.environmentId !== environment.environmentId || control.sessionId !== intent.sessionId || control.executionId !== intent.executionId) fail("dispatch changes its admitted execution identity");
5614
5413
  }
5615
- return unconfirmed;
5616
- }
5617
- function pendingCheckpoints(events, state) {
5618
- const confirmed = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint-cleanup" && event.id === state.args.nodeId && event.provider === state.provider?.name && event.confirmed ? [JSON.stringify([event.environmentId, event.checkpointId])] : []));
5619
- return events.filter((event) => event.kind === "workspace-checkpoint" && event.id === state.args.nodeId && event.provider === state.provider?.name && !confirmed.has(JSON.stringify([event.environmentId, event.checkpoint.checkpointId])));
5620
- }
5621
- // src/runtime/supervise/retained-owner-checkpoint-capture.ts
5414
+ };
5622
5415
  /**
5623
- * Delete restore-point checkpoints. A checkpoint is a restore point for a live owner, never
5624
- * evidence: the turn's workspace capture and native session export are the evidence, and the
5625
- * release keeps a source whose evidence is incomplete. An aborted parent starts no provider call.
5416
+ * The records that CLOSE a node's cursor slot: a settlement or a cancellation. The complement question to {@link outsideCursorNamespace}, and the one a resume needs —
5417
+ * a kind missing here leaves a finished node looking live, so its budget is never reclaimed and
5418
+ * its reservation is replayed as still in doubt.
5626
5419
  */
5627
- async function cleanCheckpoints(state, branching, checkpoints, parent) {
5628
- const unconfirmed = [];
5629
- for (const event of checkpoints) {
5630
- const material = {
5631
- kind: "checkpoint",
5632
- targetId: event.checkpoint.checkpointId,
5633
- provider: event.checkpoint.provider
5634
- };
5635
- const request = {
5636
- ...material,
5637
- operationId: `${event.checkpoint.idempotencyKey}:delete`,
5638
- requestDigest: workspaceCleanupRequestDigest(material)
5639
- };
5640
- let confirmed = false;
5641
- let reason;
5642
- const signal = deadlineSignal(parent, 3e4);
5643
- try {
5644
- if (parent?.aborted) reason = "cancelled before checkpoint cleanup";
5645
- else if (branching === void 0) throw new Error("source-scoped checkpoint handle unavailable");
5646
- else {
5647
- const acknowledgement = await runAbortable(() => branching.deleteCheckpoint(request, { signal }), signal, "retained owner checkpoint cleanup timed out");
5648
- confirmed = workspaceCleanupAcknowledgementMatches(request, acknowledgement) && (acknowledgement.status === "deleted" || acknowledgement.status === "already_absent");
5649
- if (!confirmed) reason = `provider acknowledged '${acknowledgement.status}'`;
5650
- }
5651
- } catch (error) {
5652
- reason = errMessage(error).slice(0, 1e3);
5653
- }
5654
- if (!confirmed) unconfirmed.push({
5655
- event,
5656
- reason: reason ?? "delete was not confirmed"
5657
- });
5658
- await state.args.journal.appendEvent(state.args.rootId, {
5659
- kind: "workspace-checkpoint-cleanup",
5660
- id: state.args.nodeId,
5661
- provider: event.provider,
5662
- environmentId: event.environmentId,
5663
- checkpointId: event.checkpoint.checkpointId,
5664
- confirmed,
5665
- ...reason === void 0 ? {} : { refused: reason.slice(0, 1e3) },
5666
- seq: state.nextSequence(),
5667
- at: new Date(state.args.now()).toISOString()
5668
- });
5669
- }
5670
- return unconfirmed;
5420
+ function closesCursorSlot(ev) {
5421
+ return ev.kind === "settled" || ev.kind === "cancelled";
5671
5422
  }
5672
- /** Destroy a capture's fork and journal whether the provider confirmed it. */
5673
- async function destroyCaptureFork(state, branching, target, parent) {
5674
- const material = {
5675
- kind: "fork",
5676
- targetId: target.fork.environmentId,
5677
- provider: target.provider
5678
- };
5679
- const request = {
5680
- ...material,
5681
- operationId: `${target.fork.idempotencyKey}:destroy`,
5682
- requestDigest: workspaceCleanupRequestDigest(material)
5683
- };
5684
- let destroyed = false;
5685
- try {
5686
- const signal = deadlineSignal(parent, 3e4);
5687
- const acknowledgement = await runAbortable(() => branching.destroyFork(request, { signal }), signal, "checkpoint capture fork cleanup timed out");
5688
- destroyed = workspaceCleanupAcknowledgementMatches(request, acknowledgement) && (acknowledgement.status === "deleted" || acknowledgement.status === "already_absent");
5689
- } catch {}
5690
- await state.args.journal.appendEvent(state.args.rootId, {
5691
- kind: "workspace-checkpoint-fork-teardown",
5692
- id: state.args.nodeId,
5693
- ...target,
5694
- destroyed,
5695
- seq: state.nextSequence(),
5696
- at: new Date(state.args.now()).toISOString()
5697
- });
5698
- return destroyed;
5423
+ const outsideKinds = /* @__PURE__ */ new Set([
5424
+ "spawned",
5425
+ "admission-queued",
5426
+ "admission-granted",
5427
+ "metered",
5428
+ "materialized",
5429
+ "execution-bound",
5430
+ "execution-input",
5431
+ "execution-admitted",
5432
+ "execution-result",
5433
+ "execution-abandoned",
5434
+ "execution-evidence",
5435
+ "evidence-pending",
5436
+ "progress",
5437
+ "reconciled",
5438
+ "edge",
5439
+ "teardown-unconfirmed",
5440
+ "teardown-pending",
5441
+ "teardown-confirmed",
5442
+ "environment-teardown",
5443
+ "environment-terminal",
5444
+ "workspace-checkpoint-requested",
5445
+ "workspace-checkpoint-refused",
5446
+ "workspace-checkpoint",
5447
+ "workspace-checkpoint-fork-requested",
5448
+ "workspace-checkpoint-fork-ready",
5449
+ "workspace-checkpoint-fork-teardown",
5450
+ "workspace-checkpoint-capture",
5451
+ "workspace-checkpoint-cleanup",
5452
+ "workspace-restored",
5453
+ "workspace-capture-started",
5454
+ "workspace-capture",
5455
+ "trace-unpropagated",
5456
+ "seat-segment",
5457
+ "seat-materialized",
5458
+ "seat-paused",
5459
+ "run-parked",
5460
+ "root-segment",
5461
+ "root-reentered",
5462
+ "reopened",
5463
+ "paused",
5464
+ "barren-pause",
5465
+ "driver-attempt",
5466
+ "node-inputs-resolved",
5467
+ "edge-verdict",
5468
+ "join-state"
5469
+ ]);
5470
+ /** True for a node-CREATION or informational record. Narrows, so a caller keeps the union's arms. */
5471
+ function outsideCursorNamespace(ev) {
5472
+ return outsideKinds.has(ev.kind);
5699
5473
  }
5700
- /** Destroy capture forks the journal does not show destroyed. An aborted parent starts no further fork call. Returns forks still unconfirmed. */
5701
- async function settleCaptureForks(state, parent) {
5702
- const { args } = state;
5703
- const providerName = state.provider?.name;
5704
- const events = (await args.journal.loadTree(args.rootId) ?? []).filter((event) => event.id === args.nodeId);
5705
- const named = (key) => {
5706
- for (const event of events) if ((event.kind === "workspace-checkpoint-capture" || event.kind === "workspace-checkpoint-fork-teardown") && event.fork.idempotencyKey === key) return event.fork.environmentId;
5707
- };
5708
- const destroyed = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed ? [event.fork.idempotencyKey] : []));
5709
- const unresolved = [];
5710
- for (const request of events) {
5711
- if (request.kind !== "workspace-checkpoint-fork-requested" || request.provider !== providerName) continue;
5712
- if (destroyed.has(request.idempotencyKey)) continue;
5713
- if (parent?.aborted) {
5714
- unresolved.push(named(request.idempotencyKey) ?? request.idempotencyKey);
5715
- continue;
5716
- }
5717
- const signal = deadlineSignal(parent, 3e4);
5718
- const branching = await checkpointHandle(state, request.environmentId, signal);
5719
- let forkEnvironmentId = named(request.idempotencyKey);
5720
- if (forkEnvironmentId === void 0 && branching !== void 0) try {
5721
- const found = await runAbortable(() => branching.lookupFork({
5722
- idempotencyKey: request.idempotencyKey,
5723
- requestDigest: request.requestDigest
5724
- }, { signal }), signal, "checkpoint capture fork lookup timed out");
5725
- if (found.status === "not_found") continue;
5726
- if (found.status === "found") forkEnvironmentId = found.environment.environmentId;
5727
- } catch {}
5728
- if (forkEnvironmentId === void 0 || branching === void 0 || !await destroyCaptureFork(state, branching, {
5729
- provider: request.provider,
5730
- environmentId: request.environmentId,
5731
- checkpointId: request.checkpointId,
5732
- fork: {
5733
- idempotencyKey: request.idempotencyKey,
5734
- environmentId: forkEnvironmentId
5735
- }
5736
- }, parent)) unresolved.push(forkEnvironmentId ?? request.idempotencyKey);
5737
- }
5738
- return unresolved;
5474
+ /** True for a record inside the cursor namespace. Narrows to {@link CursorNamespaceEvent}. */
5475
+ function insideCursorNamespace(ev) {
5476
+ return !outsideKinds.has(ev.kind);
5477
+ }
5478
+ // src/runtime/supervise/tree-key.ts
5479
+ /** Runtime tag used only for a child that owns another supervised scope. */
5480
+ const driverRuntime = "driver";
5481
+ const nestedDriverTreeOwners = /* @__PURE__ */ new WeakSet();
5482
+ /** Canonical journal key for the scope owned by one nested driver node. */
5483
+ function nestedDriverTreeRoot(parentTreeRoot, driverNodeId) {
5484
+ return `${parentTreeRoot}/${driverNodeId}`;
5485
+ }
5486
+ /** Privately mark the exact recursive executor that will create a nested journal tree. */
5487
+ function attestNestedDriverTreeOwner(owner) {
5488
+ nestedDriverTreeOwners.add(owner);
5489
+ return owner;
5490
+ }
5491
+ /** Return the canonical owned tree only for an exact privately marked recursive executor. */
5492
+ function runtimeOwnedNestedDriverTreeRoot(owner, parentTreeRoot, driverNodeId) {
5493
+ return nestedDriverTreeOwners.has(owner) ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId) : void 0;
5494
+ }
5495
+ // src/durable/spawn-journal/settlement-evidence.ts
5496
+ /** Copy a terminal record's overspend at the journal boundary; absent stays absent. */
5497
+ function budgetViolationOf(event) {
5498
+ if (event.budgetViolation === void 0) return {};
5499
+ return { budgetViolation: Object.freeze({ overspent: Object.freeze(event.budgetViolation.overspent.map((entry) => Object.freeze({
5500
+ channel: entry.channel,
5501
+ reserved: entry.reserved,
5502
+ spent: entry.spent
5503
+ }))) }) };
5739
5504
  }
5740
- // src/runtime/supervise/retained-owner-checkpoint-rotation.ts
5741
- /** Checkpoint after a coordination call once the last one is older than {@link WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS}. It never delays the call, and a failure leaves the previous restore point. */
5742
- function noteScopeRetainedOwnerCoordination(scope) {
5743
- const state = owners.get(scope);
5744
- if (state?.provider === void 0 || state.checkpointsUnavailable !== void 0) return;
5745
- if (state.checkpointing !== void 0 || state.turnEnd !== void 0 || scope.signal.aborted) return;
5746
- const now = state.args.now();
5747
- if (state.lastCheckpointAt !== void 0 && now - state.lastCheckpointAt < 6e4) return;
5748
- state.lastCheckpointAt = now;
5749
- state.checkpointing = checkpointOwnerWorkspace(scope, state).catch(() => void 0).finally(() => {
5750
- delete state.checkpointing;
5505
+ /** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */
5506
+ function copyProviderModelEvidence(evidence) {
5507
+ if (evidence === void 0) return void 0;
5508
+ const attempts = snapshotProviderObservations(evidence.attempts);
5509
+ const models = Object.freeze([...evidence.models]);
5510
+ return Object.freeze(evidence.status === "unknown" ? {
5511
+ status: "unknown",
5512
+ attempts,
5513
+ models,
5514
+ reason: evidence.reason
5515
+ } : {
5516
+ status: "known",
5517
+ attempts,
5518
+ models
5751
5519
  });
5752
5520
  }
5753
- /** @internal The checkpoint in progress for this owner, for a test or a release to wait on. */
5754
- function scopeRetainedOwnerCheckpointing(scope) {
5755
- return owners.get(scope)?.checkpointing;
5521
+ function traceEvidenceFor(event) {
5522
+ return event.trace ?? {
5523
+ status: "unavailable",
5524
+ reason: "legacy-settlement-without-trace-evidence"
5525
+ };
5756
5526
  }
5757
- async function checkpointOwnerWorkspace(scope, state) {
5758
- const { provider, args } = state;
5759
- if (provider === void 0) return;
5760
- if (!provider.get) {
5761
- state.checkpointsUnavailable = `provider ${provider.name} cannot reconstruct an environment`;
5762
- return;
5527
+ // src/durable/spawn-journal/tree-view.ts
5528
+ /**
5529
+ * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds
5530
+ * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each
5531
+ * `metered` event's driver-inference spend onto its node in a separate additive pass so the view
5532
+ * matches the recorded cursor. It does not recover live executors or driver state after restart.
5533
+ */
5534
+ function materializeTreeView(events) {
5535
+ const nodes = /* @__PURE__ */ new Map();
5536
+ let root;
5537
+ const spawns = events.filter((ev) => ev.kind === "spawned").sort((a, b) => a.seq - b.seq);
5538
+ const settlements = events.filter((ev) => insideCursorNamespace(ev)).sort((a, b) => a.seq - b.seq);
5539
+ for (const ev of spawns) {
5540
+ if (ev.parent === void 0 && root === void 0) root = ev.id;
5541
+ nodes.set(ev.id, {
5542
+ id: ev.id,
5543
+ parent: ev.parent,
5544
+ label: ev.label,
5545
+ status: "pending",
5546
+ runtime: ev.runtime,
5547
+ budget: ev.budget,
5548
+ ...ev.ownedTreeRoot === void 0 ? {} : { ownedTreeRoot: ev.ownedTreeRoot },
5549
+ ...ev.assignmentId === void 0 ? {} : { assignmentId: ev.assignmentId },
5550
+ ...ev.identity ? { identity: ev.identity } : {},
5551
+ ...ev.modelSubstitution ? { modelSubstitution: ev.modelSubstitution } : {},
5552
+ ...Number.isFinite(Date.parse(ev.at)) ? { spawnedAt: Date.parse(ev.at) } : {},
5553
+ spent: zeroSpend()
5554
+ });
5763
5555
  }
5764
- if ((await provider.capabilities()).create?.workspaceCheckpoint !== true) {
5765
- state.checkpointsUnavailable = `provider ${provider.name} cannot create an environment from a checkpoint`;
5766
- return;
5556
+ for (const ev of settlements) {
5557
+ const node = requireNode(nodes, ev.id);
5558
+ const down = ev.kind === "cancelled" || ev.status === "down";
5559
+ node.status = ev.kind === "cancelled" ? "cancelled" : down ? "failed" : "done";
5560
+ if (ev.spent !== void 0) node.spent = cloneSpend(ev.spent);
5561
+ node.providerModel = copyProviderModelEvidence(ev.providerModel);
5562
+ node.outRef = ev.outRef;
5563
+ node.failure = down ? ev.failure ?? settlementFailureCause({
5564
+ reason: ev.reason ?? (ev.kind === "settled" ? ev.verdict?.notes : void 0) ?? "child down",
5565
+ infra: ev.infra,
5566
+ retainedPendingCause: ev.retainedPendingCause
5567
+ }) : void 0;
5568
+ node.trace = ev.kind === "cancelled" ? ev.trace ?? {
5569
+ status: "unavailable",
5570
+ reason: "execution-did-not-start"
5571
+ } : traceEvidenceFor(ev);
5572
+ node.budgetViolation = budgetViolationOf(ev).budgetViolation;
5573
+ if (ev.retainedExecution !== void 0) node.retainedExecution = ev.retainedExecution;
5574
+ if (ev.retainedPendingCause !== void 0) node.retainedPendingCause = ev.retainedPendingCause;
5575
+ const settledAt = Date.parse(ev.at);
5576
+ if (Number.isFinite(settledAt)) node.settledAt = settledAt;
5767
5577
  }
5768
- const dispatched = [...state.admissions].reverse().find((admission) => admission.phase === "dispatched");
5769
- if (dispatched?.phase !== "dispatched") return;
5770
- const source = dispatched.controlRef;
5771
- const signal = AbortSignal.any([scope.signal, AbortSignal.timeout(WORKSPACE_CHECKPOINT_TIMEOUT_MS)]);
5772
- const get = provider.get.bind(provider);
5773
- const environment = await runAbortable(() => get(source.environmentId), signal, "retained owner checkpoint timed out");
5774
- if (environment === null || environment.id !== source.environmentId || environment.provider !== provider.name) return;
5775
- const branching = environment.workspaceBranching;
5776
- if (branching === void 0) {
5777
- state.checkpointsUnavailable = `environment ${environment.id} offers no durable checkpoint`;
5778
- return;
5578
+ for (const ev of events) {
5579
+ if (ev.kind !== "materialized" && ev.kind !== "seat-materialized") continue;
5580
+ const node = requireNode(nodes, ev.id);
5581
+ node.materialization = ev.receipt;
5582
+ node.runtime = ev.receipt.runtime;
5779
5583
  }
5780
- const requestOne = () => requestCheckpoint(scope, state, provider.name, environment, branching, source, signal);
5781
- if (!await requestOne() && (!await deleteOldestCheckpoint(state, branching, environment.id, signal) || !await requestOne())) return;
5782
- const owned = pendingCheckpoints(await args.journal.loadTree(args.rootId) ?? [], state).filter((event) => event.environmentId === environment.id);
5783
- const rotation = new AbortController();
5784
- state.rotationCaptures = rotation;
5785
- const timer = setTimeout(() => rotation.abort(/* @__PURE__ */ new Error(`the rotation's ${WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS} ms for checkpoint deletes ran out; checkpoint kept`)), WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS);
5786
- try {
5787
- await cleanCheckpoints(state, branching, owned.slice(0, -2), AbortSignal.any([scope.signal, rotation.signal]));
5788
- } finally {
5789
- clearTimeout(timer);
5790
- if (state.rotationCaptures === rotation) delete state.rotationCaptures;
5584
+ for (const ev of events) {
5585
+ if (ev.kind !== "execution-bound") continue;
5586
+ const node = requireNode(nodes, ev.id);
5587
+ node.executionBindings ??= [];
5588
+ node.executionBindings.push(ev.binding);
5791
5589
  }
5792
- }
5793
- /** Ask for one checkpoint and journal the answer. True when the journal holds the checkpoint. */
5794
- async function requestCheckpoint(scope, state, providerName, environment, branching, source, signal) {
5795
- const { args } = state;
5796
- const seq = state.nextSequence();
5797
- const at = new Date(args.now()).toISOString();
5798
- const name = `owner-checkpoint-${seq}`;
5799
- const marker = {
5800
- path: WORKSPACE_CHECKPOINT_MARKER_PATH,
5801
- content: `${JSON.stringify({
5802
- node: args.nodeId,
5803
- checkpoint: name,
5804
- at
5805
- })}\n`
5806
- };
5807
- const marked = await writeWorkspaceMarker(environment, marker, signal);
5808
- const material = {
5809
- source,
5810
- name
5590
+ for (const ev of events) {
5591
+ if (ev.kind !== "reconciled" && ev.kind !== "admission-queued" && ev.kind !== "admission-granted") continue;
5592
+ const node = requireNode(nodes, ev.id);
5593
+ if (node.status === "pending" || node.status === "queued" || node.status === "acquiring") {
5594
+ node.status = ev.kind === "reconciled" ? "pending" : ev.kind === "admission-queued" ? "queued" : "acquiring";
5595
+ if (ev.kind === "reconciled") {
5596
+ node.spent = cloneSpend(ev.spent);
5597
+ node.failure = ev.failure;
5598
+ }
5599
+ }
5600
+ }
5601
+ for (const ev of events) {
5602
+ if (ev.kind !== "metered") continue;
5603
+ const node = requireNode(nodes, ev.id);
5604
+ node.spent = addSpend(node.spent, ev.spend);
5605
+ }
5606
+ const snapshots = [...nodes.values()].map(freezeSnapshot);
5607
+ return {
5608
+ root: root ?? snapshots[0]?.id ?? "",
5609
+ nodes: snapshots,
5610
+ inFlight: snapshots.filter((n) => [
5611
+ "queued",
5612
+ "running",
5613
+ "acquiring"
5614
+ ].includes(n.status)).length
5811
5615
  };
5812
- const request = {
5813
- ...material,
5814
- idempotencyKey: `${args.nodeId}:workspace-checkpoint:${seq}`,
5815
- requestDigest: workspaceCheckpointRequestDigest(material)
5616
+ }
5617
+ function requireNode(nodes, id) {
5618
+ const node = nodes.get(id);
5619
+ if (!node) throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`);
5620
+ return node;
5621
+ }
5622
+ function freezeSnapshot(node) {
5623
+ return {
5624
+ id: node.id,
5625
+ parent: node.parent,
5626
+ label: node.label,
5627
+ status: node.status,
5628
+ ...node.failure === void 0 ? {} : { failure: node.failure },
5629
+ runtime: node.runtime,
5630
+ budget: node.budget,
5631
+ ownedTreeRoot: node.ownedTreeRoot,
5632
+ assignmentId: node.assignmentId,
5633
+ identity: node.identity,
5634
+ modelSubstitution: node.modelSubstitution,
5635
+ materialization: node.materialization,
5636
+ executionBindings: node.executionBindings === void 0 ? void 0 : Object.freeze([...node.executionBindings]),
5637
+ spent: node.spent,
5638
+ providerModel: node.providerModel,
5639
+ outRef: node.outRef,
5640
+ trace: node.trace,
5641
+ ...node.budgetViolation === void 0 ? {} : { budgetViolation: node.budgetViolation },
5642
+ ...node.retainedExecution === void 0 ? {} : { retainedExecution: node.retainedExecution },
5643
+ ...node.retainedPendingCause === void 0 ? {} : { retainedPendingCause: node.retainedPendingCause },
5644
+ settledAt: node.settledAt,
5645
+ spawnedAt: node.spawnedAt
5816
5646
  };
5817
- state.checkpointHandles ??= /* @__PURE__ */ new Map();
5818
- state.checkpointHandles.set(environment.id, branching);
5819
- await args.journal.appendEvent(args.rootId, {
5820
- kind: "workspace-checkpoint-requested",
5821
- id: args.nodeId,
5822
- provider: providerName,
5823
- environmentId: environment.id,
5824
- request,
5825
- ...marked ? { marker } : {},
5826
- seq,
5827
- at
5828
- });
5829
- const result = await runAbortable(() => branching.checkpoint(request, { signal }), signal, "retained owner checkpoint timed out");
5830
- if (result.status !== "created" && result.status !== "replayed") {
5831
- await args.journal.appendEvent(args.rootId, {
5832
- kind: "workspace-checkpoint-refused",
5833
- id: args.nodeId,
5834
- provider: providerName,
5835
- environmentId: environment.id,
5836
- idempotencyKey: request.idempotencyKey,
5837
- message: errorText("message" in result ? result.message : result.status),
5838
- seq: state.nextSequence(),
5839
- at
5647
+ }
5648
+ // src/durable/spawn-journal/spawn-forest.ts
5649
+ /**
5650
+ * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.
5651
+ *
5652
+ * Nested driver tree keys are a Runtime implementation detail; callers should use this reader
5653
+ * instead of deriving or scanning keys themselves. The reader follows only the explicit
5654
+ * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime
5655
+ * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are
5656
+ * intentionally treated as leaves rather than guessing or scanning convention-derived keys.
5657
+ * This preserves each tree's independent cursor namespace on flattened events.
5658
+ * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node
5659
+ * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work
5660
+ * interpretation.
5661
+ *
5662
+ * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value
5663
+ * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot
5664
+ * change the result already observed.
5665
+ */
5666
+ async function loadSpawnForest(journal, root) {
5667
+ const rootEvents = await journal.loadTree(root);
5668
+ if (rootEvents === void 0) throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`);
5669
+ const trees = [];
5670
+ const nodes = [];
5671
+ const events = [];
5672
+ const inDoubt = [];
5673
+ const missingTrees = [];
5674
+ const visited = /* @__PURE__ */ new Set();
5675
+ const queue = [{
5676
+ root,
5677
+ events: rootEvents
5678
+ }];
5679
+ for (let cursor = 0; cursor < queue.length; cursor += 1) {
5680
+ const current = queue[cursor];
5681
+ if (visited.has(current.root)) throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`);
5682
+ visited.add(current.root);
5683
+ const stableEvents = detachedSnapshot(current.events, `loadSpawnForest tree ${JSON.stringify(current.root)}`);
5684
+ const viewEvents = current.ownerSpawn === void 0 || stableEvents.some((event) => event.kind === "spawned" && event.id === current.ownerSpawn?.id) ? [...stableEvents] : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents];
5685
+ const view = detachedSnapshot(materializeTreeView(viewEvents), `loadSpawnForest view ${JSON.stringify(current.root)}`);
5686
+ trees.push({
5687
+ root: current.root,
5688
+ ...current.ownerNodeId === void 0 ? {} : { ownerNodeId: current.ownerNodeId },
5689
+ ...current.parentTreeRoot === void 0 ? {} : { parentTreeRoot: current.parentTreeRoot },
5690
+ events: stableEvents,
5691
+ view
5840
5692
  });
5841
- return false;
5693
+ nodes.push(...view.nodes.filter((node) => current.ownerNodeId === void 0 || node.id !== current.ownerNodeId).map((node) => ({
5694
+ treeRoot: current.root,
5695
+ ...node
5696
+ })));
5697
+ events.push(...stableEvents.map((event) => ({
5698
+ treeRoot: current.root,
5699
+ event
5700
+ })));
5701
+ const terminal = /* @__PURE__ */ new Set();
5702
+ for (const event of stableEvents) if (event.kind === "settled" || event.kind === "cancelled") terminal.add(event.id);
5703
+ const spawns = stableEvents.filter((event) => event.kind === "spawned").sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id));
5704
+ for (const spawn of spawns) {
5705
+ if (spawn.parent !== void 0 && !terminal.has(spawn.id)) inDoubt.push({
5706
+ treeRoot: current.root,
5707
+ nodeId: spawn.id,
5708
+ label: spawn.label,
5709
+ runtime: spawn.runtime
5710
+ });
5711
+ if (spawn.ownedTreeRoot === void 0) continue;
5712
+ const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id);
5713
+ if (spawn.ownedTreeRoot !== expectedRoot) throw new Error(`loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`);
5714
+ const nestedRoot = spawn.ownedTreeRoot;
5715
+ const nestedEvents = await journal.loadTree(nestedRoot);
5716
+ if (nestedEvents === void 0) {
5717
+ missingTrees.push({
5718
+ parentTreeRoot: current.root,
5719
+ ownerNodeId: spawn.id,
5720
+ root: nestedRoot
5721
+ });
5722
+ continue;
5723
+ }
5724
+ queue.push({
5725
+ root: nestedRoot,
5726
+ events: nestedEvents,
5727
+ ownerNodeId: spawn.id,
5728
+ parentTreeRoot: current.root,
5729
+ ownerSpawn: spawn
5730
+ });
5731
+ }
5842
5732
  }
5843
- if (!workspaceCheckpointResultMatchesRequest(request, result)) return false;
5844
- scope.signal.throwIfAborted();
5845
- await args.journal.appendEvent(args.rootId, {
5846
- kind: "workspace-checkpoint",
5847
- id: args.nodeId,
5848
- provider: providerName,
5849
- environmentId: environment.id,
5850
- checkpoint: result.checkpoint,
5851
- ...marked ? { marker } : {},
5852
- seq: state.nextSequence(),
5853
- at
5854
- });
5855
- return true;
5733
+ return detachedSnapshot({
5734
+ root,
5735
+ trees,
5736
+ nodes,
5737
+ events,
5738
+ inDoubt,
5739
+ missingTrees
5740
+ }, "loadSpawnForest result");
5856
5741
  }
5857
- /** Delete the oldest checkpoint past {@link WORKSPACE_CHECKPOINTS_KEPT}, so a snapshot limit cannot freeze the restore point. */
5858
- async function deleteOldestCheckpoint(state, branching, environmentId, signal) {
5859
- const oldest = pendingCheckpoints(await state.args.journal.loadTree(state.args.rootId) ?? [], state).filter((event) => event.environmentId === environmentId).slice(0, -2).slice(0, 1);
5860
- if (oldest.length === 0) return false;
5861
- return (await cleanCheckpoints(state, branching, oldest, signal)).length === 0;
5742
+ /** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to
5743
+ * the parent tree. Supply a view-only parentless copy so strict materialization can fold root
5744
+ * metering without weakening its missing-spawn corruption check for ordinary event lists. */
5745
+ /** @internal Exact parentless root for a Runtime-owned subtree. */
5746
+ function ownedTreeRootSpawn(spawn) {
5747
+ const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn;
5748
+ return root;
5862
5749
  }
5863
- // src/runtime/supervise/retained-owner-evidence.ts
5864
- /** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */
5865
- /** One grouping for release and the evidence gate before another owner invocation. */
5866
- function ownerWorkspaceAttempts(events, nodeId) {
5867
- const attempts = [];
5868
- let current;
5869
- const flush = () => {
5870
- if (current !== void 0) attempts.push(current);
5871
- current = void 0;
5750
+ // src/runtime/supervise/retained-owner-state.ts
5751
+ const owners = /* @__PURE__ */ new WeakMap();
5752
+ /** Bound native custody, read from its canonical receipts without probing another provider. */
5753
+ function scopeOwnerLiabilities(scope, events) {
5754
+ const state = owners.get(scope);
5755
+ if (!state) return {
5756
+ environmentHeld: false,
5757
+ invocationUnsettled: false,
5758
+ measuredResources: /* @__PURE__ */ new Map()
5872
5759
  };
5873
- const fresh = (executionId, workspaceRetention) => ({
5874
- workspaceRetention,
5875
- admissions: [],
5876
- ...executionId === void 0 ? {} : { executionId },
5877
- environmentIds: /* @__PURE__ */ new Set(),
5878
- controlByEnvironment: /* @__PURE__ */ new Map(),
5879
- evidence: []
5880
- });
5760
+ const held = /* @__PURE__ */ new Set();
5761
+ const destroyed = /* @__PURE__ */ new Set();
5762
+ const forks = /* @__PURE__ */ new Set();
5763
+ const key = (provider, id) => JSON.stringify([provider, id]);
5764
+ const forkKey = (provider, id, environmentId) => JSON.stringify([
5765
+ provider,
5766
+ id,
5767
+ environmentId ?? null
5768
+ ]);
5769
+ let invocationUnsettled = false;
5770
+ let environment;
5771
+ const measurements = /* @__PURE__ */ new Map();
5881
5772
  for (const event of events) {
5882
- if (!("id" in event) || event.id !== nodeId) continue;
5883
- if (event.kind === "execution-input") {
5884
- flush();
5885
- current = fresh(`${nodeId}:input:${event.seq}`, event.workspaceRetention);
5886
- } else if (event.kind === "execution-admitted" && event.admission.phase === "environment") {
5887
- if (current?.result !== void 0) flush();
5888
- current ??= fresh();
5889
- current.environmentIds.add(event.admission.environmentId);
5890
- current.admissions.push(event.admission);
5891
- } else if (event.kind === "execution-admitted" && event.admission.phase === "dispatched") {
5892
- current?.admissions.push(event.admission);
5893
- current?.controlByEnvironment.set(event.admission.controlRef.environmentId, event.admission.controlRef);
5894
- } else if (event.kind === "execution-admitted") {
5895
- current?.admissions.push(event.admission);
5896
- if (current && event.admission.phase === "intent" && event.admission.outputFilePolicyDigest) current.outputFilePolicyDigest = current.outputFilePolicyDigest === void 0 || current.outputFilePolicyDigest === event.admission.outputFilePolicyDigest ? event.admission.outputFilePolicyDigest : "conflicting-file-policies";
5897
- } else if (event.kind === "execution-bound") {
5898
- if (current !== void 0 && current.result === void 0) current.binding = event.binding;
5773
+ if (event.id !== state.args.nodeId) continue;
5774
+ if (event.kind === "execution-admitted") {
5775
+ invocationUnsettled = true;
5776
+ if (event.admission.phase === "environment") {
5777
+ environment = key(event.admission.provider, event.admission.environmentId);
5778
+ held.add(environment);
5779
+ destroyed.delete(environment);
5780
+ measurements.delete(environment);
5781
+ }
5899
5782
  } else if (event.kind === "execution-result") {
5900
- current ??= fresh();
5901
- current.result = event;
5902
- } else if (event.kind === "execution-evidence") current?.evidence.push(event);
5783
+ invocationUnsettled = false;
5784
+ if (environment !== void 0) measurements.set(environment, new Map(Object.entries(event.spent.resources ?? {}).flatMap(([name, value]) => value.known ? [[name, value.unit]] : [])));
5785
+ } else if (event.kind === "environment-teardown" && event.destroyed) {
5786
+ held.delete(key(event.provider, event.environmentId));
5787
+ destroyed.add(key(event.provider, event.environmentId));
5788
+ } else if (event.kind === "workspace-checkpoint-fork-requested") forks.add(forkKey(event.provider, event.idempotencyKey));
5789
+ else if (event.kind === "workspace-checkpoint-fork-ready") {
5790
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5791
+ forks.add(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5792
+ } else if (event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed) {
5793
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey));
5794
+ forks.delete(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId));
5795
+ }
5903
5796
  }
5904
- flush();
5905
- return attempts;
5797
+ const live = state.liveEnvironmentId?.();
5798
+ if (live !== void 0 && (state.provider === void 0 || !destroyed.has(key(state.provider.name, live)))) held.add(key(state.provider?.name ?? "", live));
5799
+ const measuredResources = new Map(measurements.get([...held][0] ?? "") ?? []);
5800
+ for (const reference of held) for (const [name, unit] of measuredResources) if (measurements.get(reference)?.get(name) !== unit) measuredResources.delete(name);
5801
+ if (forks.size > 0 || invocationUnsettled) measuredResources.clear();
5802
+ return {
5803
+ environmentHeld: held.size > 0 || forks.size > 0,
5804
+ invocationUnsettled,
5805
+ measuredResources
5806
+ };
5906
5807
  }
5907
- /** Group owner admissions by input. A source with no verified workspace receipt is preserved, including one a later resume can still use. */
5908
- const UNVERIFIED_SOURCE = "provider workspace retention: source preserved because the owner execution has no verified workspace receipt";
5909
- async function ownerWorkspaceRetentionFailures(events, owner) {
5910
- const attempts = ownerWorkspaceAttempts(events, owner.nodeId);
5911
- const failures = /* @__PURE__ */ new Map();
5912
- for (const index of attempts.keys()) {
5913
- const attempt = withLaterEvidence(attempts, index);
5914
- if (attempt.workspaceRetention !== true && attempt.outputFilePolicyDigest === void 0) continue;
5915
- if (attempt.environmentIds.size === 0) continue;
5916
- if (attempt.environmentIds.size > 1) {
5917
- for (const environmentId of attempt.environmentIds) failures.set(environmentId, UNVERIFIED_SOURCE);
5808
+ function scopeRetainedOwnerContext(scope) {
5809
+ return owners.get(scope)?.context;
5810
+ }
5811
+ /** The journal tree that owns this manager turn, including nested driver children. */
5812
+ function scopeRetainedOwnerJournalRoot(scope) {
5813
+ return owners.get(scope)?.args.rootId;
5814
+ }
5815
+ /** Bind the provider that owns native stop, checkpoint and environment acknowledgements. */
5816
+ function bindScopeRetainedOwnerProvider(scope, provider) {
5817
+ const state = owners.get(scope);
5818
+ if (state) state.provider = provider;
5819
+ }
5820
+ /** Bind the resolver for the owner's current environment id. Admissions alone miss a provider that never writes an environment admission. */
5821
+ function bindScopeRetainedOwnerEnvironmentId(scope, liveEnvironmentId) {
5822
+ const state = owners.get(scope);
5823
+ if (state) state.liveEnvironmentId = liveEnvironmentId;
5824
+ }
5825
+ // src/runtime/supervise/retained-owner-checkpoint-requests.ts
5826
+ /** Reconstruct authority for this source only; a replacement cannot own its snapshots. */
5827
+ async function checkpointHandle(state, sourceEnvironmentId, signal) {
5828
+ const cached = state.checkpointHandles?.get(sourceEnvironmentId);
5829
+ if (cached !== void 0) return cached;
5830
+ const provider = state.provider;
5831
+ if (provider === void 0) return void 0;
5832
+ try {
5833
+ const branching = await runAbortable(async () => {
5834
+ if (provider.workspaceBranching) return await provider.workspaceBranching.forEnvironment(sourceEnvironmentId, { signal }) ?? void 0;
5835
+ const source = await provider.get?.(sourceEnvironmentId);
5836
+ return source?.id === sourceEnvironmentId && source.provider === provider.name ? source.workspaceBranching : void 0;
5837
+ }, signal, "retained owner checkpoint handle lookup timed out");
5838
+ if (branching !== void 0) {
5839
+ state.checkpointHandles ??= /* @__PURE__ */ new Map();
5840
+ state.checkpointHandles.set(sourceEnvironmentId, branching);
5841
+ }
5842
+ return branching;
5843
+ } catch {
5844
+ return;
5845
+ }
5846
+ }
5847
+ /**
5848
+ * An aborted observation cannot prove that the provider never created a snapshot, so a request
5849
+ * whose lookup does not find it keeps its source. A `not_found` older than
5850
+ * {@link WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS} never created one. A parent abort starts no lookup.
5851
+ */
5852
+ async function reconcileCheckpointRequests(state, events, parent) {
5853
+ const operationKey = (operation) => JSON.stringify([operation.idempotencyKey, operation.requestDigest]);
5854
+ const resolved = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint" && event.id === state.args.nodeId && event.provider === state.provider?.name ? [operationKey(event.checkpoint)] : []));
5855
+ const pending = events.filter((event) => event.kind === "workspace-checkpoint-requested" && event.id === state.args.nodeId && event.provider === state.provider?.name && !resolved.has(operationKey(event.request)));
5856
+ const unconfirmed = [];
5857
+ for (const event of pending) {
5858
+ if (parent?.aborted) {
5859
+ unconfirmed.push({
5860
+ event,
5861
+ reason: "cancelled before checkpoint lookup"
5862
+ });
5918
5863
  continue;
5919
5864
  }
5920
- const environmentId = [...attempt.environmentIds][0];
5921
- const reason = await ownerAttemptHasCapture(attempt, environmentId, owner.blobs, owner);
5922
- if (reason !== void 0) failures.set(environmentId, reason);
5865
+ const signal = deadlineSignal(parent, 3e4);
5866
+ try {
5867
+ const branching = await checkpointHandle(state, event.environmentId, signal);
5868
+ if (branching === void 0) throw new Error("source-scoped checkpoint handle unavailable");
5869
+ const result = await runAbortable(() => branching.lookupCheckpoint({
5870
+ idempotencyKey: event.request.idempotencyKey,
5871
+ requestDigest: event.request.requestDigest
5872
+ }, { signal }), signal, "retained owner checkpoint lookup timed out");
5873
+ if (result.status === "not_found") {
5874
+ const requestedAt = Date.parse(event.at);
5875
+ if (Number.isFinite(requestedAt) && state.args.now() - requestedAt >= 12e5) continue;
5876
+ unconfirmed.push({
5877
+ event,
5878
+ reason: "lookup not_found while the request may be in flight"
5879
+ });
5880
+ continue;
5881
+ }
5882
+ if (result.status !== "found") {
5883
+ unconfirmed.push({
5884
+ event,
5885
+ reason: `lookup ${result.status}${"message" in result && result.message ? `: ${result.message}` : ""}`
5886
+ });
5887
+ continue;
5888
+ }
5889
+ if (!workspaceCheckpointResultMatchesRequest(event.request, result)) {
5890
+ unconfirmed.push({
5891
+ event,
5892
+ reason: "lookup found a checkpoint for another request"
5893
+ });
5894
+ continue;
5895
+ }
5896
+ const recovered = {
5897
+ kind: "workspace-checkpoint",
5898
+ id: event.id,
5899
+ provider: event.provider,
5900
+ environmentId: event.environmentId,
5901
+ checkpoint: result.checkpoint,
5902
+ ...event.marker === void 0 ? {} : { marker: event.marker },
5903
+ seq: state.nextSequence(),
5904
+ at: event.at
5905
+ };
5906
+ await state.args.journal.appendEvent(state.args.rootId, recovered);
5907
+ events.push(recovered);
5908
+ } catch (error) {
5909
+ unconfirmed.push({
5910
+ event,
5911
+ reason: `lookup failed: ${errorText(error instanceof Error ? error.message : error)}`
5912
+ });
5913
+ }
5923
5914
  }
5924
- return failures;
5915
+ return unconfirmed;
5916
+ }
5917
+ function pendingCheckpoints(events, state) {
5918
+ const confirmed = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint-cleanup" && event.id === state.args.nodeId && event.provider === state.provider?.name && event.confirmed ? [JSON.stringify([event.environmentId, event.checkpointId])] : []));
5919
+ return events.filter((event) => event.kind === "workspace-checkpoint" && event.id === state.args.nodeId && event.provider === state.provider?.name && !confirmed.has(JSON.stringify([event.environmentId, event.checkpoint.checkpointId])));
5925
5920
  }
5921
+ // src/runtime/supervise/retained-owner-checkpoint-capture.ts
5926
5922
  /**
5927
- * The attempt with the evidence journaled after it. A release's capture of a preserved source is
5928
- * journaled after later invocations began; every receipt names its exact execution, environment
5929
- * and control reference, so a receipt of another attempt never verifies this one.
5923
+ * Delete restore-point checkpoints. A checkpoint is a restore point for a live owner, never
5924
+ * evidence: the turn's workspace capture and native session export are the evidence, and the
5925
+ * release keeps a source whose evidence is incomplete. An aborted parent starts no provider call.
5930
5926
  */
5931
- function withLaterEvidence(attempts, index) {
5932
- const attempt = attempts[index];
5933
- const later = attempts.slice(index + 1).flatMap((next) => next.evidence);
5934
- return later.length === 0 ? attempt : {
5935
- ...attempt,
5936
- evidence: [...attempt.evidence, ...later]
5937
- };
5938
- }
5939
- /** Undefined when a receipt authorizes destroying the source. Otherwise why it stays. */
5940
- async function ownerAttemptHasCapture(attempt, environmentId, blobs, owner, allowPartialProcessCapture = false) {
5941
- const controlRef = attempt.controlByEnvironment.get(environmentId);
5942
- if (attempt.outputFilePolicyDigest !== void 0) {
5943
- const output = attempt.result === void 0 ? void 0 : recordValue(await storedOutput(blobs, attempt.result.outRef));
5944
- const publication = AgentRetainedFilePublicationSchema.safeParse(output?.publication);
5945
- const node = owner === void 0 ? void 0 : ownerCaptureIdentity(attempt, owner).node;
5946
- if (!output || output.kind !== "retained-file-output" || output.version !== 1 || output.invocationId !== attempt.executionId || output.policyDigest !== attempt.outputFilePolicyDigest || !Object.hasOwn(output, "submission") || !recordValue(output.node) || output.submissionRef !== contentAddress(output.submission) || !node || contentAddress(output.node) !== contentAddress(node) || !publication.success || !controlRef || !sameControlCoordinates(publication.data.controlRef, controlRef) || canonicalCandidateDigest(publication.data.policy) !== attempt.outputFilePolicyDigest) return UNVERIFIED_SOURCE;
5947
- if (attempt.workspaceRetention !== true) return void 0;
5948
- }
5949
- const receipts = [...attempt.result === void 0 || attempt.result.outputFormat === "json" ? [] : [attempt.result.outRef], ...attempt.evidence.map((event) => event.outRef)];
5950
- const identity = owner === void 0 ? void 0 : ownerCaptureIdentity(attempt, owner);
5951
- let verified = false;
5952
- let nativeHold;
5953
- for (const outRef of receipts) {
5954
- const output = await storedOutput(blobs, outRef);
5955
- const snapshot = output !== null && typeof output === "object" ? output.workspaceSnapshot : void 0;
5956
- const capture = output !== null && typeof output === "object" ? output.workspaceCapture : void 0;
5957
- const receipt = capture !== null && typeof capture === "object" ? capture : void 0;
5958
- const matches = receipt !== void 0 && receipt.environmentId === environmentId && receipt.executionId === attempt.executionId;
5959
- const durable = hasDurableWorkspaceCapture(output, snapshot, environmentId, attempt.executionId, controlRef, identity, allowPartialProcessCapture);
5960
- if (matches && receipt !== void 0) {
5961
- const hold = nativeSessionCopyHoldReason(receipt);
5962
- if (hold !== void 0) {
5963
- nativeHold = hold;
5964
- verified = false;
5965
- } else if (durable) {
5966
- nativeHold = void 0;
5967
- verified = true;
5927
+ async function cleanCheckpoints(state, branching, checkpoints, parent) {
5928
+ const unconfirmed = [];
5929
+ for (const event of checkpoints) {
5930
+ const material = {
5931
+ kind: "checkpoint",
5932
+ targetId: event.checkpoint.checkpointId,
5933
+ provider: event.checkpoint.provider
5934
+ };
5935
+ const request = {
5936
+ ...material,
5937
+ operationId: `${event.checkpoint.idempotencyKey}:delete`,
5938
+ requestDigest: workspaceCleanupRequestDigest(material)
5939
+ };
5940
+ let confirmed = false;
5941
+ let reason;
5942
+ const signal = deadlineSignal(parent, 3e4);
5943
+ try {
5944
+ if (parent?.aborted) reason = "cancelled before checkpoint cleanup";
5945
+ else if (branching === void 0) throw new Error("source-scoped checkpoint handle unavailable");
5946
+ else {
5947
+ const acknowledgement = await runAbortable(() => branching.deleteCheckpoint(request, { signal }), signal, "retained owner checkpoint cleanup timed out");
5948
+ confirmed = workspaceCleanupAcknowledgementMatches(request, acknowledgement) && (acknowledgement.status === "deleted" || acknowledgement.status === "already_absent");
5949
+ if (!confirmed) reason = `provider acknowledged '${acknowledgement.status}'`;
5968
5950
  }
5969
- } else if (nativeHold === void 0 && durable) verified = true;
5951
+ } catch (error) {
5952
+ reason = errMessage(error).slice(0, 1e3);
5953
+ }
5954
+ if (!confirmed) unconfirmed.push({
5955
+ event,
5956
+ reason: reason ?? "delete was not confirmed"
5957
+ });
5958
+ await state.args.journal.appendEvent(state.args.rootId, {
5959
+ kind: "workspace-checkpoint-cleanup",
5960
+ id: state.args.nodeId,
5961
+ provider: event.provider,
5962
+ environmentId: event.environmentId,
5963
+ checkpointId: event.checkpoint.checkpointId,
5964
+ confirmed,
5965
+ ...reason === void 0 ? {} : { refused: reason.slice(0, 1e3) },
5966
+ seq: state.nextSequence(),
5967
+ at: new Date(state.args.now()).toISOString()
5968
+ });
5970
5969
  }
5971
- if (nativeHold !== void 0) return nativeHold;
5972
- return verified ? void 0 : UNVERIFIED_SOURCE;
5970
+ return unconfirmed;
5973
5971
  }
5974
- function ownerCaptureIdentity(attempt, owner) {
5975
- const intent = attempt.admissions.find((admission) => admission.phase === "intent");
5976
- const node = attempt.binding === void 0 ? void 0 : {
5977
- rootId: owner.executionRootId ?? owner.rootId,
5978
- parentId: owner.nodeId,
5979
- nodeId: owner.nodeId,
5980
- ...owner.depth === void 0 ? {} : { depth: owner.depth },
5981
- attemptId: attempt.binding.attemptId
5972
+ /** Destroy a capture's fork and journal whether the provider confirmed it. */
5973
+ async function destroyCaptureFork(state, branching, target, parent) {
5974
+ const material = {
5975
+ kind: "fork",
5976
+ targetId: target.fork.environmentId,
5977
+ provider: target.provider
5982
5978
  };
5983
- return {
5984
- profileDigest: intent?.requestedProfileDigest,
5985
- node
5979
+ const request = {
5980
+ ...material,
5981
+ operationId: `${target.fork.idempotencyKey}:destroy`,
5982
+ requestDigest: workspaceCleanupRequestDigest(material)
5986
5983
  };
5984
+ let destroyed = false;
5985
+ try {
5986
+ const signal = deadlineSignal(parent, 3e4);
5987
+ const acknowledgement = await runAbortable(() => branching.destroyFork(request, { signal }), signal, "checkpoint capture fork cleanup timed out");
5988
+ destroyed = workspaceCleanupAcknowledgementMatches(request, acknowledgement) && (acknowledgement.status === "deleted" || acknowledgement.status === "already_absent");
5989
+ } catch {}
5990
+ await state.args.journal.appendEvent(state.args.rootId, {
5991
+ kind: "workspace-checkpoint-fork-teardown",
5992
+ id: state.args.nodeId,
5993
+ ...target,
5994
+ destroyed,
5995
+ seq: state.nextSequence(),
5996
+ at: new Date(state.args.now()).toISOString()
5997
+ });
5998
+ return destroyed;
5987
5999
  }
5988
- /** Recover evidence before reuse. Failed unverified turns keep their invocation; accepted turns owe evidence. */
5989
- async function reconcileOwnerWorkspaceBeforeReuse(state, signal, reconnecting = false) {
6000
+ /** Destroy capture forks the journal does not show destroyed. An aborted parent starts no further fork call. Returns forks still unconfirmed. */
6001
+ async function settleCaptureForks(state, parent) {
5990
6002
  const { args } = state;
5991
- const indebted = /* @__PURE__ */ new Set();
5992
- const events = await args.journal.loadTree(args.rootId) ?? [];
5993
- const attempts = ownerWorkspaceAttempts(events, args.nodeId);
5994
- const latest = attempts.at(-1);
5995
- const unusable = unusableEnvironmentIds(events.filter((event) => event.id === args.nodeId));
5996
- if (latest === void 0) return indebted;
5997
- const reusing = new Set(latest.environmentIds);
5998
- if (latest.result === void 0 && state.priorSession !== void 0) reusing.add(state.priorSession.environmentId);
5999
- for (const attempt of attempts) {
6000
- if ((attempt.workspaceRetention !== true || attempt.result === void 0) && attempt.outputFilePolicyDigest === void 0) continue;
6001
- if (reconnecting && attempt === latest && attempt.result === void 0) continue;
6002
- for (const environmentId of attempt.environmentIds) {
6003
- if (!reusing.has(environmentId) || unusable.has(environmentId)) continue;
6004
- if (await ownerAttemptHasCapture(attempt, environmentId, args.blobs, args, true) === void 0) continue;
6005
- if (attempt.outputFilePolicyDigest !== void 0) throw new RetainedExecutionPendingError(/* @__PURE__ */ new Error(UNVERIFIED_SOURCE), "unobservable");
6006
- if (attempt.result === void 0) continue;
6007
- signal.throwIfAborted();
6008
- const failure = capturePendingMessage(attempt.executionId ?? args.nodeId, /* @__PURE__ */ new Error("client capture writers are retired; a persisted verified receipt is required"));
6009
- if (executorFailureReason(attempt.result) === void 0) await owePendingEvidence(state, events, attempt, environmentId, failure);
6010
- else {
6011
- await state.context.onEvidence({
6012
- executionId: attempt.executionId,
6013
- environmentId,
6014
- controlRef: attempt.controlByEnvironment.get(environmentId),
6015
- ...ownerCaptureIdentity(attempt, args),
6016
- workspaceCaptureFailure: failure
6017
- });
6018
- throw new RetainedExecutionPendingError(new Error(failure), "unobservable");
6019
- }
6020
- indebted.add(environmentId);
6021
- state.forceNewSession = true;
6003
+ const providerName = state.provider?.name;
6004
+ const events = (await args.journal.loadTree(args.rootId) ?? []).filter((event) => event.id === args.nodeId);
6005
+ const named = (key) => {
6006
+ for (const event of events) if ((event.kind === "workspace-checkpoint-capture" || event.kind === "workspace-checkpoint-fork-teardown") && event.fork.idempotencyKey === key) return event.fork.environmentId;
6007
+ };
6008
+ const destroyed = new Set(events.flatMap((event) => event.kind === "workspace-checkpoint-fork-teardown" && event.destroyed ? [event.fork.idempotencyKey] : []));
6009
+ const unresolved = [];
6010
+ for (const request of events) {
6011
+ if (request.kind !== "workspace-checkpoint-fork-requested" || request.provider !== providerName) continue;
6012
+ if (destroyed.has(request.idempotencyKey)) continue;
6013
+ if (parent?.aborted) {
6014
+ unresolved.push(named(request.idempotencyKey) ?? request.idempotencyKey);
6015
+ continue;
6022
6016
  }
6017
+ const signal = deadlineSignal(parent, 3e4);
6018
+ const branching = await checkpointHandle(state, request.environmentId, signal);
6019
+ let forkEnvironmentId = named(request.idempotencyKey);
6020
+ if (forkEnvironmentId === void 0 && branching !== void 0) try {
6021
+ const found = await runAbortable(() => branching.lookupFork({
6022
+ idempotencyKey: request.idempotencyKey,
6023
+ requestDigest: request.requestDigest
6024
+ }, { signal }), signal, "checkpoint capture fork lookup timed out");
6025
+ if (found.status === "not_found") continue;
6026
+ if (found.status === "found") forkEnvironmentId = found.environment.environmentId;
6027
+ } catch {}
6028
+ if (forkEnvironmentId === void 0 || branching === void 0 || !await destroyCaptureFork(state, branching, {
6029
+ provider: request.provider,
6030
+ environmentId: request.environmentId,
6031
+ checkpointId: request.checkpointId,
6032
+ fork: {
6033
+ idempotencyKey: request.idempotencyKey,
6034
+ environmentId: forkEnvironmentId
6035
+ }
6036
+ }, parent)) unresolved.push(forkEnvironmentId ?? request.idempotencyKey);
6023
6037
  }
6024
- return indebted;
6038
+ return unresolved;
6039
+ }
6040
+ // src/runtime/supervise/retained-owner-checkpoint-rotation.ts
6041
+ /** Checkpoint after a coordination call once the last one is older than {@link WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS}. It never delays the call, and a failure leaves the previous restore point. */
6042
+ function noteScopeRetainedOwnerCoordination(scope) {
6043
+ const state = owners.get(scope);
6044
+ if (state?.provider === void 0 || state.checkpointsUnavailable !== void 0) return;
6045
+ if (state.checkpointing !== void 0 || state.turnEnd !== void 0 || scope.signal.aborted) return;
6046
+ const now = state.args.now();
6047
+ if (state.lastCheckpointAt !== void 0 && now - state.lastCheckpointAt < 6e4) return;
6048
+ state.lastCheckpointAt = now;
6049
+ state.checkpointing = checkpointOwnerWorkspace(scope, state).catch(() => void 0).finally(() => {
6050
+ delete state.checkpointing;
6051
+ });
6025
6052
  }
6026
- function capturePendingMessage(executionId, cause) {
6027
- return `retained workspace capture pending for ${executionId}; source environment preserved: ${cause instanceof Error ? cause.message : String(cause)}`;
6053
+ /** @internal The checkpoint in progress for this owner, for a test or a release to wait on. */
6054
+ function scopeRetainedOwnerCheckpointing(scope) {
6055
+ return owners.get(scope)?.checkpointing;
6028
6056
  }
6029
- /** Preserve a historical capture obligation without blocking work in a fresh environment. */
6030
- async function owePendingEvidence(state, events, attempt, environmentId, failure) {
6057
+ async function checkpointOwnerWorkspace(scope, state) {
6058
+ const { provider, args } = state;
6059
+ if (provider === void 0) return;
6060
+ if (!provider.get) {
6061
+ state.checkpointsUnavailable = `provider ${provider.name} cannot reconstruct an environment`;
6062
+ return;
6063
+ }
6064
+ if ((await provider.capabilities()).create?.workspaceCheckpoint !== true) {
6065
+ state.checkpointsUnavailable = `provider ${provider.name} cannot create an environment from a checkpoint`;
6066
+ return;
6067
+ }
6068
+ const dispatched = [...state.admissions].reverse().find((admission) => admission.phase === "dispatched");
6069
+ if (dispatched?.phase !== "dispatched") return;
6070
+ const source = dispatched.controlRef;
6071
+ const signal = AbortSignal.any([scope.signal, AbortSignal.timeout(WORKSPACE_CHECKPOINT_TIMEOUT_MS)]);
6072
+ const get = provider.get.bind(provider);
6073
+ const environment = await runAbortable(() => get(source.environmentId), signal, "retained owner checkpoint timed out");
6074
+ if (environment === null || environment.id !== source.environmentId || environment.provider !== provider.name) return;
6075
+ const branching = environment.workspaceBranching;
6076
+ if (branching === void 0) {
6077
+ state.checkpointsUnavailable = `environment ${environment.id} offers no durable checkpoint`;
6078
+ return;
6079
+ }
6080
+ const requestOne = () => requestCheckpoint(scope, state, provider.name, environment, branching, source, signal);
6081
+ if (!await requestOne() && (!await deleteOldestCheckpoint(state, branching, environment.id, signal) || !await requestOne())) return;
6082
+ const owned = pendingCheckpoints(await args.journal.loadTree(args.rootId) ?? [], state).filter((event) => event.environmentId === environment.id);
6083
+ const rotation = new AbortController();
6084
+ state.rotationCaptures = rotation;
6085
+ const timer = setTimeout(() => rotation.abort(/* @__PURE__ */ new Error(`the rotation's ${WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS} ms for checkpoint deletes ran out; checkpoint kept`)), WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS);
6086
+ try {
6087
+ await cleanCheckpoints(state, branching, owned.slice(0, -2), AbortSignal.any([scope.signal, rotation.signal]));
6088
+ } finally {
6089
+ clearTimeout(timer);
6090
+ if (state.rotationCaptures === rotation) delete state.rotationCaptures;
6091
+ }
6092
+ }
6093
+ /** Ask for one checkpoint and journal the answer. True when the journal holds the checkpoint. */
6094
+ async function requestCheckpoint(scope, state, providerName, environment, branching, source, signal) {
6031
6095
  const { args } = state;
6032
- if (!events.some((event) => event.kind === "evidence-pending" && event.id === args.nodeId && event.environmentId === environmentId)) {
6033
- const at = new Date(args.now()).toISOString();
6096
+ const seq = state.nextSequence();
6097
+ const at = new Date(args.now()).toISOString();
6098
+ const name = `owner-checkpoint-${seq}`;
6099
+ const marker = {
6100
+ path: WORKSPACE_CHECKPOINT_MARKER_PATH,
6101
+ content: `${JSON.stringify({
6102
+ node: args.nodeId,
6103
+ checkpoint: name,
6104
+ at
6105
+ })}\n`
6106
+ };
6107
+ const marked = await writeWorkspaceMarker(environment, marker, signal);
6108
+ const material = {
6109
+ source,
6110
+ name
6111
+ };
6112
+ const request = {
6113
+ ...material,
6114
+ idempotencyKey: `${args.nodeId}:workspace-checkpoint:${seq}`,
6115
+ requestDigest: workspaceCheckpointRequestDigest(material)
6116
+ };
6117
+ state.checkpointHandles ??= /* @__PURE__ */ new Map();
6118
+ state.checkpointHandles.set(environment.id, branching);
6119
+ await args.journal.appendEvent(args.rootId, {
6120
+ kind: "workspace-checkpoint-requested",
6121
+ id: args.nodeId,
6122
+ provider: providerName,
6123
+ environmentId: environment.id,
6124
+ request,
6125
+ ...marked ? { marker } : {},
6126
+ seq,
6127
+ at
6128
+ });
6129
+ const result = await runAbortable(() => branching.checkpoint(request, { signal }), signal, "retained owner checkpoint timed out");
6130
+ if (result.status !== "created" && result.status !== "replayed") {
6034
6131
  await args.journal.appendEvent(args.rootId, {
6035
- kind: "evidence-pending",
6132
+ kind: "workspace-checkpoint-refused",
6036
6133
  id: args.nodeId,
6037
- environmentId,
6038
- ...attempt.executionId === void 0 ? {} : { executionId: attempt.executionId },
6039
- error: failure,
6040
- since: at,
6134
+ provider: providerName,
6135
+ environmentId: environment.id,
6136
+ idempotencyKey: request.idempotencyKey,
6137
+ message: errorText("message" in result ? result.message : result.status),
6041
6138
  seq: state.nextSequence(),
6042
6139
  at
6043
6140
  });
6141
+ return false;
6044
6142
  }
6045
- }
6046
- /** A stored output whose bytes match its content reference, or undefined. */
6047
- async function storedOutput(blobs, outRef) {
6048
- try {
6049
- const output = await blobs.get(outRef);
6050
- return output === void 0 || contentAddress(output) !== outRef ? void 0 : output;
6051
- } catch {
6052
- return;
6053
- }
6054
- }
6055
- /** A stored result authorizes cleanup only for the exact source and complete capture. */
6056
- function hasDurableWorkspaceCapture(output, snapshot, environmentId, executionId, controlRef, identity, allowPartialProcessCapture = false) {
6057
- const parsed = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(snapshot);
6058
- if (!parsed.success || !("locator" in parsed.data.manifest) || !("locator" in parsed.data.archive)) return false;
6059
- if (output === null || typeof output !== "object") return false;
6060
- const capture = output.workspaceCapture;
6061
- if (capture === null || typeof capture !== "object") return false;
6062
- const receipt = capture;
6063
- if (identity !== void 0 && (identity.profileDigest === void 0 || receipt.profileDigest !== identity.profileDigest || (identity.node === void 0 ? receipt.node !== void 0 : receipt.node === void 0 || contentAddress(receipt.node) !== contentAddress(identity.node)))) return false;
6064
- const capturedControl = AgentExactRunControlRefSchema.safeParse(receipt.controlRef);
6065
- if (executionId === void 0 || controlRef === void 0 || !capturedControl.success || !sameControlCoordinates(capturedControl.data, controlRef) || receipt.environmentId !== environmentId || receipt.executionId !== executionId || !captureAuthorizesDestroy(receipt, allowPartialProcessCapture)) return false;
6066
- const linked = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(receipt.snapshot);
6067
- return linked.success && linked.data.digest === parsed.data.digest && JSON.stringify(linked.data.manifest) === JSON.stringify(parsed.data.manifest) && JSON.stringify(linked.data.archive) === JSON.stringify(parsed.data.archive);
6068
- }
6069
- const NATIVE_STORE_GAP = /(?:^|\s)((?:over_bound|store_file_):[^\s;]+)/g;
6070
- const COVERAGE_GAP_PREFIX = "provider workspace retention coverage incomplete: ";
6071
- const PROCESS_GAP = [
6072
- /^process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
6073
- /^Sandbox session [\w-]+ declared partial raw capture$/,
6074
- /^Sandbox session [\w-]+ attempt [\w-]+\/\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
6075
- /^Sandbox session [\w-]+ has no original process source: [\w-]+$/,
6076
- /^Sandbox session [\w-]+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
6077
- /^Raw native session capture for Sandbox session [\w-]+ is unavailable: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/,
6078
- /^Session [\w-]+ process streams incomplete$/,
6079
- /^Attempt [\w-]+\/\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\w-]+)?$/
6080
- ];
6081
- const EVENT_GAP = /(?:^|:\s)events_incomplete(?::[\w.-]+)?$/;
6082
- /** Keep the box when the final native copy is incomplete. Process I/O or event-log gaps do not. */
6083
- function nativeSessionCopyHoldReason(receipt) {
6084
- const provenance = receipt.provenance;
6085
- if (provenance === null || typeof provenance !== "object") return void 0;
6086
- const reported = provenance;
6087
- const sessions = Array.isArray(reported.sessions) ? reported.sessions : [];
6088
- let incomplete = false;
6089
- const tokens = /* @__PURE__ */ new Set();
6090
- const take = (value) => {
6091
- const text = Array.isArray(value) ? value.filter((item) => typeof item === "string").join("; ") : typeof value === "string" ? value : "";
6092
- for (const match of text.matchAll(NATIVE_STORE_GAP)) tokens.add(match[1]);
6093
- };
6094
- for (const session of sessions) {
6095
- if (session === null || typeof session !== "object") continue;
6096
- const row = session;
6097
- const store = row.nativeStore;
6098
- if (store !== null && typeof store === "object" && store.complete === false) incomplete = true;
6099
- take(row.nativeReason);
6100
- if (store !== null && typeof store === "object") take(store.missingReasons);
6101
- }
6102
- take(reported.missing);
6103
- if (!incomplete && tokens.size === 0) return void 0;
6104
- return `native session copy incomplete: ${tokens.size > 0 ? [...tokens].join("; ") : "nativeStore incomplete"}`;
6105
- }
6106
- function captureAuthorizesDestroy(receipt, allowPartialProcessCapture) {
6107
- if (nativeSessionCopyHoldReason(receipt) !== void 0) return false;
6108
- if (receipt.coverageComplete === true) return true;
6109
- return hasOnlyRawProcessCaptureGap(receipt, !allowPartialProcessCapture);
6110
- }
6111
- function captureGapTexts(receipt) {
6112
- const reason = receipt.incompleteReason;
6113
- const named = typeof reason === "string" && reason.startsWith(COVERAGE_GAP_PREFIX) ? reason.slice(50).split("; ") : [];
6114
- const provenance = receipt.provenance;
6115
- const missing = provenance !== null && typeof provenance === "object" && Array.isArray(provenance.missing) ? provenance.missing.filter((item) => typeof item === "string") : [];
6116
- return [...named, ...missing].map((gap) => gap.trim()).filter((gap) => gap.length > 0);
6117
- }
6118
- /**
6119
- * A process I/O gap does not invalidate a verified workspace. `includeEvents` is the release
6120
- * rule: an event-log gap alone also authorizes destroy. Any other gap keeps the source.
6121
- */
6122
- function hasOnlyRawProcessCaptureGap(receipt, includeEvents = false) {
6123
- const provenance = receipt.provenance;
6124
- if (provenance === null || typeof provenance !== "object") return false;
6125
- const reported = provenance;
6126
- const workspace = reported.workspace;
6127
- if (reported.status !== "reported" || workspace === null || typeof workspace !== "object" || workspace.complete !== true) return false;
6128
- const sessions = reported.sessions;
6129
- if (!Array.isArray(sessions) || !sessions.some((session) => session !== null && typeof session === "object" && (session.processStreams?.complete === false || includeEvents && session.nativeEvents?.complete === false))) return false;
6130
- const gaps = captureGapTexts(receipt);
6131
- return gaps.length > 0 && gaps.every((gap) => PROCESS_GAP.some((pattern) => pattern.test(gap)) || includeEvents && EVENT_GAP.test(gap));
6132
- }
6133
- /** Environments that cannot execute another turn, whether absent or terminal at the provider. */
6134
- function unusableEnvironmentIds(owned) {
6135
- return new Set(owned.flatMap((event) => event.kind === "environment-terminal" || event.kind === "environment-teardown" && event.destroyed ? [event.environmentId] : []));
6136
- }
6137
- /**
6138
- * After {@link reconcileOwnerWorkspaceBeforeReuse}: an unfinished input an older coordinator
6139
- * admitted into a source now owed evidence, but never dispatched there, is abandoned. Replaying
6140
- * it would mutate the source, so the next drive is a new invocation in another environment. A
6141
- * dispatch lost before its admission was journaled cannot be ruled out, so the outcome is
6142
- * uncertain.
6143
- */
6144
- async function abandonInputAdmittedIntoDebt(state, indebted) {
6145
- const { args } = state;
6146
- const pending = state.admissions.find((admission) => admission.phase === "environment" && indebted.has(admission.environmentId));
6147
- if (pending === void 0 || state.admissions.some((admission) => admission.phase === "dispatched")) return;
6143
+ if (!workspaceCheckpointResultMatchesRequest(request, result)) return false;
6144
+ scope.signal.throwIfAborted();
6148
6145
  await args.journal.appendEvent(args.rootId, {
6149
- kind: "execution-abandoned",
6146
+ kind: "workspace-checkpoint",
6150
6147
  id: args.nodeId,
6151
- inputSeq: state.inputSequence,
6152
- pendingCause: "unobservable",
6153
- failures: 1,
6154
- detail: `admitted into ${pending.environmentId}, whose workspace capture is pending; never dispatched there`,
6155
- outcome: "uncertain",
6148
+ provider: providerName,
6149
+ environmentId: environment.id,
6150
+ checkpoint: result.checkpoint,
6151
+ ...marked ? { marker } : {},
6156
6152
  seq: state.nextSequence(),
6157
- at: new Date(args.now()).toISOString()
6153
+ at
6158
6154
  });
6159
- delete state.inputSequence;
6160
- delete state.taskRef;
6161
- state.admissions.length = 0;
6155
+ return true;
6156
+ }
6157
+ /** Delete the oldest checkpoint past {@link WORKSPACE_CHECKPOINTS_KEPT}, so a snapshot limit cannot freeze the restore point. */
6158
+ async function deleteOldestCheckpoint(state, branching, environmentId, signal) {
6159
+ const oldest = pendingCheckpoints(await state.args.journal.loadTree(state.args.rootId) ?? [], state).filter((event) => event.environmentId === environmentId).slice(0, -2).slice(0, 1);
6160
+ if (oldest.length === 0) return false;
6161
+ return (await cleanCheckpoints(state, branching, oldest, signal)).length === 0;
6162
6162
  }
6163
6163
  // src/runtime/supervise/retained-owner-environment-recovery.ts
6164
6164
  function restoreBefore(owned, inputIndex) {
@@ -6196,8 +6196,21 @@ function continuedEnvironment(owned) {
6196
6196
  inFlight: !attempt.some((event) => event.kind === "execution-result")
6197
6197
  };
6198
6198
  }
6199
- /** Observe exact environment loss before replacing its invocation; preserve uncertain work. */
6200
- async function reconcileScopeRetainedOwnerEnvironment(scope) {
6199
+ /**
6200
+ * Observe exact environment loss before replacing its invocation; preserve uncertain work.
6201
+ *
6202
+ * An environment whose release Runtime already receipted unconfirmed (`environment-teardown`,
6203
+ * `destroyed: false`) is continued only while the provider confirms it running: a reopened run
6204
+ * continued in such a box and the Sandbox refused every attempt (real-work-benchmark-20261127a:
6205
+ * HTTP 501 "Native seat continuation requires the running retained environment";
6206
+ * claim-cycle-count-gcd-20261117a: HTTP 503 "Exact resume admission cleanup remains
6207
+ * unconfirmed" 58 times in 31 minutes). `running` asks the same of any environment, for a seat
6208
+ * change that would checkpoint it. Such an environment is retired, never retried: the next
6209
+ * invocation starts in a new one, restored from the newest checkpoint, without the conversation.
6210
+ * `released` asks the provider only about an environment whose release began, for a restarted
6211
+ * run whose own recovery reconciles any other; that other reads `unknown`.
6212
+ */
6213
+ async function reconcileScopeRetainedOwnerEnvironment(scope, need = "continue") {
6201
6214
  const state = owners.get(scope);
6202
6215
  if (!state?.provider) return { state: "none" };
6203
6216
  const { provider, args } = state;
@@ -6209,12 +6222,14 @@ async function reconcileScopeRetainedOwnerEnvironment(scope) {
6209
6222
  state: "lost",
6210
6223
  environmentId
6211
6224
  };
6212
- if (!provider.get) return {
6225
+ const released = owned.some((event) => event.kind === "environment-teardown" && event.environmentId === environmentId && !event.destroyed);
6226
+ if (!provider.get || need === "released" && !released) return {
6213
6227
  state: "unknown",
6214
6228
  environmentId
6215
6229
  };
6216
6230
  let environment;
6217
6231
  let terminalStatus;
6232
+ let status;
6218
6233
  try {
6219
6234
  environment = await runAbortable(() => provider.get(environmentId), AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)]), "retained owner environment check timed out");
6220
6235
  if (environment !== null) {
@@ -6223,20 +6238,25 @@ async function reconcileScopeRetainedOwnerEnvironment(scope) {
6223
6238
  state: "unknown",
6224
6239
  environmentId
6225
6240
  };
6226
- const status = await runAbortable(() => found.status(), AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)]), "retained owner environment status timed out");
6241
+ status = await runAbortable(() => found.status(), AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)]), "retained owner environment status timed out");
6227
6242
  if (status === "failed" || status === "expired") terminalStatus = status;
6228
6243
  }
6229
- } catch {
6230
- return {
6244
+ } catch (error) {
6245
+ scope.signal.throwIfAborted();
6246
+ if (!released) return {
6231
6247
  state: "unknown",
6232
6248
  environmentId
6233
6249
  };
6250
+ return retireOwnerEnvironment(scope, environmentId, `the provider could not confirm it running: ${errMessage(error).slice(0, 300)}`);
6251
+ }
6252
+ if (environment !== null && terminalStatus === void 0) {
6253
+ if (status !== "running" && (released || need === "running")) return retireOwnerEnvironment(scope, environmentId, `the provider reports it ${status}`);
6254
+ return {
6255
+ state: "live",
6256
+ environmentId,
6257
+ inFlight: continued.inFlight
6258
+ };
6234
6259
  }
6235
- if (environment !== null && terminalStatus === void 0) return {
6236
- state: "live",
6237
- environmentId,
6238
- inFlight: continued.inFlight
6239
- };
6240
6260
  scope.signal.throwIfAborted();
6241
6261
  await args.journal.appendEvent(args.rootId, terminalStatus === void 0 ? {
6242
6262
  kind: "environment-teardown",
@@ -6261,6 +6281,26 @@ async function reconcileScopeRetainedOwnerEnvironment(scope) {
6261
6281
  environmentId
6262
6282
  };
6263
6283
  }
6284
+ /** Journal that Runtime will not continue in `environmentId`; its destroy is still owed. */
6285
+ async function retireOwnerEnvironment(scope, environmentId, why) {
6286
+ const { provider, args, nextSequence } = owners.get(scope);
6287
+ scope.signal.throwIfAborted();
6288
+ await args.journal.appendEvent(args.rootId, {
6289
+ kind: "environment-teardown",
6290
+ id: args.nodeId,
6291
+ provider: provider.name,
6292
+ environmentId,
6293
+ destroyed: false,
6294
+ retired: true,
6295
+ detail: `retired, not running: ${why}. The next invocation starts in a new environment and a new harness session, so the conversation context is not carried`,
6296
+ seq: nextSequence(),
6297
+ at: new Date(args.now()).toISOString()
6298
+ });
6299
+ return {
6300
+ state: "lost",
6301
+ environmentId
6302
+ };
6303
+ }
6264
6304
  /** A fresh unsigned listener rekeys only after exact prior execution is terminal. */
6265
6305
  async function assertRetainedOwnerCoordinationRekey(scope) {
6266
6306
  const state = owners.get(scope);
@@ -6946,6 +6986,21 @@ function committedSession(events, before) {
6946
6986
  end = start;
6947
6987
  }
6948
6988
  }
6989
+ /**
6990
+ * The environment an invocation runs in: the one it was admitted into, or, before any, the one its
6991
+ * intent continued. A turn that continues a kept box is admitted with that box's idempotency key
6992
+ * and journals no environment admission until the provider returns the box.
6993
+ * board-conference-matrix-glm54-on-20261127a (spawn journal rows 132-136): Sandbox refused the
6994
+ * kept box's resume for 14 minutes, so the turn held only its intent when the run stopped.
6995
+ */
6996
+ function invocationTarget(admissions, owned, inputIndex) {
6997
+ const environment = admissions.find((admission) => admission.phase === "environment");
6998
+ if (environment?.phase === "environment") return environment.environmentId;
6999
+ const intent = admissions.find((admission) => admission.phase === "intent");
7000
+ if (intent?.phase !== "intent" || inputIndex < 0) return void 0;
7001
+ const continued = committedSession(owned, inputIndex);
7002
+ return continued?.idempotencyKey === intent.idempotencyKey ? continued.environmentId : void 0;
7003
+ }
6949
7004
  const ABANDON_STOP_TIMEOUT_MS = 3e4;
6950
7005
  async function releaseDeadRetainedExecution(state, events, scope) {
6951
7006
  if (state.provider === void 0) return;
@@ -7018,8 +7073,8 @@ async function prepareScopeRetainedOwnerTask(scope, task, session = "native") {
7018
7073
  await abandonInputAdmittedIntoDebt(state, await reconcileOwnerWorkspaceBeforeReuse(state, scope.signal, session === "native" && !abandoned));
7019
7074
  }
7020
7075
  const unusable = unusableEnvironmentIds(owned);
7021
- const currentEnvironment = state.admissions.find((admission) => admission.phase === "environment");
7022
- if (state.acceptedRef === void 0 && currentEnvironment?.phase === "environment" && unusable.has(currentEnvironment.environmentId)) {
7076
+ const target = invocationTarget(state.admissions, owned, latestInput === void 0 ? -1 : owned.indexOf(latestInput));
7077
+ if (state.acceptedRef === void 0 && target !== void 0 && unusable.has(target)) {
7023
7078
  delete state.inputSequence;
7024
7079
  delete state.taskRef;
7025
7080
  state.admissions.length = 0;
@@ -10348,12 +10403,14 @@ async function settleRetainedPending(attempt, err) {
10348
10403
  if (!attempt.reconciled) {
10349
10404
  const accounting = executor.accounting?.();
10350
10405
  const ms = Math.max(0, now() - live.startedAt);
10406
+ const refused = accounting === void 0 && refusedBeforeItRan(err);
10407
+ const floor = refused ? (spend) => spend : unknownFloor;
10351
10408
  live.spent = {
10352
- ...unknownFloor(withBudgetResources(accounting?.reported ?? live.spent, opts.budget, accounting !== void 0)),
10409
+ ...floor(withBudgetResources(accounting?.reported ?? live.spent, opts.budget, accounting !== void 0 || refused)),
10353
10410
  ms
10354
10411
  };
10355
10412
  attempt.reconcile({
10356
- ...unknownFloor(accounting?.reservation ?? live.spent),
10413
+ ...floor(accounting?.reservation ?? live.spent),
10357
10414
  ms
10358
10415
  });
10359
10416
  }
@@ -14248,4 +14305,4 @@ function isNonEmptySpend(s) {
14248
14305
  }
14249
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 };
14250
14307
 
14251
- //# sourceMappingURL=supervisor-accounting-BmY9xWOW.js.map
14308
+ //# sourceMappingURL=supervisor-accounting-CPDPG8mH.js.map