@tangle-network/agent-runtime 10.0.2 → 10.0.3

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 (98) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/{activation-D0Sp7wMc.d.ts → activation-DbSxPRUW.d.ts} +2 -2
  3. package/dist/{activation-B0DHGRtB.js → activation-kitznAHo.js} +2 -2
  4. package/dist/{activation-B0DHGRtB.js.map → activation-kitznAHo.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{continuation-CZaeHEzQ.js → continuation-BDeKJgV3.js} +3 -3
  8. package/dist/{continuation-CZaeHEzQ.js.map → continuation-BDeKJgV3.js.map} +1 -1
  9. package/dist/{delegate-Co5iUyS0.js → delegate-D8yX_2K7.js} +2 -2
  10. package/dist/{delegate-Co5iUyS0.js.map → delegate-D8yX_2K7.js.map} +1 -1
  11. package/dist/{driver-control-acknowledgers-B1Qx2JUz.js → driver-control-acknowledgers-BTSr3Znq.js} +7 -5
  12. package/dist/{driver-control-acknowledgers-B1Qx2JUz.js.map → driver-control-acknowledgers-BTSr3Znq.js.map} +1 -1
  13. package/dist/durable-file-DUcTDWJD.js +498 -0
  14. package/dist/durable-file-DUcTDWJD.js.map +1 -0
  15. package/dist/durable-file-XqOyDf7q.js +1 -0
  16. package/dist/durable-writer-thread.d.ts +1 -0
  17. package/dist/durable-writer-thread.js +86 -0
  18. package/dist/durable-writer-thread.js.map +1 -0
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +15 -128
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-uc4eT1wR.js → graph-4ep9laIH.js} +7 -7
  23. package/dist/{graph-uc4eT1wR.js.map → graph-4ep9laIH.js.map} +1 -1
  24. package/dist/{graph-registry-DxhlgHdA.js → graph-registry-B-EGvJ-3.js} +1 -1
  25. package/dist/{graph-registry-j9t9J0KT.js → graph-registry-BxEBeihr.js} +4 -4
  26. package/dist/{graph-registry-j9t9J0KT.js.map → graph-registry-BxEBeihr.js.map} +1 -1
  27. package/dist/{improve-BM0HlzMi.js → improve-CJf87tBs.js} +7 -7
  28. package/dist/{improve-BM0HlzMi.js.map → improve-CJf87tBs.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +9 -9
  31. package/dist/intelligence.d.ts +2 -2
  32. package/dist/intelligence.js +4 -4
  33. package/dist/{jsonl-file-BhuxeejY.js → jsonl-file-CVAWegN-.js} +53 -11
  34. package/dist/jsonl-file-CVAWegN-.js.map +1 -0
  35. package/dist/kernel.d.ts +1 -1
  36. package/dist/kernel.js +17 -15
  37. package/dist/{loop-runner-npLkvCU5.d.ts → loop-runner-CayC8e9K.d.ts} +2 -2
  38. package/dist/{loop-runner-CRC-RE4D.js → loop-runner-Ckj-Zz3-.js} +2 -2
  39. package/dist/{loop-runner-CRC-RE4D.js.map → loop-runner-Ckj-Zz3-.js.map} +1 -1
  40. package/dist/loop-runner-bin.d.ts +1 -1
  41. package/dist/loop-runner-bin.js +1 -1
  42. package/dist/mcp/bin.js +3 -3
  43. package/dist/mcp/index.d.ts +1 -1
  44. package/dist/mcp/index.js +5 -5
  45. package/dist/profiles.d.ts +1 -1
  46. package/dist/{provision-supervisor-CJrMGyZW.js → provision-supervisor-NjROV7AQ.js} +6 -6
  47. package/dist/{provision-supervisor-CJrMGyZW.js.map → provision-supervisor-NjROV7AQ.js.map} +1 -1
  48. package/dist/result-blob-store-BR-BVZrg.js +76 -0
  49. package/dist/result-blob-store-BR-BVZrg.js.map +1 -0
  50. package/dist/{run-cancellation-CBP3Bmad.js → run-cancellation-C9V1lYhq.js} +5 -209
  51. package/dist/run-cancellation-C9V1lYhq.js.map +1 -0
  52. package/dist/run-lock-Y3u9kwM0.js +193 -0
  53. package/dist/run-lock-Y3u9kwM0.js.map +1 -0
  54. package/dist/run-reopen-CHYTHk7x.js +134 -0
  55. package/dist/run-reopen-CHYTHk7x.js.map +1 -0
  56. package/dist/run-state-DgKo8_tO.js +180 -0
  57. package/dist/run-state-DgKo8_tO.js.map +1 -0
  58. package/dist/{runtime-BqSaWTEY.js → runtime-CdthBQUs.js} +21 -19
  59. package/dist/{runtime-BqSaWTEY.js.map → runtime-CdthBQUs.js.map} +1 -1
  60. package/dist/{search-executor-C9TN-KgI.js → search-executor-Bb0WuI_Z.js} +3 -3
  61. package/dist/{search-executor-C9TN-KgI.js.map → search-executor-Bb0WuI_Z.js.map} +1 -1
  62. package/dist/{server-CcMa8Lt9.js → server-BCtyL7jH.js} +3 -3
  63. package/dist/{server-CcMa8Lt9.js.map → server-BCtyL7jH.js.map} +1 -1
  64. package/dist/{settle-record-BtjYZabI.js → settle-record-Beh-sXBW.js} +5 -4
  65. package/dist/settle-record-Beh-sXBW.js.map +1 -0
  66. package/dist/{structural-rollout-2oRJjwyM.js → structural-rollout-BRfSDPkv.js} +4 -4
  67. package/dist/{structural-rollout-2oRJjwyM.js.map → structural-rollout-BRfSDPkv.js.map} +1 -1
  68. package/dist/{supervise-BrgtzJf3.js → supervise-DTUYxnoJ.js} +9 -8
  69. package/dist/{supervise-BrgtzJf3.js.map → supervise-DTUYxnoJ.js.map} +1 -1
  70. package/dist/supervise-identity-eMF-h1uP.js +210 -0
  71. package/dist/supervise-identity-eMF-h1uP.js.map +1 -0
  72. package/dist/{supervision-discovery-DLMm3UOr.js → supervision-discovery-CAUsSDno.js} +3 -3
  73. package/dist/{supervision-discovery-DLMm3UOr.js.map → supervision-discovery-CAUsSDno.js.map} +1 -1
  74. package/dist/{supervisor-ACffs_W4.js → supervisor-BtRRFbgF.js} +13 -176
  75. package/dist/supervisor-BtRRFbgF.js.map +1 -0
  76. package/dist/{supervisor-accounting-BlJqoP3k.js → supervisor-accounting-Cuehs4te.js} +59 -112
  77. package/dist/supervisor-accounting-Cuehs4te.js.map +1 -0
  78. package/dist/supervisor-root-contract-CmFKzPps.js +165 -0
  79. package/dist/supervisor-root-contract-CmFKzPps.js.map +1 -0
  80. package/dist/testing.d.ts +1 -1
  81. package/dist/testing.js +11 -11
  82. package/dist/{top-web-PYyzBMsK.js → top-web-D-wuEVdM.js} +7 -6
  83. package/dist/{top-web-PYyzBMsK.js.map → top-web-D-wuEVdM.js.map} +1 -1
  84. package/dist/tui/bin.js +3 -3
  85. package/dist/tui/index.d.ts +1 -1
  86. package/dist/tui/index.js +2 -2
  87. package/dist/{types-DX1OGeHE.d.ts → types-PBoTtcbX.d.ts} +2 -2
  88. package/package.json +1 -1
  89. package/dist/durable-file-CksURHlH.js +0 -1
  90. package/dist/durable-file-DstVeHcj.js +0 -228
  91. package/dist/durable-file-DstVeHcj.js.map +0 -1
  92. package/dist/jsonl-file-BhuxeejY.js.map +0 -1
  93. package/dist/run-cancellation-CBP3Bmad.js.map +0 -1
  94. package/dist/run-state-BnhCVbTY.js +0 -357
  95. package/dist/run-state-BnhCVbTY.js.map +0 -1
  96. package/dist/settle-record-BtjYZabI.js.map +0 -1
  97. package/dist/supervisor-ACffs_W4.js.map +0 -1
  98. package/dist/supervisor-accounting-BlJqoP3k.js.map +0 -1
package/dist/tui/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { n as cancelRun } from "../run-cancellation-CBP3Bmad.js";
3
- import { D as writeWorkerSteer, u as cancelWorker, x as supervisorRunsRoot } from "../supervisor-accounting-BlJqoP3k.js";
4
- import { c as numberValue, f as totalSpend, i as aggregateSnapshot, l as parseSpend, n as runTopWeb, s as loadTopSnapshot, u as parseTime } from "../top-web-PYyzBMsK.js";
2
+ import { n as cancelRun } from "../run-cancellation-C9V1lYhq.js";
3
+ import { T as supervisorRunsRoot, j as writeWorkerSteer, m as cancelWorker } from "../supervisor-accounting-Cuehs4te.js";
4
+ import { c as numberValue, f as totalSpend, i as aggregateSnapshot, l as parseSpend, n as runTopWeb, s as loadTopSnapshot, u as parseTime } from "../top-web-D-wuEVdM.js";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { resolve } from "node:path";
7
7
  import { hostname, userInfo } from "node:os";
@@ -1,4 +1,4 @@
1
- import { $d as PursuitRunProjection, E as Budget, Ga as ProfileMaterializationReceipt, La as ExecutionBindingReceipt, Qd as PursuitProjection, Rr as provisionSupervisor, Wa as NodeExecutionIdentity, Yd as PursuitNodeProjection, cC as HarnessTranscriptArtifact, dC as HarnessTranscriptEvidence, ia as ResultBlobStore, j as Spend, xb as RouteFlowEvent } from "../types-DX1OGeHE.js";
1
+ import { $d as PursuitRunProjection, E as Budget, Ga as ProfileMaterializationReceipt, La as ExecutionBindingReceipt, Qd as PursuitProjection, Rr as provisionSupervisor, Wa as NodeExecutionIdentity, Yd as PursuitNodeProjection, cC as HarnessTranscriptArtifact, dC as HarnessTranscriptEvidence, ia as ResultBlobStore, j as Spend, xb as RouteFlowEvent } from "../types-PBoTtcbX.js";
2
2
  import { c as AgentCandidateArtifactPort } from "../workspace-archive-DS9E9tUr.js";
3
3
  type BaselineAuthority = {
4
4
  readonly kind: 'retained-workspace' | 'git-object' | 'git-diff';
package/dist/tui/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as provisionSupervisor } from "../provision-supervisor-CJrMGyZW.js";
2
- import { _ as topAgentMetadata, a as buildSupervisorView, d as topSnapshot, g as readTopAgentInspection, h as readTopAgentHistory, m as harnessSessionRows, o as isSpawnEvent, p as createTopAgentStream, r as serveTopWeb, s as loadTopSnapshot, t as TOP_SNAPSHOT_RECONCILE_MS, v as topAgentWorker } from "../top-web-PYyzBMsK.js";
1
+ import { t as provisionSupervisor } from "../provision-supervisor-NjROV7AQ.js";
2
+ import { _ as topAgentMetadata, a as buildSupervisorView, d as topSnapshot, g as readTopAgentInspection, h as readTopAgentHistory, m as harnessSessionRows, o as isSpawnEvent, p as createTopAgentStream, r as serveTopWeb, s as loadTopSnapshot, t as TOP_SNAPSHOT_RECONCILE_MS, v as topAgentWorker } from "../top-web-D-wuEVdM.js";
3
3
  export { TOP_SNAPSHOT_RECONCILE_MS, createTopAgentStream, harnessSessionRows, isSpawnEvent as isTopJournalEvent, loadTopSnapshot, topSnapshot as projectTopSnapshot, buildSupervisorView as projectTopSupervisor, provisionSupervisor, readTopAgentHistory, readTopAgentInspection, serveTopWeb, topAgentMetadata, topAgentWorker };
@@ -19210,9 +19210,9 @@ declare const runtimeFailureCauseSchema: z.ZodReadonly<z.ZodObject<{
19210
19210
  unknown: "unknown";
19211
19211
  }>;
19212
19212
  owner: z.ZodEnum<{
19213
- provider: "provider";
19214
19213
  platform: "platform";
19215
19214
  unknown: "unknown";
19215
+ provider: "provider";
19216
19216
  runtime: "runtime";
19217
19217
  work: "work";
19218
19218
  caller: "caller";
@@ -19780,4 +19780,4 @@ interface KnowledgeReadinessDecision {
19780
19780
  nonBlockingGapIds: string[];
19781
19781
  }
19782
19782
  export { BlockedToolReport as $, LoopResult as $C, RetainedRunHandle as $S, FeedbackRefersTo as $_, ExecutorResult as $a, PEER_MAIL_WIRE_KEY as $b, LoopDispatchOptions as $c, PursuitRunProjection as $d, IsolatedCheckOutputFailure as $f, RouterTransportConfig as $g, InboxLease as $h, GraphDesignerExtraTools as $i, strategyAuthorSystemPrompt as $l, CoordinationDeliveryEvidence as $m, searchPresets as $n, visibleCheckScore as $o, ReservationShortfall as $p, InPlaceCliExecutorOptions as $r, resolveSandboxClient as $s, AnalystAuthoring as $t, RunPersonified as $u, decodeHarnessUsage as $v, materializeTreeView as $x, createRuntimeEventCollector as $y, ResourceSpend as A, retainHarnessTranscript as AC, ConfigError as AS, DelegationResumeDriver as A_, ReenteredWorkers as Aa, QuestionEscalationRecord as Ab, PairedCommandMeasurement as Ac, NextPursuitVersionInput as Ad, EdgeTraversal as Af, createActivityLog as Ag, McpEventSource as Ah, graphRegistry as Ai, CorpusReadbackOptions as Al, StopRule as Am, gitWorkspace as An, CheckOutcome as Ao, formatPromptHandle as Ap, RemoteSupervisorTree as Ar, S3PrivateCasStore as As, CreateSandboxOptions$1 as At, PipelineStage as Au, gateOnDeliverable as Av, TraceSource as Ax, plateauLength as Ay, SpawnOpts as B, AgentRunSpec as BC, RecoverRetainedRunResult as BS, DelegateResearchConfig as B_, ExecutorNodeContext as Ba, ContinuationInstruction as Bb, McpEnvironmentOptions as Bc, SupervisePursuitOptions as Bd, runGraphWithTestBrain as Bf, resolveSecretEnv as Bg, CliWorktreeBridgeSeam as Bh, GraphTriggerBinding as Bi, AuthorStrategyOptions as Bl, FinalizeContext as Bm, createRootHandle as Bn, VisibleCheck as Bo, DeadlineCheckIn as Bp, ProfileRunRecord as Br, ClaimRetainedInteractiveControlOptions as Bs, makeFinding$1 as Bt, VerifySpec as Bu, stopSentinel as Bv, AuthoredAnalystLimits as Bx, OtelExportStats as By, RuntimeFailureCause as C, HarnessTranscriptMetadata as CC, InMemorySpawnJournal as CS, createSiblingSandboxExecutor as C_, SupervisedResult as Ca, RouteMatch as Cb, RegistryAnalyzeProjection as Cc, checkProgramDigest as Cd, GraphCheckNodes as Cf, ActivityLog as Cg, resolveSpawnResourcePaths as Ch, GraphSelection as Ci, materializeLocalMcp as Cl, ManagerWakePolicy as Cm, copyUntrackedIntoClone as Cn, asAuthoredProfile as Co, PromptRegistry as Cp, workerInboxFileFromEventDir as Cr, openSandboxRun as Cs, AgentSessionRef as Ct, FanoutWinnerSelector as Cu, CoderOutput as Cv, PublishOptions as Cx, renderPairwiseMarkdown as Cy, BudgetOverspend as D, RetainedHarnessTranscriptDescriptor as DC, AgentEvalError$1 as DS, DelegationArgs as D_, ExecutorRegistry as Da, Question as Db, registryScopeAnalyst as Dc, readDeclaredCheck as Dd, GraphFromStoredOptions as Df, ScopeProgressInput as Dg, EventSubscription as Dh, graphCorpusSummary as Di, AgenticTask as Dl, PlateauOptions as Dm, Workspace as Dn, supervisorInstructions as Do, delegatesWorkerBriefPrompt as Dp, RemoteSupervisorControl as Dr, SandboxEvidenceReceipt as Ds, CheckpointRef as Dt, PanelJudge as Du, CompletionCheckContext as Dv, watchTrace as Dx, anytimeReport as Dy, Budget as E, RetainedHarnessTranscriptCapture as EC, defaultRedactor as ES, runDetachedTurn as E_, ExecutorFactory as Ea, EscalateQuestion as Eb, createScopeAnalyst as Ec, declaredCheckJudge as Ed, GraphCommandCheck as Ef, ExecutorProgress as Eg, createMcpServer as Eh, digestOfGraph as Ei, AgenticSurface as El, NoProgressForOptions as Em, Shell as En, profileRichnessFinding as Eo, createPromptRegistry as Ep, RemoteSupervisorCancelResult as Er, createSandboxLineage as Es, AnalystFinding$1 as Et, Panel as Eu, CheckVerdict as Ev, defaultToolDetectors as Ex, AnytimeTaskCurve as Ey, NodeId as F, ProviderWorkspaceEntryMetadata as FC, NativeContextContinuationHandle as FS, SubmitInput as F_, WidenGate as Fa, QuestionRecord as Fb, SnapshotKind as Fc, VersionJudge as Fd, GraphTopology as Ff, KeyProvider as Fg, createExecutorRegistry as Fh, pickBestGraph as Fi, breadthStrategy as Fl, ReentryContinuity as Fm, analyzeTrace as Fn, RepairStop as Fo, SupervisorSpanOptions as Fp, ProvisionSupervisorRequest as Fr, PrivateCasNamespaceRetirement as Fs, ResourceRequest$1 as Ft, SteerContext as Fu, CompletionPolicy as Fv, AnalystLensOutput as Fx, createWaterfallCollector as Fy, TreeView as G, LoopDecisionPayload as GC, RetainedRunAdmission as GS, DelegationFeedbackSnapshot as G_, ProfileMaterializationReceipt as Ga, DownMessageEvent as Gb, BenchmarkLift as Gc, PursuitObserverDelivery as Gd, IsolatedCheckBox as Gf, createSandboxToolPartState as Gg, SandboxSeam as Gh, DispatchStopReason as Gi, StrategyCtx as Gl, CoordinationControlAccess as Gm, createFencedSqlRunContext as Gn, defaultStructuralRolloutPolicy as Go, readRunParking as Gp, profileRunsForName as Gr, ReconnectRetainedInteractiveRunOptions as Gs, SurfaceDiff as Gt, WinnerStrategy as Gu, CodexRolloutStoreRef as Gv, runLocalHarness as Gx, loopEventToOtelSpan as Gy, SpawnRejection as H, Driver as HC, RetainedInteractiveEnvironmentAdmission as HS, DelegateUiAuditConfig as H_, MaterializedModelIdentity as Ha, DownMessageAuthorizationInput as Hb, sanitizeMcpToolSchema as Hc, superviseGraphPursuit as Hd, GraphRouteError as Hf, SandboxLeafOut as Hg, ProviderSeam as Hh, graphFileSchema as Hi, ShotSpec as Hl, SupervisorFinalizer as Hm, validateStoredGraph as Hn, compareCheckOutcomes as Ho, RunParkedError as Hp, loadProfile as Hr, reconnectRetainedInteractiveRun as Hs, createVerifierEnvironment as Ht, WidenDecision as Hu, CodexRolloutIdentity as Hv, CodexExecutionEvidence as Hx, OtelSpan as Hy, NodeSnapshot as I, ExecutorProgressEvent as IC, NativeContextContinuationInput as IS, SubmitOutput as I_, AgentExecutionRef as Ia, QuestionUrgency as Ib, canonicalObservedModelParts as Ic, VersionVerdict as Id, RunGraphOptions as If, ResolvedMcpServerLaunch as Ig, ExecutorConfig as Ih, recordGraphRun as Ii, depthStrategy as Il, ReentryTaskInput as Im, WorkerToolTraceArtifact as In, StructuralRolloutConfig as Io, SupervisorSpanOutcome as Ip, ProvisionedSupervisor as Ir, reconnectRetainedRun as Is, SandboxEvent$1 as It, TrajectoryNode as Iu, CompletionVerdict as Iv, AnalystRegistry$1 as Ix, RunAgentRoundsOptions as Iy, DriverAttemptRecord as J, LoopIterationEndedPayload as JC, RetainedRunCancellation as JS, DelegationProgress as J_, EnvironmentTeardownReceipt as Ja, MapOnSettleRoute as Jb, BenchmarkTaskRow as Jc, PursuitNodePlatform as Jd, IsolatedCheckOptions as Jf, SandboxServedBackend as Jg, SteerableSandboxArgs as Jh, freeSlots as Ji, assertStrategyContract as Jl, CoordinationReadAccess as Jm, SearchSpec as Jn, officialChecksFromMeta as Jo, BudgetReadout as Jp, InteractiveWorkerEnvironment as Jr, RetainedInteractiveEnvironmentInput as Js, SurfaceReader as Jt, LoopShape as Ju, addHarnessUsage as Jv, CodexTokenUsage as Jx, RuntimeStreamEventSink as Jy, EvidencePendingEvent as K, LoopEndedPayload as KC, RetainedRunAdmissionHook as KS, DelegationHistoryArgs as K_, RootMaterialization as Ka, WorkerResumeContext as Kb, BenchmarkReport as Kc, PursuitCostProvenance as Kd, IsolatedCheckBoxEvidence as Kf, mapSandboxEvent as Kg, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Kh, DispatchUnit as Ki, StrategyResult as Kl, CoordinationMcpHandle as Km, CompiledSearchSpec as Kn, filterAuthoredAsserts as Ko, BudgetPool as Kp, recordProfileRun as Kr, RecoverRetainedInteractiveRunOptions as Ks, SurfaceReadBox as Kt, DefinePersona as Ku, CodexRolloutTurn as Kv, LOCAL_HARNESSES as Kx, RuntimeEventCollector as Ky, NodeStatus as L, ExecutorToolCall as LC, ReconnectRetainedRunOptions as LS, DelegateCodeArgs as L_, ExecutionBindingReceipt as La, questionEscalationTargets as Lb, observedModelHasSnapshot as Lc, assertPursuitVersions as Ld, RunGraphTestOptions as Lf, envKeyProvider as Lg, createExecutor as Lh, recordStoredGraphRun as Li, refine as Ll, UNPROVEN_CONTINUITY as Lm, parseWorkerToolTraceArtifact as Ln, StructuralRolloutMessage as Lo, SupervisorSpanRecorder as Lp, SupervisorCleanupReceipt as Lr, recoverRetainedRun as Ls, SandboxInstance$1 as Lt, TrajectoryReport as Lu, completionAuthorizes as Lv, AnalystRunContext as Lx, runAgentRounds as Ly, SpendChannel as M, ProviderWorkspaceCaptureProvenance as MC, NotFoundError as MS, DelegationRunContext as M_, ResumedWork as Ma, QuestionLevel as Mb, measurePairedCommands as Mc, PursuitVersionStop as Md, GraphEdgeCapError as Mf, BridgeHarnessStore as Mg, DelegateHandlerOptions as Mh, listGraphRuns as Mi, StrategyMessage as Ml, anyOf as Mm, localShell as Mn, CheckRunner as Mo, naiveContinuationPrompt as Mp, connectRemoteSupervisor as Mr, createS3PrivateCasStore as Ms, ExecResult as Mt, ScopeAnalyst as Mu, verdictFromJudgeScore as Mv, AnalystAssignmentRecord as Mx, WaterfallCollector as My, SpendGap as N, ProviderWorkspaceCaptureReceipt as NC, ValidationError as NS, DelegationTaskQueue as N_, Scope as Na, QuestionOption as Nb, observationFromRegistry as Nc, PursuitVersions as Nd, GraphNode as Nf, BridgeModelCredential as Ng, DelegateResult as Nh, loadGraph as Ni, StrategyShotResult as Nl, noProgressFor as Nm, runInWorkspace as Nn, CheckSource as No, promptHandle as Np, connectRemoteSupervisorControl as Nr, PrivateCasNamespaceInventory as Ns, ForkRequest as Nt, ScopeAnalyzeInput as Nu, CompletionAnalyst as Nv, AnalystFindingEvent as Nx, WaterfallReport as Ny, BudgetViolation as O, readBoundHarnessSessions$1 as OC, AgentEvalErrorCode as OS, DelegationRecord as O_, SpawnModelSubstitution as Oa, QuestionDecision as Ob, PairedCommandCall as Oc, JudgedPursuitVersion as Od, AgentGraph as Of, TeamProgress as Og, EventSubscriptionStore as Oh, graphDigest as Oi, AgenticTool as Ol, ProgressView as Om, WorkspaceCommit as On, RunCancellationReason as Oo, dumbContinuationFailPrompt as Op, RemoteSupervisorReader as Or, AcquireOptions as Os, CheckpointRequest as Ot, PanelSpec as Ou, DeliverableSpec as Ov, SessionMessageLike as Ox, areaUnderCurve as Oy, Handle as P, ProviderWorkspaceCaptureResult as PC, NativeContextContinuationExecution as PS, DelegationTaskQueueOptions as P_, UnconfirmedTeardown as Pa, QuestionPolicy as Pb, CanonicalObservedModelParts as Pc, SettledPursuitVersion as Pd, GraphResult as Pf, BridgeSeam as Pg, createDelegateHandler as Ph, lookupGraph as Pi, SurfaceScore as Pl, plateau as Pm, TrajectoryAnalysis as Pn, CheckSourceCtx as Po, SupervisorSpanAttributes as Pp, ProvisionSupervisorConnection as Pr, PrivateCasNamespaceObject as Ps, PlacementInfo as Pt, ScopeWidenGate as Pu, CompletionEvidence as Pv, AnalystKind as Px, WaterfallSpan as Py, DriverRepromptRefusal as Q, LoopPlanPayload as QC, RetainedRunEventOptions as QS, FeedbackRating as Q_, ExecutorCancellationRequest as Qa, DEFAULT_PEER_MAIL_LIMITS as Qb, LoopCampaignDispatchOptions as Qc, PursuitProjection as Qd, IsolatedCheckOutputEvidence as Qf, RouterResponseReceipt as Qg, Inbox as Qh, DesignerToolsEnv as Qi, strategyAuthorContract as Ql, CoordinationRejectReason as Qm, compileSearchSpec as Qn, structuralRollout as Qo, ReservationRejection as Qp, workerFromInteractiveProvider as Qr, ResolveSandboxClientOptions as Qs, harvestSurfaceDiffs as Qt, PersonaExecutors as Qu, HarnessUsage as Qv, SqlAdapter as Qx, SanitizedKnowledgeRequirement as Qy, RetainedExecutionState as R, TokenUsageProvenance as RC, RecoverRetainedRunIntentOptions as RS, DelegateCodeConfig as R_, ExecutorExecutionBinding as Ra, AuthorizeDownMessage as Rb, observedModelMatchesDeclared as Rc, SuperviseGraphPursuitOptions as Rd, TraversalContinuity as Rf, mcpSecretEnvMetadataKey as Rg, CliInPlaceSeam as Rh, storedGraphDigests as Ri, runAgentic as Rl, composeReentryTask as Rm, DEFAULT_MAX_DEPTH as Rn, StructuralRolloutPolicy as Ro, createSupervisorSpanRecorder as Rp, provisionSupervisor as Rr, startRetainedRun as Rs, WorkspaceRequest as Rt, TrajectoryReportOptions as Ru, deterministicCompletion as Rv, AnalyzeOnSettleRoute as Rx, OtelAttribute as Ry, RuntimeStreamEvent as S, HarnessFileBinding as SC, InMemoryResultBlobStore as SS, createFleetWorkspaceExecutor as S_, RootStreamReceipt as Sa, RouteGate as Sb, CreateScopeAnalystOptions as Sc, assertDeclaredCheck as Sd, GraphCheckNode as Sf, ProviderPlacement as Sg, environmentReader as Sh, GraphRunRecord as Si, connectStdioMcp as Sl, SupervisorToolInvocationContext as Sm, UntrackedCopyStats as Sn, ProfileRichnessThresholds as So, PromptHandle as Sp, supervisorRunsRoot as Sr, TurnResult as Ss, AgentSession as St, FanoutSynthesis as Su, FileDelegationStoreOptions as Sv, startRuntimeRun as Sw, EventBus as Sx, renderLeaderboardSvg as Sy, RuntimeFailureOwner as T, HarnessTranscriptReadOptions as TC, Redactor as TS, RunDetachedTurnOptions as T_, ExecutorContext as Ta, ChildQuestionInbox as Tb, buildSteerContext as Tc, declaredCheckDigest as Td, GraphCheckPlacement as Tf, DEFAULT_STALL_AFTER_MS as Tg, McpServerOptions as Th, StoredGraphInput as Ti, AgenticRunResult as Tl, AllWorkersStalledOptions as Tm, GitWorkspaceOptions as Tn, defaultProfileRichnessThresholds as To, analyzesFindingsReportPrompt as Tp, RemoteSupervisorAgent as Tr, SandboxLineageHandle as Ts, AgentTurnResult$2 as Tt, LoopUntilState as Tu, CheckUnavailableError as Tv, WatchTraceOptions as Tx, AnytimeStrategySummary as Ty, SubtreeResult as U, ExecCtx as UC, RetainedInteractiveIntentAdmission as US, DelegateUiAuditRoute as U_, MaterializedResources as Ua, DownMessageDeliveryAttempt as Ub, BenchmarkCell as Uc, supervisePursuit as Ud, PortableContinuationPolicy as Uf, SandboxOutputMarker as Ug, RouterSeam as Uh, graphRouteWhenSchema as Ui, Strategy as Ul, bestDelivered as Um, FencedSqlRunContext as Un, composeCheckSources as Uo, RunParkingPolicy as Up, pickBestProfile as Ur, recoverRetainedInteractiveRun as Us, BoxSurfaceReaderOptions as Ut, WidenLineage as Uu, CodexRolloutSession as Uv, LocalHarnessResult as Ux, buildLoopOtelSpans as Uy, SpawnPrior as V, DefaultVerdict$2 as VC, RetainedInteractiveAdmission as VS, DelegateUiAuditArgs as V_, MaterializedExecutionIdentity as Va, ContinuityMode as Vb, createMcpEnvironment as Vc, SupervisedPursuitResult as Vd, defaultEdgeTraversalCap as Vf, secretEnvOfMcpServer as Vg, CliWorktreeSeam as Vh, graphFileNeedSchema as Vi, AuthoredStrategy as Vl, FinalizerSettled as Vm, ValidateStoredGraphOptions as Vn, canDisplace as Vo, ParkedRun as Vp, bestProfileFor as Vr, claimRetainedInteractiveControl as Vs, VerifierEnvironmentOptions as Vt, Widen as Vu, CodexForkBoundary as Vv, DefinedAnalystRecord as Vx, OtelExporter as Vy, SubtreeSummary as W, Iteration as WC, RetainedInteractiveStartedAdmission as WS, DelegationError as W_, NodeExecutionIdentity as Wa, DownMessageDeliveryOutcome as Wb, BenchmarkConfig as Wc, RunReopen as Wd, portableContinuationPolicySchema as Wf, SandboxToolPartState as Wg, RouterToolsSeam as Wh, DispatchReport as Wi, StrategyArtifacts as Wl, CoordinationAuthentication as Wm, SqlRunContextOptions as Wn, defaultExtractCandidate as Wo, RunParkingRecord as Wp, profileRegistry as Wr, startRetainedInteractiveRun as Ws, HarvestSurfaceDiffsOptions as Wt, WidenSpec as Wu, CodexRolloutStoreReader as Wv, RunLocalHarnessOptions as Wx, createOtelExporter as Wy, DriverContinuationRecord as X, LoopLineageOptions as XC, RetainedRunEffect as XS, DelegationStatus as X_, ExecutorAccounting as Xa, MapTraversalEvent as Xb, printBenchmarkReport as Xc, PursuitNodeTiming as Xd, runIsolatedCheck as Xf, extractLlmCallEvent as Xg, createSteerableSandboxSession as Xh, rollingDispatch as Xi, defineStrategy as Xl, serveCoordinationMcp as Xm, SearchSpecOwnedOption as Xn, sandboxCheckRunner as Xo, ReservationFloor as Xp, InteractiveWorkerOptions as Xr, RetainedInteractiveStartMaterial as Xs, boxSurfaceReader as Xt, Persona as Xu, harnessUsageIsEmpty as Xv, SqlRunOwnershipError as Xx, RuntimeTelemetryOptions as Xy, DriverAttemptStop as Y, LoopIterationStartedPayload as YC, RetainedRunDispatchedAdmission as YS, DelegationResultPayload as Y_, Executor as Ya, MapSpawnMarker as Yb, Environment as Yc, PursuitNodeProjection as Yd, IsolatedCheckResult as Yf, SandboxUsageLedger as Yg, SteerableSandboxSession as Yh, queueOf as Yi, authorStrategy as Yl, CoordinationTransportOptions as Ym, SearchSpecInputs as Yn, resolveEntrySymbol as Yo, LeakedReservation as Yp, InteractiveWorkerKeyInput as Yr, RetainedInteractiveRunHandle as Ys, WatchedSurface as Yt, Outcome as Yu, createCodexRolloutStoreReader as Yv, CodexExecutionPolicy as Yx, RuntimeStreamEventSummary as Yy, DriverFailureClass as Z, LoopPlanDescription as ZC, RetainedRunEnvironmentAdmission as ZS, DelegationStatusResult as Z_, ExecutorCancellation as Za, AUTHORITY_MARKERS as Zb, runBenchmark as Zc, PursuitNodeUsage as Zd, IsolatedCheckOutputDeclaration as Zf, sumSandboxUsage as Zg, AuthorityInboxMessage as Zh, DesignerRunGraphEnv as Zi, sampleThenRefine as Zl, CoordinationHttpAudit as Zm, assertSearchSpec as Zn, selectBestIndex as Zo, ReservationHolder as Zp, InteractiveWorkerResult as Zr, StartRetainedInteractiveRunOptions as Zs, fsSurfaceReader as Zt, PersonaContext as Zu, readCodexRolloutSession as Zv, openSqlRunStore as Zx, SanitizedKnowledgeReadinessReport as Zy, RunAgentTaskOptions as _, captureHarnessTranscript as _C, RunCancelRequest as _S, detachedSessionDelegate as __, FleetYield as _a, GateDecision as _b, panel as _c, LeaderboardSpec as _d, SuperviseTestOptions as _f, ProviderExecutorOptions as _g, ResolveSpawnResourcePathsResult as _h, loadGraphFile as _i, MaterializeLocalMcpOptions as _l, SupervisorAgentDeps as _m, closingWorkerNote as _n, chatTransportExecutor as _o, RunContext as _p, readWorkerCancellation as _r, OpenSandboxRunBeforeStartContext as _s, AgentEnvironmentProvider$1 as _t, CorpusRecord as _u, DelegationTraceSpan as _v, RuntimeRunHandle as _w, McpToolDescriptor as _x, ScoreOf as _y, AgentKnowledgeProvider as a, StartRetainedRunInEnvironmentOptions as aC, SpawnForestTree as aS, ToolLoopCompactionOptions as a_, SpawnEvent as aa, WorktreeHarnessResult as ab, PrivateCasOptions as ac, ProviderAsSandboxClientOptions as ad, ObserverRecord as af, SharedBoxPlacement as ag, ContinuationEntry as ah, DeepReadonly as ai, superviseDispatch as al, readRootStream as am, WorktreeCliExecutorOptions as an, WorkerInteractiveSession as ao, IsolatedCheckCpuResources as ap, TRACE_SUMMARY_SCHEMA as ar, collectAgentTurn as as, MakeWorkerAgent as at, Observation as au, UiFindingSeverity as av, LoopTraceEvent as aw, PeerMailRefusal as ax, RunCodeModeOptions as ay, RuntimeSession as b, BoundHarnessSession as bC, readRunCancelRequest as bS, FleetWorkspaceExecutorOptions as b_, ProviderModelExecutionEvidence as ba, RouteFlow as bb, verify as bc, DeclaredCheckPlacement as bd, SuperviseRegistry as bf, providerAsExecutor as bg, SpawnResourceRead as bh, GraphRegistryDir as bi, StdioMcpConnection as bl, SupervisorNodeContextSeed as bm, spendFromUsageEvents as bn, AuthoredProfile as bo, createInMemoryRunContext as bp, safeWorkerFile as br, SandboxRun as bs, AgentEnvironmentSummary as bt, EqualKVerdict as bu, DelegationStore as bv, RuntimeRunRow as bw, BusRecord as bx, renderLeaderboardHtml as by, AgentTaskContext as c, HarnessTranscriptArtifact as cC, replaySpawnTree as cS, FeedbackEvent as c_, WorkspaceCheckpointMarker as ca, AwaitWakeInput as cb, trajectoryReport as cc, DefinedLeaderboard as cd, PursuitFork as cf, SharedWorkerIdentity as cg, ContinuationPanelResult as ch, ObservedSessionFacts as ci, TerminalDecision as cl, supervisorAgent as cm, AttachWorkerOptions as cn, WorkerTraceUnavailableReason as co, createIsolatedCheckCpuSession as cp, RunTraceSources as cr, EvolutionReport as cs, SpawnPreflight as ct, ObserveInput as cu, KnowledgeUpdate as cv, MountRecorder as cw, PeerMailboxOptions as cx, AxisScoresOf as cy, AgentTaskStatus as d, HarnessTranscriptEvidence as dC, SpawnJournalReadRecord as dS, CoderReview as d_, RootSegment as da, LeadMessage as db, FileCorpus as dc, LeaderboardBenchmarkAdapter as dd, superviseFleetCapabilities as df, sharedBoxRefusal as dg, PanelFinding as dh, GraphFileNeed as di, InProcessOnPrompt as dl, CoordinationVerbs as dm, attachWorker as dn, WorkerEventPage as do, SeatSelectionInput as dp, WorkerSteerAcknowledgement as dr, StrategyTournament as ds, SpawnRefusalCause as dt, observe as du, ResearchTask as dv, SandboxClient as dw, isPeerMailEnvelope as dx, Leaderboard as dy, RetainedRunIntentAdmission as eC, SpawnForest as eS, RouterRouting as e_, graphDesignerExtraTools as ea, createRuntimeStreamEventCollector as eb, profileChatClient as ec, RunPersonifiedOptions as ed, PursuitRunTotals as ef, InboxMessage as eg, CoordinationLog as eh, createInPlaceCliExecutor as ei, LoopOptionsForDispatch as el, ReservationStage as em, analystsFromRegistry as en, ExecutorTeardownWarning as eo, IsolatedCheckOutputOptions as ep, searchSpecDigest as er, AgentTurnBackend as es, CoordinationStats as et, HarvestCorpusOptions as eu, ResearchOutputShape as ev, LoopSandboxPlacement as ew, PeerMailEnvelope as ex, CodeModeStore as ey, BackendErrorDetail as f, HarnessTranscriptFile as fC, SpawnJournalReadResult as fS, CoderReviewer as f_, RootSegmentEntry as fa, ManagerReentryState as fb, InMemoryCorpus as fc, LeaderboardFlagSpec as fd, superviseWithTestBrain as ff, sharedWorkerClientName as fg, VerdictSummary as fh, GraphFileResolutionError as fi, InProcessPromptCtx as fl, DriveHarness as fm, readWorkerInteractiveBinding as fn, ChatCompletionsTransport as fo, SeatStage as fp, WorkerSteerRequest as fr, TournamentCell as fs, SuperviseProfileEntry as ft, renderReport as fu, ResearcherProfileOptions as fv, SelectionReceipt as fw, peerMailTools as fx, LeaderboardOptions as fy, OpenAIChatToolChoice as g, captureBoundHarnessTranscript as gC, readRunState as gS, UiAuditorDelegate as g_, SupervisorOpts as ga, DecideGate as gb, loopUntil as gc, LeaderboardScore as gd, SuperviseOptions as gf, resolveAgentEnvironmentProvider as gg, DriverRetryPolicy as gh, graphWorkspace as gi, LocalMcpMaterialization as gl, ResolveSupervisorTools as gm, WorkerEvidenceInput as gn, ChatWorkerSeamOptions as go, InMemoryRunContextOptions as gp, legacySupervisorRunDir as gr, Deliverable as gs, AgentEnvironmentEvent$1 as gt, CorpusFilter as gu, readTraceContextFromEnv as gv, RuntimeRunCost as gw, McpToolAnnotations as gx, ProfileKeyOf as gy, OpenAIChatTool as h, ReadableEnvironment as hC, RunState as hS, DetachedWinnerSelection as h_, Supervisor as ha, WorkerWatchOptions as hb, flatWidenGate as hc, LeaderboardScenario as hd, AuthorizedSpawnContext as hf, createAgentEnvironmentProviderRegistry as hg, DriverReentry as hh, LoadedGraphFile as hi, HttpMcpServerSpec as hl, ResolveDriveHarness as hm, VERIFY_TAIL_CHARS as hn, ChatTransportTool as ho, InMemoryRunContext as hp, fileEscalateQuestion as hr, strategyTournament as hs, AgentEnvironmentCapabilities$1 as ht, Corpus as hu, createPropagatingTraceEmitter as hv, RuntimeRunCompleteInput as hw, JsonRpcResponse as hx, PairwiseVerdict as hy, AgentExecutionBackend as i, RetainedRunTurnInput as iC, SpawnForestNode as iS, ToolLoopCompaction as i_, ResultBlobStore as ia, WorktreeCommandResult as ib, PrivateCasOffloadReport as ic, readHarnessTranscriptSessions as id, ObserverJournal as if, SharedBoxCloseReceipt as ig, ContinuationAppend as ih, setGraphStrings as ii, loopDispatch as il, RootStreamRecord as im, worktreeFanout as in, Runtime as io, IsolatedCheckCpuIdentity as ip, TRACE_ROOT_SCHEMA as ir, StreamAgentTurnOptions as is, GraphSubtasks as it, harvestCorpus as iu, UiFindingScreenshot as iv, LoopTraceEmitter as iw, PeerMailReadout as ix, CodeModeToolset as iy, Spend as j, ProviderWorkspaceAttemptProvenance as jC, JudgeError as jS, DelegationResumeTick as j_, ResumedKeyState as ja, QuestionEscalationTarget as jb, PairedCommandOptions as jc, PursuitVersionChain as jd, GraphEdge as jf, readWorkerProgress as jg, DelegateError as jh, graphRunsFor as ji, RunAgenticOptions as jl, allWorkersStalled as jm, jjWorkspace as jn, CheckRunContext as jo, kernelPromptRegistry as jp, RemoteWorkerEvents as jr, S3PrivateCasStoreOptions as js, ExecRequest as jt, RenderCorpusToInstructionsOptions as ju, mapExecutorResult as jv, createPushTraceSource as jx, renderAnytimeTable as jy, ResourceLimit as k, resolveHarnessTranscriptCapture as kC, BackendTransportError as kS, DelegationResumeContext as k_, Agent as ka, QuestionEscalationOutcome as kb, PairedCommandInput as kc, NextPursuitVersion as kd, EdgeDeliveryOutcome as kf, WorkerProgress as kg, McpEventRecord as kh, graphFromStored as ki, ArtifactHandle as kl, StopDecision as km, WorkspaceRun as kn, CheckExecChannel as ko, dumbContinuationPassPrompt as kp, RemoteSupervisorSteerResult as kr, acquireSandbox as ks, CreateAgentEnvironmentInput$1 as kt, PanelVerdict as ku, ExecutorResultMapping as kv, ToolStepInput as kx, bestSoFar as ky, AgentTaskRunResult as l, HarnessTranscriptBinding as lC, SpawnJournalCursor as lS, FeedbackStore as l_, RecursiveReservationPolicy as la, CoordinationEvent as lb, definePersona as lc, LeaderboardBenchScore as ld, RUN_FORK_CORRELATION_KEYS as lf, sharedBoxPlacement as lg, ContinuationPolicy as lh, graphFromSessionFacts as li, defaultSelectWinner as ll, supervisorAgentWithTestBrain as lm, WorkerInteractiveBinding as ln, WorkerEventCursor as lo, SeatSegment as lp, runToolSpans as lr, EvolutionStrategy as ls, SpawnPreflightContext as lt, ObserveOptions as lu, ResearchOutput as lv, OutputAdapter as lw, claimsAuthority as lx, GroupOf as ly, OpenAIChatResponseFormat as m, HarnessTranscriptUnavailableReason as mC, FileSpawnJournal as mS, DetachedSessionDelegateOptions as m_, SteerableRootHandle as ma, ToolOutcomeEvent as mb, fanout as mc, LeaderboardRunContext as md, AuthorizedSpawn as mf, AgentEnvironmentProviderRegistry as mg, DriverContractState as mh, LoadGraphFileOptions as mi, inProcessSandboxClient as ml, ObserveSupervisorNodeEvent as mm, NOTE_MAX_CHARS as mn, ChatTransportExecutorOptions as mo, subscriptionUsageLimitSignal as mp, cancelWorker as mr, runStrategyEvolution as ms, AgentEnvironment$1 as mt, CombinatorShape as mu, TraceContext as mv, Validator as mw, JsonRpcMessage as mx, PairwiseOptions as my, AgentBackendContext as n, RetainedRunSnapshot as nC, SpawnForestInDoubtNode as nS, ToolLoopCallContext as n_, defaultDelegateBudget as na, InPlaceHarnessResult as nb, PrivateCasArtifactPort as nc, ShapeContext as nd, projectPursuit as nf, DEFAULT_SHARED_BOX_RESOURCES as ng, PriorCoordination as nh, readGraphStrings as ni, SuperviseOptionsForDispatch as nl, ReserveOptions as nm, AuthoredHarness as nn, HeldForContinuation as no, IsolatedCheckCpuCounters as np, createScope as nr, AgentTurnUsage as ns, CoordinationToolsOptions as nt, HarvestFailure as nu, UiAuditorDelegationOutput as nv, LoopTeardownFailedPayload as nw, PeerMailLimits as nx, CodeModeToolContext as ny, AgentRuntimeEvent as o, StartRetainedRunOptions as oC, loadSpawnForest as oS, ToolLoopMessageRecord as o_, SpawnJournal as oa, WorktreeProfileMaterializationReceipt as ob, createPrivateCasArtifactPort as oc, providerAsSandboxClient as od, ObserverRecordKind as of, SharedBoxPlacementOptions as og, ContinuationPanel as oh, ReadonlyAgentProfile as oi, LocalSandboxClientOptions as ol, readRootStreamReceipt as om, WorktreePatchArtifact as on, WorkerInteractiveUnavailableReason as oo, IsolatedCheckCpuSession as op, TraceRootArtifact as or, streamAgentTurn as os, PeerAuditAccess as ot, ObservationAnalysis as ou, UiLens as ov, LoopWinner as ow, PeerMailSendInput as ox, createCodeModeTools as oy, KnowledgeReadinessDecision as p, HarnessTranscriptUnavailable as pC, readSpawnJournal as pS, DelegateRunCtx as p_, RootSignal as pa, ManagerWake as pb, renderCorpusToInstructions as pc, LeaderboardIterationInfo as pd, workerFromBackend as pf, AgentEnvironmentProviderRef as pg, admitContinuationPolicy as ph, GraphFileSeat as pi, InProcessSandboxClientOptions as pl, DriveHarnessOwnerContext as pm, EVIDENCE_MAX_CHARS as pn, ChatSessionStore as po, SelectSeat as pp, WriteWorkerSteerOptions as pr, TournamentRow as ps, WorkerSpawnContext as pt, AssertTraceDerivedFindings as pu, researcherProfile as pv, ValidationCtx as pw, peerMailVerbNames as px, LeaderboardRow as py, RetainedPendingCause as q, LoopIterationDispatchPayload as qC, RetainedRunCancelOptions as qS, DelegationHistoryEntry as q_, UnknownMaterializationReason as qa, MapItemFailurePolicy as qb, BenchmarkStrategySummary as qc, PursuitNodeCost as qd, IsolatedCheckCommandEvidence as qf, mapSandboxToolEvent as qg, SandboxSteeringOptions as qh, RollingDispatchOptions as qi, adaptiveRefine as ql, CoordinationPublicAddress as qm, SEARCH_SPEC_CORRELATION_KEY as qn, modelAuthoredChecks as qo, BudgetPoolRestore as qp, profileBridgeWireModel as qr, RetainedInteractiveAdmissionHook as qs, SurfaceReadOutcome as qt, DefinePersonaInput as qu, CodexStoreDelta as qv, LocalHarness as qx, RuntimeStreamEventCollector as qy, AgentBackendInput as r, RetainedRunStartMaterial as rC, SpawnForestMissingTree as rS, ToolLoopChat as r_, delegate as ra, WorktreeCheckRunner as rb, PrivateCasDurableStore as rc, ShapeRegistry as rd, FileObserverJournal as rf, DEFAULT_SHARED_BOX_WORKERS as rg, CheckRead as rh, setGraphProfile as ri, loopCampaignDispatch as rl, createBudgetPool as rm, WorktreeFanoutOptions as rn, HeldRelease as ro, IsolatedCheckCpuEvidence as rp, ScopeArgs as rr, CollectedAgentTurn as rs, GraphSubtaskPreparation as rt, HarvestReport as ru, UiFinding as rv, LoopTokenUsage as rw, PeerMailOutcome as rx, CodeModeToolsOptions as ry, AgentRuntimeEventSink as s, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as sC, FileResultBlobStore as sS, ToolLoopToolCall as s_, TraceRootReceipt as sa, GitRunner as sb, equalKOnCost as sc, RetainedFileOutput as sd, observerRecordDigest as sf, SharedBoxStats as sg, ContinuationPanelInput as sh, GraphSessionObservationOptions as si, TERMINAL_DECISIONS as sl, SettledUsage as sm, createWorktreeCliExecutor as sn, WorkerTraceEvidence as so, IsolatedCheckCpuSessionResult as sp, TraceSummary as sr, EvolutionAuthor as ss, SettledWorker as st, ObservationError as su, KnowledgeItem as sv, MountManifestEntry as sw, PeerMailbox as sx, runCodeMode as sy, AgentAdapter as t, RetainedRunReplayPoint as tC, SpawnForestEvent as tS, ToolSpec as t_, DelegateOptions as ta, sanitizeKnowledgeReadinessReport as tb, profileOptimizerModelCall as tc, ShapeBudget as td, PursuitStatus as tf, PeerInboxMessage as tg, FileCoordinationLog as th, readGraphProfile as ti, SuperviseDispatchOptions as tl, ReservationTicket as tm, failuresAnalyst as tn, HeldEnvironment as to, validateIsolatedCheckOutputs as tp, settledToIteration as tr, AgentTurnInput$1 as ts, CoordinationTools as tt, HarvestError as tu, UiAuditLensFilter as tv, LoopStartedPayload as tw, PeerMailEvent as tx, CodeModeTool as ty, AgentTaskSpec as u, HarnessTranscriptCapture as uC, SpawnJournalReadOptions as uS, CoderDelegate as u_, RootHandle as ua, EventAcknowledgement as ub, runPersonified as uc, LeaderboardBenchTask as ud, supervise as uf, ROUTER_CLIENT_HEADER as ug, ContinuationProfile as uh, graphFlowSpawnProfile as ui, inlineSandboxClient as ul, CoordinationToolFace as um, WorkerInteractiveProviderSource as un, WorkerEventEntry as uo, SeatSelection as up, WorkerCancellation as ur, StrategyEvolutionConfig as us, SpawnRefusal as ut, defaultAnalystInstruction as uu, ResearchSource as uv, RunProvenance as uw, createPeerMailbox as ux, Interval as uy, RunAgentTaskStreamOptions as v, harnessTranscriptArtifact as vC, RunCancellation as vS, DelegationExecutor as v_, NoWinnerError as va, GateRequest as vb, pipeline as vc, defineLeaderboard as vd, WorkerSlots as vf, ProviderLeafOut as vg, ResolvedSpawnResourcePath as vh, GraphCorpusGroup as vi, McpListedTool as vl, SupervisorAgentTestDeps as vm, composeWorkerEvidence as vn, chatWorkerSeam as vo, RunContextLease as vp, readWorkerSteerAcknowledgement as vr, OpenSandboxRunOptions as vs, AgentEnvironmentQuery as vt, EqualKArm as vu, composeLoopTraceEmitters as vv, RuntimeRunOptions as vw, McpTransport as vx, leaderboard as vy, RuntimeFailureCode as w, HarnessTranscriptReadLimits as wC, contentAddress as wS, DetachedTurn as w_, AgentSpec as wa, RouteWhen as wb, assertTraceDerivedFindings as wc, declaredCheckDeliverable as wd, GraphCheckOutput as wf, ActivityNote as wg, McpServer as wh, StoredGraph as wi, AgenticOptions as wl, SupervisorProfile as wm, withUntrackedArtifacts as wn, assessAuthoredProfile as wo, RegisteredPrompt as wp, writeWorkerSteer as wr, SandboxLineage as ws, AgentSessionStatus$1 as wt, LoopUntilSpec as wu, CoderTask as wv, createEventBus as wx, AnytimeReport as wy, RuntimeSessionStore as x, HARNESS_TRANSCRIPT_READ_LIMITS as xC, readRunCancellation as xS, SiblingSandboxExecutorOptions as x_, RootProviderModelEvidence as xa, RouteFlowEvent as xb, widen as xc, DeclaredCheckStateCapture as xd, SuperviseRegistryTable as xf, UnavailablePausePolicy as xg, SpawnResourceReader as xh, GraphRunQuery as xi, StdioMcpServerSpec as xl, SupervisorToolDescriptor as xm, CopyOptions as xn, ProfileRichness as xo, withRunContext as xp, supervisorRunDir as xr, SandboxRunAbortError as xs, AgentProfile$2 as xt, FanoutOptions as xu, FileDelegationStore as xv, RuntimeRunStatus as xw, BusStats as xx, renderLeaderboardMarkdown as xy, RuntimeCanonicalStreamEvent as y, persistHarnessTranscript as yC, cancelRun as yS, FleetHandle as y_, ProviderModelAttemptEvidence as ya, JsonScalar as yb, selectValidWinner as yc, DeclaredCheck as yd, createWorkerSlots as yf, ProviderPromptOptions as yg, SpawnResourceBytes as yh, GraphCorpusSummary as yi, McpSpawnFault as yl, SupervisorNodeContext as ym, settledWorkerOut as yn, createChatSessionStore as yo, createFileRunContext as yp, readWorkerSteerRequests as yr, OpenSandboxRunPromptOptions as ys, AgentEnvironmentStatus as yt, EqualKOnCostOptions as yu, DelegationPersistenceError as yv, RuntimeRunPersistenceAdapter as yw, BusEvent as yx, pairwiseSignificance as yy, Settled as z, UsageEvent as zC, RecoverRetainedRunOptions as zS, DelegateResearchArgs as z_, ExecutorMaterialization as za, AuthorizedDownMessage as zb, McpEndpoint as zc, SupervisePursuitError as zd, runGraph as zf, resolveMcpServerLaunch as zg, CliSeam as zh, taskShapeDigest as zi, sample as zl, DeliveredOutput as zm, createSupervisor as zn, StructuralRolloutResult as zo, WorkerTraceResolver as zp, ProfileRegistryDir as zr, startRetainedRunInEnvironment as zs, computeFindingId$1 as zt, Verify as zu, sentinelCompletion as zv, AuthoredAnalystDefinition as zx, OtelExportConfig as zy };
19783
- //# sourceMappingURL=types-DX1OGeHE.d.ts.map
19783
+ //# sourceMappingURL=types-PBoTtcbX.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "10.0.2",
3
+ "version": "10.0.3",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- export { a as writeAtomicDurableFile } from "./durable-file-DstVeHcj.js";
@@ -1,228 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { tryAcquireAtomicFileLock } from "@tangle-network/agent-eval/ledger-core";
3
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
4
- import { dirname, join, relative, resolve } from "node:path";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- // src/durable/run-fence.ts
7
- const claims = new AsyncLocalStorage();
8
- const publications = new AsyncLocalStorage();
9
- /** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */
10
- function runWithWriteClaim(claim, operation) {
11
- return claims.run(claim, operation);
12
- }
13
- /** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */
14
- function captureRunWriteContext() {
15
- let claim = claims.getStore();
16
- return (operation) => {
17
- claim ??= claims.getStore();
18
- return claims.run(claim, operation);
19
- };
20
- }
21
- /** Serialize claim changes and file mutations under the same cross-process guard. @internal */
22
- function mutateRunClaim(path, operation) {
23
- const legacyGuard = `${path}.guard`;
24
- if (existsSync(legacyGuard)) throw new Error(`supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`);
25
- const deadline = performance.now() + 5e3;
26
- const sleeper = new Int32Array(new SharedArrayBuffer(4));
27
- for (;;) {
28
- const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` });
29
- if (acquisition.acquired) try {
30
- return operation();
31
- } finally {
32
- acquisition.lock.release();
33
- }
34
- if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`);
35
- Atomics.wait(sleeper, 0, 0, 10);
36
- }
37
- }
38
- /**
39
- * Fence an actual file mutation, not an earlier advisory check. No await occurs between the
40
- * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone
41
- * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.
42
- * @internal
43
- */
44
- function fenceRunWrite(operation) {
45
- const claim = claims.getStore();
46
- if (claim === void 0) return operation();
47
- const publication = publications.getStore();
48
- if (publication?.active && publication.claim.path === claim.path && publication.claim.generation === claim.generation) return operation();
49
- return mutateRunClaim(claim.path, () => {
50
- let holder;
51
- try {
52
- const fd = openSync(claim.path, "r");
53
- try {
54
- const stat = fstatSync(fd, { bigint: true });
55
- if (stat.dev.toString() !== claim.lock.dev || stat.ino.toString() !== claim.lock.ino || stat.birthtimeNs.toString() !== claim.lock.birthtimeNs) throw new Error("run lock inode changed");
56
- holder = JSON.parse(readFileSync(fd, "utf8"));
57
- } finally {
58
- closeSync(fd);
59
- }
60
- } catch (cause) {
61
- throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause });
62
- }
63
- if (holder?.generation !== claim.generation || holder.lock?.dev !== claim.lock.dev || holder.lock?.ino !== claim.lock.ino || holder.lock?.birthtimeNs !== claim.lock.birthtimeNs) throw new Error(`run directory generation ${claim.generation} lost its claim`);
64
- const publication = {
65
- claim,
66
- active: true
67
- };
68
- try {
69
- return publications.run(publication, operation);
70
- } finally {
71
- publication.active = false;
72
- }
73
- });
74
- }
75
- /** Persistent generation counter survives a clean release of supervise.lock. @internal */
76
- function runGenerationPath(runDir) {
77
- return resolve(runDir, "supervise.generation");
78
- }
79
- // src/runtime/supervise/durable-file.ts
80
- /**
81
- * Small filesystem durability primitives for Runtime-owned state.
82
- *
83
- * Callers must validate their path and parent directory before invoking these functions.
84
- * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one
85
- * state file after its temporary contents reach stable storage.
86
- *
87
- * @internal
88
- */
89
- /**
90
- * Publish a new file without replacing a concurrent winner. The published entry is a hard link
91
- * of the temporary file, so a content function sees the published file's inode.
92
- */
93
- function publishExclusiveDurableFile(filePath, content, options = {}) {
94
- return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options));
95
- }
96
- function publishExclusiveDurableFileUnchecked(filePath, content, options = {}) {
97
- const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
98
- let operationFailed = false;
99
- let operationError;
100
- let published = false;
101
- try {
102
- writeExclusiveDurableFile(temporaryPath, content, options);
103
- try {
104
- linkSync(temporaryPath, filePath);
105
- syncDurableDirectory(dirname(filePath));
106
- published = true;
107
- } catch (error) {
108
- if (!isAlreadyExistsError(error)) throw error;
109
- }
110
- } catch (error) {
111
- operationFailed = true;
112
- operationError = error;
113
- }
114
- let cleanupError;
115
- try {
116
- unlinkSync(temporaryPath);
117
- } catch (error) {
118
- if (!isNoEntryError(error)) cleanupError = error;
119
- }
120
- if (operationFailed) throw operationError;
121
- if (cleanupError !== void 0) throw cleanupError;
122
- return published;
123
- }
124
- /** Fsync a directory after publishing a durable file entry. */
125
- function syncDurableDirectory(directoryPath) {
126
- const fd = openSync(directoryPath, "r");
127
- try {
128
- fsyncSync(fd);
129
- } finally {
130
- closeSync(fd);
131
- }
132
- }
133
- /** Fsync one durable file after its contents reach stable storage. */
134
- function syncDurableFile(filePath, exactMode) {
135
- const fd = openSync(filePath, "r");
136
- try {
137
- if (exactMode !== void 0 && process.platform !== "win32") fchmodSync(fd, exactMode);
138
- fsyncSync(fd);
139
- } finally {
140
- closeSync(fd);
141
- }
142
- }
143
- /** Append one record with O_APPEND, then fsync the file and containing directory. */
144
- function appendDurableFile(filePath, content, options = {}) {
145
- fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options));
146
- }
147
- function appendDurableFileUnchecked(filePath, content, options = {}) {
148
- const flags = constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0);
149
- const fd = openSync(filePath, flags, options.mode ?? 384);
150
- try {
151
- if (process.platform !== "win32") fchmodSync(fd, options.mode ?? 384);
152
- const expectedBytes = Buffer.byteLength(content, "utf8");
153
- const writtenBytes = writeSync(fd, content, void 0, "utf8");
154
- if (writtenBytes !== expectedBytes) throw new Error(`durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`);
155
- fsyncSync(fd);
156
- } finally {
157
- closeSync(fd);
158
- }
159
- syncDurableDirectory(dirname(filePath));
160
- }
161
- /** Reject a path that escapes its run directory or traverses a symbolic link. */
162
- function assertNoSymlinkDescendant(root, target, label = "path") {
163
- const base = resolve(root);
164
- const exact = resolve(target);
165
- const rel = relative(base, exact);
166
- if (rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) throw new Error(`${label} path escapes its run directory`);
167
- if (existsSync(base) && lstatSync(base).isSymbolicLink()) throw new Error(`${label} path contains a symbolic link: ${base}`);
168
- let current = base;
169
- for (const part of rel.split(/[\\/]/u).filter(Boolean)) {
170
- current = join(current, part);
171
- if (!existsSync(current)) continue;
172
- if (lstatSync(current).isSymbolicLink()) throw new Error(`${label} path contains a symbolic link: ${current}`);
173
- }
174
- }
175
- /** Write, fsync, atomically replace, and fsync one Runtime-owned state file.
176
- * preserveMode retains ordinary access permissions despite the current umask; a new
177
- * file keeps normal creation semantics. Callers still own path validation and write exclusion. */
178
- function writeAtomicDurableFile(filePath, content, options = {}) {
179
- fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options));
180
- }
181
- function writeAtomicDurableFileUnchecked(filePath, content, options = {}) {
182
- const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
183
- let operationFailed = false;
184
- let operationError;
185
- try {
186
- let mode = options.mode;
187
- let exactMode = false;
188
- if (options.preserveMode) try {
189
- mode = statSync(filePath).mode & 511;
190
- exactMode = true;
191
- } catch (error) {
192
- if (!isNoEntryError(error)) throw error;
193
- }
194
- writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode);
195
- renameSync(temporaryPath, filePath);
196
- syncDurableDirectory(dirname(filePath));
197
- } catch (error) {
198
- operationFailed = true;
199
- operationError = error;
200
- }
201
- let cleanupError;
202
- try {
203
- unlinkSync(temporaryPath);
204
- } catch (error) {
205
- if (!isNoEntryError(error)) cleanupError = error;
206
- }
207
- if (operationFailed) throw operationError;
208
- if (cleanupError !== void 0) throw cleanupError;
209
- }
210
- function writeExclusiveDurableFile(filePath, content, options, exactMode = false) {
211
- const fd = openSync(filePath, "wx", options.mode ?? 438);
212
- try {
213
- const text = typeof content === "string" ? content : content(fstatSync(fd, { bigint: true }));
214
- writeFileSync(fd, text, "utf8");
215
- } finally {
216
- closeSync(fd);
217
- }
218
- syncDurableFile(filePath, exactMode ? options.mode : void 0);
219
- }
220
- function isAlreadyExistsError(error) {
221
- return error !== null && typeof error === "object" && "code" in error && error.code === "EEXIST";
222
- }
223
- function isNoEntryError(error) {
224
- return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
225
- }
226
- export { writeAtomicDurableFile as a, mutateRunClaim as c, syncDurableDirectory as i, runGenerationPath as l, assertNoSymlinkDescendant as n, captureRunWriteContext as o, publishExclusiveDurableFile as r, fenceRunWrite as s, appendDurableFile as t, runWithWriteClaim as u };
227
-
228
- //# sourceMappingURL=durable-file-DstVeHcj.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-file-DstVeHcj.js","names":["fsConstants"],"sources":["../src/durable/run-fence.ts","../src/runtime/supervise/durable-file.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { closeSync, existsSync, fstatSync, openSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { tryAcquireAtomicFileLock } from '@tangle-network/agent-eval/ledger-core'\nimport type { LockIdentity } from '@tangle-network/agent-eval/lock-holder'\n\n/** The immutable claim carried by every write in one directory execution. @internal */\nexport interface RunWriteClaim {\n readonly path: string\n readonly generation: number\n readonly lock: LockIdentity\n}\n\nconst claims = new AsyncLocalStorage<RunWriteClaim | undefined>()\nconst publications = new AsyncLocalStorage<{ readonly claim: RunWriteClaim; active: boolean }>()\n\n/** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */\nexport function runWithWriteClaim<T>(claim: RunWriteClaim, operation: () => T): T {\n return claims.run(claim, operation)\n}\n\n/** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */\nexport function captureRunWriteContext(): <T>(operation: () => T) => T {\n let claim = claims.getStore()\n return <T>(operation: () => T): T => {\n claim ??= claims.getStore()\n return claims.run(claim, operation)\n }\n}\n\n/** Serialize claim changes and file mutations under the same cross-process guard. @internal */\nexport function mutateRunClaim<T>(path: string, operation: () => T): T {\n // Old writers use an unowned directory guard. Never race one or guess that it is stale.\n const legacyGuard = `${path}.guard`\n if (existsSync(legacyGuard)) {\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`,\n )\n }\n const deadline = performance.now() + 5_000\n const sleeper = new Int32Array(new SharedArrayBuffer(4))\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` })\n if (acquisition.acquired) {\n try {\n return operation()\n } finally {\n acquisition.lock.release()\n }\n }\n if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`)\n Atomics.wait(sleeper, 0, 0, 10)\n }\n}\n\n/**\n * Fence an actual file mutation, not an earlier advisory check. No await occurs between the\n * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone\n * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.\n * @internal\n */\nexport function fenceRunWrite<T>(operation: () => T): T {\n const claim = claims.getStore()\n if (claim === undefined) return operation()\n const publication = publications.getStore()\n if (\n publication?.active &&\n publication.claim.path === claim.path &&\n publication.claim.generation === claim.generation\n )\n return operation()\n return mutateRunClaim(claim.path, () => {\n let holder: Partial<RunWriteClaim> | undefined\n try {\n const fd = openSync(claim.path, 'r')\n try {\n const stat = fstatSync(fd, { bigint: true })\n if (\n stat.dev.toString() !== claim.lock.dev ||\n stat.ino.toString() !== claim.lock.ino ||\n stat.birthtimeNs.toString() !== claim.lock.birthtimeNs\n ) {\n throw new Error('run lock inode changed')\n }\n holder = JSON.parse(readFileSync(fd, 'utf8')) as Partial<RunWriteClaim>\n } finally {\n closeSync(fd)\n }\n } catch (cause) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause })\n }\n if (\n holder?.generation !== claim.generation ||\n holder.lock?.dev !== claim.lock.dev ||\n holder.lock?.ino !== claim.lock.ino ||\n holder.lock?.birthtimeNs !== claim.lock.birthtimeNs\n ) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`)\n }\n // Nested synchronous primitives share the guard. A callback queued here keeps its claim,\n // but cannot inherit a live guard after this publication has returned.\n const publication = { claim, active: true }\n try {\n return publications.run(publication, operation)\n } finally {\n publication.active = false\n }\n })\n}\n\n/** Persistent generation counter survives a clean release of supervise.lock. @internal */\nexport function runGenerationPath(runDir: string): string {\n return resolve(runDir, 'supervise.generation')\n}\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { fenceRunWrite } from '../../durable/run-fence'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/**\n * File content, or content computed from the new file's own stat when it must name the file's\n * inode (a lock record that later proves it was written for this very file).\n */\ntype DurableFileContent = string | ((file: BigIntStats) => string)\n\n/**\n * Publish a new file without replacing a concurrent winner. The published entry is a hard link\n * of the temporary file, so a content function sees the published file's inode.\n */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options))\n}\n\nfunction publishExclusiveDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options))\n}\n\nfunction appendDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options))\n}\n\nfunction writeAtomicDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n const fd = openSync(filePath, 'wx', options.mode ?? 0o666)\n try {\n const text = typeof content === 'string' ? content : content(fstatSync(fd, { bigint: true }))\n writeFileSync(fd, text, 'utf8')\n } finally {\n closeSync(fd)\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;AAaA,MAAM,SAAS,IAAI,kBAA6C;AAChE,MAAM,eAAe,IAAI,kBAAsE;;AAG/F,SAAgB,kBAAqB,OAAsB,WAAuB;CAChF,OAAO,OAAO,IAAI,OAAO,SAAS;AACpC;;AAGA,SAAgB,yBAAuD;CACrE,IAAI,QAAQ,OAAO,SAAS;CAC5B,QAAW,cAA0B;EACnC,UAAU,OAAO,SAAS;EAC1B,OAAO,OAAO,IAAI,OAAO,SAAS;CACpC;AACF;;AAGA,SAAgB,eAAkB,MAAc,WAAuB;CAErE,MAAM,cAAc,GAAG,KAAK;CAC5B,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,MACR,mCAAmC,KAAK,YAAY,YAAY,gEAClE;CAEF,MAAM,WA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Y,QAAQ,OAAO,KAAA,CAAS;AAChE;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,eAAe,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonl-file-BhuxeejY.js","names":[],"sources":["../src/runtime/supervise/abortable.ts","../src/content-digest.ts","../src/durable/jsonl-append.ts","../src/durable/jsonl-file.ts"],"sourcesContent":["/** Provenance of an explicit cancellation, preserved through every abort link. */\nexport class RunCancellationReason extends Error {\n constructor(\n readonly source: string,\n reason: string,\n readonly operationId?: string,\n /** Who stopped the run, from the durable cancel request; absent for an in-process abort. */\n readonly operator?: string,\n ) {\n super(reason)\n this.name = 'RunCancellationReason'\n }\n\n override toString(): string {\n return this.message\n }\n}\n\n/** The signal's explicit reason, or the caller's fallback when none was supplied. */\nexport function abortReason(signal: AbortSignal, fallback: string): unknown {\n const reason = signal.reason\n if (reason instanceof RunCancellationReason) return reason\n if (typeof reason === 'string' && reason.length > 0) return reason\n // A default AbortError carries no caller reason.\n if (reason instanceof Error && reason.name !== 'AbortError' && reason.message.length > 0) {\n return reason.message\n }\n return fallback\n}\n\n/** An `AbortError` carrying the signal's own string reason, or `fallback` when it states none. */\nexport function signalAbortError(signal: AbortSignal, fallback: string): Error {\n const reason = abortReason(signal, fallback)\n const error = new Error(\n reason instanceof Error\n ? reason.message\n : typeof reason === 'string' && reason.length > 0\n ? reason\n : fallback,\n )\n error.name = 'AbortError'\n return error\n}\n\n/** A parent abort stops the call at once. The timeout still bounds a parent that stays open. */\nexport function deadlineSignal(parent: AbortSignal | undefined, ms: number): AbortSignal {\n const timeout = AbortSignal.timeout(ms)\n return parent === undefined ? timeout : AbortSignal.any([parent, timeout])\n}\n\ninterface LinkedAbort {\n readonly signal: AbortSignal\n abort(reason?: unknown): void\n /** Stop listening to the sources. Idempotent; required where a source outlives the link. */\n release(): void\n}\n\n/** Cascade source aborts and preserve their reason; release removes the source listeners. */\nexport function linkAbort(...sources: ReadonlyArray<AbortSignal>): LinkedAbort {\n const controller = new AbortController()\n const listeners: Array<{ source: AbortSignal; onAbort: () => void }> = []\n const release = (): void => {\n for (const { source, onAbort } of listeners) source.removeEventListener('abort', onAbort)\n listeners.length = 0\n }\n const abort = (reason?: unknown): void => {\n release()\n controller.abort(reason)\n }\n const alreadyAborted = sources.find((source) => source.aborted)\n if (alreadyAborted !== undefined) {\n controller.abort(abortReason(alreadyAborted, 'aborted by parent scope'))\n return { signal: controller.signal, abort, release }\n }\n for (const source of sources) {\n const onAbort = (): void => abort(abortReason(source, 'aborted by parent scope'))\n listeners.push({ source, onAbort })\n source.addEventListener('abort', onAbort, { once: true })\n }\n return { signal: controller.signal, abort, release }\n}\n\n/** Settle work against cancellation once, observing the losing promise.\n * Defer abort one microtask so already-completed work wins. An action's own abort listener\n * cannot win this race: this function subscribes before invoking it.\n */\nexport async function runAbortable<T>(\n act: () => Promise<T>,\n signal: AbortSignal,\n /** The abort's message when the signal states none, or the abort error itself. */\n fallback: string | (() => unknown),\n): Promise<T> {\n const aborted = () =>\n typeof fallback === 'string' ? signalAbortError(signal, fallback) : fallback()\n if (signal.aborted) throw aborted()\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(aborted())\n })\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let work: Promise<T>\n try {\n work = Promise.resolve(act())\n } catch (error) {\n cleanup()\n reject(error)\n return\n }\n work.then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n","import { createHash } from 'node:crypto'\n\nexport function sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n","import {\n closeSync,\n fstatSync,\n fsync,\n fsyncSync,\n ftruncateSync,\n openSync,\n readSync,\n writeSync,\n} from 'node:fs'\nimport { promisify } from 'node:util'\nimport { fenceRunWrite } from './run-fence'\n\n/** Append one JSONL record under the caller's existing single-writer discipline.\n * The caller creates the parent directory. Recover only an uncommitted tail and handle short\n * writes under one generation fence; fsync after the fence, off the event loop (#2362), and\n * resolve only once the bytes are durable. An optional acknowledgement reads the same open\n * descriptor inside the fence (the spawn journal validates its file stamp here).\n * @internal\n */\nexport function appendCommittedJsonLine(path: string, record: unknown): Promise<void>\nexport function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge: (fd: number) => T,\n): Promise<T>\nexport async function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge?: (fd: number) => T,\n): Promise<T | undefined> {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new TypeError('JSONL records must be JSON serializable')\n let fd: number | undefined\n try {\n const acknowledged = fenceRunWrite(() => {\n const bytes = Buffer.from(`${prepareJsonlTail(path) ? '\\n' : ''}${encoded}\\n`)\n fd = openSync(path, 'a')\n let offset = 0\n while (offset < bytes.length) {\n const written = writeSync(fd, bytes, offset, bytes.length - offset)\n if (written <= 0)\n throw new Error(`append-only file write made no progress at byte ${offset}`)\n offset += written\n }\n return acknowledge?.(fd)\n })\n await promisify(fsync)(fd as number)\n return acknowledged\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\n/** Recover only an uncommitted tail. Caller holds the generation fence. @internal */\nexport function prepareJsonlTail(path: string): boolean {\n let fd: number\n try {\n fd = openSync(path, 'r+')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n try {\n const size = fstatSync(fd).size\n if (size === 0) return false\n const last = Buffer.allocUnsafe(1)\n readAt(fd, last, size - 1)\n if (last[0] === 0x0a) return false\n const chunks: Buffer[] = []\n let end = size\n let tailStart = 0\n while (end > 0) {\n const start = Math.max(0, end - 65_536)\n const chunk = Buffer.allocUnsafe(end - start)\n readAt(fd, chunk, start)\n const newline = chunk.lastIndexOf(0x0a)\n chunks.push(chunk.subarray(newline + 1))\n if (newline >= 0) {\n tailStart = start + newline + 1\n break\n }\n end = start\n }\n try {\n JSON.parse(Buffer.concat(chunks.reverse()).toString('utf8'))\n return true\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error\n ftruncateSync(fd, tailStart)\n fsyncSync(fd)\n return false\n }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction readAt(fd: number, buffer: Buffer, position: number): void {\n let offset = 0\n while (offset < buffer.length) {\n const read = readSync(fd, buffer, offset, buffer.length - offset, position + offset)\n if (read === 0) throw new Error('journal changed while preparing its append tail')\n offset += read\n }\n}\n","import type { FileHandle } from 'node:fs/promises'\nimport { prepareJsonlTail } from './jsonl-append'\nimport { fenceRunWrite } from './run-fence'\n\n/** Parse in-memory evidence with the same commit boundary as streamed journal reads. */\nexport function parseCommittedJsonLines<T>(text: string, source: string): T[] {\n const lines = text.split('\\n')\n const records: T[] = []\n for (const [index, line] of lines.entries()) {\n const record = parseRecord<T>(line, source, index + 1, index < lines.length - 1)\n if (record !== undefined) records.push(record.value)\n }\n return records\n}\n\n/** Read a fixed file prefix one record at a time, never allocating the whole journal as a string.\n * A reader cannot chase concurrent appends forever. Missing files are empty only when requested;\n * corruption, short reads, and other I/O errors remain failures. Closing the iterator closes the fd. */\nexport async function* readCommittedJsonLines<T>(\n path: string,\n options: {\n allowMissing?: boolean\n allowWhitespaceLines?: boolean\n invalid?: 'throw' | 'skip'\n onBytes?: (bytes: Uint8Array) => void\n /** Internal fixed-prefix range. The caller supplies a record boundary and owns the handle. */\n handle?: FileHandle\n start?: number\n end?: number\n strictUtf8?: boolean\n onCommit?: (offset: number) => void\n } = {},\n): AsyncGenerator<T> {\n const fs = await import('node:fs/promises')\n let handle: FileHandle\n try {\n handle = options.handle ?? (await fs.open(path, 'r'))\n } catch (error) {\n if (options.allowMissing && isNoEntError(error)) return\n throw error\n }\n try {\n const start = options.start ?? 0\n const end = options.end ?? (await handle.stat()).size\n if (end <= start) return\n const fragments: Buffer[] = []\n let offset = start\n let lineNumber = 1\n const parse = (terminated: boolean): { value: T } | undefined => {\n const bytes = Buffer.concat(fragments)\n let line: string\n try {\n line = options.strictUtf8\n ? new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n : bytes.toString('utf8')\n } catch (cause) {\n if (!terminated || (options.invalid === 'skip' && cause instanceof TypeError))\n return undefined\n throw new Error(`${path}: malformed UTF-8 at line ${lineNumber}`, { cause })\n }\n return parseRecord<T>(\n line,\n path,\n lineNumber++,\n terminated,\n options.allowWhitespaceLines,\n options.invalid,\n )\n }\n let position = start\n while (position < end) {\n const buffer = Buffer.alloc(Math.min(65_536, end - position))\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, position)\n if (bytesRead === 0) {\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n }\n position += bytesRead\n const bytes = buffer.subarray(0, bytesRead)\n options.onBytes?.(bytes)\n let start = 0\n for (let end = bytes.indexOf(10); end !== -1; end = bytes.indexOf(10, start)) {\n fragments.push(bytes.subarray(start, end))\n const record = parse(true)\n offset += fragments.reduce((size, part) => size + part.length, 0) + 1\n fragments.length = 0\n options.onCommit?.(offset)\n if (record !== undefined) yield record.value\n start = end + 1\n }\n if (start < bytes.length) fragments.push(bytes.subarray(start))\n }\n const record = parse(false)\n if (record !== undefined) {\n options.onCommit?.(end)\n yield record.value\n }\n } finally {\n if (options.handle === undefined) await handle.close()\n }\n}\n\n/** An invalid unterminated tail may be a torn write; other parse failures are not evidence of one. */\nfunction parseRecord<T>(\n line: string,\n source: string,\n lineNumber: number,\n terminated: boolean,\n allowWhitespaceLines = false,\n invalid: 'throw' | 'skip' = 'throw',\n): { value: T } | undefined {\n if (line.length === 0 || (allowWhitespaceLines && line.trim().length === 0)) return undefined\n try {\n return { value: JSON.parse(line) as T }\n } catch (cause) {\n if (!(cause instanceof SyntaxError)) throw cause\n if (!terminated || invalid === 'skip') return undefined\n throw new Error(`${source}: malformed JSONL record at line ${lineNumber}`, { cause })\n }\n}\n\nexport { appendCommittedJsonLine } from './jsonl-append'\n\n/** Serialize JSONL file updates across processes and aliases using Eval's existing file lock.\n * The caller owns validation and the record format. The lock path names the canonical file,\n * including its first write, so two directory aliases cannot acquire different write heads.\n * @internal\n */\nexport async function withJsonlFileLock<T>(\n path: string,\n operation: (canonicalPath: string) => Promise<T>,\n): Promise<T> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n const { tryAcquireAtomicFileLock } = await import('@tangle-network/agent-eval/ledger-core')\n await fs.mkdir(dirname(path), { recursive: true })\n const file = await fs.open(path, 'a')\n await file.close()\n const canonicalPath = await fs.realpath(path)\n const deadline = Date.now() + 5000\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${canonicalPath}.lock` })\n if (!acquisition.acquired) {\n if (Date.now() >= deadline) {\n throw new Error(`journal file lock unavailable after 5000ms: ${canonicalPath}`)\n }\n await new Promise((resolve) => setTimeout(resolve, 25))\n continue\n }\n try {\n return await operation(canonicalPath)\n } finally {\n acquisition.lock.release()\n }\n }\n}\n\n/** Read one keyed registry snapshot without an extra whole-file text allocation.\n * Historical registry files allow whitespace-only separators; append journals remain strict.\n * @internal\n */\nexport async function readCommittedJsonFile<T>(path: string): Promise<T[]> {\n const records: T[] = []\n for await (const record of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n records.push(record)\n }\n return records\n}\n\n/** Replace one keyed row and publish one durable snapshot. The caller holds the file lock.\n * Keep unrelated rows in order and put the replacement last. No revision archive is retained.\n * @internal\n */\nexport async function upsertCommittedJsonLine<T>(\n path: string,\n record: T,\n key: (record: T) => string,\n): Promise<void> {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new Error('JSONL records must be JSON serializable')\n const snapshot: T = JSON.parse(encoded)\n const id = key(snapshot)\n const updated: T[] = []\n for await (const prior of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n if (key(prior) !== id) updated.push(prior)\n }\n updated.push(snapshot)\n // Reuse Runtime's file publication owner; this module owns JSONL framing, not another\n // durability implementation. Preserve the existing snapshot's permissions across rename.\n const { writeAtomicDurableFile } = await import('../runtime/supervise/durable-file')\n writeAtomicDurableFile(path, `${updated.map((row) => JSON.stringify(row)).join('\\n')}\\n`, {\n preserveMode: true,\n })\n}\n\n/** Recover a torn tail under the same generation fence as durable publications. @internal */\nexport async function prepareJsonlAppend(path: string): Promise<boolean> {\n return fenceRunWrite(() => prepareJsonlTail(path))\n}\n\n/** True for a filesystem error meaning \"the file is not there yet\" — the one condition an\n * append-only reader treats as an empty log rather than a fault. */\nexport function isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;AACA,IAAa,wBAAb,cAA2C,MAAM;CAEpC;CAEA;CAEA;CALX,YACE,QACA,QACA,aAEA,UACA;EACA,MAAM,MAAM;EANH,KAAA,SAAA;EAEA,KAAA,cAAA;EAEA,KAAA,WAAA;EAGT,KAAK,OAAO;CACd;CAEA,WAA4B;EAC1B,OAAO,KAAK;CACd;AACF;;AAGA,SAAgB,YAAY,QAAqB,UAA2B;CAC1E,MAAM,SAAS,OAAO;CACtB,IAAI,kBAAkB,uBAAuB,OAAO;CACpD,IAAI,OAAO,WAAW,YAAY,OAAO,SAAS,GAAG,OAAO;CAE5D,IAAI,kBAAkB,SAAS,OAAO,SAAS,gBAAgB,OAAO,QAAQ,SAAS,GACrF,OAAO,OAAO;CAEhB,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAAqB,UAAyB;CAC7E,MAAM,SAAS,YAAY,QAAQ,QAAQ;CAC3C,MAAM,QAAQ,IAAI,MAChB,kBAAkB,QACd,OAAO,UACP,OAAO,WAAW,YAAY,OAAO,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MAAM,OAAO;CAChD,uBAAuB,MAAM,GAAG,QAAQ,KAAK,QAAQ,KAAK,UAAU,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,EACxF,cAAc,KAChB,CAAC;AACH;;AAGA,eAAsB,mBAAmB,MAAgC;CACvE,OAAO,oBAAoB,iBAAiB,IAAI,CAAC;AACnD;;;AAIA,SAAgB,aAAa,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA4B,SAAS;AAE1C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-cancellation-CBP3Bmad.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.ts","../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport { appendCommittedJsonLine, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { captureRunWriteContext } from '../../durable/run-fence'\nimport type {\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from '../../mcp/tools/coordination-analysts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport type { ContinuationInstruction } from '../../mcp/tools/coordination-messages'\nimport type {\n QuestionEscalationRecord,\n QuestionRecord,\n} from '../../mcp/tools/coordination-questions'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every `ask_parent` escalation the prior process made, raise order. An undelivered one names a\n * question the run raised that nothing above it received — retained so a resuming operator sees\n * it, never auto-redelivered. */\n readonly escalations: ReadonlyArray<QuestionEscalationRecord>\n /** Every lens the prior process DEFINED at run time, definition order. The exact authored bytes\n * and their digest, so an invented lens can be re-registered and any finding it produced can be\n * traced to the words that produced it. Re-registration is the owner's decision, never automatic:\n * the registry may have changed between processes. */\n readonly analystDefinitions: ReadonlyArray<DefinedAnalystRecord>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private readonly writeContext = captureRunWriteContext()\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() =>\n this.writeContext(() => this.appendRecord(runId, record, ownerId)),\n )\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n const record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n await appendCommittedJsonLine(this.path, record)\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\n return foldCoordinationRecords(\n readCommittedJsonLines<CoordinationLogRecord | LegacyCoordinationLogRecord>(this.path, {\n allowMissing: true,\n }),\n runId,\n ownerId,\n )\n }\n}\n\n/** @internal Shared replay semantics for file and SQL coordination evidence. */\nexport async function foldCoordinationRecords(\n source:\n | Iterable<CoordinationLogRecord | LegacyCoordinationLogRecord>\n | AsyncIterable<CoordinationLogRecord | LegacyCoordinationLogRecord>,\n runId: string,\n ownerId?: CoordinationOwnerId,\n): Promise<PriorCoordination> {\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const escalations: QuestionEscalationRecord[] = []\n const analystDefinitions: DefinedAnalystRecord[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for await (const stored of source) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n } else if (ev.type === 'escalation') {\n escalations.push(ev.escalation)\n } else if (ev.type === 'analyst-defined') {\n analystDefinitions.push(ev.analyst)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n escalations,\n analystDefinitions,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport { deriveNodeExecutionIdentity } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type { SupervisorNodeContext } from './supervisor-agent'\nimport type { AgentExecutionRef, NodeExecutionIdentity } from './types'\n\nexport function externalExecutionId(kind: string, identity: unknown): string {\n const digest = canonicalCandidateDigest({ kind, identity })\n return `${kind}-${digest.slice('sha256:'.length)}`\n}\n\nexport function freezeDetached<T>(value: T): T {\n return detachedSnapshot(value, 'supervise')\n}\n\nexport function freezeDetachedProfile(value: unknown): AgentProfile {\n return freezeDetached(agentProfileSchema.parse(value))\n}\n\nexport function canonicalExecution(\n profile: AgentProfile,\n task: unknown,\n rawExecution: AgentExecutionRef | undefined,\n context: string,\n): { readonly identity: NodeExecutionIdentity; readonly ref?: AgentExecutionRef } {\n const execution = rawExecution === undefined ? undefined : freezeDetached(rawExecution)\n if (execution !== undefined) {\n if (typeof execution !== 'object' || execution === null || Array.isArray(execution)) {\n throw new ValidationError(`${context}: execution must be an object`)\n }\n const unknown = Object.keys(execution).filter(\n (key) => key !== 'candidateDigest' && key !== 'correlation',\n )\n if (unknown.length > 0) {\n throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(', ')}`)\n }\n }\n const identity = deriveNodeExecutionIdentity({ profile, execution }, task)\n if (!identity?.profileDigest || !identity.taskDigest) {\n throw new ValidationError(\n `${context}: profile and task must be finite, acyclic canonical JSON for durable identity`,\n )\n }\n const ref: AgentExecutionRef | undefined =\n identity.candidateDigest || identity.correlation\n ? Object.freeze({\n ...(identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {}),\n ...(identity.correlation ? { correlation: identity.correlation } : {}),\n })\n : undefined\n return { identity, ...(ref ? { ref } : {}) }\n}\n\nexport function rootCoordinationOwner(identity: NodeExecutionIdentity): string {\n return canonicalCandidateDigest({ kind: 'supervisor-root', identity })\n}\n\nexport function childCoordinationOwner(\n parentOwnerId: string,\n identity: NodeExecutionIdentity,\n context: WorkerSpawnContext,\n depth: number,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervisor-child',\n parentOwnerId,\n identity,\n assignment: {\n id: context.assignmentId,\n label: context.label,\n key: context.key ?? null,\n depth,\n },\n })\n}\n\nexport function supervisionRunNamespace(runDir: string | undefined, runId: string): string {\n return canonicalCandidateDigest(\n runDir === undefined\n ? { kind: 'supervise-ephemeral-run', runId, nonce: randomUUID() }\n : { kind: 'supervise-durable-run', runId, runDir: resolve(runDir) },\n )\n}\n\nexport function workerAssignmentNamespace(\n runNamespace: string,\n parentOwnerId: string,\n assignmentId: string,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervise-worker-assignment',\n runNamespace,\n parentOwnerId,\n assignmentId,\n })\n}\n\n/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a\n * resumed projection's marker describes the reader, not the original settlement. */\nexport function coordinationEventId(\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n): Sha256Digest {\n const durableEvent =\n event.type === 'settled' && event.worker.resumed === true\n ? (() => {\n const { resumed: _resumed, ...worker } = event.worker\n return { type: 'settled' as const, worker }\n })()\n : event\n return canonicalCandidateDigest({\n kind: 'supervise-coordination-event',\n runNamespace: context.runNamespace,\n ownerId: context.ownerId,\n event: detachedSnapshot(durableEvent, 'supervise coordination event identity'),\n })\n}\n","import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport { assertNoSymlinkDescendant, writeAtomicDurableFile } from './durable-file'\nimport { appendWorkerControlEvent, workerCancellationsDir } from './run-layout'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: 'observer' | 'turn-boundary' | 'fallback' = 'turn-boundary',\n): RunCancellation | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return prior\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(dir, record)\n return record\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n const check = (path: 'observer' | 'fallback' = 'observer'): void => {\n if (failure !== undefined) throw failure\n if (active) applyRunCancellation(dir, abortOnce, () => new Date().toISOString(), path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n try {\n check()\n } catch (error) {\n fail(error)\n }\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => {\n try {\n check('fallback')\n } catch (error) {\n fail(error)\n }\n }, 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n } = {},\n): RunCancellation {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending === undefined) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n writeAtomicDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`, { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n })\n }\n return {\n operationId: opId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string') &&\n (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,UAAU,OAAmC;CACpD,OAAO,MAAM,SAAS;AACxB;;AAGA,IAAa,sBAAb,MAA4D;CAI7B;CAH7B,eAAgC,uBAAuB;CACvD,aAAoC,QAAQ,QAAQ;CAEpD,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,MAAM,OACJ,OACA,QACA,S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