@tangle-network/agent-runtime 10.0.4 → 10.0.5

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 +26 -0
  2. package/dist/{activation-38MolXIP.js → activation-DvvM7gG5.js} +2 -2
  3. package/dist/{activation-38MolXIP.js.map → activation-DvvM7gG5.js.map} +1 -1
  4. package/dist/{activation-Ckx0yHjT.d.ts → activation-DyFt-GHq.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{continuation-CL4B1Y4M.js → continuation-Bccak14N.js} +3 -3
  8. package/dist/{continuation-CL4B1Y4M.js.map → continuation-Bccak14N.js.map} +1 -1
  9. package/dist/{delegate-dhNeiaH_.js → delegate-YBqrrbq7.js} +2 -2
  10. package/dist/{delegate-dhNeiaH_.js.map → delegate-YBqrrbq7.js.map} +1 -1
  11. package/dist/{driver-control-acknowledgers-C6GaGBf_.js → driver-control-acknowledgers-CNNRjIo9.js} +8 -7
  12. package/dist/{driver-control-acknowledgers-C6GaGBf_.js.map → driver-control-acknowledgers-CNNRjIo9.js.map} +1 -1
  13. package/dist/durable-file-iPCEs_-s.js +1 -0
  14. package/dist/{durable-file-lXnojyij.js → durable-file-pao7FijS.js} +7 -11
  15. package/dist/durable-file-pao7FijS.js.map +1 -0
  16. package/dist/durable-writer-thread.js +5 -5
  17. package/dist/durable.d.ts +4 -1
  18. package/dist/durable.js +21 -15
  19. package/dist/durable.js.map +1 -1
  20. package/dist/failure-cause-DoCCGLDH.js.map +1 -1
  21. package/dist/{graph-CwLg3LGC.js → graph-CUUtx7qT.js} +8 -12
  22. package/dist/{graph-CwLg3LGC.js.map → graph-CUUtx7qT.js.map} +1 -1
  23. package/dist/{graph-registry-Bs6mGKou.js → graph-registry-CGKyYabE.js} +1 -1
  24. package/dist/{graph-registry-DtGd03zk.js → graph-registry-CRskE_Yp.js} +4 -4
  25. package/dist/{graph-registry-DtGd03zk.js.map → graph-registry-CRskE_Yp.js.map} +1 -1
  26. package/dist/{improve-C_LKfgH9.js → improve-Cy8PZUdw.js} +8 -8
  27. package/dist/{improve-C_LKfgH9.js.map → improve-Cy8PZUdw.js.map} +1 -1
  28. package/dist/index.d.ts +3 -3
  29. package/dist/index.js +10 -10
  30. package/dist/intelligence.d.ts +2 -2
  31. package/dist/intelligence.js +4 -4
  32. package/dist/{jsonl-file-DyzefaZ6.js → jsonl-file-vE9H9UXa.js} +3 -3
  33. package/dist/{jsonl-file-DyzefaZ6.js.map → jsonl-file-vE9H9UXa.js.map} +1 -1
  34. package/dist/kernel.d.ts +1 -1
  35. package/dist/kernel.js +18 -18
  36. package/dist/{loop-runner-BS3ru-yj.js → loop-runner-BwkX4ViS.js} +2 -2
  37. package/dist/{loop-runner-BS3ru-yj.js.map → loop-runner-BwkX4ViS.js.map} +1 -1
  38. package/dist/{loop-runner-LWqWf8FD.d.ts → loop-runner-Icc1iBR-.d.ts} +2 -2
  39. package/dist/loop-runner-bin.d.ts +1 -1
  40. package/dist/loop-runner-bin.js +1 -1
  41. package/dist/mcp/bin.js +3 -3
  42. package/dist/mcp/index.d.ts +1 -1
  43. package/dist/mcp/index.js +6 -6
  44. package/dist/{model-policy-DZnL8Yj9.js → model-policy-DTbTFyOG.js} +12 -6
  45. package/dist/model-policy-DTbTFyOG.js.map +1 -0
  46. package/dist/profiles.d.ts +1 -1
  47. package/dist/profiles.js +1 -1
  48. package/dist/{provision-supervisor-D8N0l2DM.js → provision-supervisor-Dtn8RjHe.js} +7 -7
  49. package/dist/{provision-supervisor-D8N0l2DM.js.map → provision-supervisor-Dtn8RjHe.js.map} +1 -1
  50. package/dist/{result-blob-store-DfTcyQ05.js → result-blob-store-UGXQYACQ.js} +3 -3
  51. package/dist/{result-blob-store-DfTcyQ05.js.map → result-blob-store-UGXQYACQ.js.map} +1 -1
  52. package/dist/{run-cancellation-D3qc9wAD.js → run-cancellation-BpUQZqBS.js} +3 -3
  53. package/dist/{run-cancellation-D3qc9wAD.js.map → run-cancellation-BpUQZqBS.js.map} +1 -1
  54. package/dist/{run-lock-D1xnb9ve.js → run-lock-Ckakh1Uq.js} +3 -3
  55. package/dist/{run-lock-D1xnb9ve.js.map → run-lock-Ckakh1Uq.js.map} +1 -1
  56. package/dist/{run-reopen-DVM5AEKV.js → run-reopen-BvF3Gjj9.js} +6 -6
  57. package/dist/{run-reopen-DVM5AEKV.js.map → run-reopen-BvF3Gjj9.js.map} +1 -1
  58. package/dist/{run-state-tgQ-S9Ln.js → run-state-CZcFJjHn.js} +7 -7
  59. package/dist/{run-state-tgQ-S9Ln.js.map → run-state-CZcFJjHn.js.map} +1 -1
  60. package/dist/{runtime-BTECV05R.js → runtime-BvDaNyFf.js} +44 -53
  61. package/dist/runtime-BvDaNyFf.js.map +1 -0
  62. package/dist/{search-executor-Uco2_KTB.js → search-executor-DWQW-9WN.js} +4 -4
  63. package/dist/{search-executor-Uco2_KTB.js.map → search-executor-DWQW-9WN.js.map} +1 -1
  64. package/dist/{server-BMp24-xn.js → server-D5GpuQnT.js} +3 -3
  65. package/dist/{server-BMp24-xn.js.map → server-D5GpuQnT.js.map} +1 -1
  66. package/dist/{settle-record-au3w7bQG.js → settle-record-BFhJigPW.js} +4 -4
  67. package/dist/{settle-record-au3w7bQG.js.map → settle-record-BFhJigPW.js.map} +1 -1
  68. package/dist/{structural-rollout-D8wufVJI.js → structural-rollout-D1pZn6Cu.js} +4 -4
  69. package/dist/{structural-rollout-D8wufVJI.js.map → structural-rollout-D1pZn6Cu.js.map} +1 -1
  70. package/dist/{supervise-DtVdvZpr.js → supervise-fmugf6Y2.js} +16 -15
  71. package/dist/supervise-fmugf6Y2.js.map +1 -0
  72. package/dist/{supervise-identity-S5XwgaF3.js → supervise-identity-7_7DUghQ.js} +4 -4
  73. package/dist/{supervise-identity-S5XwgaF3.js.map → supervise-identity-7_7DUghQ.js.map} +1 -1
  74. package/dist/{supervision-discovery-Cqu4NxPV.js → supervision-discovery-DwRtZNdy.js} +5 -8
  75. package/dist/supervision-discovery-DwRtZNdy.js.map +1 -0
  76. package/dist/{supervisor-CHgCAMjm.js → supervisor-BlACe-uO.js} +126 -61
  77. package/dist/supervisor-BlACe-uO.js.map +1 -0
  78. package/dist/{supervisor-accounting-CZ7i4cd5.js → supervisor-accounting-DuFyM-_h.js} +49 -18
  79. package/dist/supervisor-accounting-DuFyM-_h.js.map +1 -0
  80. package/dist/{supervisor-root-contract-D70KTGXF.js → supervisor-root-contract-DCMw4u0V.js} +2 -2
  81. package/dist/{supervisor-root-contract-D70KTGXF.js.map → supervisor-root-contract-DCMw4u0V.js.map} +1 -1
  82. package/dist/testing.d.ts +1 -1
  83. package/dist/testing.js +11 -11
  84. package/dist/{top-web-COrMqTRC.js → top-web-C5vhiOFA.js} +7 -7
  85. package/dist/{top-web-COrMqTRC.js.map → top-web-C5vhiOFA.js.map} +1 -1
  86. package/dist/tui/bin.js +3 -3
  87. package/dist/tui/index.d.ts +1 -1
  88. package/dist/tui/index.js +2 -2
  89. package/dist/{types-9xsn2GGY.d.ts → types-CFmKHKiN.d.ts} +10 -4
  90. package/package.json +1 -1
  91. package/dist/durable-file-DJ3JsA4B.js +0 -1
  92. package/dist/durable-file-lXnojyij.js.map +0 -1
  93. package/dist/model-policy-DZnL8Yj9.js.map +0 -1
  94. package/dist/runtime-BTECV05R.js.map +0 -1
  95. package/dist/supervise-DtVdvZpr.js.map +0 -1
  96. package/dist/supervision-discovery-Cqu4NxPV.js.map +0 -1
  97. package/dist/supervisor-CHgCAMjm.js.map +0 -1
  98. package/dist/supervisor-accounting-CZ7i4cd5.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-D3qc9wAD.js";
3
- import { T as supervisorRunsRoot, j as writeWorkerSteer, m as cancelWorker } from "../supervisor-accounting-CZ7i4cd5.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-COrMqTRC.js";
2
+ import { n as cancelRun } from "../run-cancellation-BpUQZqBS.js";
3
+ import { T as supervisorRunsRoot, j as writeWorkerSteer, m as cancelWorker } from "../supervisor-accounting-DuFyM-_h.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-C5vhiOFA.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 PursuitProjection, E as Budget, Ga as NodeExecutionIdentity, Ka as ProfileMaterializationReceipt, Ra as ExecutionBindingReceipt, Sb as RouteFlowEvent, Xd as PursuitNodeProjection, aa as ResultBlobStore, ef as PursuitRunProjection, fC as HarnessTranscriptEvidence, j as Spend, lC as HarnessTranscriptArtifact, zr as provisionSupervisor } from "../types-9xsn2GGY.js";
1
+ import { $d as PursuitProjection, E as Budget, Ga as NodeExecutionIdentity, Ka as ProfileMaterializationReceipt, Ra as ExecutionBindingReceipt, Sb as RouteFlowEvent, Xd as PursuitNodeProjection, aa as ResultBlobStore, ef as PursuitRunProjection, fC as HarnessTranscriptEvidence, j as Spend, lC as HarnessTranscriptArtifact, zr as provisionSupervisor } from "../types-CFmKHKiN.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-D8N0l2DM.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-COrMqTRC.js";
1
+ import { t as provisionSupervisor } from "../provision-supervisor-Dtn8RjHe.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-C5vhiOFA.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 };
@@ -10228,8 +10228,11 @@ type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown';
10228
10228
  interface PursuitNodeUsage {
10229
10229
  readonly input: number;
10230
10230
  readonly output: number;
10231
+ readonly freshInput?: number;
10231
10232
  readonly cacheRead?: number;
10232
10233
  readonly cacheWrite?: number;
10234
+ /** False when the observed prompt subtotal does not have a complete cache classification. */
10235
+ readonly cacheBreakdownKnown?: false;
10233
10236
  readonly reasoning?: number;
10234
10237
  readonly tokensKnown: boolean;
10235
10238
  }
@@ -12550,6 +12553,8 @@ interface CanonicalObservedModelParts {
12550
12553
  readonly base: string;
12551
12554
  readonly snapshot?: string;
12552
12555
  readonly snapshotKind?: SnapshotKind;
12556
+ /** The complete provider model id is immutable without a separate snapshot suffix. */
12557
+ readonly fixed?: true;
12553
12558
  readonly canonical: string;
12554
12559
  }
12555
12560
  /** Match equivalent bare and provider-qualified spellings without discarding observed identity. */
@@ -17169,8 +17174,9 @@ declare function writeWorkerSteer(rootDir: string, supervisorId: string, worker:
17169
17174
  };
17170
17175
  /**
17171
17176
  * Admit one steer like `writeWorkerSteer`, without blocking the calling thread on the disk.
17172
- * The request file is published by the durable writer, so an event loop that admits steers keeps
17173
- * running while the file and its directory reach disk. Same admission, replay and conflict rules.
17177
+ * The request file is published by the durable writer whether or not the caller holds a run claim
17178
+ * (a coordinator outside the run holds none), so an event loop that admits steers keeps running
17179
+ * while the file and its directory reach disk. Same admission, replay and conflict rules.
17174
17180
  * @stable
17175
17181
  */
17176
17182
  declare function writeWorkerSteerAsync(rootDir: string, supervisorId: string, worker: string, options: WriteWorkerSteerOptions): Promise<ReturnType<typeof writeWorkerSteer>>;
@@ -19217,9 +19223,9 @@ declare const runtimeFailureCauseSchema: z.ZodReadonly<z.ZodObject<{
19217
19223
  unknown: "unknown";
19218
19224
  }>;
19219
19225
  owner: z.ZodEnum<{
19226
+ provider: "provider";
19220
19227
  platform: "platform";
19221
19228
  unknown: "unknown";
19222
- provider: "provider";
19223
19229
  runtime: "runtime";
19224
19230
  work: "work";
19225
19231
  caller: "caller";
@@ -19787,4 +19793,4 @@ interface KnowledgeReadinessDecision {
19787
19793
  nonBlockingGapIds: string[];
19788
19794
  }
19789
19795
  export { BlockedToolReport as $, LoopPlanPayload as $C, RetainedRunEventOptions as $S, FeedbackRating as $_, ExecutorCancellationRequest as $a, DEFAULT_PEER_MAIL_LIMITS as $b, LoopCampaignDispatchOptions as $c, PursuitProjection as $d, IsolatedCheckOutputEvidence as $f, RouterResponseReceipt as $g, Inbox as $h, DesignerToolsEnv as $i, strategyAuthorContract as $l, CoordinationRejectReason as $m, searchPresets as $n, structuralRollout as $o, ReservationRejection as $p, workerFromInteractiveProvider as $r, ResolveSandboxClientOptions as $s, AnalystAuthoring as $t, PersonaExecutors as $u, HarnessUsage as $v, SqlAdapter as $x, SanitizedKnowledgeRequirement as $y, ResourceSpend as A, resolveHarnessTranscriptCapture as AC, BackendTransportError as AS, DelegationResumeContext as A_, Agent as Aa, QuestionEscalationOutcome as Ab, PairedCommandInput as Ac, NextPursuitVersion as Ad, EdgeDeliveryOutcome as Af, WorkerProgress as Ag, McpEventRecord as Ah, graphFromStored as Ai, ArtifactHandle as Al, StopDecision as Am, gitWorkspace as An, CheckExecChannel as Ao, dumbContinuationPassPrompt as Ap, RemoteSupervisorSteerResult as Ar, acquireSandbox as As, CreateSandboxOptions$1 as At, PanelVerdict as Au, ExecutorResultMapping as Av, ToolStepInput as Ax, bestSoFar as Ay, SpawnOpts as B, UsageEvent as BC, RecoverRetainedRunOptions as BS, DelegateResearchArgs as B_, ExecutorMaterialization as Ba, AuthorizedDownMessage as Bb, McpEndpoint as Bc, SupervisePursuitError as Bd, runGraph as Bf, resolveMcpServerLaunch as Bg, CliSeam as Bh, taskShapeDigest as Bi, sample as Bl, DeliveredOutput as Bm, createRootHandle as Bn, StructuralRolloutResult as Bo, WorkerTraceResolver as Bp, ProfileRegistryDir as Br, startRetainedRunInEnvironment as Bs, makeFinding$1 as Bt, Verify as Bu, sentinelCompletion as Bv, AuthoredAnalystDefinition as Bx, OtelExportConfig as By, RuntimeFailureCause as C, HarnessFileBinding as CC, InMemoryResultBlobStore as CS, createFleetWorkspaceExecutor as C_, RootStreamReceipt as Ca, RouteGate as Cb, CreateScopeAnalystOptions as Cc, assertDeclaredCheck as Cd, GraphCheckNode as Cf, ProviderPlacement as Cg, environmentReader as Ch, GraphRunRecord as Ci, connectStdioMcp as Cl, SupervisorToolInvocationContext as Cm, copyUntrackedIntoClone as Cn, ProfileRichnessThresholds as Co, PromptHandle as Cp, workerInboxFileFromEventDir as Cr, TurnResult as Cs, AgentSessionRef as Ct, FanoutSynthesis as Cu, FileDelegationStoreOptions as Cv, startRuntimeRun as Cw, EventBus as Cx, renderLeaderboardSvg as Cy, BudgetOverspend as D, RetainedHarnessTranscriptCapture as DC, defaultRedactor as DS, runDetachedTurn as D_, ExecutorFactory as Da, EscalateQuestion as Db, createScopeAnalyst as Dc, declaredCheckJudge as Dd, GraphCommandCheck as Df, ExecutorProgress as Dg, createMcpServer as Dh, digestOfGraph as Di, AgenticSurface as Dl, NoProgressForOptions as Dm, Workspace as Dn, profileRichnessFinding as Do, createPromptRegistry as Dp, RemoteSupervisorCancelResult as Dr, createSandboxLineage as Ds, CheckpointRef as Dt, Panel as Du, CheckVerdict as Dv, defaultToolDetectors as Dx, AnytimeTaskCurve as Dy, Budget as E, HarnessTranscriptReadOptions as EC, Redactor as ES, RunDetachedTurnOptions as E_, ExecutorContext as Ea, ChildQuestionInbox as Eb, buildSteerContext as Ec, declaredCheckDigest as Ed, GraphCheckPlacement as Ef, DEFAULT_STALL_AFTER_MS as Eg, McpServerOptions as Eh, StoredGraphInput as Ei, AgenticRunResult as El, AllWorkersStalledOptions as Em, Shell as En, defaultProfileRichnessThresholds as Eo, analyzesFindingsReportPrompt as Ep, RemoteSupervisorAgent as Er, SandboxLineageHandle as Es, AnalystFinding$1 as Et, LoopUntilState as Eu, CheckUnavailableError as Ev, WatchTraceOptions as Ex, AnytimeStrategySummary as Ey, NodeId as F, ProviderWorkspaceCaptureResult as FC, NativeContextContinuationExecution as FS, DelegationTaskQueueOptions as F_, UnconfirmedTeardown as Fa, QuestionPolicy as Fb, CanonicalObservedModelParts as Fc, SettledPursuitVersion as Fd, GraphResult as Ff, BridgeSeam as Fg, createDelegateHandler as Fh, lookupGraph as Fi, SurfaceScore as Fl, plateau as Fm, analyzeTrace as Fn, CheckSourceCtx as Fo, SupervisorSpanAttributes as Fp, ProvisionSupervisorConnection as Fr, PrivateCasNamespaceObject as Fs, ResourceRequest$1 as Ft, ScopeWidenGate as Fu, CompletionEvidence as Fv, AnalystKind as Fx, WaterfallSpan as Fy, TreeView as G, Iteration as GC, RetainedInteractiveStartedAdmission as GS, DelegationError as G_, NodeExecutionIdentity as Ga, DownMessageDeliveryOutcome as Gb, BenchmarkConfig as Gc, RunReopen as Gd, portableContinuationPolicySchema as Gf, SandboxToolPartState as Gg, RouterToolsSeam as Gh, DispatchReport as Gi, StrategyArtifacts as Gl, CoordinationAuthentication as Gm, createFencedSqlRunContext as Gn, defaultExtractCandidate as Go, RunParkingRecord as Gp, profileRegistry as Gr, startRetainedInteractiveRun as Gs, SurfaceDiff as Gt, WidenSpec as Gu, CodexRolloutStoreReader as Gv, RunLocalHarnessOptions as Gx, createOtelExporter as Gy, SpawnRejection as H, DefaultVerdict$2 as HC, RetainedInteractiveAdmission as HS, DelegateUiAuditArgs as H_, MaterializedExecutionIdentity as Ha, ContinuityMode as Hb, createMcpEnvironment as Hc, SupervisedPursuitResult as Hd, defaultEdgeTraversalCap as Hf, secretEnvOfMcpServer as Hg, CliWorktreeSeam as Hh, graphFileNeedSchema as Hi, AuthoredStrategy as Hl, FinalizerSettled as Hm, validateStoredGraph as Hn, canDisplace as Ho, ParkedRun as Hp, bestProfileFor as Hr, claimRetainedInteractiveControl as Hs, createVerifierEnvironment as Ht, Widen as Hu, CodexForkBoundary as Hv, DefinedAnalystRecord as Hx, OtelExporter as Hy, NodeSnapshot as I, ProviderWorkspaceEntryMetadata as IC, NativeContextContinuationHandle as IS, SubmitInput as I_, WidenGate as Ia, QuestionRecord as Ib, SnapshotKind as Ic, VersionJudge as Id, GraphTopology as If, KeyProvider as Ig, createExecutorRegistry as Ih, pickBestGraph as Ii, breadthStrategy as Il, ReentryContinuity as Im, WorkerToolTraceArtifact as In, RepairStop as Io, SupervisorSpanOptions as Ip, ProvisionSupervisorRequest as Ir, PrivateCasNamespaceRetirement as Is, SandboxEvent$1 as It, SteerContext as Iu, CompletionPolicy as Iv, AnalystLensOutput as Ix, createWaterfallCollector as Iy, DriverAttemptRecord as J, LoopIterationDispatchPayload as JC, RetainedRunCancelOptions as JS, DelegationHistoryEntry as J_, UnknownMaterializationReason as Ja, MapItemFailurePolicy as Jb, BenchmarkStrategySummary as Jc, PursuitNodeCost as Jd, IsolatedCheckCommandEvidence as Jf, mapSandboxToolEvent as Jg, SandboxSteeringOptions as Jh, RollingDispatchOptions as Ji, adaptiveRefine as Jl, CoordinationPublicAddress as Jm, SearchSpec as Jn, modelAuthoredChecks as Jo, BudgetPoolRestore as Jp, profileBridgeWireModel as Jr, RetainedInteractiveAdmissionHook as Js, SurfaceReader as Jt, DefinePersonaInput as Ju, CodexStoreDelta as Jv, LocalHarness as Jx, RuntimeStreamEventCollector as Jy, EvidencePendingEvent as K, LoopDecisionPayload as KC, RetainedRunAdmission as KS, DelegationFeedbackSnapshot as K_, ProfileMaterializationReceipt as Ka, DownMessageEvent as Kb, BenchmarkLift as Kc, PursuitObserverDelivery as Kd, IsolatedCheckBox as Kf, createSandboxToolPartState as Kg, SandboxSeam as Kh, DispatchStopReason as Ki, StrategyCtx as Kl, CoordinationControlAccess as Km, CompiledSearchSpec as Kn, defaultStructuralRolloutPolicy as Ko, readRunParking as Kp, profileRunsForName as Kr, ReconnectRetainedInteractiveRunOptions as Ks, SurfaceReadBox as Kt, WinnerStrategy as Ku, CodexRolloutStoreRef as Kv, runLocalHarness as Kx, loopEventToOtelSpan as Ky, NodeStatus as L, ExecutorProgressEvent as LC, NativeContextContinuationInput as LS, SubmitOutput as L_, AgentExecutionRef as La, QuestionUrgency as Lb, canonicalObservedModelParts as Lc, VersionVerdict as Ld, RunGraphOptions as Lf, ResolvedMcpServerLaunch as Lg, ExecutorConfig as Lh, recordGraphRun as Li, depthStrategy as Ll, ReentryTaskInput as Lm, parseWorkerToolTraceArtifact as Ln, StructuralRolloutConfig as Lo, SupervisorSpanOutcome as Lp, ProvisionedSupervisor as Lr, reconnectRetainedRun as Ls, SandboxInstance$1 as Lt, TrajectoryNode as Lu, CompletionVerdict as Lv, AnalystRegistry$1 as Lx, RunAgentRoundsOptions as Ly, SpendChannel as M, ProviderWorkspaceAttemptProvenance as MC, JudgeError as MS, DelegationResumeTick as M_, ResumedKeyState as Ma, QuestionEscalationTarget as Mb, PairedCommandOptions as Mc, PursuitVersionChain as Md, GraphEdge as Mf, readWorkerProgress as Mg, DelegateError as Mh, graphRunsFor as Mi, RunAgenticOptions as Ml, allWorkersStalled as Mm, localShell as Mn, CheckRunContext as Mo, kernelPromptRegistry as Mp, RemoteWorkerEvents as Mr, S3PrivateCasStoreOptions as Ms, ExecResult as Mt, RenderCorpusToInstructionsOptions as Mu, mapExecutorResult as Mv, createPushTraceSource as Mx, renderAnytimeTable as My, SpendGap as N, ProviderWorkspaceCaptureProvenance as NC, NotFoundError as NS, DelegationRunContext as N_, ResumedWork as Na, QuestionLevel as Nb, measurePairedCommands as Nc, PursuitVersionStop as Nd, GraphEdgeCapError as Nf, BridgeHarnessStore as Ng, DelegateHandlerOptions as Nh, listGraphRuns as Ni, StrategyMessage as Nl, anyOf as Nm, runInWorkspace as Nn, CheckRunner as No, naiveContinuationPrompt as Np, connectRemoteSupervisor as Nr, createS3PrivateCasStore as Ns, ForkRequest as Nt, ScopeAnalyst as Nu, verdictFromJudgeScore as Nv, AnalystAssignmentRecord as Nx, WaterfallCollector as Ny, BudgetViolation as O, RetainedHarnessTranscriptDescriptor as OC, AgentEvalError$1 as OS, DelegationArgs as O_, ExecutorRegistry as Oa, Question as Ob, registryScopeAnalyst as Oc, readDeclaredCheck as Od, GraphFromStoredOptions as Of, ScopeProgressInput as Og, EventSubscription as Oh, graphCorpusSummary as Oi, AgenticTask as Ol, PlateauOptions as Om, WorkspaceCommit as On, supervisorInstructions as Oo, delegatesWorkerBriefPrompt as Op, RemoteSupervisorControl as Or, SandboxEvidenceReceipt as Os, CheckpointRequest as Ot, PanelJudge as Ou, CompletionCheckContext as Ov, watchTrace as Ox, anytimeReport as Oy, Handle as P, ProviderWorkspaceCaptureReceipt as PC, ValidationError as PS, DelegationTaskQueue as P_, Scope as Pa, QuestionOption as Pb, observationFromRegistry as Pc, PursuitVersions as Pd, GraphNode as Pf, BridgeModelCredential as Pg, DelegateResult as Ph, loadGraph as Pi, StrategyShotResult as Pl, noProgressFor as Pm, TrajectoryAnalysis as Pn, CheckSource as Po, promptHandle as Pp, connectRemoteSupervisorControl as Pr, PrivateCasNamespaceInventory as Ps, PlacementInfo as Pt, ScopeAnalyzeInput as Pu, CompletionAnalyst as Pv, AnalystFindingEvent as Px, WaterfallReport as Py, DriverRepromptRefusal as Q, LoopPlanDescription as QC, RetainedRunEnvironmentAdmission as QS, DelegationStatusResult as Q_, ExecutorCancellation as Qa, AUTHORITY_MARKERS as Qb, runBenchmark as Qc, PursuitNodeUsage as Qd, IsolatedCheckOutputDeclaration as Qf, sumSandboxUsage as Qg, AuthorityInboxMessage as Qh, DesignerRunGraphEnv as Qi, sampleThenRefine as Ql, CoordinationHttpAudit as Qm, compileSearchSpec as Qn, selectBestIndex as Qo, ReservationHolder as Qp, InteractiveWorkerResult as Qr, StartRetainedInteractiveRunOptions as Qs, harvestSurfaceDiffs as Qt, PersonaContext as Qu, readCodexRolloutSession as Qv, openSqlRunStore as Qx, SanitizedKnowledgeReadinessReport as Qy, RetainedExecutionState as R, ExecutorToolCall as RC, ReconnectRetainedRunOptions as RS, DelegateCodeArgs as R_, ExecutionBindingReceipt as Ra, questionEscalationTargets as Rb, observedModelHasSnapshot as Rc, assertPursuitVersions as Rd, RunGraphTestOptions as Rf, envKeyProvider as Rg, createExecutor as Rh, recordStoredGraphRun as Ri, refine as Rl, UNPROVEN_CONTINUITY as Rm, DEFAULT_MAX_DEPTH as Rn, StructuralRolloutMessage as Ro, SupervisorSpanRecorder as Rp, SupervisorCleanupReceipt as Rr, recoverRetainedRun as Rs, WorkspaceRequest as Rt, TrajectoryReport as Ru, completionAuthorizes as Rv, AnalystRunContext as Rx, runAgentRounds as Ry, RuntimeStreamEvent as S, HARNESS_TRANSCRIPT_READ_LIMITS as SC, readRunCancellation as SS, SiblingSandboxExecutorOptions as S_, RootProviderModelEvidence as Sa, RouteFlowEvent as Sb, widen as Sc, DeclaredCheckStateCapture as Sd, SuperviseRegistryTable as Sf, UnavailablePausePolicy as Sg, SpawnResourceReader as Sh, GraphRunQuery as Si, StdioMcpServerSpec as Sl, SupervisorToolDescriptor as Sm, UntrackedCopyStats as Sn, ProfileRichness as So, withRunContext as Sp, supervisorRunsRoot as Sr, SandboxRunAbortError as Ss, AgentSession as St, FanoutOptions as Su, FileDelegationStore as Sv, RuntimeRunStatus as Sw, BusStats as Sx, renderLeaderboardMarkdown as Sy, RuntimeFailureOwner as T, HarnessTranscriptReadLimits as TC, contentAddress as TS, DetachedTurn as T_, AgentSpec as Ta, RouteWhen as Tb, assertTraceDerivedFindings as Tc, declaredCheckDeliverable as Td, GraphCheckOutput as Tf, ActivityNote as Tg, McpServer as Th, StoredGraph as Ti, AgenticOptions as Tl, SupervisorProfile as Tm, GitWorkspaceOptions as Tn, assessAuthoredProfile as To, RegisteredPrompt as Tp, writeWorkerSteerAsync as Tr, SandboxLineage as Ts, AgentTurnResult$2 as Tt, LoopUntilSpec as Tu, CoderTask as Tv, createEventBus as Tx, AnytimeReport as Ty, SubtreeResult as U, Driver as UC, RetainedInteractiveEnvironmentAdmission as US, DelegateUiAuditConfig as U_, MaterializedModelIdentity as Ua, DownMessageAuthorizationInput as Ub, sanitizeMcpToolSchema as Uc, superviseGraphPursuit as Ud, GraphRouteError as Uf, SandboxLeafOut as Ug, ProviderSeam as Uh, graphFileSchema as Ui, ShotSpec as Ul, SupervisorFinalizer as Um, FencedSqlRunContext as Un, compareCheckOutcomes as Uo, RunParkedError as Up, loadProfile as Ur, reconnectRetainedInteractiveRun as Us, BoxSurfaceReaderOptions as Ut, WidenDecision as Uu, CodexRolloutIdentity as Uv, CodexExecutionEvidence as Ux, OtelSpan as Uy, SpawnPrior as V, AgentRunSpec as VC, RecoverRetainedRunResult as VS, DelegateResearchConfig as V_, ExecutorNodeContext as Va, ContinuationInstruction as Vb, McpEnvironmentOptions as Vc, SupervisePursuitOptions as Vd, runGraphWithTestBrain as Vf, resolveSecretEnv as Vg, CliWorktreeBridgeSeam as Vh, GraphTriggerBinding as Vi, AuthorStrategyOptions as Vl, FinalizeContext as Vm, ValidateStoredGraphOptions as Vn, VisibleCheck as Vo, DeadlineCheckIn as Vp, ProfileRunRecord as Vr, ClaimRetainedInteractiveControlOptions as Vs, VerifierEnvironmentOptions as Vt, VerifySpec as Vu, stopSentinel as Vv, AuthoredAnalystLimits as Vx, OtelExportStats as Vy, SubtreeSummary as W, ExecCtx as WC, RetainedInteractiveIntentAdmission as WS, DelegateUiAuditRoute as W_, MaterializedResources as Wa, DownMessageDeliveryAttempt as Wb, BenchmarkCell as Wc, supervisePursuit as Wd, PortableContinuationPolicy as Wf, SandboxOutputMarker as Wg, RouterSeam as Wh, graphRouteWhenSchema as Wi, Strategy as Wl, bestDelivered as Wm, SqlRunContextOptions as Wn, composeCheckSources as Wo, RunParkingPolicy as Wp, pickBestProfile as Wr, recoverRetainedInteractiveRun as Ws, HarvestSurfaceDiffsOptions as Wt, WidenLineage as Wu, CodexRolloutSession as Wv, LocalHarnessResult as Wx, buildLoopOtelSpans as Wy, DriverContinuationRecord as X, LoopIterationStartedPayload as XC, RetainedRunDispatchedAdmission as XS, DelegationResultPayload as X_, Executor as Xa, MapSpawnMarker as Xb, Environment as Xc, PursuitNodeProjection as Xd, IsolatedCheckResult as Xf, SandboxUsageLedger as Xg, SteerableSandboxSession as Xh, queueOf as Xi, authorStrategy as Xl, CoordinationTransportOptions as Xm, SearchSpecOwnedOption as Xn, resolveEntrySymbol as Xo, LeakedReservation as Xp, InteractiveWorkerKeyInput as Xr, RetainedInteractiveRunHandle as Xs, boxSurfaceReader as Xt, Outcome as Xu, createCodexRolloutStoreReader as Xv, CodexExecutionPolicy as Xx, RuntimeStreamEventSummary as Xy, DriverAttemptStop as Y, LoopIterationEndedPayload as YC, RetainedRunCancellation as YS, DelegationProgress as Y_, EnvironmentTeardownReceipt as Ya, MapOnSettleRoute as Yb, BenchmarkTaskRow as Yc, PursuitNodePlatform as Yd, IsolatedCheckOptions as Yf, SandboxServedBackend as Yg, SteerableSandboxArgs as Yh, freeSlots as Yi, assertStrategyContract as Yl, CoordinationReadAccess as Ym, SearchSpecInputs as Yn, officialChecksFromMeta as Yo, BudgetReadout as Yp, InteractiveWorkerEnvironment as Yr, RetainedInteractiveEnvironmentInput as Ys, WatchedSurface as Yt, LoopShape as Yu, addHarnessUsage as Yv, CodexTokenUsage as Yx, RuntimeStreamEventSink as Yy, DriverFailureClass as Z, LoopLineageOptions as ZC, RetainedRunEffect as ZS, DelegationStatus as Z_, ExecutorAccounting as Za, MapTraversalEvent as Zb, printBenchmarkReport as Zc, PursuitNodeTiming as Zd, runIsolatedCheck as Zf, extractLlmCallEvent as Zg, createSteerableSandboxSession as Zh, rollingDispatch as Zi, defineStrategy as Zl, serveCoordinationMcp as Zm, assertSearchSpec as Zn, sandboxCheckRunner as Zo, ReservationFloor as Zp, InteractiveWorkerOptions as Zr, RetainedInteractiveStartMaterial as Zs, fsSurfaceReader as Zt, Persona as Zu, harnessUsageIsEmpty as Zv, SqlRunOwnershipError as Zx, RuntimeTelemetryOptions as Zy, RunAgentTaskOptions as _, captureBoundHarnessTranscript as _C, readRunState as _S, UiAuditorDelegate as __, SupervisorOpts as _a, DecideGate as _b, loopUntil as _c, LeaderboardScore as _d, SuperviseOptions as _f, resolveAgentEnvironmentProvider as _g, DriverRetryPolicy as _h, graphWorkspace as _i, LocalMcpMaterialization as _l, ResolveSupervisorTools as _m, closingWorkerNote as _n, ChatWorkerSeamOptions as _o, InMemoryRunContextOptions as _p, readWorkerCancellation as _r, Deliverable as _s, AgentEnvironmentProvider$1 as _t, CorpusFilter as _u, readTraceContextFromEnv as _v, RuntimeRunCost as _w, McpToolAnnotations as _x, ProfileKeyOf as _y, AgentKnowledgeProvider as a, RetainedRunTurnInput as aC, SpawnForestNode as aS, ToolLoopCompaction as a_, ResultBlobStore as aa, WorktreeCommandResult as ab, PrivateCasOffloadReport as ac, readHarnessTranscriptSessions as ad, ObserverJournal as af, SharedBoxCloseReceipt as ag, ContinuationAppend as ah, setGraphStrings as ai, loopDispatch as al, RootStreamRecord as am, WorktreeCliExecutorOptions as an, Runtime as ao, IsolatedCheckCpuIdentity as ap, TRACE_SUMMARY_SCHEMA as ar, StreamAgentTurnOptions as as, MakeWorkerAgent as at, harvestCorpus as au, UiFindingScreenshot as av, LoopTraceEmitter as aw, PeerMailReadout as ax, CodeModeToolset as ay, RuntimeSession as b, persistHarnessTranscript as bC, cancelRun as bS, FleetHandle as b_, ProviderModelAttemptEvidence as ba, JsonScalar as bb, selectValidWinner as bc, DeclaredCheck as bd, createWorkerSlots as bf, ProviderPromptOptions as bg, SpawnResourceBytes as bh, GraphCorpusSummary as bi, McpSpawnFault as bl, SupervisorNodeContext as bm, spendFromUsageEvents as bn, createChatSessionStore as bo, createFileRunContext as bp, safeWorkerFile as br, OpenSandboxRunPromptOptions as bs, AgentEnvironmentSummary as bt, EqualKOnCostOptions as bu, DelegationPersistenceError as bv, RuntimeRunPersistenceAdapter as bw, BusEvent as bx, pairwiseSignificance as by, AgentTaskContext as c, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS as cC, FileResultBlobStore as cS, ToolLoopToolCall as c_, TraceRootReceipt as ca, GitRunner as cb, equalKOnCost as cc, RetainedFileOutput as cd, observerRecordDigest as cf, SharedBoxStats as cg, ContinuationPanelInput as ch, GraphSessionObservationOptions as ci, TERMINAL_DECISIONS as cl, SettledUsage as cm, AttachWorkerOptions as cn, WorkerTraceEvidence as co, IsolatedCheckCpuSessionResult as cp, RunTraceSources as cr, EvolutionAuthor as cs, SpawnPreflight as ct, ObservationError as cu, KnowledgeItem as cv, MountManifestEntry as cw, PeerMailbox as cx, runCodeMode as cy, AgentTaskStatus as d, HarnessTranscriptCapture as dC, SpawnJournalReadOptions as dS, CoderDelegate as d_, RootHandle as da, EventAcknowledgement as db, runPersonified as dc, LeaderboardBenchTask as dd, supervise as df, ROUTER_CLIENT_HEADER as dg, ContinuationProfile as dh, graphFlowSpawnProfile as di, inlineSandboxClient as dl, CoordinationToolFace as dm, attachWorker as dn, WorkerEventEntry as do, SeatSelection as dp, WorkerSteerAcknowledgement as dr, StrategyEvolutionConfig as ds, SpawnRefusalCause as dt, defaultAnalystInstruction as du, ResearchSource as dv, RunProvenance as dw, createPeerMailbox as dx, Interval as dy, RetainedRunHandle as eC, materializeTreeView as eS, RouterTransportConfig as e_, GraphDesignerExtraTools as ea, createRuntimeEventCollector as eb, resolveSandboxClient as ec, RunPersonified as ed, PursuitRunProjection as ef, InboxLease as eg, CoordinationDeliveryEvidence as eh, InPlaceCliExecutorOptions as ei, LoopDispatchOptions as el, ReservationShortfall as em, analystsFromRegistry as en, ExecutorResult as eo, IsolatedCheckOutputFailure as ep, searchSpecDigest as er, visibleCheckScore as es, CoordinationStats as et, strategyAuthorSystemPrompt as eu, FeedbackRefersTo as ev, LoopResult as ew, PEER_MAIL_WIRE_KEY as ex, decodeHarnessUsage as ey, BackendErrorDetail as f, HarnessTranscriptEvidence as fC, SpawnJournalReadRecord as fS, CoderReview as f_, RootSegment as fa, LeadMessage as fb, FileCorpus as fc, LeaderboardBenchmarkAdapter as fd, superviseFleetCapabilities as ff, sharedBoxRefusal as fg, PanelFinding as fh, GraphFileNeed as fi, InProcessOnPrompt as fl, CoordinationVerbs as fm, readWorkerInteractiveBinding as fn, WorkerEventPage as fo, SeatSelectionInput as fp, WorkerSteerRequest as fr, StrategyTournament as fs, SuperviseProfileEntry as ft, observe as fu, ResearchTask as fv, SandboxClient as fw, isPeerMailEnvelope as fx, Leaderboard as fy, OpenAIChatToolChoice as g, ReadableEnvironment as gC, RunState as gS, DetachedWinnerSelection as g_, Supervisor as ga, WorkerWatchOptions as gb, flatWidenGate as gc, LeaderboardScenario as gd, AuthorizedSpawnContext as gf, createAgentEnvironmentProviderRegistry as gg, DriverReentry as gh, LoadedGraphFile as gi, HttpMcpServerSpec as gl, ResolveDriveHarness as gm, WorkerEvidenceInput as gn, ChatTransportTool as go, InMemoryRunContext as gp, legacySupervisorRunDir as gr, strategyTournament as gs, AgentEnvironmentEvent$1 as gt, Corpus as gu, createPropagatingTraceEmitter as gv, RuntimeRunCompleteInput as gw, JsonRpcResponse as gx, PairwiseVerdict as gy, OpenAIChatTool as h, HarnessTranscriptUnavailableReason as hC, FileSpawnJournal as hS, DetachedSessionDelegateOptions as h_, SteerableRootHandle as ha, ToolOutcomeEvent as hb, fanout as hc, LeaderboardRunContext as hd, AuthorizedSpawn as hf, AgentEnvironmentProviderRegistry as hg, DriverContractState as hh, LoadGraphFileOptions as hi, inProcessSandboxClient as hl, ObserveSupervisorNodeEvent as hm, VERIFY_TAIL_CHARS as hn, ChatTransportExecutorOptions as ho, subscriptionUsageLimitSignal as hp, fileEscalateQuestion as hr, runStrategyEvolution as hs, AgentEnvironmentCapabilities$1 as ht, CombinatorShape as hu, TraceContext as hv, Validator as hw, JsonRpcMessage as hx, PairwiseOptions as hy, AgentExecutionBackend as i, RetainedRunStartMaterial as iC, SpawnForestMissingTree as iS, ToolLoopChat as i_, delegate as ia, WorktreeCheckRunner as ib, PrivateCasDurableStore as ic, ShapeRegistry as id, FileObserverJournal as if, DEFAULT_SHARED_BOX_WORKERS as ig, CheckRead as ih, setGraphProfile as ii, loopCampaignDispatch as il, createBudgetPool as im, worktreeFanout as in, HeldRelease as io, IsolatedCheckCpuEvidence as ip, TRACE_ROOT_SCHEMA as ir, CollectedAgentTurn as is, GraphSubtasks as it, HarvestReport as iu, UiFinding as iv, LoopTokenUsage as iw, PeerMailOutcome as ix, CodeModeToolsOptions as iy, Spend as j, retainHarnessTranscript as jC, ConfigError as jS, DelegationResumeDriver as j_, ReenteredWorkers as ja, QuestionEscalationRecord as jb, PairedCommandMeasurement as jc, NextPursuitVersionInput as jd, EdgeTraversal as jf, createActivityLog as jg, McpEventSource as jh, graphRegistry as ji, CorpusReadbackOptions as jl, StopRule as jm, jjWorkspace as jn, CheckOutcome as jo, formatPromptHandle as jp, RemoteSupervisorTree as jr, S3PrivateCasStore as js, ExecRequest as jt, PipelineStage as ju, gateOnDeliverable as jv, TraceSource as jx, plateauLength as jy, ResourceLimit as k, readBoundHarnessSessions$1 as kC, AgentEvalErrorCode as kS, DelegationRecord as k_, SpawnModelSubstitution as ka, QuestionDecision as kb, PairedCommandCall as kc, JudgedPursuitVersion as kd, AgentGraph as kf, TeamProgress as kg, EventSubscriptionStore as kh, graphDigest as ki, AgenticTool as kl, ProgressView as km, WorkspaceRun as kn, RunCancellationReason as ko, dumbContinuationFailPrompt as kp, RemoteSupervisorReader as kr, AcquireOptions as ks, CreateAgentEnvironmentInput$1 as kt, PanelSpec as ku, DeliverableSpec as kv, SessionMessageLike as kx, areaUnderCurve as ky, AgentTaskRunResult as l, HarnessTranscriptArtifact as lC, replaySpawnTree as lS, FeedbackEvent as l_, WorkspaceCheckpointMarker as la, AwaitWakeInput as lb, trajectoryReport as lc, DefinedLeaderboard as ld, PursuitFork as lf, SharedWorkerIdentity as lg, ContinuationPanelResult as lh, ObservedSessionFacts as li, TerminalDecision as ll, supervisorAgent as lm, WorkerInteractiveBinding as ln, WorkerTraceUnavailableReason as lo, createIsolatedCheckCpuSession as lp, runToolSpans as lr, EvolutionReport as ls, SpawnPreflightContext as lt, ObserveInput as lu, KnowledgeUpdate as lv, MountRecorder as lw, PeerMailboxOptions as lx, AxisScoresOf as ly, OpenAIChatResponseFormat as m, HarnessTranscriptUnavailable as mC, readSpawnJournal as mS, DelegateRunCtx as m_, RootSignal as ma, ManagerWake as mb, renderCorpusToInstructions as mc, LeaderboardIterationInfo as md, workerFromBackend as mf, AgentEnvironmentProviderRef as mg, admitContinuationPolicy as mh, GraphFileSeat as mi, InProcessSandboxClientOptions as ml, DriveHarnessOwnerContext as mm, NOTE_MAX_CHARS as mn, ChatSessionStore as mo, SelectSeat as mp, cancelWorker as mr, TournamentRow as ms, AgentEnvironment$1 as mt, AssertTraceDerivedFindings as mu, researcherProfile as mv, ValidationCtx as mw, peerMailVerbNames as mx, LeaderboardRow as my, AgentBackendContext as n, RetainedRunReplayPoint as nC, SpawnForestEvent as nS, ToolSpec as n_, DelegateOptions as na, sanitizeKnowledgeReadinessReport as nb, profileOptimizerModelCall as nc, ShapeBudget as nd, PursuitStatus as nf, PeerInboxMessage as ng, FileCoordinationLog as nh, readGraphProfile as ni, SuperviseDispatchOptions as nl, ReservationTicket as nm, AuthoredHarness as nn, HeldEnvironment as no, validateIsolatedCheckOutputs as np, createScope as nr, AgentTurnInput$1 as ns, CoordinationToolsOptions as nt, HarvestError as nu, UiAuditLensFilter as nv, LoopStartedPayload as nw, PeerMailEvent as nx, CodeModeTool as ny, AgentRuntimeEvent as o, StartRetainedRunInEnvironmentOptions as oC, SpawnForestTree as oS, ToolLoopCompactionOptions as o_, SpawnEvent as oa, WorktreeHarnessResult as ob, PrivateCasOptions as oc, ProviderAsSandboxClientOptions as od, ObserverRecord as of, SharedBoxPlacement as og, ContinuationEntry as oh, DeepReadonly as oi, superviseDispatch as ol, readRootStream as om, WorktreePatchArtifact as on, WorkerInteractiveSession as oo, IsolatedCheckCpuResources as op, TraceRootArtifact as or, collectAgentTurn as os, PeerAuditAccess as ot, Observation as ou, UiFindingSeverity as ov, LoopTraceEvent as ow, PeerMailRefusal as ox, RunCodeModeOptions as oy, KnowledgeReadinessDecision as p, HarnessTranscriptFile as pC, SpawnJournalReadResult as pS, CoderReviewer as p_, RootSegmentEntry as pa, ManagerReentryState as pb, InMemoryCorpus as pc, LeaderboardFlagSpec as pd, superviseWithTestBrain as pf, sharedWorkerClientName as pg, VerdictSummary as ph, GraphFileResolutionError as pi, InProcessPromptCtx as pl, DriveHarness as pm, EVIDENCE_MAX_CHARS as pn, ChatCompletionsTransport as po, SeatStage as pp, WriteWorkerSteerOptions as pr, TournamentCell as ps, WorkerSpawnContext as pt, renderReport as pu, ResearcherProfileOptions as pv, SelectionReceipt as pw, peerMailTools as px, LeaderboardOptions as py, RetainedPendingCause as q, LoopEndedPayload as qC, RetainedRunAdmissionHook as qS, DelegationHistoryArgs as q_, RootMaterialization as qa, WorkerResumeContext as qb, BenchmarkReport as qc, PursuitCostProvenance as qd, IsolatedCheckBoxEvidence as qf, mapSandboxEvent as qg, DEFAULT_SANDBOX_STEERING_MAX_TURNS as qh, DispatchUnit as qi, StrategyResult as ql, CoordinationMcpHandle as qm, SEARCH_SPEC_CORRELATION_KEY as qn, filterAuthoredAsserts as qo, BudgetPool as qp, recordProfileRun as qr, RecoverRetainedInteractiveRunOptions as qs, SurfaceReadOutcome as qt, DefinePersona as qu, CodexRolloutTurn as qv, LOCAL_HARNESSES as qx, RuntimeEventCollector as qy, AgentBackendInput as r, RetainedRunSnapshot as rC, SpawnForestInDoubtNode as rS, ToolLoopCallContext as r_, defaultDelegateBudget as ra, InPlaceHarnessResult as rb, PrivateCasArtifactPort as rc, ShapeContext as rd, projectPursuit as rf, DEFAULT_SHARED_BOX_RESOURCES as rg, PriorCoordination as rh, readGraphStrings as ri, SuperviseOptionsForDispatch as rl, ReserveOptions as rm, WorktreeFanoutOptions as rn, HeldForContinuation as ro, IsolatedCheckCpuCounters as rp, ScopeArgs as rr, AgentTurnUsage as rs, GraphSubtaskPreparation as rt, HarvestFailure as ru, UiAuditorDelegationOutput as rv, LoopTeardownFailedPayload as rw, PeerMailLimits as rx, CodeModeToolContext as ry, AgentRuntimeEventSink as s, StartRetainedRunOptions as sC, loadSpawnForest as sS, ToolLoopMessageRecord as s_, SpawnJournal as sa, WorktreeProfileMaterializationReceipt as sb, createPrivateCasArtifactPort as sc, providerAsSandboxClient as sd, ObserverRecordKind as sf, SharedBoxPlacementOptions as sg, ContinuationPanel as sh, ReadonlyAgentProfile as si, LocalSandboxClientOptions as sl, readRootStreamReceipt as sm, createWorktreeCliExecutor as sn, WorkerInteractiveUnavailableReason as so, IsolatedCheckCpuSession as sp, TraceSummary as sr, streamAgentTurn as ss, SettledWorker as st, ObservationAnalysis as su, UiLens as sv, LoopWinner as sw, PeerMailSendInput as sx, createCodeModeTools as sy, AgentAdapter as t, RetainedRunIntentAdmission as tC, SpawnForest as tS, RouterRouting as t_, graphDesignerExtraTools as ta, createRuntimeStreamEventCollector as tb, profileChatClient as tc, RunPersonifiedOptions as td, PursuitRunTotals as tf, InboxMessage as tg, CoordinationLog as th, createInPlaceCliExecutor as ti, LoopOptionsForDispatch as tl, ReservationStage as tm, failuresAnalyst as tn, ExecutorTeardownWarning as to, IsolatedCheckOutputOptions as tp, settledToIteration as tr, AgentTurnBackend as ts, CoordinationTools as tt, HarvestCorpusOptions as tu, ResearchOutputShape as tv, LoopSandboxPlacement as tw, PeerMailEnvelope as tx, CodeModeStore as ty, AgentTaskSpec as u, HarnessTranscriptBinding as uC, SpawnJournalCursor as uS, FeedbackStore as u_, RecursiveReservationPolicy as ua, CoordinationEvent as ub, definePersona as uc, LeaderboardBenchScore as ud, RUN_FORK_CORRELATION_KEYS as uf, sharedBoxPlacement as ug, ContinuationPolicy as uh, graphFromSessionFacts as ui, defaultSelectWinner as ul, supervisorAgentWithTestBrain as um, WorkerInteractiveProviderSource as un, WorkerEventCursor as uo, SeatSegment as up, WorkerCancellation as ur, EvolutionStrategy as us, SpawnRefusal as ut, ObserveOptions as uu, ResearchOutput as uv, OutputAdapter as uw, claimsAuthority as ux, GroupOf as uy, RunAgentTaskStreamOptions as v, captureHarnessTranscript as vC, RunCancelRequest as vS, detachedSessionDelegate as v_, FleetYield as va, GateDecision as vb, panel as vc, LeaderboardSpec as vd, SuperviseTestOptions as vf, ProviderExecutorOptions as vg, ResolveSpawnResourcePathsResult as vh, loadGraphFile as vi, MaterializeLocalMcpOptions as vl, SupervisorAgentDeps as vm, composeWorkerEvidence as vn, chatTransportExecutor as vo, RunContext as vp, readWorkerSteerAcknowledgement as vr, OpenSandboxRunBeforeStartContext as vs, AgentEnvironmentQuery as vt, CorpusRecord as vu, DelegationTraceSpan as vv, RuntimeRunHandle as vw, McpToolDescriptor as vx, ScoreOf as vy, RuntimeFailureCode as w, HarnessTranscriptMetadata as wC, InMemorySpawnJournal as wS, createSiblingSandboxExecutor as w_, SupervisedResult as wa, RouteMatch as wb, RegistryAnalyzeProjection as wc, checkProgramDigest as wd, GraphCheckNodes as wf, ActivityLog as wg, resolveSpawnResourcePaths as wh, GraphSelection as wi, materializeLocalMcp as wl, ManagerWakePolicy as wm, withUntrackedArtifacts as wn, asAuthoredProfile as wo, PromptRegistry as wp, writeWorkerSteer as wr, openSandboxRun as ws, AgentSessionStatus$1 as wt, FanoutWinnerSelector as wu, CoderOutput as wv, PublishOptions as wx, renderPairwiseMarkdown as wy, RuntimeSessionStore as x, BoundHarnessSession as xC, readRunCancelRequest as xS, FleetWorkspaceExecutorOptions as x_, ProviderModelExecutionEvidence as xa, RouteFlow as xb, verify as xc, DeclaredCheckPlacement as xd, SuperviseRegistry as xf, providerAsExecutor as xg, SpawnResourceRead as xh, GraphRegistryDir as xi, StdioMcpConnection as xl, SupervisorNodeContextSeed as xm, CopyOptions as xn, AuthoredProfile as xo, createInMemoryRunContext as xp, supervisorRunDir as xr, SandboxRun as xs, AgentProfile$2 as xt, EqualKVerdict as xu, DelegationStore as xv, RuntimeRunRow as xw, BusRecord as xx, renderLeaderboardHtml as xy, RuntimeCanonicalStreamEvent as y, harnessTranscriptArtifact as yC, RunCancellation as yS, DelegationExecutor as y_, NoWinnerError as ya, GateRequest as yb, pipeline as yc, defineLeaderboard as yd, WorkerSlots as yf, ProviderLeafOut as yg, ResolvedSpawnResourcePath as yh, GraphCorpusGroup as yi, McpListedTool as yl, SupervisorAgentTestDeps as ym, settledWorkerOut as yn, chatWorkerSeam as yo, RunContextLease as yp, readWorkerSteerRequests as yr, OpenSandboxRunOptions as ys, AgentEnvironmentStatus as yt, EqualKArm as yu, composeLoopTraceEmitters as yv, RuntimeRunOptions as yw, McpTransport as yx, leaderboard as yy, Settled as z, TokenUsageProvenance as zC, RecoverRetainedRunIntentOptions as zS, DelegateCodeConfig as z_, ExecutorExecutionBinding as za, AuthorizeDownMessage as zb, observedModelMatchesDeclared as zc, SuperviseGraphPursuitOptions as zd, TraversalContinuity as zf, mcpSecretEnvMetadataKey as zg, CliInPlaceSeam as zh, storedGraphDigests as zi, runAgentic as zl, composeReentryTask as zm, createSupervisor as zn, StructuralRolloutPolicy as zo, createSupervisorSpanRecorder as zp, provisionSupervisor as zr, startRetainedRun as zs, computeFindingId$1 as zt, TrajectoryReportOptions as zu, deterministicCompletion as zv, AnalyzeOnSettleRoute as zx, OtelAttribute as zy };
19790
- //# sourceMappingURL=types-9xsn2GGY.d.ts.map
19796
+ //# sourceMappingURL=types-CFmKHKiN.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "10.0.4",
3
+ "version": "10.0.5",
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 { d as writeAtomicDurableFile } from "./durable-file-lXnojyij.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-file-lXnojyij.js","names":["fsConstants"],"sources":["../src/durable/run-fence.ts","../src/durable/durable-writer.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 { isMainThread } from 'node:worker_threads'\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// Set on the durable writer thread (durable-writer-thread.ts): the one thread that runs claimed writes.\nlet writerThread = false\n\n/** Mark this thread as the process's durable writer. @internal */\nexport function markDurableWriterThread(): void {\n writerThread = true\n}\n\n/** True on the durable writer thread. @internal */\nexport function onDurableWriterThread(): boolean {\n return writerThread\n}\n\n/** The claim the current asynchronous context carries, if any. @internal */\nexport function currentRunWriteClaim(): RunWriteClaim | undefined {\n return claims.getStore()\n}\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 // A claimed write on the main thread would hold the run's mutation lock against the durable\n // writer and block the event loop on the disk: it must be sent through `runFenced`.\n if (isMainThread && !writerThread) {\n throw new Error('a claimed run write reached the main thread; send it through runFenced')\n }\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 * The durable writer: one thread per process that performs every claimed run-directory write.\n *\n * A fenced write is synchronous by contract (lock, claim check, mutation and fsync with no await\n * between them), and on a saturated disk its open, link and fsync calls wait on the filesystem\n * journal: a coordinator whose event loop ran them was measured blocked 20 to 70 s at a time.\n * Here the same synchronous code runs on its own thread. Only that thread takes a run directory's\n * mutation lock in this process, so a caller never spins on a lock this process holds.\n *\n * - `durableCall` blocks the calling thread until the writer answers, exactly as the inline write\n * did, for callers whose contract is synchronous.\n * - `durableCallAsync` resolves with the writer's answer and leaves the event loop free.\n * - On the writer thread both run the operation inline, so a fenced helper may call another.\n * - Operations run in the order they were sent, sync and async alike.\n * - A call the writer does not answer within `DURABLE_WRITER_DEADLINE_MS` fails, and the writer\n * keeps running. A writer that errors or exits fails every waiting and later call and is never\n * replaced. Nothing falls back to writing on the calling thread.\n *\n * @internal\n */\n\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { isMainThread, MessageChannel, receiveMessageOnPort, Worker } from 'node:worker_threads'\nimport {\n currentRunWriteClaim,\n markDurableWriterThread,\n onDurableWriterThread,\n type RunWriteClaim,\n} from './run-fence'\n\n/** Longer than the worst fsync measured on a saturated disk (70 s), so only a dead writer trips it. */\nexport const DURABLE_WRITER_DEADLINE_MS = 180_000\n\n/** A named operation and its JSON arguments; names resolve in `durable-writer-thread.ts`. */\nexport interface DurableOperation {\n readonly name: string\n readonly args: readonly unknown[]\n}\n\ninterface Request extends DurableOperation {\n readonly id: number\n readonly claim: RunWriteClaim | undefined\n readonly sync: boolean\n}\n\ntype Reply =\n | { readonly id: number; readonly ok: true; readonly value: unknown }\n | {\n readonly id: number\n readonly ok: false\n readonly error: {\n message: string\n name?: string\n code?: string\n stack?: string\n fields?: Record<string, unknown>\n }\n }\n\nlet runInline: ((operation: DurableOperation) => unknown) | undefined\n\n/** Called by the writer thread's entry: operations sent from this thread now run inline. */\nexport function becomeDurableWriter(inline: (operation: DurableOperation) => unknown): void {\n markDurableWriterThread()\n runInline = inline\n}\n\n/**\n * Whether a write goes to the writer: a claimed write made by the main thread, or with `always`,\n * any write the main thread makes (run-directory acquisition and release take the same lock before\n * a claim exists). Unclaimed writes keep their caller-owned single-writer contract and run inline,\n * and other worker threads never start a second writer that would contend for the same lock.\n */\nexport function routesToDurableWriter(always = false): boolean {\n return (\n !onDurableWriterThread() && isMainThread && (always || currentRunWriteClaim() !== undefined)\n )\n}\n\n/**\n * Run the fenced operation `fn(...args)`: inline when the write is not routed, otherwise on the\n * writer under the caller's claim, blocking this thread until it answers. `fn` takes its own fence\n * (`fenceRunWrite` or `mutateRunClaim`) and is registered under `name` in durable-writer-thread.ts;\n * arguments and the result cross the thread as structured clones.\n */\nexport function runFenced<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): T {\n return routesToDurableWriter() ? durableCall<T>({ name, args }) : fn(...args)\n}\n\n/** `runFenced` without blocking: the event loop stays free while the writer works. */\nexport function runFencedAsync<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter()) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\n/** `runFencedAsync` for run-directory acquisition and release, routed from the main thread even\n * before a claim exists, since they take the same mutation lock the writer holds. */\nexport function runFencedAlways<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter(true)) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\ninterface Writer {\n readonly worker: Worker\n readonly syncReplies: MessageChannel\n readonly signal: Int32Array\n readonly pending: Map<\n number,\n { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >\n}\n\nlet writer: Writer | undefined\n// Set when the writer errors or exits. It is never replaced: it may have died inside a fence\n// holding the run's mutation lock under this live pid, and a new writer could only spin on that\n// lock. Every later routed write fails at once with this cause.\nlet writerDeath: Error | undefined\nlet nextId = 0\n\n// Errors an operation throws are rebuilt on the caller's thread as their own class, with their\n// own fields, so `instanceof` and fields such as a lock holder survive the thread boundary.\nconst errorClasses = new Map<string, { prototype: Error }>()\n\n/** Rebuild errors named `name` thrown on the writer as instances of `errorClass`. @internal */\nexport function registerDurableErrorClass(name: string, errorClass: { prototype: Error }): void {\n errorClasses.set(name, errorClass)\n}\n\n/**\n * The writer's entry beside this module: TypeScript in a source checkout, JavaScript in a built\n * package. A tool that bundles Runtime again must emit `src/durable/durable-writer-thread.ts` as\n * `durable-writer-thread.js` (or `.mjs`) beside the bundle; without it, writes fail with this cause.\n */\nfunction threadUrl(): URL {\n const here = import.meta.url\n if (here.endsWith('.ts')) return new URL('./durable-writer-thread.ts', here)\n for (const name of ['./durable-writer-thread.js', './durable-writer-thread.mjs']) {\n const candidate = new URL(name, here)\n if (existsSync(candidate)) return candidate\n }\n throw new Error(\n `durable writer entry durable-writer-thread.js is not beside ${fileURLToPath(here)}; a bundle of Runtime must emit it there`,\n )\n}\n\nfunction start(): Writer {\n const url = threadUrl()\n // Source checkouts (tests) load the TypeScript entry through tsx; a built package ships JavaScript.\n // Only what the entry needs: some of the parent's flags (--expose-gc) are refused in a worker.\n const execArgv = url.pathname.endsWith('.ts')\n ? ['--import', createRequire(import.meta.url).resolve('tsx')]\n : []\n const syncReplies = new MessageChannel()\n const signal = new Int32Array(new SharedArrayBuffer(4))\n const worker = new Worker(fileURLToPath(url), {\n execArgv,\n workerData: { syncReplies: syncReplies.port2, signal },\n transferList: [syncReplies.port2],\n })\n worker.unref()\n const state: Writer = { worker, syncReplies, signal, pending: new Map() }\n const die = (error: Error) => {\n writerDeath ??= error\n for (const waiting of state.pending.values()) {\n clearTimeout(waiting.timer)\n waiting.reject(writerDeath)\n }\n state.pending.clear()\n }\n worker.on('message', (reply: Reply) => {\n const waiting = state.pending.get(reply.id)\n // A reply whose caller already gave up at its deadline has nobody to answer.\n if (!waiting) return\n state.pending.delete(reply.id)\n clearTimeout(waiting.timer)\n if (state.pending.size === 0) worker.unref()\n if (reply.ok) waiting.resolve(reply.value)\n else waiting.reject(revive(reply.error))\n })\n worker.on('error', (error: Error) =>\n die(new Error(`durable writer failed: ${error.message}`, { cause: error })),\n )\n worker.on('exit', (code) => die(new Error(`durable writer exited with code ${code}`)))\n return state\n}\n\nfunction current(): Writer {\n if (writerDeath !== undefined) throw writerDeath\n writer ??= start()\n return writer\n}\n\nfunction revive(error: Extract<Reply, { ok: false }>['error']): Error {\n const errorClass = error.name === undefined ? undefined : errorClasses.get(error.name)\n const revived: Error = errorClass ? Object.create(errorClass.prototype) : new Error(error.message)\n return Object.assign(revived, error.fields ?? {}, {\n message: error.message,\n name: error.name ?? 'Error',\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n })\n}\n\nfunction overdue(operation: DurableOperation): Error {\n // The writer keeps running: stopping it inside a fence would leave the run's mutation lock held.\n return new Error(\n `durable writer did not answer ${operation.name} within ${DURABLE_WRITER_DEADLINE_MS} ms; the writer is still running`,\n )\n}\n\nfunction request(operation: DurableOperation, sync: boolean): Request {\n return {\n id: ++nextId,\n name: operation.name,\n args: operation.args,\n claim: currentRunWriteClaim(),\n sync,\n }\n}\n\n/** Perform `operation` on the writer and wait for it, blocking this thread as the inline write did. */\nexport function durableCall<T>(operation: DurableOperation): T {\n if (onDurableWriterThread()) return runInline!(operation) as T\n const state = current()\n const sent = request(operation, true)\n const deadline = performance.now() + DURABLE_WRITER_DEADLINE_MS\n Atomics.store(state.signal, 0, 0)\n state.worker.postMessage(sent)\n // The writer's exit and error events need this loop, which waits here; the deadline catches a\n // writer killed without a reply (out of memory, native abort) and a backlog that never drains.\n for (;;) {\n for (\n let received = receiveMessageOnPort(state.syncReplies.port1);\n received;\n received = receiveMessageOnPort(state.syncReplies.port1)\n ) {\n const reply = received.message as Reply\n // An older id is the late answer to a call that already failed at its deadline.\n if (reply.id !== sent.id) continue\n if (!reply.ok) throw revive(reply.error)\n return reply.value as T\n }\n const remaining = deadline - performance.now()\n if (remaining <= 0) throw overdue(operation)\n Atomics.wait(state.signal, 0, 0, remaining)\n Atomics.store(state.signal, 0, 0)\n }\n}\n\n/** Perform `operation` on the writer without blocking this thread. */\nexport function durableCallAsync<T>(operation: DurableOperation): Promise<T> {\n if (onDurableWriterThread()) {\n try {\n return Promise.resolve(runInline!(operation) as T)\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let state: Writer\n try {\n state = current()\n } catch (error) {\n return Promise.reject(error)\n }\n const sent = request(operation, false)\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n state.pending.delete(sent.id)\n if (state.pending.size === 0) state.worker.unref()\n reject(overdue(operation))\n }, DURABLE_WRITER_DEADLINE_MS)\n timer.unref()\n state.pending.set(sent.id, { resolve: resolve as (value: unknown) => void, reject, timer })\n state.worker.ref()\n state.worker.postMessage(sent)\n })\n}\n\nexport type { Reply as DurableWriterReply, Request as DurableWriterRequest }\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 appendFileSync,\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\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 { runFenced, runFencedAlways } from '../../durable/durable-writer'\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 // Content computed from the new file's own stat cannot cross a thread; its one caller, run-lock\n // acquisition, already runs on the durable writer.\n return typeof content === 'string'\n ? runFenced('publishExclusiveDurableFile', publishExclusiveFenced, filePath, content, options)\n : publishExclusiveFenced(filePath, content, options)\n}\n\n/**\n * `publishExclusiveDurableFile` without blocking the calling thread on the disk: from the main\n * thread the write runs on the durable writer whether or not a run claim is held.\n */\nexport function publishExclusiveDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): Promise<boolean> {\n return runFencedAlways(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n filePath,\n content,\n options,\n )\n}\n\n/** The fenced exclusive publication the durable writer runs. @internal */\nexport function publishExclusiveFenced(\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/**\n * Append whole lines to a run file under the fence, creating `directory` first when given. Each\n * line is one O_APPEND write (well under PIPE_BUF), so concurrent writers never interleave; there\n * is no fsync, as for the observability logs that use it.\n */\nexport function appendRunLines(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n runFenced('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** `appendRunLines` without blocking the calling thread on the disk, claimed or not. */\nexport function appendRunLinesAsync(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): Promise<void> {\n return runFencedAlways('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** The fenced line append the durable writer runs. @internal */\nexport function appendRunLinesFenced(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n fenceRunWrite(() => {\n if (options.directory !== undefined) mkdirSync(options.directory, { recursive: true })\n const fd = openSync(filePath, 'a', options.mode ?? 0o666)\n try {\n for (const line of lines) appendFileSync(fd, line)\n } finally {\n closeSync(fd)\n }\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 runFenced('appendDurableFile', appendDurableFenced, filePath, content, options)\n}\n\n/** The fenced durable append the durable writer runs. @internal */\nexport function appendDurableFenced(\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 if (typeof content === 'string')\n runFenced('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n else writeAtomicFenced(filePath, content, options)\n}\n\n/** `writeAtomicDurableFile` without blocking the calling thread on the disk, claimed or not. */\nexport function writeAtomicDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): Promise<void> {\n return runFencedAlways('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n}\n\n/** The fenced atomic replacement the durable writer runs. @internal */\nexport function writeAtomicFenced(\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":";;;;;;;;;AAcA,MAAM,SAAS,IAAI,kBAA6C;AAChE,MAAM,eAAe,IAAI,kBAAsE;AAG/F,IAAI,eAAe;;AAGnB,SAAgB,0BAAgC;CAC9C,eAAe;AACjB;;AAGA,SAAgB,wBAAiC;CAC/C,OAAO;AACT;;AAGA,SAAgB,uBAAkD;CAChE,OAAO,OAAO,SAAS;AACzB;;AAGA,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,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Ae,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"model-policy-DZnL8Yj9.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/model-identity.ts","../src/runtime/router-auto-evidence.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { harnessTypeSchema } from '@tangle-network/agent-interface'\n\nconst SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u\nconst datedIsoSuffix = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/u\nconst datedCompactSuffix = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/u\nconst datedMonthSuffix = /^(.*)-(\\d{4})-(\\d{2})$/u\n\nexport type SnapshotKind = 'date' | 'opaque'\n\ninterface ModelIdentityParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n}\n\nexport interface CanonicalObservedModelParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n readonly canonical: string\n}\n\n/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */\nexport function observedModelMatchesDeclared(observed: string, declared: string): boolean {\n const observedIdentity = modelIdentityParts(observed)\n const declaredIdentity = modelIdentityParts(declared)\n if (!observedIdentity || !declaredIdentity) return false\n if (\n declaredIdentity.snapshot !== undefined &&\n (observedIdentity.snapshot !== declaredIdentity.snapshot ||\n observedIdentity.snapshotKind !== declaredIdentity.snapshotKind)\n ) {\n return false\n }\n return equivalentModelBase(observedIdentity.base, declaredIdentity.base)\n}\n\n/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */\nexport function mergeObservedModelIdentity(current: string, next: string): string | undefined {\n const currentIdentity = modelIdentityParts(current)\n const nextIdentity = modelIdentityParts(next)\n if (!currentIdentity || !nextIdentity) return undefined\n if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return undefined\n if (\n currentIdentity.snapshot !== undefined &&\n nextIdentity.snapshot !== undefined &&\n (currentIdentity.snapshot !== nextIdentity.snapshot ||\n currentIdentity.snapshotKind !== nextIdentity.snapshotKind)\n ) {\n return undefined\n }\n return currentIdentity.snapshot === undefined && nextIdentity.snapshot !== undefined\n ? next\n : current\n}\n\n/** Return the canonical model and its validated snapshot kind for runtime evidence reduction. */\nexport function canonicalObservedModelParts(\n model: string,\n): CanonicalObservedModelParts | undefined {\n const identity = modelIdentityParts(model)\n if (!identity) return undefined\n const base = identity.base.slice(identity.base.lastIndexOf('/') + 1)\n const canonical =\n identity.snapshot === undefined\n ? base\n : identity.snapshotKind === 'date'\n ? `${base}-${identity.snapshot}`\n : `${base}@${identity.snapshot}`\n return {\n base,\n ...(identity.snapshot !== undefined ? { snapshot: identity.snapshot } : {}),\n ...(identity.snapshotKind !== undefined ? { snapshotKind: identity.snapshotKind } : {}),\n canonical,\n }\n}\n\n/** Return whether an observed identity includes a provider snapshot. */\nexport function observedModelHasSnapshot(model: string): boolean {\n return modelIdentityParts(model)?.snapshot !== undefined\n}\n\n/**\n * Judge one model a provider reported it served against the declared model. A different model is\n * a conflict. The request's own wire id is transport metadata, and a model without a snapshot\n * cannot name what ran, so neither is recorded; a snapshot-bearing match is provider evidence.\n */\nexport function reportedServedModel(\n reported: string,\n declared: string,\n wireModel?: string,\n): 'conflict' | 'record' | 'unrecorded' {\n if (!observedModelMatchesDeclared(reported, declared)) return 'conflict'\n if (reported === wireModel || !observedModelHasSnapshot(reported)) return 'unrecorded'\n return 'record'\n}\n\nfunction modelIdentityParts(model: string): ModelIdentityParts | null {\n if (model.length === 0) return null\n const at = model.lastIndexOf('@')\n if (at < 0) {\n const dated = datedModelIdentity(model)\n if (dated !== undefined) return dated\n return modelLeaf(model).length === 0 ? null : { base: model }\n }\n const base = model.slice(0, at)\n const snapshot = model.slice(at + 1)\n if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) {\n return null\n }\n return { base, snapshot, snapshotKind: 'opaque' }\n}\n\nfunction equivalentModelBase(observed: string, declared: string): boolean {\n const observedPath = modelBaseParts(observed)\n const declaredPath = modelBaseParts(declared)\n if (!samePath(observedPath.path, declaredPath.path)) return servesClaudeAlias(observed, declared)\n\n // A bare id omits provider routing. It can match an explicitly qualified spelling\n // only when the model path is otherwise identical.\n if (\n observedPath.provider === undefined ||\n declaredPath.provider === undefined ||\n sameProvider(observedPath.provider, declaredPath.provider)\n ) {\n return true\n }\n\n // Tangle Router may report the upstream provider's qualified spelling. Preserve this\n // one documented alias without allowing arbitrary provider-to-provider substitutions.\n if (observedPath.provider === 'tangle-router' || declaredPath.provider === 'tangle-router') {\n const router = observedPath.provider === 'tangle-router' ? observedPath : declaredPath\n const upstream = observedPath.provider === 'tangle-router' ? declaredPath : observedPath\n if (upstream.provider === undefined) return false\n return (\n samePath(router.path, upstream.path) ||\n (router.path[0] === upstream.provider && samePath(router.path.slice(1), upstream.path))\n )\n }\n\n return false\n}\n\n// Claude Code serves a family alias (`anthropic/opus`) as its current model (`claude-opus-5-5`).\nfunction servesClaudeAlias(observed: string, declared: string): boolean {\n const route = '^(?:claude-code/)?(?:anthropic/)?'\n const alias = new RegExp(`${route}(opus|sonnet|haiku)$`, 'u').exec(declared)?.[1]\n return alias !== undefined && new RegExp(`${route}claude-${alias}-[\\\\w.-]+$`, 'u').test(observed)\n}\n\n/**\n * Compare provider slugs across catalogs that spell one vendor with or without hyphens,\n * such as `zai` and OpenRouter's `z-ai`. Any other provider difference is a substitution.\n */\nfunction sameProvider(left: string, right: string): boolean {\n return left.replaceAll('-', '') === right.replaceAll('-', '')\n}\n\ninterface ModelBaseParts {\n readonly provider: string | undefined\n readonly path: ReadonlyArray<string>\n}\n\nfunction modelBaseParts(model: string): ModelBaseParts {\n const segments = model.split('/')\n const normalized =\n segments.length > 1 && isHarnessPrefix(segments[0]) ? segments.slice(1) : segments\n if (normalized.length === 1) return { provider: undefined, path: normalized }\n return { provider: normalized[0], path: normalized.slice(1) }\n}\n\nfunction isHarnessPrefix(segment: string | undefined): boolean {\n return segment !== undefined && harnessTypeSchema.safeParse(segment).success\n}\n\nfunction samePath(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index])\n}\n\nfunction modelLeaf(model: string): string {\n return model.slice(model.lastIndexOf('/') + 1)\n}\n\n/**\n * Parse the provider's documented dated snapshot forms.\n *\n * `undefined` means that the model has no dated shape and must be treated as a normal base.\n * `null` means that it has a dated shape but the date is invalid, so identity matching fails.\n */\nfunction datedModelIdentity(model: string): ModelIdentityParts | null | undefined {\n const iso = datedIsoSuffix.exec(model)\n if (iso) {\n const [, base, yearText, monthText, dayText] = iso\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const compact = datedCompactSuffix.exec(model)\n if (compact) {\n const [, base, yearText, monthText, dayText] = compact\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const month = datedMonthSuffix.exec(model)\n if (month) {\n const [, base, yearText, monthText] = month\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}`,\n isValidCalendarMonth(yearText, monthText),\n )\n }\n\n return undefined\n}\n\nfunction buildDatedIdentity(\n base: string | undefined,\n snapshot: string,\n valid: boolean,\n): ModelIdentityParts | null | undefined {\n // A date that is the entire model segment is not a snapshot suffix.\n if (base === undefined || base.length === 0 || base.endsWith('/')) return undefined\n return valid ? { base, snapshot, snapshotKind: 'date' } : null\n}\n\nfunction isValidCalendarDate(\n yearText: string | undefined,\n monthText: string | undefined,\n dayText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined || dayText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n const day = Number(dayText)\n if (year < 2000 || year > 2099 || month < 1 || month > 12 || day < 1 || day > 31) {\n return false\n }\n const date = new Date(Date.UTC(year, month - 1, day))\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n )\n}\n\nfunction isValidCalendarMonth(\n yearText: string | undefined,\n monthText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n return year >= 2000 && year <= 2099 && month >= 1 && month <= 12\n}\n","import { ValidationError } from '../errors'\nimport { observedModelMatchesDeclared } from './model-identity'\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError('Router Auto requires an inline policy and routing receipt')\n }\n return value as Record<string, unknown>\n}\n\n/** Router owns policy parsing. Runtime requires visible model authority before dispatch. */\nexport function assertRouterAutoDeclaration(value: unknown, stream: boolean | undefined): void {\n const policy = object(value)\n if (stream === true) throw new ValidationError('Router Auto requires buffered transport')\n if (\n policy.version !== 1 ||\n typeof policy.id !== 'string' ||\n typeof policy.revision !== 'string' ||\n !Array.isArray(policy.strategies) ||\n policy.strategies.length === 0\n ) {\n throw new ValidationError(\n 'Router Auto requires a versioned inline policy with concrete strategies',\n )\n }\n for (const raw of policy.strategies) {\n const strategy = object(raw)\n if (\n typeof strategy.id !== 'string' ||\n typeof strategy.model !== 'string' ||\n strategy.model === 'tangle/auto' ||\n strategy.model.length === 0\n ) {\n throw new ValidationError('Router Auto strategy model authority is missing')\n }\n }\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined && typeof object(policy[phase]).model !== 'string') {\n throw new ValidationError('Router Auto assessment model authority is missing')\n }\n }\n}\n\n/** An alias does not waive identity checks. Every reported child must match its declared phase. */\nexport function assertRouterAutoResponse(\n policyValue: unknown,\n response: unknown,\n served: string | undefined,\n): void {\n const policy = object(policyValue)\n const receipt = object(object(response).tangle_auto)\n const decision = object(receipt.decision)\n const strategies = policy.strategies as unknown[]\n const selected = strategies.map(object).find((strategy) => strategy.id === decision.strategyId)\n if (\n decision.requestedModel !== 'tangle/auto' ||\n decision.policyId !== policy.id ||\n decision.policyRevision !== policy.revision ||\n typeof decision.policyDigest !== 'string' ||\n !selected ||\n decision.selectedModel !== selected.model ||\n served === undefined ||\n !observedModelMatchesDeclared(served, String(selected.model))\n ) {\n throw new ValidationError(\n 'Router Auto response does not match AgentProfile policy/model authority',\n )\n }\n if (!Array.isArray(receipt.calls) || receipt.calls.length === 0) {\n throw new ValidationError('Router Auto response is missing physical call receipts')\n }\n for (const raw of receipt.calls) {\n const call = object(raw)\n const declared =\n call.phase === 'selector'\n ? object(policy.selector).model\n : call.phase === 'review'\n ? object(policy.review).model\n : call.phase === 'initial' || call.phase === 'escalation'\n ? strategies.map(object).map((strategy) => strategy.model)\n : []\n const allowed = Array.isArray(declared) ? declared : [declared]\n if (\n typeof call.model !== 'string' ||\n !allowed.some(\n (model) =>\n typeof model === 'string' && observedModelMatchesDeclared(call.model as string, model),\n )\n )\n throw new ValidationError('Router Auto physical call exceeds AgentProfile model authority')\n }\n}\n\n/** The concrete authority declared by an inline Auto policy, including paid assessments. */\nexport function routerAutoDeclaredModels(value: unknown): readonly string[] {\n assertRouterAutoDeclaration(value, undefined)\n const policy = object(value)\n const models = (policy.strategies as unknown[]).map((raw) => String(object(raw).model))\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined) models.push(String(object(policy[phase]).model))\n }\n return [...new Set(models)]\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(\n policy.requestTimeoutMs,\n 0,\n `${context}.requestTimeoutMs`,\n Number.MAX_SAFE_INTEGER - Date.now(),\n )\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(\n value: unknown,\n fallback: number,\n context: string,\n maximum = maximumTimerMs,\n): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximum\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximum}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { routerAutoDeclaredModels } from '../router-auto-evidence'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nfunction isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/**\n * The `model` string Runtime sends to cli-bridge for a profile: `harness/provider/model`.\n *\n * Takes the profile's `harness` and `model` (`provider`, `default`). A model already prefixed with\n * its harness or provider is not prefixed again. The harness segment is always added, so a\n * provider named like its harness keeps both: harness `opencode`, provider `opencode`, model\n * `glm-5.3-flash-free` (or `opencode/glm-5.3-flash-free`) returns\n * `opencode/opencode/glm-5.3-flash-free`. Returns the provider/model alone without a harness, the\n * harness alone without a concrete model, and `undefined` with neither.\n *\n * @experimental\n */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n // Always add the harness segment: a provider may share the harness's name. opencode's own keyless\n // provider is `opencode`, so `opencode/glm-5.3-flash-free` is a provider/model pair; reading it as\n // already harness-prefixed sent `opencode/glm-5.3-flash-free`, cli-bridge removed the harness, and\n // opencode received the bare model and could not resolve it (\"Model not found\").\n return `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model. Every missing field is named in ONE refusal, so a caller that cannot see\n * the contract learns it in one round trip, not one per field (#1329).\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n const failures: string[] = []\n if (profile.harness === undefined) {\n failures.push('AgentProfile.harness must be explicit before execution')\n }\n const declared = profile.model?.default\n if (!concreteModelId(declared)) {\n failures.push(\n `AgentProfile.model.default is ${isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n failures.push('AgentProfile.model.provider must be explicit before execution')\n }\n if (failures.length > 0) {\n throw new ConfigError(`${context}: the profile cannot run yet: ${failures.join('; ')}`)\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\ntype ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n /**\n * Take each Router completion over SSE, with or without tools. The Router's request deadline ends\n * when response headers are committed, so a long thinking-model answer needs a stream to finish.\n * Requires the HTTP transport; an injected buffered `complete` transport is refused.\n */\n readonly stream?: boolean\n /**\n * This node's action space is CODE, not JSON tool calls (router-tools backend\n * only): the model is shown `tool_search` + `codemode` instead of the raw tool\n * set, and composes the granted handlers as one QuickJS program. `true` takes\n * host settings or engine defaults; an object can tighten host ceilings and\n * add direct-only tools. `false` selects ordinary tools for this node. Host\n * state and direct-only restrictions survive every enabled profile declaration.\n */\n readonly codeMode?: boolean | ProfileCodeModeSettings\n}\n\n/** The per-node code-mode controls a profile may pin — the seam's subset, minus\n * host-only (wasm/workerUrl) and executor-owned (store) options. */\nexport interface ProfileCodeModeSettings {\n /** Includes time in tools; at most 2,147,483,647 ms. */\n readonly timeoutMs?: number\n readonly memoryLimitBytes?: number\n /** Excess calls queue; Promise.all does not fail simply because the queue is full. */\n readonly concurrency?: number\n /** Bounds total admitted calls, including queued calls. */\n readonly maxCalls?: number\n /** These capabilities keep their direct model tools and are not callable from code. */\n readonly directTools?: ReadonlyArray<string>\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'codeMode',\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read execution controls from the exact profile and reject unknown controls.\n * Credential intent reaches environment providers unchanged; other paths cannot enforce it.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n path: ModelExecutionPath = 'router',\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter(\n (key) =>\n !PROFILE_MODEL_METADATA_KEYS.has(key) && !(path === 'provider' && key === 'credentialSource'),\n )\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n // The credential vocabulary is router | api-key | subscription (agent-sdk #440); `managed` is\n // the deprecated spelling of `router` and stays readable so authored profiles keep parsing.\n if (\n metadata.credentialSource !== undefined &&\n metadata.credentialSource !== 'router' &&\n metadata.credentialSource !== 'api-key' &&\n metadata.credentialSource !== 'subscription' &&\n metadata.credentialSource !== 'managed'\n ) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.credentialSource must be router, api-key, subscription, or the deprecated managed`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n const codeMode = profileCodeModeSettings(metadata.codeMode, context)\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n ...(codeMode !== undefined ? { codeMode } : {}),\n }\n}\n\nconst PROFILE_CODE_MODE_KEYS = new Set([\n 'concurrency',\n 'directTools',\n 'maxCalls',\n 'memoryLimitBytes',\n 'timeoutMs',\n])\n\n/** Validate `AgentProfile.model.metadata.codeMode`: a boolean, or an object pinning\n * exactly the subset a node may choose (host-only wasm/workerUrl and the\n * executor-owned store are refused — those belong to the seam). */\nfunction profileCodeModeSettings(\n value: unknown,\n context: string,\n): boolean | ProfileCodeModeSettings | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'boolean') return value\n const label = `${context}: codeMode`\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ConfigError(`${label} must be a boolean or an object of engine settings`)\n }\n const input = value as Record<string, unknown>\n const unknown = Object.keys(input).filter((key) => !PROFILE_CODE_MODE_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${label} refuses unsupported fields: ${unknown.join(', ')} (allowed: ${[...PROFILE_CODE_MODE_KEYS].join(', ')}; wasm/workerUrl/store belong to the executor seam)`,\n )\n }\n const timeoutMs = positiveInteger(input.timeoutMs, `${label}.timeoutMs`)\n const memoryLimitBytes = positiveInteger(input.memoryLimitBytes, `${label}.memoryLimitBytes`)\n const concurrency = positiveInteger(input.concurrency, `${label}.concurrency`)\n const maxCalls = positiveInteger(input.maxCalls, `${label}.maxCalls`)\n const directTools = input.directTools\n if (\n directTools !== undefined &&\n (!Array.isArray(directTools) || directTools.some((name) => typeof name !== 'string' || !name))\n ) {\n throw new ConfigError(`${label}.directTools must be an array of tool names`)\n }\n return Object.freeze({\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(memoryLimitBytes !== undefined ? { memoryLimitBytes } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n ...(maxCalls !== undefined ? { maxCalls } : {}),\n ...(Array.isArray(directTools) ? { directTools: Object.freeze([...directTools]) } : {}),\n })\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nfunction profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n if (profile.model?.default === 'tangle/auto') {\n const extra = profile.model.metadata?.extraBody\n const policy =\n extra !== null && typeof extra === 'object'\n ? (extra as Record<string, unknown>).auto\n : undefined\n for (const model of routerAutoDeclaredModels(policy)) assertModelAllowed(model, allowed)\n }\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AA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