@tangle-network/agent-runtime 0.353.3 → 2.0.1

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-DTgC0RvI.js → activation-ZQWz04u8.js} +4 -4
  3. package/dist/{activation-DTgC0RvI.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-D-J0Osf4.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-DfRQSGVk.js → delegate-C-MUU6ML.js} +2 -2
  15. package/dist/{delegate-DfRQSGVk.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-BtGsqcOF.js → graph-CM-6CV_K.js} +6 -5
  23. package/dist/{graph-BtGsqcOF.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-CL-Dsf63.js → improve-BuZ-I8DP.js} +9 -8
  28. package/dist/{improve-CL-Dsf63.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-B1Xpgp2w.js → loop-runner-BWD6v1rd.js} +2 -2
  41. package/dist/{loop-runner-B1Xpgp2w.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-CzCFHTxe.js → provision-supervisor-BWEeWag1.js} +8 -6
  54. package/dist/{provision-supervisor-CzCFHTxe.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-DmdhgaTH.js → runtime-Cnr3213E.js} +18 -15
  58. package/dist/{runtime-DmdhgaTH.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-Djo4ssci.js → search-executor-__X1VKnU.js} +5 -5
  62. package/dist/{search-executor-Djo4ssci.js.map → search-executor-__X1VKnU.js.map} +1 -1
  63. package/dist/{server-DAanPY7z.js → server-CntFSTpW.js} +4 -4
  64. package/dist/{server-DAanPY7z.js.map → server-CntFSTpW.js.map} +1 -1
  65. package/dist/{structural-rollout-qqsbQW8M.js → structural-rollout-s8W19Mws.js} +5 -5
  66. package/dist/{structural-rollout-qqsbQW8M.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
  67. package/dist/{supervise-DKwnVruI.js → supervise-Cl0F57m9.js} +13 -601
  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-C3JhrVVU.js → supervisor-L7u3pQ1j.js} +84 -140
  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-CkXPPXjI.js +1114 -0
  79. package/dist/top-web-CkXPPXjI.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 +11 -11
  88. package/skills/agent-graphs/references/authoring.md +1 -0
  89. package/dist/coordination-manager-D-J0Osf4.js.map +0 -1
  90. package/dist/journal-store-BJPMUydp.js.map +0 -1
  91. package/dist/supervise-DKwnVruI.js.map +0 -1
  92. package/dist/supervision-discovery-CewADdEs.js.map +0 -1
  93. package/dist/supervisor-C3JhrVVU.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, fi as isRuntimeFlowBrain, 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, mi as runtimeFlowBrain, n as createSupervisor, ni as runtimeOwnedDriveHarnessProviderEvidence, nt as scopeRetainedOwnerPriorSpend, o as bindScopeParkingDrain, oi as runtimeOwnedPendingExecutorMaterialization, or as bestComposite, ot as reconcileScopeRetainedOwnerEnvironment, p as createRootHandle, pi as runtimeFlowAgent, 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-C3JhrVVU.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-D-J0Osf4.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";
@@ -7385,597 +7388,6 @@ function admitSpawn(env, seat, authoredProfile, spawnContext, recovering) {
7385
7388
  usesRuntimeCoordination: declaredRuntimeToolNames(authorized).length > 0 || seatManagedLeaf
7386
7389
  };
7387
7390
  }
7388
- // src/runtime/supervise/graph-file-schema.ts
7389
- const scalar = z.union([
7390
- z.string(),
7391
- z.number().finite(),
7392
- z.boolean(),
7393
- z.null()
7394
- ]);
7395
- const pointer = z.string().regex(/^(?:\/(?:[^~]|~[01])*)*$/);
7396
- const matchBase = {
7397
- node: z.string().min(1).optional(),
7398
- pointer
7399
- };
7400
- const equals = z.strictObject({
7401
- ...matchBase,
7402
- equals: scalar
7403
- });
7404
- const oneOf = z.strictObject({
7405
- ...matchBase,
7406
- in: z.array(scalar)
7407
- });
7408
- const exists = z.strictObject({
7409
- ...matchBase,
7410
- exists: z.boolean()
7411
- });
7412
- const match = z.union([
7413
- equals,
7414
- oneOf,
7415
- exists
7416
- ]);
7417
- /** The same data grammar as routes; no executable expressions or additional operators. */
7418
- const graphRouteWhenSchema = z.union([match, z.strictObject({ all: z.array(match).min(1) })]);
7419
- const parameter = z.strictObject({
7420
- default: z.unknown().optional(),
7421
- type: z.enum([
7422
- "string",
7423
- "number",
7424
- "integer",
7425
- "boolean",
7426
- "object",
7427
- "array",
7428
- "null"
7429
- ]).optional()
7430
- });
7431
- const command = z.strictObject({
7432
- command: z.string().min(1),
7433
- timeoutMs: z.number().int().positive().optional()
7434
- });
7435
- const nonnegativeInteger = z.number().int().nonnegative();
7436
- /** Authoring envelope. Canonical profiles and topology are validated by their existing owners. */
7437
- const graphFileSchema = z.strictObject({
7438
- digest: z.string().min(1).optional(),
7439
- graph: z.string().min(1).optional(),
7440
- describe: z.string().optional(),
7441
- params: z.record(z.string().min(1), parameter).optional(),
7442
- nodes: z.array(z.strictObject({
7443
- id: z.string().min(1),
7444
- profile: z.record(z.string(), z.unknown()).optional(),
7445
- seat: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]).optional(),
7446
- needs: z.array(z.string().min(1)).optional()
7447
- })).min(1),
7448
- entry: z.array(z.union([z.string().min(1), z.strictObject({
7449
- node: z.string().min(1),
7450
- task: z.unknown()
7451
- })])).min(1).optional(),
7452
- edges: z.array(z.record(z.string(), z.unknown())),
7453
- gates: z.array(z.unknown()).optional(),
7454
- budget: z.strictObject({
7455
- maxIterations: nonnegativeInteger,
7456
- maxTokens: nonnegativeInteger,
7457
- maxUsd: z.number().finite().nonnegative().optional(),
7458
- deadlineMs: nonnegativeInteger.optional(),
7459
- resources: z.record(z.string(), z.strictObject({
7460
- unit: z.string().min(1),
7461
- limit: nonnegativeInteger
7462
- })).optional()
7463
- }),
7464
- check: z.union([
7465
- equals.extend({ describe: z.string().optional() }),
7466
- oneOf.extend({ describe: z.string().optional() }),
7467
- exists.extend({ describe: z.string().optional() }),
7468
- z.strictObject({
7469
- describe: z.string().optional(),
7470
- all: z.array(match).min(1)
7471
- }),
7472
- z.strictObject({
7473
- describe: z.string().optional(),
7474
- command
7475
- })
7476
- ]).optional(),
7477
- deliverable: z.strictObject({
7478
- describe: z.string().optional(),
7479
- checkRef: z.string().min(1),
7480
- command: command.optional(),
7481
- when: graphRouteWhenSchema.optional()
7482
- }).optional(),
7483
- on: z.unknown().optional()
7484
- });
7485
- /** Judge the flow's terminal-output map with RouteWhen's own JSON-pointer semantics. */
7486
- function checkGraphRoute(when, output) {
7487
- return ("all" in when ? when.all : [when]).every((condition) => {
7488
- let document = output;
7489
- if (condition.node !== void 0) {
7490
- if (!output || typeof output !== "object" || !Object.hasOwn(output, condition.node)) return false;
7491
- document = output[condition.node];
7492
- }
7493
- const selected = resolveJsonPointer(document, condition.pointer);
7494
- if ("exists" in condition) return selected.found === condition.exists;
7495
- if (!selected.found) return false;
7496
- return "equals" in condition ? selected.value === condition.equals : condition.in.some((value) => value === selected.value);
7497
- });
7498
- }
7499
- // src/runtime/supervise/graph-parameters.ts
7500
- const triggerPart = z.strictObject({ trigger: z.array(z.string()).min(1) });
7501
- const literalPart = z.strictObject({ literal: z.string() });
7502
- /** Explicit authored trigger slots in compiled graph data. An empty list marks fully bound data. */
7503
- const graphTriggerBindingsSchema = z.array(z.strictObject({
7504
- path: z.array(z.union([z.string(), z.number().int().nonnegative()])).min(1),
7505
- mode: z.enum(["value", "text"]),
7506
- parts: z.array(z.union([literalPart, triggerPart])).min(1)
7507
- }).superRefine((slot, context) => {
7508
- if (!slot.parts.some((part) => "trigger" in part) || slot.mode === "value" && (slot.parts.length !== 1 || !("trigger" in slot.parts[0]))) context.addIssue({
7509
- code: "custom",
7510
- message: "binding requires authored trigger parts; value slots require one trigger"
7511
- });
7512
- }));
7513
- function readBinding(namespace, keys, bindings) {
7514
- let found = bindings[namespace];
7515
- for (const key of keys) {
7516
- if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
7517
- found = found[key];
7518
- }
7519
- if (found === void 0) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
7520
- return structuredClone(found);
7521
- }
7522
- function textValue(value, expression) {
7523
- if (value !== null && typeof value === "object") throw new ValidationError(`graph parameters: ${expression} needs a whole JSON slot`);
7524
- return String(value);
7525
- }
7526
- function pendingText(parts) {
7527
- return parts.map((part) => "literal" in part ? part.literal : `\${trigger.${part.trigger.join(".")}}`).join("");
7528
- }
7529
- /** Compile authored slots once. Inserted values are data, never recursively parsed templates. */
7530
- function compileGraphParameters(value, bindings, options = {}) {
7531
- const visiting = /* @__PURE__ */ new Set();
7532
- const triggerBindings = [];
7533
- const bind = (item, path) => {
7534
- if (typeof item === "string") {
7535
- if (item.replace(/\$\{[^{}]+\}/g, "").includes("${")) throw new ValidationError("graph parameters: malformed reference");
7536
- const whole = /^\$\{([^{}]+)\}$/.exec(item);
7537
- const parts = [];
7538
- let cursor = 0;
7539
- let wholeValue;
7540
- let boundWhole = false;
7541
- for (const match of item.matchAll(/\$\{([^{}]+)\}/g)) {
7542
- if (match.index > cursor) parts.push({ literal: item.slice(cursor, match.index) });
7543
- const [namespace, ...keys] = match[1].split(".");
7544
- if (namespace !== "params" && namespace !== "trigger" || keys.length === 0) throw new ValidationError(`graph parameters: unsupported reference \${${match[1]}}`);
7545
- if (options.defer?.includes(namespace)) {
7546
- if (namespace === "trigger") parts.push({ trigger: keys });
7547
- else parts.push({ literal: match[0] });
7548
- } else {
7549
- const found = readBinding(namespace, keys, bindings);
7550
- if (whole) {
7551
- wholeValue = found;
7552
- boundWhole = true;
7553
- } else parts.push({ literal: textValue(found, match[1]) });
7554
- }
7555
- cursor = match.index + match[0].length;
7556
- }
7557
- if (boundWhole) return wholeValue;
7558
- if (cursor === 0) return item;
7559
- if (cursor < item.length) parts.push({ literal: item.slice(cursor) });
7560
- if (parts.some((part) => "trigger" in part)) triggerBindings.push({
7561
- path,
7562
- mode: whole ? "value" : "text",
7563
- parts
7564
- });
7565
- return pendingText(parts);
7566
- }
7567
- if (!item || typeof item !== "object") return item;
7568
- if (visiting.has(item)) throw new ValidationError("graph parameters: cyclic data is not JSON");
7569
- visiting.add(item);
7570
- 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])]));
7571
- visiting.delete(item);
7572
- return bound;
7573
- };
7574
- return {
7575
- value: bind(value, []),
7576
- triggerBindings
7577
- };
7578
- }
7579
- /** Legacy authored-data binding. Compiled graphs use bindCompiledGraphTriggers instead. */
7580
- function bindGraphParameters(value, bindings, options = {}) {
7581
- return compileGraphParameters(value, bindings, options).value;
7582
- }
7583
- /** Check provenance against the exact provisional values without reading trigger data. */
7584
- function assertGraphTriggerBindings(value, slots) {
7585
- const seen = /* @__PURE__ */ new Set();
7586
- for (const slot of graphTriggerBindingsSchema.parse(slots)) {
7587
- const key = JSON.stringify(slot.path.map(String));
7588
- if (seen.has(key)) throw new ValidationError("graph parameters: duplicate trigger binding path");
7589
- seen.add(key);
7590
- let found = value;
7591
- for (const key of slot.path) {
7592
- if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError("graph parameters: trigger binding path does not exist");
7593
- found = found[key];
7594
- }
7595
- if (found !== pendingText(slot.parts)) throw new ValidationError("graph parameters: trigger binding does not match its provisional value");
7596
- }
7597
- }
7598
- /** Only explicitly recorded authored slots bind. Literal parameter/trigger values are untouched. */
7599
- function bindCompiledGraphTriggers(value, slots, trigger) {
7600
- assertGraphTriggerBindings(value, slots);
7601
- const bound = structuredClone(value);
7602
- for (const slot of slots) {
7603
- let parent = bound;
7604
- for (const key of slot.path.slice(0, -1)) parent = parent[key];
7605
- 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("");
7606
- }
7607
- return bound;
7608
- }
7609
- // src/runtime/supervise/graph-registry.ts
7610
- /**
7611
- * `graph-registry` — the designer's memory: graphs and their outcomes as files.
7612
- *
7613
- * The AgentGraph algebra makes a graph PLAIN DATA (nodes with pinned profiles,
7614
- * edges with registry-versioned directives, a budget, a deliverable
7615
- * description), which is the property that lets a graph be stored, replayed
7616
- * byte-identical, and mutated like code. This module is the thin durable layer
7617
- * on top: one JSONL record per run, the exact graph content-addressed beside
7618
- * it. The natural home is a SANDBOX WORKSPACE — the platform's snapshot story
7619
- * (Firecracker restore, warm leases, `continuity: 'resume'`) then makes the
7620
- * registry the agent's compounding execution memory across runs: a rerun over
7621
- * the same sandbox finds every graph the designer ever ran, what each cost,
7622
- * and whether it delivered.
7623
- *
7624
- * ORACLES STAY ENVIRONMENT-OWNED. `DeliverableSpec.check` is a function and is
7625
- * deliberately NOT stored: a stored graph keeps the deliverable's `describe`
7626
- * and an optional `checkRef`, and replay re-binds the check from the caller's
7627
- * environment. This is the graph contract's own doctrine — graders are
7628
- * environment, never workers — applied to persistence.
7629
- *
7630
- * Scoring is a documented heuristic, not a learned model: delivered beats
7631
- * failed, then cheaper (tokens, then iterations), then most recent. A designer
7632
- * that needs better selection replaces `pickBest`, not the records.
7633
- */
7634
- var graph_registry_exports = /* @__PURE__ */ __exportAll({
7635
- digestOfGraph: () => digestOfGraph,
7636
- graphCorpusSummary: () => graphCorpusSummary,
7637
- graphDigest: () => graphDigest,
7638
- graphFromStored: () => graphFromStored,
7639
- graphRegistry: () => graphRegistry,
7640
- graphRunsFor: () => graphRunsFor,
7641
- listGraphRuns: () => listGraphRuns,
7642
- loadGraph: () => loadGraph,
7643
- lookupGraph: () => lookupGraph,
7644
- pickBestGraph: () => pickBestGraph,
7645
- recordGraphRun: () => recordGraphRun,
7646
- recordStoredGraphRun: () => recordStoredGraphRun,
7647
- storedGraphDigests: () => storedGraphDigests,
7648
- taskShapeDigest: () => taskShapeDigest
7649
- });
7650
- const RECORDS_FILE = "records.jsonl";
7651
- const GRAPHS_DIR = "graphs";
7652
- /** Canonical serialization for content-addressing: stable key order, sorted. */
7653
- function canonicalJson$1(value) {
7654
- if (Array.isArray(value)) return `[${value.map(canonicalJson$1).join(",")}]`;
7655
- 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(",")}}`;
7656
- return JSON.stringify(value);
7657
- }
7658
- /** Digest of the exact graph (nodes + edges + budget + deliverable describe, and a flow graph's
7659
- * entry and gates). An absent key is not serialized, so a graph without `entry` keeps the digest
7660
- * it had before flow graphs were stored. */
7661
- function graphDigest(graph) {
7662
- return sha256(canonicalJson$1(graph));
7663
- }
7664
- /** Digest of the normalized task shape a designer looks records up by. */
7665
- function taskShapeDigest(taskShape) {
7666
- return sha256(canonicalJson$1(taskShape));
7667
- }
7668
- /** Digest of a runnable graph exactly as the registry stores it — the value
7669
- * `recordGraphRun` demands. Callers recording real runs hash through this,
7670
- * never hand-rolled, so a record always matches its graph. */
7671
- function digestOfGraph(graph) {
7672
- return storeGraph(graph).digest;
7673
- }
7674
- function storeGraph(graph) {
7675
- const { describe, checkRef, command, when } = graph.deliverable;
7676
- const content = {
7677
- nodes: graph.nodes,
7678
- edges: graph.edges,
7679
- budget: graph.budget,
7680
- ...graph.triggerBindings === void 0 ? {} : { triggerBindings: graph.triggerBindings },
7681
- deliverable: {
7682
- ...describe ? { describe } : {},
7683
- ...checkRef ? { checkRef } : {},
7684
- ...command ? { command } : {},
7685
- ...when ? { when } : {}
7686
- },
7687
- ...graph.entry === void 0 ? {} : { entry: graph.entry },
7688
- ...graph.gates === void 0 ? {} : { gates: graph.gates }
7689
- };
7690
- return {
7691
- digest: graphDigest(content),
7692
- ...content
7693
- };
7694
- }
7695
- function assertRecord(record) {
7696
- if (typeof record.graphDigest !== "string" || record.graphDigest.length === 0) throw new ValidationError("graph-registry: record.graphDigest is required");
7697
- if (typeof record.taskDigest !== "string" || record.taskDigest.length === 0) throw new ValidationError("graph-registry: record.taskDigest is required");
7698
- if (!Number.isFinite(Date.parse(record.startedAt))) throw new ValidationError("graph-registry: record.startedAt must be a timestamp");
7699
- if (![
7700
- "delivered",
7701
- "no-winner",
7702
- "unknown",
7703
- "running"
7704
- ].includes(record.outcome.kind)) throw new ValidationError("graph-registry: invalid record.outcome.kind");
7705
- 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");
7706
- if ((record.outcome.kind === "unknown" || record.outcome.kind === "running") && !record.outcome.reason) throw new ValidationError("graph-registry: incomplete outcomes require a reason");
7707
- if (record.source && (!record.source.kind || !record.source.id)) throw new ValidationError("graph-registry: source.kind and source.id are required");
7708
- 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");
7709
- 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}`);
7710
- }
7711
- function recordKey(record) {
7712
- assertRecord(record);
7713
- if (record.source) return JSON.stringify([
7714
- "source",
7715
- record.source.kind,
7716
- record.source.id
7717
- ]);
7718
- return JSON.stringify([
7719
- record.taskDigest,
7720
- record.graphDigest,
7721
- record.startedAt
7722
- ]);
7723
- }
7724
- /** Open (or lazily create) a registry rooted at a workspace directory. The
7725
- * directory is the sandbox workspace; snapshots carry it across runs. */
7726
- function graphRegistry(root) {
7727
- if (!root || root.trim().length === 0) throw new ValidationError("graphRegistry: root directory is required");
7728
- return { root };
7729
- }
7730
- /** Append one run record; the exact graph is content-addressed beside it.
7731
- * Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with
7732
- * the same key replaces the prior row rather than duplicating it. */
7733
- async function recordGraphRun(reg, graph, record) {
7734
- return recordStoredGraphRun(reg, storeGraph(graph), record);
7735
- }
7736
- /** Store an executable graph or an observed external topology in the same registry.
7737
- * Imported observations retain their source identity and never authorize replay.
7738
- * A reader refreshing facts can preserve independently joined labels; an explicit
7739
- * correction leaves preserveLabels unset and replaces the record. */
7740
- async function recordStoredGraphRun(reg, definition, record, options = {}) {
7741
- const { digest, ...content } = definition;
7742
- const stored = {
7743
- ...content,
7744
- digest: digest ?? graphDigest(content)
7745
- };
7746
- if (stored.observed && !record) throw new ValidationError("graph-registry: observed graphs require a source run identity");
7747
- if (record) {
7748
- assertRecord(record);
7749
- if (stored.observed && !record.source) throw new ValidationError("graph-registry: observed graphs require a source run identity");
7750
- if (!stored.observed && !record.finishedAt) throw new ValidationError("graph-registry: native graph runs require a completion timestamp");
7751
- 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");
7752
- 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`);
7753
- }
7754
- if (graphDigest(content) !== stored.digest) throw new ValidationError("graph-registry: stored graph content does not match its digest");
7755
- await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true });
7756
- const file = join(reg.root, RECORDS_FILE);
7757
- return withJsonlFileLock(file, async (canonicalPath) => {
7758
- if (!record) {
7759
- await persistGraph(reg, stored);
7760
- return stored;
7761
- }
7762
- let persisted = record;
7763
- if (options.preserveLabels && record.source) {
7764
- const prior = (await readCommittedJsonFile(canonicalPath)).find((row) => row.source?.kind === record.source.kind && row.source.id === record.source.id);
7765
- if (prior) {
7766
- const taskType = record.taskType ?? prior.taskType;
7767
- const priorTerminal = prior.outcome.kind === "delivered" || prior.outcome.kind === "no-winner";
7768
- const incomingUnassessed = record.outcome.kind === "unknown" || record.outcome.kind === "running";
7769
- if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt) throw new ValidationError("graph-registry: preserving labels requires the same task start and source identity");
7770
- const evidence = [...prior.evidence ?? [], ...record.evidence ?? []];
7771
- persisted = {
7772
- ...record,
7773
- ...taskType ? { taskType } : {},
7774
- ...record.unknowns ? { unknowns: record.unknowns.filter((reason) => !(taskType && reason === "task type not explicitly labeled")) } : {},
7775
- ...evidence.length ? { evidence: [...new Map(evidence.map((entry) => [canonicalJson$1(entry), entry])).values()] } : {},
7776
- ...priorTerminal && incomingUnassessed ? {
7777
- outcome: prior.outcome,
7778
- finishedAt: prior.finishedAt,
7779
- cost: {
7780
- ...record.cost,
7781
- ...prior.cost.ms === void 0 ? {} : { ms: prior.cost.ms },
7782
- ...prior.cost.mergeMs === void 0 ? {} : { mergeMs: prior.cost.mergeMs }
7783
- }
7784
- } : {}
7785
- };
7786
- }
7787
- }
7788
- assertRecord(persisted);
7789
- await persistGraph(reg, stored);
7790
- await upsertCommittedJsonLine(canonicalPath, persisted, recordKey);
7791
- return stored;
7792
- });
7793
- }
7794
- async function persistGraph(reg, stored) {
7795
- const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`);
7796
- try {
7797
- const { digest: existingDigest, ...existing } = JSON.parse(await readFile(revisionPath, "utf8"));
7798
- if (existingDigest !== stored.digest || graphDigest(existing) !== stored.digest) throw new ValidationError("graph-registry: stored graph revision is immutable but its content differs");
7799
- } catch (error) {
7800
- if (!isNoEntError(error)) throw error;
7801
- writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true });
7802
- }
7803
- }
7804
- /** All records, newest last. */
7805
- async function listGraphRuns(reg) {
7806
- return readCommittedJsonFile(join(reg.root, RECORDS_FILE));
7807
- }
7808
- function observedTopology(record) {
7809
- return record.topologyDigest ?? (record.source ? "unknown" : record.graphDigest);
7810
- }
7811
- /** Records for one task shape or deterministic label query, newest last. */
7812
- async function graphRunsFor(reg, query = {}) {
7813
- const filters = typeof query === "string" ? { taskDigest: query } : query;
7814
- 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));
7815
- }
7816
- function medianKnown(values) {
7817
- const known = values.filter((value) => value !== void 0 && Number.isFinite(value) && value >= 0).sort((a, b) => a - b);
7818
- const middle = Math.floor(known.length / 2);
7819
- return {
7820
- count: known.length,
7821
- median: known.length === 0 ? null : known.length % 2 ? known[middle] : (known[middle - 1] + known[middle]) / 2
7822
- };
7823
- }
7824
- function observedGraphSummary(records) {
7825
- const groups = /* @__PURE__ */ new Map();
7826
- for (const record of records) {
7827
- const key = JSON.stringify([record.taskType ?? "unknown", observedTopology(record)]);
7828
- const rows = groups.get(key);
7829
- if (rows) rows.push(record);
7830
- else groups.set(key, [record]);
7831
- }
7832
- const summaries = [...groups.values()].map((runs) => {
7833
- const assessed = runs.filter((run) => run.outcome.kind === "delivered" || run.outcome.kind === "no-winner");
7834
- const delivered = assessed.filter((run) => run.outcome.kind === "delivered");
7835
- const wall = medianKnown(assessed.map((run) => run.cost.ms));
7836
- const merge = medianKnown(delivered.filter((run) => run.evidence?.some((entry) => entry.kind === "pr-merged")).map((run) => run.cost.mergeMs));
7837
- const tokens = medianKnown(assessed.map((run) => run.cost.tokens));
7838
- const human = medianKnown(assessed.map((run) => run.cost.humanMessages));
7839
- return {
7840
- taskType: runs[0].taskType ?? "unknown",
7841
- topologyDigest: observedTopology(runs[0]),
7842
- delivered: delivered.length,
7843
- assessed: assessed.length,
7844
- unknown: runs.length - assessed.length,
7845
- deliveredRate: assessed.length ? delivered.length / assessed.length : null,
7846
- medianWallMs: wall.median,
7847
- wallMsCount: wall.count,
7848
- medianMergeMs: merge.median,
7849
- mergeMsCount: merge.count,
7850
- medianTokens: tokens.median,
7851
- tokenCount: tokens.count,
7852
- medianHumanMessages: human.median,
7853
- humanMessageCount: human.count,
7854
- runs
7855
- };
7856
- });
7857
- summaries.sort((a, b) => {
7858
- const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1);
7859
- if (delivered) return delivered;
7860
- for (const key of [
7861
- "medianWallMs",
7862
- "medianTokens",
7863
- "medianHumanMessages"
7864
- ]) {
7865
- if (a[key] === b[key]) continue;
7866
- if (a[key] === null) return 1;
7867
- if (b[key] === null) return -1;
7868
- return a[key] - b[key];
7869
- }
7870
- return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest);
7871
- });
7872
- return {
7873
- recordCount: records.length,
7874
- groups: summaries
7875
- };
7876
- }
7877
- /** Query and rank the same registry records using the opt-in observational
7878
- * policy: delivery rate, wall time, tokens, then human messages; unknowns last. */
7879
- async function graphCorpusSummary(reg, query = {}) {
7880
- return observedGraphSummary(await graphRunsFor(reg, query));
7881
- }
7882
- /** The documented heuristic: delivered beats failed; among delivered, cheaper
7883
- * (tokens, then iterations) wins; ties go to the most recent. */
7884
- function pickBestGraph(records, options = {}) {
7885
- if (options.policy === "observed") {
7886
- const group = observedGraphSummary(records).groups[0];
7887
- return group && pickBestGraph(group.runs);
7888
- }
7889
- const delivered = records.filter((row) => row.outcome.kind === "delivered");
7890
- if (delivered.length === 0) return void 0;
7891
- const better = (a, b) => {
7892
- const aTokens = a.cost.tokens ?? Number.POSITIVE_INFINITY;
7893
- const bTokens = b.cost.tokens ?? Number.POSITIVE_INFINITY;
7894
- if (aTokens !== bTokens) return aTokens < bTokens ? a : b;
7895
- const aIter = a.cost.iterations ?? Number.POSITIVE_INFINITY;
7896
- const bIter = b.cost.iterations ?? Number.POSITIVE_INFINITY;
7897
- if (aIter !== bIter) return aIter < bIter ? a : b;
7898
- return a.finishedAt >= b.finishedAt ? a : b;
7899
- };
7900
- return delivered.reduce((best, row) => better(best, row) === best ? best : row);
7901
- }
7902
- /** Load a stored graph by digest. */
7903
- async function loadGraph(reg, digest) {
7904
- try {
7905
- return JSON.parse(await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), "utf8"));
7906
- } catch {
7907
- return;
7908
- }
7909
- }
7910
- /** The designer's lookup: replay the known-good graph for this task shape, or
7911
- * author a new one — with the reason stated either way (the decision is data). */
7912
- async function lookupGraph(reg, taskDigest) {
7913
- const records = await graphRunsFor(reg, taskDigest);
7914
- const candidates = [];
7915
- const loaded = /* @__PURE__ */ new Map();
7916
- for (const record of records) {
7917
- if (!loaded.has(record.graphDigest)) loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest));
7918
- if (!loaded.get(record.graphDigest)?.observed) candidates.push(record);
7919
- }
7920
- if (records.length && !candidates.length) return {
7921
- kind: "author",
7922
- reason: "only observed topologies are available; author an executable graph"
7923
- };
7924
- const best = pickBestGraph(candidates);
7925
- if (best) {
7926
- const graph = await loadGraph(reg, best.graphDigest);
7927
- if (graph) return {
7928
- kind: "replay",
7929
- graph,
7930
- record: best
7931
- };
7932
- return {
7933
- kind: "author",
7934
- reason: `best record's graph ${best.graphDigest.slice(0, 12)} is missing from the registry`
7935
- };
7936
- }
7937
- return {
7938
- kind: "author",
7939
- reason: records.length === 0 ? "first run for this task shape" : "no graph delivered for this task shape yet"
7940
- };
7941
- }
7942
- /** Rehydrate a stored graph, binding trigger data and an environment-owned named check. */
7943
- function graphFromStored(stored, environment = {}) {
7944
- if (stored.observed) throw new ValidationError("graphFromStored: observed topology cannot be replayed");
7945
- 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 ?? {} });
7946
- 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;
7947
- if (!selected) throw new ValidationError(`graphFromStored: unknown checkRef ${deliverable.checkRef ?? "(missing)"}`);
7948
- const materialized = stored.triggerBindings === void 0 ? {} : { triggerBindings: [] };
7949
- if (typeof selected === "function") {
7950
- const { command: _command, ...description } = deliverable;
7951
- return {
7952
- ...topology,
7953
- ...materialized,
7954
- deliverable: {
7955
- ...description,
7956
- check: selected
7957
- }
7958
- };
7959
- }
7960
- const command = selected === deliverable.command ? selected : bindGraphParameters(selected, { trigger: environment.trigger ?? {} });
7961
- return {
7962
- ...topology,
7963
- ...materialized,
7964
- deliverable: {
7965
- ...deliverable,
7966
- command,
7967
- check: () => false
7968
- }
7969
- };
7970
- }
7971
- /** Digests present on disk (integrity probe for tests and audits). */
7972
- async function storedGraphDigests(reg) {
7973
- try {
7974
- return (await readdir(join(reg.root, GRAPHS_DIR))).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5)).sort();
7975
- } catch {
7976
- return [];
7977
- }
7978
- }
7979
7391
  // src/runtime/supervise/supervise-graph-subtasks.ts
7980
7392
  /** A stored graph's topology, from the registry `SuperviseOptions.graphRegistry` names. */
7981
7393
  async function storedGraphTopology(dir, digest) {
@@ -10178,6 +9590,6 @@ function superviseWithContext(profile, task, opts, brain) {
10178
9590
  ...signal === void 0 ? {} : { signal }
10179
9591
  }, brain));
10180
9592
  }
10181
- export { dumbContinuationFailPrompt as $, graphRouteWhenSchema as A, createGraphOverlay as B, storedGraphDigests as C, compileGraphParameters as D, bindGraphParameters as E, composeReentryTask as F, routeFlowOf as G, createFlowRun as H, serveCoordinationMcp as I, graphRootProfile as J, validateFlowGraph as K, coordinationControlToolNames as L, supervisorAgent as M, supervisorAgentWithTestBrain as N, graphTriggerBindingsSchema as O, UNPROVEN_CONTINUITY as P, delegatesWorkerBriefPrompt as Q, driverAgent as R, recordStoredGraphRun as S, assertGraphTriggerBindings as T, flowRootProfile as U, GraphRouteError as V, journaledGateDecider as W, analyzesFindingsReportPrompt as X, validateGraphTopology as Y, createPromptRegistry as Z, listGraphRuns as _, superviseRootProfile as a, allWorkersStalled as at, pickBestGraph as b, retryPreSpawnRefusals as c, plateau as ct, graphCorpusSummary as d, bestSoFar as dt, dumbContinuationPassPrompt as et, graphDigest as f, plateauLength as ft, graph_registry_exports as g, createSupervisorSpanRecorder as gt, graphRunsFor as h, readRootStreamReceipt as ht, profileGuidanceComposer as i, promptHandle as it, workerFromBackend as j, graphFileSchema as k, withWorkerSpawnRetry as l, anytimeReport as lt, graphRegistry as m, readRootStream as mt, superviseFleetCapabilities as n, kernelPromptRegistry as nt, isPreSpawnExecutorFailure as o, anyOf as ot, graphFromStored as p, renderAnytimeTable as pt, defaultEdgeTraversalCap as q, superviseWithTestBrain as r, naiveContinuationPrompt as rt, resolveWorkerSpawnRetry as s, noProgressFor as st, supervise as t, formatPromptHandle as tt, digestOfGraph as u, areaUnderCurve 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 };
10182
9594
 
10183
- //# sourceMappingURL=supervise-DKwnVruI.js.map
9595
+ //# sourceMappingURL=supervise-Cl0F57m9.js.map