@tangle-network/agent-runtime 1.0.0 → 2.0.2

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 (96) hide show
  1. package/dist/{activation-CFS31SWI.d.ts → activation-BuK2H7qx.d.ts} +2 -2
  2. package/dist/{activation-BwoSqHCc.js → activation-ZQWz04u8.js} +4 -4
  3. package/dist/{activation-BwoSqHCc.js.map → activation-ZQWz04u8.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +4 -3
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-DeDkJbsr.js → bundle-PDYNXIEf.js} +2 -2
  8. package/dist/{bundle-DeDkJbsr.js.map → bundle-PDYNXIEf.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +4 -4
  10. package/dist/{coordination-manager-ewBF777W.js → coordination-manager-BZLp9qpE.js} +8 -363
  11. package/dist/coordination-manager-BZLp9qpE.js.map +1 -0
  12. package/dist/coordination-map-routing-CUvwHAtv.js +362 -0
  13. package/dist/coordination-map-routing-CUvwHAtv.js.map +1 -0
  14. package/dist/{delegate-BiuSfwBa.js → delegate-C-MUU6ML.js} +2 -2
  15. package/dist/{delegate-BiuSfwBa.js.map → delegate-C-MUU6ML.js.map} +1 -1
  16. package/dist/durable-file-CksURHlH.js +1 -0
  17. package/dist/durable-file-DstVeHcj.js +228 -0
  18. package/dist/durable-file-DstVeHcj.js.map +1 -0
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +10 -8
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-D6FL1xze.js → graph-CM-6CV_K.js} +6 -5
  23. package/dist/{graph-D6FL1xze.js.map → graph-CM-6CV_K.js.map} +1 -1
  24. package/dist/graph-registry-72DlMnUl.js +585 -0
  25. package/dist/graph-registry-72DlMnUl.js.map +1 -0
  26. package/dist/graph-registry-CAX15LO6.js +1 -0
  27. package/dist/{improve-SiKDcz5_.js → improve-BuZ-I8DP.js} +9 -8
  28. package/dist/{improve-SiKDcz5_.js.map → improve-BuZ-I8DP.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +12 -11
  31. package/dist/index.js.map +1 -1
  32. package/dist/intelligence.d.ts +2 -2
  33. package/dist/intelligence.js +7 -7
  34. package/dist/{journal-store-BJPMUydp.js → journal-store-BpCOCDoO.js} +208 -635
  35. package/dist/journal-store-BpCOCDoO.js.map +1 -0
  36. package/dist/jsonl-file-BBP9Dz9w.js +429 -0
  37. package/dist/jsonl-file-BBP9Dz9w.js.map +1 -0
  38. package/dist/kernel.d.ts +1 -1
  39. package/dist/kernel.js +13 -12
  40. package/dist/{loop-runner-CqlcC0i4.js → loop-runner-BWD6v1rd.js} +2 -2
  41. package/dist/{loop-runner-CqlcC0i4.js.map → loop-runner-BWD6v1rd.js.map} +1 -1
  42. package/dist/{loop-runner-D9rcTNf2.d.ts → loop-runner-BpLTU_J4.d.ts} +2 -2
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +1 -1
  47. package/dist/mcp/index.js +5 -5
  48. package/dist/{prepare-XWwsOh8O.js → prepare-Bv6X2Wnx.js} +4 -4
  49. package/dist/{prepare-XWwsOh8O.js.map → prepare-Bv6X2Wnx.js.map} +1 -1
  50. package/dist/{profile-C01SQZKa.js → profile-Dir2A1_2.js} +2 -2
  51. package/dist/{profile-C01SQZKa.js.map → profile-Dir2A1_2.js.map} +1 -1
  52. package/dist/profiles.d.ts +1 -1
  53. package/dist/{provision-supervisor-DnwR0AyW.js → provision-supervisor-BWEeWag1.js} +8 -6
  54. package/dist/{provision-supervisor-DnwR0AyW.js.map → provision-supervisor-BWEeWag1.js.map} +1 -1
  55. package/dist/{run-cancellation-CoJRKvih.js → run-cancellation-Cpm-BIUu.js} +3 -2
  56. package/dist/{run-cancellation-CoJRKvih.js.map → run-cancellation-Cpm-BIUu.js.map} +1 -1
  57. package/dist/{runtime-DSYZeav8.js → runtime-Cnr3213E.js} +18 -15
  58. package/dist/{runtime-DSYZeav8.js.map → runtime-Cnr3213E.js.map} +1 -1
  59. package/dist/{sandbox-profile-compat-CXjozdWL.js → sandbox-profile-compat-DRiz9kME.js} +2 -2
  60. package/dist/{sandbox-profile-compat-CXjozdWL.js.map → sandbox-profile-compat-DRiz9kME.js.map} +1 -1
  61. package/dist/{search-executor-DcGAOrAh.js → search-executor-__X1VKnU.js} +5 -5
  62. package/dist/{search-executor-DcGAOrAh.js.map → search-executor-__X1VKnU.js.map} +1 -1
  63. package/dist/{server-SrPLb8w0.js → server-CntFSTpW.js} +4 -4
  64. package/dist/{server-SrPLb8w0.js.map → server-CntFSTpW.js.map} +1 -1
  65. package/dist/{structural-rollout-C_lg83-u.js → structural-rollout-s8W19Mws.js} +5 -5
  66. package/dist/{structural-rollout-C_lg83-u.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
  67. package/dist/{supervise-BXw89Ajc.js → supervise-Cl0F57m9.js} +32 -647
  68. package/dist/supervise-Cl0F57m9.js.map +1 -0
  69. package/dist/{supervision-discovery-CewADdEs.js → supervision-discovery-C3t0Xw-T.js} +5 -158
  70. package/dist/supervision-discovery-C3t0Xw-T.js.map +1 -0
  71. package/dist/{supervisor-hHU3ZJnR.js → supervisor-L7u3pQ1j.js} +99 -150
  72. package/dist/supervisor-L7u3pQ1j.js.map +1 -0
  73. package/dist/task-queue-DbpZAp6C.js +49 -0
  74. package/dist/task-queue-DbpZAp6C.js.map +1 -0
  75. package/dist/task-queue.js +1 -49
  76. package/dist/testing.d.ts +1 -1
  77. package/dist/testing.js +13 -13
  78. package/dist/top-web-BXICdHgc.js +1121 -0
  79. package/dist/top-web-BXICdHgc.js.map +1 -0
  80. package/dist/tui/bin.js +4 -3
  81. package/dist/tui/bin.js.map +1 -1
  82. package/dist/tui/index.d.ts +22 -2
  83. package/dist/tui/index.js +3 -3
  84. package/dist/{types-DTHxh4X9.d.ts → types-BfnQq-_k.d.ts} +17 -21
  85. package/dist/{util-ebWMWzY0.js → util-BX20UJ9X.js} +2 -2
  86. package/dist/{util-ebWMWzY0.js.map → util-BX20UJ9X.js.map} +1 -1
  87. package/package.json +10 -10
  88. package/skills/agent-graphs/references/authoring.md +1 -0
  89. package/dist/coordination-manager-ewBF777W.js.map +0 -1
  90. package/dist/journal-store-BJPMUydp.js.map +0 -1
  91. package/dist/supervise-BXw89Ajc.js.map +0 -1
  92. package/dist/supervision-discovery-CewADdEs.js.map +0 -1
  93. package/dist/supervisor-hHU3ZJnR.js.map +0 -1
  94. package/dist/task-queue.js.map +0 -1
  95. package/dist/top-snapshot-DcV7VG4m.js +0 -520
  96. package/dist/top-snapshot-DcV7VG4m.js.map +0 -1
@@ -1,21 +1,24 @@
1
- import { G as cappedDoublingMs, J as unavailableResumeAt, K as jitteredMs, P as RetainedExecutionPendingError, St as newUsageTotals, T as sha256, Tt as assertValidBudget, V as retainedExecutorSeamKey, Xt as __exportAll, a as isNoEntError, at as executorFailure, b as captureRunWriteContext, c as readCommittedJsonLines, ft as errMessage, g as assertNoSymlinkDescendant, l as upsertCommittedJsonLine, o as prepareJsonlAppend, q as unavailablePauseMs, rt as contentAddress, s as readCommittedJsonFile, tt as detachedSnapshot, u as withJsonlFileLock, wt as spendFromUsageTotals, x as fenceRunWrite, xt as meterUsageEvent, y as writeAtomicDurableFile, z as registerRetainedExecutorPreparation } from "./journal-store-BJPMUydp.js";
2
- import { $ as abandonScopeRetainedOwnerInvocation, $n as CheckUnavailableError, A as noteScopeOwnerPlannedExecution, B as deriveNodeExecutionIdentity, Bn as DriverAttemptsExhaustedError, Br as renderUnsupported, Cn as INBOX_RECEIPT_KEY, F as coordinationProfileToolPrefix, Fr as defineProfileMaterializationContract, Ft as createCodeModeTools, G as meterRuntimeOwnedProviderAttempt, Gn as summarizeDriverAttempts, Hn as abandonablePending, Hr as sandboxProfileMaterialization, I as providerVisibleProfile, In as createActivityLog, Ir as fullProfileMaterialization, J as recordScopeOwnerPause, Jn as SeatChain, K as recordScopeOwnerBarrenPause, Kn as undispatchedCredentialExit, Kr as attestRuntimeOwnedScopeOwner, L as runtimeGraphMetadataKey, Lr as profileMaterializationAxes$1, Lt as toolResultText, M as restoreScopeOwnerAcceptedExecution, Mr as assertProfileMaterialization, N as scopeOwnerExecutorNodeContext, Nt as codeModeArguments, On as PEER_MAIL_WIRE_KEY, P as coordinationMcpAlias, Pr as controlProfileMaterialization, Pt as codeModeModelOutput, Rn as isLiveNodeStatus, Rr as promptControlProfileMaterialization, Rt as createRouterTranscript, Sr as runAbortable, St as snapshotExecutorConfig, Tr as bridgeStopSignalKey, Un as causedByPartialFailure, Ur as unsupportedProfileDimensions, Vn as HarnessTurnFailedError, Vt as resolveAgentEnvironmentProvider, W as meterRuntimeOwnedAccounting, Wn as classifyDriverFailure, Wr as worktreeCliProfileMaterialization, X as scopeRetainedOwnerResourceReader, Xn as authoredSeatStages, Xr as inheritRuntimeOwnedExecutorAttestation, Y as prepareScopeRetainedOwnerSeatSwitch, Yn as SeatChainExhaustedError, Zn as seatExecutionProfile, _n as generateSpanId, a as assertRunParking, ai as runtimeOwnedExecutorProviderEvidence, ar as admitContinuationPolicy, at as scopeRetainedOwnerTurnEnded, br as RunCancellationReason, bt as captureReusableExecutorConfig, c as sleepScopeWait, cn as WORKER_TRACE_PROPAGATION, cr as createContinuationKeeper, ct as noteScopeRetainedOwnerCoordination, d as runFinalizer, dr as bridgeAdmissionRefusal, dt as scopeRetainedOwnerContext, ei as providerAttemptEvidence, en as persistHarnessTranscript, er as gateFactoryOnDeliverable, et as consumeScopeRetainedOwnerResult, f as runTree, fr as bridgeModelRouteRefusal, ft as scopeRetainedOwnerJournalRoot, g as isDriverSpec, h as driverExecutorFactory, hn as createOtelExporter, i as RunParkedError, ii as runtimeOwnedExecutorMaterialization, ir as CONTINUATIONS_DIR, it as beginScopeRetainedOwnerDrive, j as recordScopeOwnerMaterialization, jn as isPeerMailEnvelope, k as beginScopeOwnerAttempt, l as withRunParking, lt as bindScopeRetainedOwnerEnvironmentId, m as driverChild, n as createSupervisor, ni as runtimeOwnedDriveHarnessProviderEvidence, nt as scopeRetainedOwnerPriorSpend, o as bindScopeParkingDrain, oi as runtimeOwnedPendingExecutorMaterialization, or as bestComposite, ot as reconcileScopeRetainedOwnerEnvironment, p as createRootHandle, q as recordScopeOwnerDriverAttempt, qn as upstreamUnavailableSignal, qr as authoredAgentIdentity, ri as runtimeOwnedExecutorExecutionBinding, rt as scopeRetainedOwnerResult, si as runtimeOwnedScopeOwnerRuntime, sr as checkVerdictOf, st as scopeRetainedOwnerRestorePoint, ti as recordRuntimeOwnedDriveHarnessProviderEvidence, tn as readHarnessTranscript, tt as prepareScopeRetainedOwnerTask, u as bestDelivered, ut as bindScopeRetainedOwnerProvider, wn as createInbox, wr as bridgeRuntimeAttachmentsKey, x as parseWorkerToolTraceArtifact, xr as linkAbort, xt as createExecutor, yt as bindReusableExecutorExecutionId, z as assertRecursiveReservationPolicy, zn as isTerminalNodeStatus, zr as promptModelProfileMaterialization, zt as routerBrain } from "./supervisor-hHU3ZJnR.js";
1
+ import { $ as abandonScopeRetainedOwnerInvocation, $n as gateFactoryOnDeliverable, $r as providerAttemptEvidence, $t as persistHarnessTranscript, A as noteScopeOwnerPlannedExecution, An as isPeerMailEnvelope, B as deriveNodeExecutionIdentity, Bn as HarnessTurnFailedError, Bt as resolveAgentEnvironmentProvider, Cn as createInbox, Cr as bridgeRuntimeAttachmentsKey, Dn as PEER_MAIL_WIRE_KEY, F as coordinationProfileToolPrefix, Fn as createActivityLog, Fr as fullProfileMaterialization, G as meterRuntimeOwnedProviderAttempt, Gn as undispatchedCredentialExit, Gr as attestRuntimeOwnedScopeOwner, Hn as causedByPartialFailure, Hr as unsupportedProfileDimensions, I as providerVisibleProfile, Ir as profileMaterializationAxes$1, It as toolResultText, J as recordScopeOwnerPause, Jn as SeatChainExhaustedError, K as recordScopeOwnerBarrenPause, Kn as upstreamUnavailableSignal, Kr as authoredAgentIdentity, L as runtimeGraphMetadataKey, Ln as isLiveNodeStatus, Lr as promptControlProfileMaterialization, Lt as createRouterTranscript, M as restoreScopeOwnerAcceptedExecution, Mt as codeModeArguments, N as scopeOwnerExecutorNodeContext, Nr as controlProfileMaterialization, Nt as codeModeModelOutput, P as coordinationMcpAlias, Pr as defineProfileMaterializationContract, Pt as createCodeModeTools, Qn as CheckUnavailableError, Rn as isTerminalNodeStatus, Rr as promptModelProfileMaterialization, Rt as routerBrain, Sn as INBOX_RECEIPT_KEY, Un as classifyDriverFailure, Ur as worktreeCliProfileMaterialization, Vn as abandonablePending, Vr as sandboxProfileMaterialization, W as meterRuntimeOwnedAccounting, Wn as summarizeDriverAttempts, X as scopeRetainedOwnerResourceReader, Xn as seatExecutionProfile, Y as prepareScopeRetainedOwnerSeatSwitch, Yn as authoredSeatStages, Yr as inheritRuntimeOwnedExecutorAttestation, a as assertRunParking, ai as runtimeOwnedPendingExecutorMaterialization, ar as bestComposite, at as scopeRetainedOwnerTurnEnded, br as linkAbort, bt as createExecutor, c as sleepScopeWait, ct as noteScopeRetainedOwnerCoordination, d as runFinalizer, di as isRuntimeFlowBrain, dr as bridgeModelRouteRefusal, dt as scopeRetainedOwnerContext, ei as recordRuntimeOwnedDriveHarnessProviderEvidence, en as readHarnessTranscript, et as consumeScopeRetainedOwnerResult, f as runTree, fi as runtimeFlowAgent, ft as scopeRetainedOwnerJournalRoot, g as isDriverSpec, gn as generateSpanId, h as driverExecutorFactory, i as RunParkedError, ii as runtimeOwnedExecutorProviderEvidence, ir as admitContinuationPolicy, it as beginScopeRetainedOwnerDrive, j as recordScopeOwnerMaterialization, jr as assertProfileMaterialization, k as beginScopeOwnerAttempt, l as withRunParking, lt as bindScopeRetainedOwnerEnvironmentId, m as driverChild, mn as createOtelExporter, n as createSupervisor, ni as runtimeOwnedExecutorExecutionBinding, nt as scopeRetainedOwnerPriorSpend, o as bindScopeParkingDrain, oi as runtimeOwnedScopeOwnerRuntime, or as checkVerdictOf, ot as reconcileScopeRetainedOwnerEnvironment, p as createRootHandle, pi as runtimeFlowBrain, q as recordScopeOwnerDriverAttempt, qn as SeatChain, ri as runtimeOwnedExecutorMaterialization, rr as CONTINUATIONS_DIR, rt as scopeRetainedOwnerResult, sn as WORKER_TRACE_PROPAGATION, sr as createContinuationKeeper, st as scopeRetainedOwnerRestorePoint, ti as runtimeOwnedDriveHarnessProviderEvidence, tt as prepareScopeRetainedOwnerTask, u as bestDelivered, ur as bridgeAdmissionRefusal, ut as bindScopeRetainedOwnerProvider, vt as bindReusableExecutorExecutionId, wr as bridgeStopSignalKey, x as parseWorkerToolTraceArtifact, xr as runAbortable, xt as snapshotExecutorConfig, yr as RunCancellationReason, yt as captureReusableExecutorConfig, z as assertRecursiveReservationPolicy, zn as DriverAttemptsExhaustedError, zr as renderUnsupported } from "./supervisor-L7u3pQ1j.js";
3
2
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-AzSuGI23.js";
4
- import { B as teardownExecutor, C as withTimeout, E as addResourceSpend, N as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, O as resourceTelemetry, R as isDeadlineAbortReason, S as unmeteredSpend, V as teardownSurfaces, c as errorMessage, f as isAsyncIterable, i as chargedTokens, k as withBudgetResources, m as promptCacheTokenClasses, n as addSpend, v as sleep, w as zeroSpend } from "./util-ebWMWzY0.js";
3
+ import { B as teardownExecutor, C as withTimeout, E as addResourceSpend, N as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, O as resourceTelemetry, R as isDeadlineAbortReason, S as unmeteredSpend, V as teardownSurfaces, c as errorMessage, f as isAsyncIterable, i as chargedTokens, k as withBudgetResources, m as promptCacheTokenClasses, n as addSpend, v as sleep, w as zeroSpend } from "./util-BX20UJ9X.js";
4
+ import { $ as newUsageTotals, D as registerRetainedExecutorPreparation, F as unavailablePauseMs, H as contentAddress, I as unavailableResumeAt, N as cappedDoublingMs, P as jitteredMs, Q as meterUsageEvent, S as RetainedExecutionPendingError, W as executorFailure, k as retainedExecutorSeamKey, nt as assertValidBudget, tt as spendFromUsageTotals } from "./journal-store-BpCOCDoO.js";
5
+ import { d as detachedSnapshot, i as prepareJsonlAppend, m as errMessage, n as isNoEntError, o as readCommittedJsonLines } from "./jsonl-file-BBP9Dz9w.js";
5
6
  import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, l as profileProviderModel, n as assertModelAllowed, o as enforceTokenLimits, r as assertProfileModelsAllowed, s as profileBridgeWireModel, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-C-RGAUW4.js";
7
+ import { n as assertNoSymlinkDescendant, o as captureRunWriteContext, s as fenceRunWrite } from "./durable-file-DstVeHcj.js";
6
8
  import { t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
7
- import { c as createCancelAcknowledger, d as normalizeAnalyzeOnSettle, f as coordinationVerbNames, g as withRunContext, h as createInMemoryRunContext, l as createSteerAcknowledger, m as createFileRunContext, n as createCoordinationToolsForManager, o as resolveJsonPointer, p as safeJsonText, t as createCoordinationTools, u as budgetOverspendText } from "./coordination-manager-ewBF777W.js";
8
- import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, s as watchRunCancellation, t as applyRunCancellation } from "./run-cancellation-CoJRKvih.js";
9
+ import { c as createSteerAcknowledger, d as coordinationVerbNames, f as createFileRunContext, l as budgetOverspendText, m as withRunContext, n as createCoordinationToolsForManager, p as createInMemoryRunContext, s as createCancelAcknowledger, t as createCoordinationTools, u as normalizeAnalyzeOnSettle } from "./coordination-manager-BZLp9qpE.js";
10
+ import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, s as watchRunCancellation, t as applyRunCancellation } from "./run-cancellation-Cpm-BIUu.js";
11
+ import { o as safeJsonText } from "./coordination-map-routing-CUvwHAtv.js";
9
12
  import { n as createStdioToolServer, t as PROTOCOL_VERSION } from "./tool-server-CZWd_Opp.js";
13
+ import { a as graphRegistry, c as loadGraph } from "./graph-registry-72DlMnUl.js";
10
14
  import { ATTR, agentIdentityAttributes } from "@tangle-network/agent-trace-contract";
11
15
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
12
16
  import { toolSpansToTraceAnalysisStore } from "@tangle-network/agent-eval";
13
17
  import { isRecord } from "@tangle-network/agent-core";
14
- import { z } from "zod";
15
18
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
16
19
  import { closeSync, constants, fsyncSync, openSync, writeSync } from "node:fs";
17
- import { dirname, join, resolve } from "node:path";
18
- import { mkdir, readFile, readdir } from "node:fs/promises";
20
+ import { dirname, resolve } from "node:path";
21
+ import { mkdir } from "node:fs/promises";
19
22
  import { isMaterializerHarness } from "@tangle-network/agent-profile-materialize";
20
23
  import { createServer } from "node:http";
21
24
  import { msToUnixNano, toOtlpAttributes } from "@tangle-network/agent-trace-contract/otlp";
@@ -1868,10 +1871,6 @@ var GraphRouteError = class extends Error {
1868
1871
  const flowRootProfile = Object.freeze({
1869
1872
  name: "flow",
1870
1873
  harness: "cli-base",
1871
- model: {
1872
- provider: "runtime",
1873
- default: "runtime/flow"
1874
- },
1875
1874
  tools: { [`${coordinationProfileToolPrefix}spawn_worker`]: true }
1876
1875
  });
1877
1876
  /** The nodes a routes edge starts: one, every node of a fork, or none for a stop or finish. */
@@ -2623,27 +2622,6 @@ function ledgerAnalyzes(ledger, edge, outcome, bytes, reason, workerId) {
2623
2622
  ...workerId !== void 0 ? { workerId } : {}
2624
2623
  }, true);
2625
2624
  }
2626
- // src/runtime/supervise/flow-brain.ts
2627
- const flowBrains = /* @__PURE__ */ new WeakSet();
2628
- /**
2629
- * The brain of a flow graph's runtime-owned root manager. It never calls a model: every turn
2630
- * returns no tool call and reports no usage, so the manager only waits while the flow's runtime
2631
- * spawns are open and ends when none is. The driver recognizes it by identity, places no provider
2632
- * attempt for its turns, and bounds them by the flow's edge caps, the pool, the deadline and the
2633
- * abort signal instead of the unmetered-turn bound.
2634
- */
2635
- function runtimeFlowBrain() {
2636
- const brain = async () => ({
2637
- content: null,
2638
- toolCalls: []
2639
- });
2640
- flowBrains.add(brain);
2641
- return brain;
2642
- }
2643
- /** True only for a brain `runtimeFlowBrain` minted. */
2644
- function isRuntimeFlowBrain(brain) {
2645
- return flowBrains.has(brain);
2646
- }
2647
2625
  // src/runtime/supervise/supervise-budget.ts
2648
2626
  /**
2649
2627
  * Which of a driver's budget channels are spent, with their numbers, or `undefined` while none is.
@@ -6671,7 +6649,7 @@ function routerBrainFromProfile(profile, router) {
6671
6649
  // src/runtime/supervise/supervisor-agent-build.ts
6672
6650
  function buildSupervisorAgent(profile, deps, testBrain) {
6673
6651
  const exactProfile = agentProfileSchema.parse(profile);
6674
- assertExecutableAgentProfile(exactProfile, "supervisorAgent");
6652
+ if (!testBrain || !isRuntimeFlowBrain(testBrain)) assertExecutableAgentProfile(exactProfile, "supervisorAgent");
6675
6653
  const stableProfile = detachedSnapshot(exactProfile, "supervisorAgent profile");
6676
6654
  const registeredProfile = deps.registeredProfile === void 0 ? stableProfile : detachedSnapshot(agentProfileSchema.parse(deps.registeredProfile), "supervisorAgent registered profile");
6677
6655
  const stableRouter = deps.router === void 0 ? void 0 : snapshotRouterTransportConfig(deps.router);
@@ -6690,17 +6668,20 @@ function buildSupervisorAgent(profile, deps, testBrain) {
6690
6668
  assertCoordinationBinding(coordination);
6691
6669
  assertSupervisorArmPolicy(harness, deps, runtimeToolNames, coordination);
6692
6670
  const continuationDeadlineMs = deps.continuation === void 0 ? void 0 : admitContinuationPolicy(deps.continuation, "supervisorAgent");
6693
- if (harness === null) return routerSupervisorAgent({
6694
- name,
6695
- deps,
6696
- profile: stableProfile,
6697
- runtimeToolNames,
6698
- nodeContextSeed,
6699
- testBrain,
6700
- router: stableRouter,
6701
- resolveTools,
6702
- observeNodeEvent
6703
- });
6671
+ if (harness === null) {
6672
+ const agent = routerSupervisorAgent({
6673
+ name,
6674
+ deps,
6675
+ profile: stableProfile,
6676
+ runtimeToolNames,
6677
+ nodeContextSeed,
6678
+ testBrain,
6679
+ router: stableRouter,
6680
+ resolveTools,
6681
+ observeNodeEvent
6682
+ });
6683
+ return runtimeFlowAgent(agent, testBrain);
6684
+ }
6704
6685
  return externalSupervisorAgent({
6705
6686
  name,
6706
6687
  deps,
@@ -7407,597 +7388,6 @@ function admitSpawn(env, seat, authoredProfile, spawnContext, recovering) {
7407
7388
  usesRuntimeCoordination: declaredRuntimeToolNames(authorized).length > 0 || seatManagedLeaf
7408
7389
  };
7409
7390
  }
7410
- // src/runtime/supervise/graph-file-schema.ts
7411
- const scalar = z.union([
7412
- z.string(),
7413
- z.number().finite(),
7414
- z.boolean(),
7415
- z.null()
7416
- ]);
7417
- const pointer = z.string().regex(/^(?:\/(?:[^~]|~[01])*)*$/);
7418
- const matchBase = {
7419
- node: z.string().min(1).optional(),
7420
- pointer
7421
- };
7422
- const equals = z.strictObject({
7423
- ...matchBase,
7424
- equals: scalar
7425
- });
7426
- const oneOf = z.strictObject({
7427
- ...matchBase,
7428
- in: z.array(scalar)
7429
- });
7430
- const exists = z.strictObject({
7431
- ...matchBase,
7432
- exists: z.boolean()
7433
- });
7434
- const match = z.union([
7435
- equals,
7436
- oneOf,
7437
- exists
7438
- ]);
7439
- /** The same data grammar as routes; no executable expressions or additional operators. */
7440
- const graphRouteWhenSchema = z.union([match, z.strictObject({ all: z.array(match).min(1) })]);
7441
- const parameter = z.strictObject({
7442
- default: z.unknown().optional(),
7443
- type: z.enum([
7444
- "string",
7445
- "number",
7446
- "integer",
7447
- "boolean",
7448
- "object",
7449
- "array",
7450
- "null"
7451
- ]).optional()
7452
- });
7453
- const command = z.strictObject({
7454
- command: z.string().min(1),
7455
- timeoutMs: z.number().int().positive().optional()
7456
- });
7457
- const nonnegativeInteger = z.number().int().nonnegative();
7458
- /** Authoring envelope. Canonical profiles and topology are validated by their existing owners. */
7459
- const graphFileSchema = z.strictObject({
7460
- digest: z.string().min(1).optional(),
7461
- graph: z.string().min(1).optional(),
7462
- describe: z.string().optional(),
7463
- params: z.record(z.string().min(1), parameter).optional(),
7464
- nodes: z.array(z.strictObject({
7465
- id: z.string().min(1),
7466
- profile: z.record(z.string(), z.unknown()).optional(),
7467
- seat: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]).optional(),
7468
- needs: z.array(z.string().min(1)).optional()
7469
- })).min(1),
7470
- entry: z.array(z.union([z.string().min(1), z.strictObject({
7471
- node: z.string().min(1),
7472
- task: z.unknown()
7473
- })])).min(1).optional(),
7474
- edges: z.array(z.record(z.string(), z.unknown())),
7475
- gates: z.array(z.unknown()).optional(),
7476
- budget: z.strictObject({
7477
- maxIterations: nonnegativeInteger,
7478
- maxTokens: nonnegativeInteger,
7479
- maxUsd: z.number().finite().nonnegative().optional(),
7480
- deadlineMs: nonnegativeInteger.optional(),
7481
- resources: z.record(z.string(), z.strictObject({
7482
- unit: z.string().min(1),
7483
- limit: nonnegativeInteger
7484
- })).optional()
7485
- }),
7486
- check: z.union([
7487
- equals.extend({ describe: z.string().optional() }),
7488
- oneOf.extend({ describe: z.string().optional() }),
7489
- exists.extend({ describe: z.string().optional() }),
7490
- z.strictObject({
7491
- describe: z.string().optional(),
7492
- all: z.array(match).min(1)
7493
- }),
7494
- z.strictObject({
7495
- describe: z.string().optional(),
7496
- command
7497
- })
7498
- ]).optional(),
7499
- deliverable: z.strictObject({
7500
- describe: z.string().optional(),
7501
- checkRef: z.string().min(1),
7502
- command: command.optional(),
7503
- when: graphRouteWhenSchema.optional()
7504
- }).optional(),
7505
- on: z.unknown().optional()
7506
- });
7507
- /** Judge the flow's terminal-output map with RouteWhen's own JSON-pointer semantics. */
7508
- function checkGraphRoute(when, output) {
7509
- return ("all" in when ? when.all : [when]).every((condition) => {
7510
- let document = output;
7511
- if (condition.node !== void 0) {
7512
- if (!output || typeof output !== "object" || !Object.hasOwn(output, condition.node)) return false;
7513
- document = output[condition.node];
7514
- }
7515
- const selected = resolveJsonPointer(document, condition.pointer);
7516
- if ("exists" in condition) return selected.found === condition.exists;
7517
- if (!selected.found) return false;
7518
- return "equals" in condition ? selected.value === condition.equals : condition.in.some((value) => value === selected.value);
7519
- });
7520
- }
7521
- // src/runtime/supervise/graph-parameters.ts
7522
- const triggerPart = z.strictObject({ trigger: z.array(z.string()).min(1) });
7523
- const literalPart = z.strictObject({ literal: z.string() });
7524
- /** Explicit authored trigger slots in compiled graph data. An empty list marks fully bound data. */
7525
- const graphTriggerBindingsSchema = z.array(z.strictObject({
7526
- path: z.array(z.union([z.string(), z.number().int().nonnegative()])).min(1),
7527
- mode: z.enum(["value", "text"]),
7528
- parts: z.array(z.union([literalPart, triggerPart])).min(1)
7529
- }).superRefine((slot, context) => {
7530
- if (!slot.parts.some((part) => "trigger" in part) || slot.mode === "value" && (slot.parts.length !== 1 || !("trigger" in slot.parts[0]))) context.addIssue({
7531
- code: "custom",
7532
- message: "binding requires authored trigger parts; value slots require one trigger"
7533
- });
7534
- }));
7535
- function readBinding(namespace, keys, bindings) {
7536
- let found = bindings[namespace];
7537
- for (const key of keys) {
7538
- if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
7539
- found = found[key];
7540
- }
7541
- if (found === void 0) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
7542
- return structuredClone(found);
7543
- }
7544
- function textValue(value, expression) {
7545
- if (value !== null && typeof value === "object") throw new ValidationError(`graph parameters: ${expression} needs a whole JSON slot`);
7546
- return String(value);
7547
- }
7548
- function pendingText(parts) {
7549
- return parts.map((part) => "literal" in part ? part.literal : `\${trigger.${part.trigger.join(".")}}`).join("");
7550
- }
7551
- /** Compile authored slots once. Inserted values are data, never recursively parsed templates. */
7552
- function compileGraphParameters(value, bindings, options = {}) {
7553
- const visiting = /* @__PURE__ */ new Set();
7554
- const triggerBindings = [];
7555
- const bind = (item, path) => {
7556
- if (typeof item === "string") {
7557
- if (item.replace(/\$\{[^{}]+\}/g, "").includes("${")) throw new ValidationError("graph parameters: malformed reference");
7558
- const whole = /^\$\{([^{}]+)\}$/.exec(item);
7559
- const parts = [];
7560
- let cursor = 0;
7561
- let wholeValue;
7562
- let boundWhole = false;
7563
- for (const match of item.matchAll(/\$\{([^{}]+)\}/g)) {
7564
- if (match.index > cursor) parts.push({ literal: item.slice(cursor, match.index) });
7565
- const [namespace, ...keys] = match[1].split(".");
7566
- if (namespace !== "params" && namespace !== "trigger" || keys.length === 0) throw new ValidationError(`graph parameters: unsupported reference \${${match[1]}}`);
7567
- if (options.defer?.includes(namespace)) {
7568
- if (namespace === "trigger") parts.push({ trigger: keys });
7569
- else parts.push({ literal: match[0] });
7570
- } else {
7571
- const found = readBinding(namespace, keys, bindings);
7572
- if (whole) {
7573
- wholeValue = found;
7574
- boundWhole = true;
7575
- } else parts.push({ literal: textValue(found, match[1]) });
7576
- }
7577
- cursor = match.index + match[0].length;
7578
- }
7579
- if (boundWhole) return wholeValue;
7580
- if (cursor === 0) return item;
7581
- if (cursor < item.length) parts.push({ literal: item.slice(cursor) });
7582
- if (parts.some((part) => "trigger" in part)) triggerBindings.push({
7583
- path,
7584
- mode: whole ? "value" : "text",
7585
- parts
7586
- });
7587
- return pendingText(parts);
7588
- }
7589
- if (!item || typeof item !== "object") return item;
7590
- if (visiting.has(item)) throw new ValidationError("graph parameters: cyclic data is not JSON");
7591
- visiting.add(item);
7592
- const bound = Array.isArray(item) ? item.map((child, index) => bind(child, [...path, index])) : Object.fromEntries(Object.entries(item).map(([key, child]) => [key, bind(child, [...path, key])]));
7593
- visiting.delete(item);
7594
- return bound;
7595
- };
7596
- return {
7597
- value: bind(value, []),
7598
- triggerBindings
7599
- };
7600
- }
7601
- /** Legacy authored-data binding. Compiled graphs use bindCompiledGraphTriggers instead. */
7602
- function bindGraphParameters(value, bindings, options = {}) {
7603
- return compileGraphParameters(value, bindings, options).value;
7604
- }
7605
- /** Check provenance against the exact provisional values without reading trigger data. */
7606
- function assertGraphTriggerBindings(value, slots) {
7607
- const seen = /* @__PURE__ */ new Set();
7608
- for (const slot of graphTriggerBindingsSchema.parse(slots)) {
7609
- const key = JSON.stringify(slot.path.map(String));
7610
- if (seen.has(key)) throw new ValidationError("graph parameters: duplicate trigger binding path");
7611
- seen.add(key);
7612
- let found = value;
7613
- for (const key of slot.path) {
7614
- if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError("graph parameters: trigger binding path does not exist");
7615
- found = found[key];
7616
- }
7617
- if (found !== pendingText(slot.parts)) throw new ValidationError("graph parameters: trigger binding does not match its provisional value");
7618
- }
7619
- }
7620
- /** Only explicitly recorded authored slots bind. Literal parameter/trigger values are untouched. */
7621
- function bindCompiledGraphTriggers(value, slots, trigger) {
7622
- assertGraphTriggerBindings(value, slots);
7623
- const bound = structuredClone(value);
7624
- for (const slot of slots) {
7625
- let parent = bound;
7626
- for (const key of slot.path.slice(0, -1)) parent = parent[key];
7627
- parent[slot.path.at(-1)] = slot.mode === "value" ? readBinding("trigger", slot.parts[0].trigger, { trigger }) : slot.parts.map((part) => "literal" in part ? part.literal : textValue(readBinding("trigger", part.trigger, { trigger }), `trigger.${part.trigger.join(".")}`)).join("");
7628
- }
7629
- return bound;
7630
- }
7631
- // src/runtime/supervise/graph-registry.ts
7632
- /**
7633
- * `graph-registry` — the designer's memory: graphs and their outcomes as files.
7634
- *
7635
- * The AgentGraph algebra makes a graph PLAIN DATA (nodes with pinned profiles,
7636
- * edges with registry-versioned directives, a budget, a deliverable
7637
- * description), which is the property that lets a graph be stored, replayed
7638
- * byte-identical, and mutated like code. This module is the thin durable layer
7639
- * on top: one JSONL record per run, the exact graph content-addressed beside
7640
- * it. The natural home is a SANDBOX WORKSPACE — the platform's snapshot story
7641
- * (Firecracker restore, warm leases, `continuity: 'resume'`) then makes the
7642
- * registry the agent's compounding execution memory across runs: a rerun over
7643
- * the same sandbox finds every graph the designer ever ran, what each cost,
7644
- * and whether it delivered.
7645
- *
7646
- * ORACLES STAY ENVIRONMENT-OWNED. `DeliverableSpec.check` is a function and is
7647
- * deliberately NOT stored: a stored graph keeps the deliverable's `describe`
7648
- * and an optional `checkRef`, and replay re-binds the check from the caller's
7649
- * environment. This is the graph contract's own doctrine — graders are
7650
- * environment, never workers — applied to persistence.
7651
- *
7652
- * Scoring is a documented heuristic, not a learned model: delivered beats
7653
- * failed, then cheaper (tokens, then iterations), then most recent. A designer
7654
- * that needs better selection replaces `pickBest`, not the records.
7655
- */
7656
- var graph_registry_exports = /* @__PURE__ */ __exportAll({
7657
- digestOfGraph: () => digestOfGraph,
7658
- graphCorpusSummary: () => graphCorpusSummary,
7659
- graphDigest: () => graphDigest,
7660
- graphFromStored: () => graphFromStored,
7661
- graphRegistry: () => graphRegistry,
7662
- graphRunsFor: () => graphRunsFor,
7663
- listGraphRuns: () => listGraphRuns,
7664
- loadGraph: () => loadGraph,
7665
- lookupGraph: () => lookupGraph,
7666
- pickBestGraph: () => pickBestGraph,
7667
- recordGraphRun: () => recordGraphRun,
7668
- recordStoredGraphRun: () => recordStoredGraphRun,
7669
- storedGraphDigests: () => storedGraphDigests,
7670
- taskShapeDigest: () => taskShapeDigest
7671
- });
7672
- const RECORDS_FILE = "records.jsonl";
7673
- const GRAPHS_DIR = "graphs";
7674
- /** Canonical serialization for content-addressing: stable key order, sorted. */
7675
- function canonicalJson$1(value) {
7676
- if (Array.isArray(value)) return `[${value.map(canonicalJson$1).join(",")}]`;
7677
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson$1(v)}`).join(",")}}`;
7678
- return JSON.stringify(value);
7679
- }
7680
- /** Digest of the exact graph (nodes + edges + budget + deliverable describe, and a flow graph's
7681
- * entry and gates). An absent key is not serialized, so a graph without `entry` keeps the digest
7682
- * it had before flow graphs were stored. */
7683
- function graphDigest(graph) {
7684
- return sha256(canonicalJson$1(graph));
7685
- }
7686
- /** Digest of the normalized task shape a designer looks records up by. */
7687
- function taskShapeDigest(taskShape) {
7688
- return sha256(canonicalJson$1(taskShape));
7689
- }
7690
- /** Digest of a runnable graph exactly as the registry stores it — the value
7691
- * `recordGraphRun` demands. Callers recording real runs hash through this,
7692
- * never hand-rolled, so a record always matches its graph. */
7693
- function digestOfGraph(graph) {
7694
- return storeGraph(graph).digest;
7695
- }
7696
- function storeGraph(graph) {
7697
- const { describe, checkRef, command, when } = graph.deliverable;
7698
- const content = {
7699
- nodes: graph.nodes,
7700
- edges: graph.edges,
7701
- budget: graph.budget,
7702
- ...graph.triggerBindings === void 0 ? {} : { triggerBindings: graph.triggerBindings },
7703
- deliverable: {
7704
- ...describe ? { describe } : {},
7705
- ...checkRef ? { checkRef } : {},
7706
- ...command ? { command } : {},
7707
- ...when ? { when } : {}
7708
- },
7709
- ...graph.entry === void 0 ? {} : { entry: graph.entry },
7710
- ...graph.gates === void 0 ? {} : { gates: graph.gates }
7711
- };
7712
- return {
7713
- digest: graphDigest(content),
7714
- ...content
7715
- };
7716
- }
7717
- function assertRecord(record) {
7718
- if (typeof record.graphDigest !== "string" || record.graphDigest.length === 0) throw new ValidationError("graph-registry: record.graphDigest is required");
7719
- if (typeof record.taskDigest !== "string" || record.taskDigest.length === 0) throw new ValidationError("graph-registry: record.taskDigest is required");
7720
- if (!Number.isFinite(Date.parse(record.startedAt))) throw new ValidationError("graph-registry: record.startedAt must be a timestamp");
7721
- if (![
7722
- "delivered",
7723
- "no-winner",
7724
- "unknown",
7725
- "running"
7726
- ].includes(record.outcome.kind)) throw new ValidationError("graph-registry: invalid record.outcome.kind");
7727
- if ((record.outcome.kind === "delivered" || record.outcome.kind === "no-winner") && (!record.finishedAt || !Number.isFinite(Date.parse(record.finishedAt)))) throw new ValidationError("graph-registry: terminal outcomes require record.finishedAt");
7728
- if ((record.outcome.kind === "unknown" || record.outcome.kind === "running") && !record.outcome.reason) throw new ValidationError("graph-registry: incomplete outcomes require a reason");
7729
- if (record.source && (!record.source.kind || !record.source.id)) throw new ValidationError("graph-registry: source.kind and source.id are required");
7730
- if (record.finishedAt && (!Number.isFinite(Date.parse(record.finishedAt)) || Date.parse(record.finishedAt) < Date.parse(record.startedAt))) throw new ValidationError("graph-registry: finishedAt precedes startedAt or is invalid");
7731
- for (const [channel, value] of Object.entries(record.cost)) if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) throw new ValidationError(`graph-registry: invalid cost.${channel}`);
7732
- }
7733
- function recordKey(record) {
7734
- assertRecord(record);
7735
- if (record.source) return JSON.stringify([
7736
- "source",
7737
- record.source.kind,
7738
- record.source.id
7739
- ]);
7740
- return JSON.stringify([
7741
- record.taskDigest,
7742
- record.graphDigest,
7743
- record.startedAt
7744
- ]);
7745
- }
7746
- /** Open (or lazily create) a registry rooted at a workspace directory. The
7747
- * directory is the sandbox workspace; snapshots carry it across runs. */
7748
- function graphRegistry(root) {
7749
- if (!root || root.trim().length === 0) throw new ValidationError("graphRegistry: root directory is required");
7750
- return { root };
7751
- }
7752
- /** Append one run record; the exact graph is content-addressed beside it.
7753
- * Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with
7754
- * the same key replaces the prior row rather than duplicating it. */
7755
- async function recordGraphRun(reg, graph, record) {
7756
- return recordStoredGraphRun(reg, storeGraph(graph), record);
7757
- }
7758
- /** Store an executable graph or an observed external topology in the same registry.
7759
- * Imported observations retain their source identity and never authorize replay.
7760
- * A reader refreshing facts can preserve independently joined labels; an explicit
7761
- * correction leaves preserveLabels unset and replaces the record. */
7762
- async function recordStoredGraphRun(reg, definition, record, options = {}) {
7763
- const { digest, ...content } = definition;
7764
- const stored = {
7765
- ...content,
7766
- digest: digest ?? graphDigest(content)
7767
- };
7768
- if (stored.observed && !record) throw new ValidationError("graph-registry: observed graphs require a source run identity");
7769
- if (record) {
7770
- assertRecord(record);
7771
- if (stored.observed && !record.source) throw new ValidationError("graph-registry: observed graphs require a source run identity");
7772
- if (!stored.observed && !record.finishedAt) throw new ValidationError("graph-registry: native graph runs require a completion timestamp");
7773
- if ((!stored.observed || record.traversals !== void 0) && (!Number.isSafeInteger(record.traversals) || record.traversals < 0)) throw new ValidationError("graph-registry: native graphs require metered traversals; observed counts must be non-negative integers");
7774
- if (stored.digest !== record.graphDigest) throw new ValidationError(`graph-registry: record.graphDigest ${record.graphDigest} does not match the supplied graph (${stored.digest}) — record the graph that actually ran`);
7775
- }
7776
- if (graphDigest(content) !== stored.digest) throw new ValidationError("graph-registry: stored graph content does not match its digest");
7777
- await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true });
7778
- const file = join(reg.root, RECORDS_FILE);
7779
- return withJsonlFileLock(file, async (canonicalPath) => {
7780
- if (!record) {
7781
- await persistGraph(reg, stored);
7782
- return stored;
7783
- }
7784
- let persisted = record;
7785
- if (options.preserveLabels && record.source) {
7786
- const prior = (await readCommittedJsonFile(canonicalPath)).find((row) => row.source?.kind === record.source.kind && row.source.id === record.source.id);
7787
- if (prior) {
7788
- const taskType = record.taskType ?? prior.taskType;
7789
- const priorTerminal = prior.outcome.kind === "delivered" || prior.outcome.kind === "no-winner";
7790
- const incomingUnassessed = record.outcome.kind === "unknown" || record.outcome.kind === "running";
7791
- if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt) throw new ValidationError("graph-registry: preserving labels requires the same task start and source identity");
7792
- const evidence = [...prior.evidence ?? [], ...record.evidence ?? []];
7793
- persisted = {
7794
- ...record,
7795
- ...taskType ? { taskType } : {},
7796
- ...record.unknowns ? { unknowns: record.unknowns.filter((reason) => !(taskType && reason === "task type not explicitly labeled")) } : {},
7797
- ...evidence.length ? { evidence: [...new Map(evidence.map((entry) => [canonicalJson$1(entry), entry])).values()] } : {},
7798
- ...priorTerminal && incomingUnassessed ? {
7799
- outcome: prior.outcome,
7800
- finishedAt: prior.finishedAt,
7801
- cost: {
7802
- ...record.cost,
7803
- ...prior.cost.ms === void 0 ? {} : { ms: prior.cost.ms },
7804
- ...prior.cost.mergeMs === void 0 ? {} : { mergeMs: prior.cost.mergeMs }
7805
- }
7806
- } : {}
7807
- };
7808
- }
7809
- }
7810
- assertRecord(persisted);
7811
- await persistGraph(reg, stored);
7812
- await upsertCommittedJsonLine(canonicalPath, persisted, recordKey);
7813
- return stored;
7814
- });
7815
- }
7816
- async function persistGraph(reg, stored) {
7817
- const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`);
7818
- try {
7819
- const { digest: existingDigest, ...existing } = JSON.parse(await readFile(revisionPath, "utf8"));
7820
- if (existingDigest !== stored.digest || graphDigest(existing) !== stored.digest) throw new ValidationError("graph-registry: stored graph revision is immutable but its content differs");
7821
- } catch (error) {
7822
- if (!isNoEntError(error)) throw error;
7823
- writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true });
7824
- }
7825
- }
7826
- /** All records, newest last. */
7827
- async function listGraphRuns(reg) {
7828
- return readCommittedJsonFile(join(reg.root, RECORDS_FILE));
7829
- }
7830
- function observedTopology(record) {
7831
- return record.topologyDigest ?? (record.source ? "unknown" : record.graphDigest);
7832
- }
7833
- /** Records for one task shape or deterministic label query, newest last. */
7834
- async function graphRunsFor(reg, query = {}) {
7835
- const filters = typeof query === "string" ? { taskDigest: query } : query;
7836
- return (await listGraphRuns(reg)).filter((row) => (filters.taskDigest === void 0 || row.taskDigest === filters.taskDigest) && (filters.taskType === void 0 || (row.taskType ?? "unknown") === filters.taskType) && (filters.topologyDigest === void 0 || observedTopology(row) === filters.topologyDigest) && (filters.sourceKind === void 0 || (row.source?.kind ?? "native") === filters.sourceKind));
7837
- }
7838
- function medianKnown(values) {
7839
- const known = values.filter((value) => value !== void 0 && Number.isFinite(value) && value >= 0).sort((a, b) => a - b);
7840
- const middle = Math.floor(known.length / 2);
7841
- return {
7842
- count: known.length,
7843
- median: known.length === 0 ? null : known.length % 2 ? known[middle] : (known[middle - 1] + known[middle]) / 2
7844
- };
7845
- }
7846
- function observedGraphSummary(records) {
7847
- const groups = /* @__PURE__ */ new Map();
7848
- for (const record of records) {
7849
- const key = JSON.stringify([record.taskType ?? "unknown", observedTopology(record)]);
7850
- const rows = groups.get(key);
7851
- if (rows) rows.push(record);
7852
- else groups.set(key, [record]);
7853
- }
7854
- const summaries = [...groups.values()].map((runs) => {
7855
- const assessed = runs.filter((run) => run.outcome.kind === "delivered" || run.outcome.kind === "no-winner");
7856
- const delivered = assessed.filter((run) => run.outcome.kind === "delivered");
7857
- const wall = medianKnown(assessed.map((run) => run.cost.ms));
7858
- const merge = medianKnown(delivered.filter((run) => run.evidence?.some((entry) => entry.kind === "pr-merged")).map((run) => run.cost.mergeMs));
7859
- const tokens = medianKnown(assessed.map((run) => run.cost.tokens));
7860
- const human = medianKnown(assessed.map((run) => run.cost.humanMessages));
7861
- return {
7862
- taskType: runs[0].taskType ?? "unknown",
7863
- topologyDigest: observedTopology(runs[0]),
7864
- delivered: delivered.length,
7865
- assessed: assessed.length,
7866
- unknown: runs.length - assessed.length,
7867
- deliveredRate: assessed.length ? delivered.length / assessed.length : null,
7868
- medianWallMs: wall.median,
7869
- wallMsCount: wall.count,
7870
- medianMergeMs: merge.median,
7871
- mergeMsCount: merge.count,
7872
- medianTokens: tokens.median,
7873
- tokenCount: tokens.count,
7874
- medianHumanMessages: human.median,
7875
- humanMessageCount: human.count,
7876
- runs
7877
- };
7878
- });
7879
- summaries.sort((a, b) => {
7880
- const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1);
7881
- if (delivered) return delivered;
7882
- for (const key of [
7883
- "medianWallMs",
7884
- "medianTokens",
7885
- "medianHumanMessages"
7886
- ]) {
7887
- if (a[key] === b[key]) continue;
7888
- if (a[key] === null) return 1;
7889
- if (b[key] === null) return -1;
7890
- return a[key] - b[key];
7891
- }
7892
- return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest);
7893
- });
7894
- return {
7895
- recordCount: records.length,
7896
- groups: summaries
7897
- };
7898
- }
7899
- /** Query and rank the same registry records using the opt-in observational
7900
- * policy: delivery rate, wall time, tokens, then human messages; unknowns last. */
7901
- async function graphCorpusSummary(reg, query = {}) {
7902
- return observedGraphSummary(await graphRunsFor(reg, query));
7903
- }
7904
- /** The documented heuristic: delivered beats failed; among delivered, cheaper
7905
- * (tokens, then iterations) wins; ties go to the most recent. */
7906
- function pickBestGraph(records, options = {}) {
7907
- if (options.policy === "observed") {
7908
- const group = observedGraphSummary(records).groups[0];
7909
- return group && pickBestGraph(group.runs);
7910
- }
7911
- const delivered = records.filter((row) => row.outcome.kind === "delivered");
7912
- if (delivered.length === 0) return void 0;
7913
- const better = (a, b) => {
7914
- const aTokens = a.cost.tokens ?? Number.POSITIVE_INFINITY;
7915
- const bTokens = b.cost.tokens ?? Number.POSITIVE_INFINITY;
7916
- if (aTokens !== bTokens) return aTokens < bTokens ? a : b;
7917
- const aIter = a.cost.iterations ?? Number.POSITIVE_INFINITY;
7918
- const bIter = b.cost.iterations ?? Number.POSITIVE_INFINITY;
7919
- if (aIter !== bIter) return aIter < bIter ? a : b;
7920
- return a.finishedAt >= b.finishedAt ? a : b;
7921
- };
7922
- return delivered.reduce((best, row) => better(best, row) === best ? best : row);
7923
- }
7924
- /** Load a stored graph by digest. */
7925
- async function loadGraph(reg, digest) {
7926
- try {
7927
- return JSON.parse(await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), "utf8"));
7928
- } catch {
7929
- return;
7930
- }
7931
- }
7932
- /** The designer's lookup: replay the known-good graph for this task shape, or
7933
- * author a new one — with the reason stated either way (the decision is data). */
7934
- async function lookupGraph(reg, taskDigest) {
7935
- const records = await graphRunsFor(reg, taskDigest);
7936
- const candidates = [];
7937
- const loaded = /* @__PURE__ */ new Map();
7938
- for (const record of records) {
7939
- if (!loaded.has(record.graphDigest)) loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest));
7940
- if (!loaded.get(record.graphDigest)?.observed) candidates.push(record);
7941
- }
7942
- if (records.length && !candidates.length) return {
7943
- kind: "author",
7944
- reason: "only observed topologies are available; author an executable graph"
7945
- };
7946
- const best = pickBestGraph(candidates);
7947
- if (best) {
7948
- const graph = await loadGraph(reg, best.graphDigest);
7949
- if (graph) return {
7950
- kind: "replay",
7951
- graph,
7952
- record: best
7953
- };
7954
- return {
7955
- kind: "author",
7956
- reason: `best record's graph ${best.graphDigest.slice(0, 12)} is missing from the registry`
7957
- };
7958
- }
7959
- return {
7960
- kind: "author",
7961
- reason: records.length === 0 ? "first run for this task shape" : "no graph delivered for this task shape yet"
7962
- };
7963
- }
7964
- /** Rehydrate a stored graph, binding trigger data and an environment-owned named check. */
7965
- function graphFromStored(stored, environment = {}) {
7966
- if (stored.observed) throw new ValidationError("graphFromStored: observed topology cannot be replayed");
7967
- const { digest: _digest, observed: _observed, triggerBindings: _triggerBindings, deliverable, ...topology } = stored.triggerBindings !== void 0 ? bindCompiledGraphTriggers(stored, stored.triggerBindings, typeof environment === "function" ? void 0 : environment.trigger ?? {}) : typeof environment === "function" ? stored : bindGraphParameters(stored, { trigger: environment.trigger ?? {} });
7968
- const selected = typeof environment === "function" ? environment : environment.checks && Object.hasOwn(environment.checks, deliverable.checkRef ?? "") ? environment.checks[deliverable.checkRef] : deliverable.checkRef === "command" ? deliverable.command : deliverable.checkRef === "route" && deliverable.when ? ((out, context) => context ? context.originalVerdict?.valid !== false : checkGraphRoute(deliverable.when, out)) : void 0;
7969
- if (!selected) throw new ValidationError(`graphFromStored: unknown checkRef ${deliverable.checkRef ?? "(missing)"}`);
7970
- const materialized = stored.triggerBindings === void 0 ? {} : { triggerBindings: [] };
7971
- if (typeof selected === "function") {
7972
- const { command: _command, ...description } = deliverable;
7973
- return {
7974
- ...topology,
7975
- ...materialized,
7976
- deliverable: {
7977
- ...description,
7978
- check: selected
7979
- }
7980
- };
7981
- }
7982
- const command = selected === deliverable.command ? selected : bindGraphParameters(selected, { trigger: environment.trigger ?? {} });
7983
- return {
7984
- ...topology,
7985
- ...materialized,
7986
- deliverable: {
7987
- ...deliverable,
7988
- command,
7989
- check: () => false
7990
- }
7991
- };
7992
- }
7993
- /** Digests present on disk (integrity probe for tests and audits). */
7994
- async function storedGraphDigests(reg) {
7995
- try {
7996
- return (await readdir(join(reg.root, GRAPHS_DIR))).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5)).sort();
7997
- } catch {
7998
- return [];
7999
- }
8000
- }
8001
7391
  // src/runtime/supervise/supervise-graph-subtasks.ts
8002
7392
  /** A stored graph's topology, from the registry `SuperviseOptions.graphRegistry` names. */
8003
7393
  async function storedGraphTopology(dir, digest) {
@@ -9701,7 +9091,10 @@ function prepareSuperviseRun(profile, task, opts, testBrain) {
9701
9091
  const { applyTraceTools, composeSpawnProfile } = traceToolPolicy(options, guidanceComposer);
9702
9092
  const peerAuditFor = peerAuditRegistry(options);
9703
9093
  const registeredProfile = applyTraceTools(superviseRootProfile(profile, options.profileGuidance));
9704
- const canonicalProfile = admitRootSegment(registeredProfile, options);
9094
+ if (options.segment !== void 0) admitSegment(options.segment);
9095
+ const canonicalProfile = options.segment === void 0 ? registeredProfile : withRootSegment(registeredProfile, options.segment);
9096
+ if (!testBrain || !isRuntimeFlowBrain(testBrain)) assertExecutableAgentProfile(canonicalProfile, "supervise root");
9097
+ if (authoredSeatStages(canonicalProfile) !== void 0 && options.selectSeat === void 0) throw new ValidationError("supervise: AgentProfile.seats requires selectSeat before execution");
9705
9098
  const canonicalTask = freezeDetached(task);
9706
9099
  assertWorkerSeams(options);
9707
9100
  const authorizeDownFor = downMessageAuthorizer(options);
@@ -9832,14 +9225,6 @@ function peerAuditRegistry(options) {
9832
9225
  }
9833
9226
  } : void 0;
9834
9227
  }
9835
- /** The profile this process executes: the registered root, or the segment the options name. */
9836
- function admitRootSegment(registeredProfile, options) {
9837
- if (options.segment !== void 0) admitSegment(options.segment);
9838
- const canonicalProfile = options.segment === void 0 ? registeredProfile : withRootSegment(registeredProfile, options.segment);
9839
- assertExecutableAgentProfile(canonicalProfile, "supervise root");
9840
- if (authoredSeatStages(canonicalProfile) !== void 0 && options.selectSeat === void 0) throw new ValidationError("supervise: AgentProfile.seats requires selectSeat before execution");
9841
- return canonicalProfile;
9842
- }
9843
9228
  function assertWorkerSeams(options) {
9844
9229
  if (options.makeWorkerAgent && options.authorizeSpawn) throw new ValidationError("supervise: authorizeSpawn cannot be combined with caller-owned makeWorkerAgent; use makeLeafAgent to override leaf execution inside the authorized path, or use backend-derived workers");
9845
9230
  if (options.makeWorkerAgent && options.makeLeafAgent) throw new ValidationError("supervise: makeWorkerAgent replaces the worker path and makeLeafAgent overrides a leaf inside it; pass one");
@@ -10205,6 +9590,6 @@ function superviseWithContext(profile, task, opts, brain) {
10205
9590
  ...signal === void 0 ? {} : { signal }
10206
9591
  }, brain));
10207
9592
  }
10208
- export { delegatesWorkerBriefPrompt as $, graphRouteWhenSchema as A, runtimeFlowBrain as B, storedGraphDigests as C, compileGraphParameters as D, bindGraphParameters as E, composeReentryTask as F, journaledGateDecider as G, GraphRouteError as H, serveCoordinationMcp as I, defaultEdgeTraversalCap as J, routeFlowOf as K, coordinationControlToolNames as L, supervisorAgent as M, supervisorAgentWithTestBrain as N, graphTriggerBindingsSchema as O, UNPROVEN_CONTINUITY as P, createPromptRegistry as Q, driverAgent as R, recordStoredGraphRun as S, assertGraphTriggerBindings as T, createFlowRun as U, createGraphOverlay as V, flowRootProfile as W, validateGraphTopology as X, graphRootProfile as Y, analyzesFindingsReportPrompt as Z, listGraphRuns as _, createSupervisorSpanRecorder as _t, superviseRootProfile as a, promptHandle as at, pickBestGraph as b, retryPreSpawnRefusals as c, noProgressFor as ct, graphCorpusSummary as d, areaUnderCurve as dt, dumbContinuationFailPrompt as et, graphDigest as f, bestSoFar as ft, graph_registry_exports as g, readRootStreamReceipt as gt, graphRunsFor as h, readRootStream as ht, profileGuidanceComposer as i, naiveContinuationPrompt as it, workerFromBackend as j, graphFileSchema as k, withWorkerSpawnRetry as l, plateau as lt, graphRegistry as m, renderAnytimeTable as mt, superviseFleetCapabilities as n, formatPromptHandle as nt, isPreSpawnExecutorFailure as o, allWorkersStalled as ot, graphFromStored as p, plateauLength as pt, validateFlowGraph as q, superviseWithTestBrain as r, kernelPromptRegistry as rt, resolveWorkerSpawnRetry as s, anyOf as st, supervise as t, dumbContinuationPassPrompt as tt, digestOfGraph as u, anytimeReport as ut, loadGraph as v, taskShapeDigest as w, recordGraphRun as x, lookupGraph as y, runBrainLoop as z };
9593
+ export { createPromptRegistry as A, noProgressFor as B, journaledGateDecider as C, graphRootProfile as D, defaultEdgeTraversalCap as E, kernelPromptRegistry as F, plateauLength as G, anytimeReport as H, naiveContinuationPrompt as I, readRootStreamReceipt as J, renderAnytimeTable as K, promptHandle as L, dumbContinuationFailPrompt as M, dumbContinuationPassPrompt as N, validateGraphTopology as O, formatPromptHandle as P, allWorkersStalled as R, flowRootProfile as S, validateFlowGraph as T, areaUnderCurve as U, plateau as V, bestSoFar as W, createSupervisorSpanRecorder as Y, driverAgent as _, superviseRootProfile as a, GraphRouteError as b, retryPreSpawnRefusals as c, supervisorAgent as d, supervisorAgentWithTestBrain as f, coordinationControlToolNames as g, serveCoordinationMcp as h, profileGuidanceComposer as i, delegatesWorkerBriefPrompt as j, analyzesFindingsReportPrompt as k, withWorkerSpawnRetry as l, composeReentryTask as m, superviseFleetCapabilities as n, isPreSpawnExecutorFailure as o, UNPROVEN_CONTINUITY as p, readRootStream as q, superviseWithTestBrain as r, resolveWorkerSpawnRetry as s, supervise as t, workerFromBackend as u, runBrainLoop as v, routeFlowOf as w, createFlowRun as x, createGraphOverlay as y, anyOf as z };
10209
9594
 
10210
- //# sourceMappingURL=supervise-BXw89Ajc.js.map
9595
+ //# sourceMappingURL=supervise-Cl0F57m9.js.map