@tangle-network/agent-runtime 0.132.4 → 0.132.6

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 (66) hide show
  1. package/README.md +2 -2
  2. package/dist/{activation-DFJBEC62.js → activation-U2mou_hT.js} +2 -2
  3. package/dist/{activation-DFJBEC62.js.map → activation-U2mou_hT.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{authoring-WS1l0lU1.js → authoring-sf0VpHlY.js} +2 -2
  7. package/dist/{authoring-WS1l0lU1.js.map → authoring-sf0VpHlY.js.map} +1 -1
  8. package/dist/{conversation-D95pue6P.js → conversation-BiII3X_6.js} +3 -3
  9. package/dist/{conversation-D95pue6P.js.map → conversation-BiII3X_6.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/conversation.js +1 -1
  12. package/dist/{environment-provider-DlYw_pjo.d.ts → environment-provider-CkSDxRZd.d.ts} +2 -2
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/{graph-B9hFN-zX.js → graph-DjTw-HMK.js} +2 -2
  15. package/dist/{graph-B9hFN-zX.js.map → graph-DjTw-HMK.js.map} +1 -1
  16. package/dist/{improvement-cycle-DgZtiPDT.js → improvement-cycle-paspYVfE.js} +4 -4
  17. package/dist/{improvement-cycle-DgZtiPDT.js.map → improvement-cycle-paspYVfE.js.map} +1 -1
  18. package/dist/{index-CcpNgmQY.d.ts → index-BsrFZu0N.d.ts} +4 -4
  19. package/dist/{index-iwZ0at5o.d.ts → index-Cdf9NET5.d.ts} +2 -2
  20. package/dist/{index-D9dVsozT.d.ts → index-DixXnx07.d.ts} +73 -7
  21. package/dist/index.d.ts +8 -8
  22. package/dist/index.js +10 -10
  23. package/dist/index.js.map +1 -1
  24. package/dist/intelligence.d.ts +4 -4
  25. package/dist/intelligence.js +3 -3
  26. package/dist/kernel.d.ts +6 -6
  27. package/dist/kernel.js +7 -7
  28. package/dist/{knowledge-By_lZ80W.js → knowledge-DV8PEBph.js} +3 -3
  29. package/dist/{knowledge-By_lZ80W.js.map → knowledge-DV8PEBph.js.map} +1 -1
  30. package/dist/knowledge.d.ts +1 -1
  31. package/dist/knowledge.js +1 -1
  32. package/dist/{loop-runner-bin-D9OAFkP_.d.ts → loop-runner-bin-BqJGlXju.d.ts} +3 -3
  33. package/dist/{loop-runner-bin-CjsTZUVS.js → loop-runner-bin-C1G7gPX0.js} +3 -3
  34. package/dist/{loop-runner-bin-CjsTZUVS.js.map → loop-runner-bin-C1G7gPX0.js.map} +1 -1
  35. package/dist/loop-runner-bin.d.ts +1 -1
  36. package/dist/loop-runner-bin.js +1 -1
  37. package/dist/{materialization-DBXuH34A.js → materialization-JR_nN_oT.js} +18 -2
  38. package/dist/materialization-JR_nN_oT.js.map +1 -0
  39. package/dist/mcp/bin.js +3 -3
  40. package/dist/mcp/index.d.ts +3 -3
  41. package/dist/mcp/index.js +4 -4
  42. package/dist/{openai-tools-BATxru3h.js → openai-tools-Ba0yu9hI.js} +2 -2
  43. package/dist/{openai-tools-BATxru3h.js.map → openai-tools-Ba0yu9hI.js.map} +1 -1
  44. package/dist/primeintellect/index.d.ts +1 -1
  45. package/dist/{redact-mWj5eu4X.d.ts → redact-BAnM2avI.d.ts} +3 -3
  46. package/dist/{runtime-YuPbrgG1.js → runtime-BeBAzfnW.js} +65 -15
  47. package/dist/runtime-BeBAzfnW.js.map +1 -0
  48. package/dist/{runtime-aXvRThzL.d.ts → runtime-CKk_poJ-.d.ts} +3 -3
  49. package/dist/{stream-agent-turn-BxwZJVfZ.js → stream-agent-turn-Bo5ZSAUR.js} +2 -2
  50. package/dist/{stream-agent-turn-BxwZJVfZ.js.map → stream-agent-turn-Bo5ZSAUR.js.map} +1 -1
  51. package/dist/{stream-agent-turn-BXiMHdCf.d.ts → stream-agent-turn-By46GZlo.d.ts} +2 -2
  52. package/dist/{structural-rollout-Dq0j-JHl.js → structural-rollout-DGkq_Grt.js} +18 -9
  53. package/dist/structural-rollout-DGkq_Grt.js.map +1 -0
  54. package/dist/{supervise-BDj-uFfb.js → supervise-B2fTctMn.js} +40 -5
  55. package/dist/supervise-B2fTctMn.js.map +1 -0
  56. package/dist/{supervisor-DlVTwwJb.js → supervisor-BTuNGicF.js} +36 -5
  57. package/dist/supervisor-BTuNGicF.js.map +1 -0
  58. package/dist/testing.d.ts +2 -2
  59. package/dist/testing.js +11 -11
  60. package/dist/{types-B9KAen_0.d.ts → types-BjUQODeG.d.ts} +21 -2
  61. package/package.json +4 -4
  62. package/dist/materialization-DBXuH34A.js.map +0 -1
  63. package/dist/runtime-YuPbrgG1.js.map +0 -1
  64. package/dist/structural-rollout-Dq0j-JHl.js.map +0 -1
  65. package/dist/supervise-BDj-uFfb.js.map +0 -1
  66. package/dist/supervisor-DlVTwwJb.js.map +0 -1
package/dist/kernel.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { C as MountRecorder, D as SelectionReceipt, E as SandboxClient, O as ValidationCtx, S as MountManifestEntry, T as RunProvenance, _ as LoopTeardownFailedPayload, a as Iteration, b as LoopTraceEvent, c as LoopIterationDispatchPayload, d as LoopLineageOptions, f as LoopPlanDescription, g as LoopStartedPayload, h as LoopSandboxPlacement, i as ExecCtx, k as Validator, l as LoopIterationEndedPayload, m as LoopResult, n as DefaultVerdict, o as LoopDecisionPayload, p as LoopPlanPayload, r as Driver, s as LoopEndedPayload, t as AgentRunSpec, u as LoopIterationStartedPayload, v as LoopTokenUsage, w as OutputAdapter, x as LoopWinner, y as LoopTraceEmitter } from "./types-6zHo67jn.js";
2
- import { $ as legacySupervisorRunsRoot, $a as ResolveDriveHarness, $c as ScoreOf, $i as BenchmarkLift, $n as selectBestIndex, $o as classifyDriverFailure, $r as AcquireOptions, $s as ScopeAnalyzeInput, $t as rollingDispatch, A as GitWorkspaceOptions, Aa as LoopCampaignDispatchOptions, Ac as LeaderboardIterationInfo, Af as materializeTreeView, Ai as FileCorpus, Al as CoordinationEvent, An as supervisorInstructions, Ao as createProgressTracker, Ar as Deliverable, As as CorpusFilter, At as runGraph, B as analyzeTrace, Ba as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, Bc as completionAuthorizes, Bi as widen, Bn as StructuralRolloutPolicy, Bo as FinalizeContext, Br as SandboxLineage, Bs as FlatWidenGate, Bt as formatPromptHandle, C as closingWorkerNote, Ca as breadthStrategy, Cc as ShapeContext, Cf as SpawnForest, Ci as equalKOnCost, Cl as AnalystFindingEvent, Cn as AuthoredProfile, Co as ProgressTrackerOptions, Cr as MaterializeLocalMcpOptions, Cs as ObserveOptions, Ct as GraphEdgeCapError, D as UntrackedCopyStats, Da as runAgentic, Dc as LeaderboardBenchTask, Df as SpawnForestNode, Di as registerShape, Dl as AuthorizedDownMessage, Dn as assessAuthoredProfile, Do as allOf, Dr as StdioMcpServerSpec, Ds as AssertTraceDerivedFindings, E as CopyOptions, Ea as refine, Ec as LeaderboardBenchScore, Ef as SpawnForestMissingTree, Ei as createShapeRegistry, El as AuthorizeDownMessage, En as asAuthoredProfile, Eo as StopRule, Er as StdioMcpConnection, Es as renderReport, Et as RunGraphOptions, F as gitWorkspace, Fa as loopCampaignDispatch, Fc as defineLeaderboard, Fi as loopUntil, Fl as DownMessageDeliveryAttempt, Fn as CheckSource, Fo as SupervisorSpanOptions, Fr as SandboxRunAbortError, Fs as EqualKVerdict, Ft as analyzesFindingsReportPrompt, G as workerTraceAnalysisStore, Gc as GroupOf, Gi as createScopeAnalyst, Gn as composeCheckSources, Go as pickBestDelivered, Gr as createSandboxToolPartState, Gs as PanelJudge, Gt as ConcurrencyCaps, H as WorkerToolTraceArtifact, Ha as SuperviseOptions, Hc as sentinelCompletion, Hi as RegistryAnalyzeProjection, Hn as VisibleCheck, Ho as SupervisorFinalizer, Hr as SessionCapableBox, Hs as LoopUntilSpec, Ht as naiveContinuationPrompt, I as jjWorkspace, Ia as loopDispatch, Ic as CompletionAnalyst, Ii as panel, Il as DownMessageDeliveryOutcome, In as CheckSourceCtx, Io as SupervisorSpanOutcome, Ir as TurnResult, Is as Fanout, It as createPromptRegistry, J as ScopeArgs, Ja as workerFromBackend, Jc as LeaderboardOptions, Ji as McpEnvironmentOptions, Jl as WorkerSpawnContext, Jn as filterAuthoredAsserts, Jo as DriverAttemptRecord, Jr as mapSandboxToolEvent, Js as Pipeline, Jt as DispatchUnit, K as createRootHandle, Ka as supervise, Kc as Interval, Ki as registryScopeAnalyst, Kn as defaultExtractCandidate, Ko as runFinalizer, Kr as extractLlmCallEvent, Ks as PanelSpec, Kt as DispatchReport, L as localShell, La as superviseDispatch, Lc as CompletionEvidence, Li as pipeline, Ll as DownMessageEvent, Ln as RepairStop, Lo as SupervisorSpanRecorder, Lr as openSandboxRun, Ls as FanoutOptions, Lt as delegatesWorkerBriefPrompt, M as Workspace, Ma as LoopOptionsForDispatch, Mc as LeaderboardScenario, Mf as replaySpawnTree, Mi as renderCorpusToInstructions, Mn as CheckOutcome, Mo as plateau, Mr as OpenSandboxRunOptions, Ms as EqualKArm, Mt as PromptHandle, N as WorkspaceCommit, Na as SuperviseDispatchOptions, Nc as LeaderboardScore, Nf as contentAddress, Ni as fanout, Nl as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Nn as CheckRunContext, No as sampleFromSettled, Nr as OpenSandboxRunPromptOptions, Ns as EqualKOnCost, Nt as PromptRegistry, O as copyUntrackedIntoClone, Oa as sample, Oc as LeaderboardBenchmarkAdapter, Of as SpawnForestTree, Oi as definePersona, Ol as ContinuationInstruction, On as defaultProfileRichnessThresholds, Oo as allWorkersStalled, Or as connectStdioMcp, Os as CombinatorShape, Ot as TraversalContinuity, P as WorkspaceRun, Pa as SuperviseOptionsForDispatch, Pc as LeaderboardSpec, Pi as flatWidenGate, Pl as DownMessageAuthorizationInput, Pn as CheckRunner, Po as SupervisorSpanAttributes, Pr as SandboxRun, Ps as EqualKOnCostOptions, Pt as RegisteredPrompt, Q as legacySupervisorRunDir, Qa as ObserveSupervisorNodeEvent, Qc as ProfileKeyOf, Qi as BenchmarkConfig, Ql as normalizeAnalyzeOnSettle, Qn as sandboxCheckRunner, Qo as DriverRetryPolicy, Qr as probeSandboxCapabilities, Qs as ScopeAnalyst, Qt as queueOf, R as runInWorkspace, Ra as AuthorizedSpawn, Rc as CompletionPolicy, Ri as selectValidWinner, Rl as MakeWorkerAgent, Rn as StructuralRolloutConfig, Ro as createSupervisorSpanRecorder, Rr as CheckpointCapableBox, Rs as FanoutSynthesis, Rt as dumbContinuationFailPrompt, S as WorkerEvidenceInput, Sa as adaptiveRefine, Sc as ShapeBudget, Sf as InMemorySpawnJournal, Si as assertProfileModelsAllowed, Sl as createWaterfallCollector, Sn as spendFromUsageEvents, So as ProgressTracker, Sr as LocalMcpMaterialization, Ss as ObserveInput, St as GraphEdge, T as settledWorkerOut, Ta as depthStrategy, Tc as DefinedLeaderboard, Tf as SpawnForestInDoubtNode, Ti as builtinShapes, Tl as AnalyzeOnSettleRoute, Tn as ProfileRichnessThresholds, To as StopDecision, Tr as McpToolDescriptor, Ts as observe, Tt as GraphResult, U as captureWorkerTraceEvidence, Ua as SuperviseRegistry, Uc as stopSentinel, Ui as assertTraceDerivedFindings, Un as canDisplace, Uo as bestDelivered, Ur as createSandboxLineage, Us as LoopUntilState, Ut as promptHandle, V as WORKER_TOOL_TRACE_SCHEMA_VERSION, Va as DeliverableResolutionInput, Vc as deterministicCompletion, Vi as CreateScopeAnalystOptions, Vn as StructuralRolloutResult, Vo as FinalizerSettled, Vr as SandboxLineageHandle, Vs as LoopUntil, Vt as kernelPromptRegistry, W as parseWorkerToolTraceArtifact, Wa as SuperviseRegistryTable, Wc as AxisScoresOf, Wi as buildSteerContext, Wn as compareCheckOutcomes, Wo as collectDelivered, Wr as SandboxToolPartState, Ws as Panel, Wt as supervisorPolicyPrompt, X as settledToIteration, Xa as DriveHarness, Xc as PairwiseOptions, Xi as sanitizeMcpToolSchema, Xl as canonicalFindingEvent, Xn as officialChecksFromMeta, Xo as DriverAttemptsExhaustedError, Xr as CriuCapableClient, Xs as RenderCorpusToInstructions, Xt as effectiveConcurrency, Y as createScope, Ya as CoordinationBinding, Yc as LeaderboardRow, Yi as createMcpEnvironment, Yl as WorkerWatchOptions, Yn as modelAuthoredChecks, Yo as DriverAttemptStop, Yr as sumSandboxUsage, Ys as PipelineStage, Yt as RollingDispatchOptions, Z as WorkerSteerRequest, Za as DriveHarnessOwnerContext, Zc as PairwiseVerdict, Zi as BenchmarkCell, Zn as resolveEntrySymbol, Zo as DriverProgressMark, Zr as SandboxCapabilities, Zs as RenderCorpusToInstructionsOptions, Zt as freeSlots, _ as WorktreeFanoutOptions, _a as StrategyCtx, _c as Persona, _f as gateOnDeliverable, _i as PromotionVerdict, _l as plateauLength, _n as BudgetPoolRestore, _o as PriorCoordination, _r as AuthoredStrategy, _s as HarvestCorpusOptions, _t as WorktreePatchArtifact, a as SandboxInstance, aa as runBenchmark, ac as TrajectoryReportOptions, ai as ReconnectRetainedRunOptions, al as renderPairwiseMarkdown, ao as SupervisorNodeContextSeed, ar as EvolutionAuthor, as as KeyProvider, at as workerControlLogFile, b as NOTE_MAX_CHARS, ba as StrategyShotResult, bc as RunPersonified, bf as FileSpawnJournal, bi as profileOptimizerModelCall, bl as WaterfallReport, bn as ReservationTicket, bo as PlateauOptions, br as strategyAuthorContract, bs as harvestCorpus, bt as EdgeDeliveryOutcome, c as VerifierEnvironmentOptions, ca as AgenticSurface, cc as Widen, cf as BusStats, ci as RetainedRunEffect, cl as IntentAudit, cn as ChatCompletionsTransport, co as SupervisorToolInvocationContext, cr as EvolutionGeneration, cs as mcpSecretEnvMetadataKey, ct as writeWorkerSteer, d as SuperviseSurfaceResult, da as ArtifactHandle, dc as WidenSpec, df as createEventBus, di as RetainedRunReplayPoint, dl as AnytimeReport, dn as ChatTransportTool, do as supervisorAgent, dr as StrategyEvolutionConfig, ds as secretEnvOfMcpServer, dt as RunContext, ea as BenchmarkReport, ec as ScopeWidenGate, ei as acquireSandbox, el as leaderboard, en as DelegateOptions, eo as ResolveSupervisorTools, er as structuralRollout, es as RunAgentRoundsOptions, et as readWorkerSteerRequests, f as SurfaceWorkerConfig, fa as CorpusReadbackOptions, fc as WinnerStrategy, ff as WatchTraceOptions, fi as RetainedRunSnapshot, fl as AnytimeStrategySummary, fn as ChatWorkerSeamOptions, fr as discriminatingMeans, fs as inlineSandboxClient, ft as createFileRunContext, g as AuthoredHarness, ga as StrategyArtifacts, gc as Outcome, gf as ExecutorResultMapping, gi as PromotionGateOptions, gl as bestSoFar, gn as BudgetPool, go as FileCoordinationLog, gr as AuthorStrategyOptions, gs as inProcessSandboxClient, gt as WorktreeCliExecutorOptions, h as superviseSurface, ha as Strategy, hc as LoopShape, hf as DeliverableSpec, hi as resolveSandboxClient, hl as areaUnderCurve, hn as createChatSessionStore, ho as CoordinationOwnerId, hr as selectChampion, hs as InProcessSandboxClientOptions, ht as patchDelivered, i as SandboxEvent, ia as printBenchmarkReport, ic as TrajectoryReportFn, ii as NativeContextContinuationInput, il as renderLeaderboardSvg, in as serveCoordinationMcp, io as SupervisorNodeContext, ir as EvolutionArchiveNode, is as localSandboxClient, it as supervisorWorkersDir, j as Shell, ja as LoopDispatchOptions, jc as LeaderboardRunContext, jf as pendingWaits, ji as InMemoryCorpus, jn as CheckExecChannel, jo as noProgressFor, jr as OpenSandboxRunBeforeStartContext, js as CorpusRecord, k as withUntrackedArtifacts, ka as sampleThenRefine, kc as LeaderboardFlagSpec, kf as loadSpawnForest, ki as runPersonified, kl as ContinuityMode, kn as profileRichnessFinding, ko as anyOf, kr as materializeLocalMcp, ks as Corpus, kt as defaultEdgeTraversalCap, l as createVerifierEnvironment, la as AgenticTask, lc as WidenDecision, lf as EventBus, li as RetainedRunEventOptions, ll as auditIntent, ln as ChatSessionStore, lo as assertCoordinationBinding, lr as EvolutionReport, ls as resolveMcpServerLaunch, lt as InMemoryRunContext, m as failuresAnalyst, ma as ShotSpec, mc as DefinePersonaInput, mf as watchTrace, mi as ResolveSandboxClientOptions, ml as anytimeReport, mn as chatWorkerSeam, mo as CoordinationLog, mr as runStrategyEvolution, ms as InProcessPromptCtx, mt as PatchDeliverableOptions, n as AnalystFinding, na as BenchmarkTaskRow, nc as TrajectoryNode, ni as startRetainedRun, nl as renderLeaderboardHtml, nn as delegate, no as SupervisorAgentDeps, nr as ChampionPick, ns as runAgentRounds, nt as supervisorRunDir, o as computeFindingId, oa as AgenticOptions, oc as Verify, of as BusEvent, oi as RetainedRunCancelOptions, ol as AuditIntentInput, oo as SupervisorProfile, or as EvolutionBandInfo, os as ResolvedMcpServerLaunch, ot as workerInboxFile, p as SurfaceWorkerOut, pa as RunAgenticOptions, pc as DefinePersona, pf as defaultToolDetectors, pi as StartRetainedRunOptions, pl as AnytimeTaskCurve, pn as chatTransportExecutor, po as CoordinationDeliveryEvidence, pr as pickChampion, ps as InProcessOnPrompt, pt as createInMemoryRunContext, q as createSupervisor, qc as Leaderboard, qi as McpEndpoint, ql as WorkerResumeContext, qn as defaultStructuralRolloutPolicy, qo as runTree, qr as mapSandboxEvent, qs as PanelVerdict, qt as DispatchStopReason, r as CreateSandboxOptions, ra as Environment, rc as TrajectoryReport, ri as NativeContextContinuationExecution, rl as renderLeaderboardMarkdown, rn as CoordinationMcpHandle, rr as ChampionPolicy, rs as LocalSandboxClientOptions, rt as supervisorRunsRoot, s as makeFinding, sa as AgenticRunResult, sc as VerifySpec, sf as BusRecord, si as RetainedRunCancellation, sl as AuditIntentOptions, sn as finalizeBestDelivered, so as SupervisorToolDescriptor, sr as EvolutionCandidate, ss as envKeyProvider, st as workerInboxFileFromEventDir, t as AgentProfile, ta as BenchmarkStrategySummary, tc as SteerContext, ti as reconnectRetainedRun, tl as pairwiseSignificance, tn as defaultDelegateBudget, to as ResolvedSupervisorProfile, tr as visibleCheckScore, ts as defaultSelectWinner, tt as safeWorkerFile, u as SuperviseSurfaceOptions, ua as AgenticTool, uc as WidenLineage, uf as PublishOptions, ui as RetainedRunHandle, ul as defaultAuditorInstruction, un as ChatTransportExecutorOptions, uo as resolveSupervisorProfile, ur as ReproductionCheck, us as resolveSecretEnv, ut as InMemoryRunContextOptions, v as worktreeFanout, va as StrategyMessage, vc as PersonaContext, vf as mapExecutorResult, vi as promotionGate, vl as renderAnytimeTable, vn as BudgetReadout, vo as AllWorkersStalledOptions, vr as assertStrategyContract, vs as HarvestFailure, vt as createWorktreeCliExecutor, w as composeWorkerEvidence, wa as defineStrategy, wc as ShapeRegistry, wf as SpawnForestEvent, wi as trajectoryReport, wl as AnalystRegistry, wn as ProfileRichness, wo as ProgressView, wr as McpSpawnFault, ws as defaultAnalystInstruction, wt as GraphNode, x as VERIFY_TAIL_CHARS, xa as SurfaceScore, xc as RunPersonifiedOptions, xf as InMemoryResultBlobStore, xi as assertModelAllowed, xl as WaterfallSpan, xn as createBudgetPool, xo as ProgressSample, xr as strategyAuthorSystemPrompt, xs as Observation, xt as EdgeTraversal, y as EVIDENCE_MAX_CHARS, ya as StrategyResult, yc as PersonaExecutors, yf as FileResultBlobStore, yi as profileChatClient, yl as WaterfallCollector, yn as ReservationRejection, yo as NoProgressForOptions, yr as authorStrategy, ys as HarvestReport, yt as AgentGraph, z as TrajectoryAnalysis, za as AuthorizedSpawnContext, zc as CompletionVerdict, zi as verify, zn as StructuralRolloutMessage, zo as DeliveredOutput, zr as ForkCapableBox, zs as FanoutWinnerSelector, zt as dumbContinuationPassPrompt } from "./index-D9dVsozT.js";
3
- import { $ as WorkerTraceUnavailableReason, $t as pollFor, A as RootMaterialization, B as Spend, C as NodeStatus, D as ResumedKeyState, E as ResultBlobStore, Et as createOtelExporter, F as SpawnEvent, G as Supervisor, Gt as PendingWait, H as SpendGap, I as SpawnJournal, J as UnknownMaterializationReason, Jt as WaitProbeRegistry, K as SupervisorOpts, Kt as WaitOutcome, L as SpawnOpts, M as Runtime, N as Scope, O as ResumedWork, P as Settled, Q as WorkerTraceEvidence, Qt as isWaitOutcome, R as SpawnPrior, S as NodeSnapshot, T as Restart, Tt as createOpenInferenceFileExporter, U as SteerableRootHandle, V as SpendChannel, W as SupervisedResult, X as WaitOpts, Xt as WaitSpec, Y as UsageEvent, Yt as WaitRejection, Z as WidenGate, Zt as createWaitProbes, _ as MaterializedExecutionIdentity, _n as readWorkerProgress, an as ToolStepInput, at as workerTraceSeamKey, b as NodeExecutionIdentity, c as ExecutorAccounting, cn as decodeToolPart, d as ExecutorFactory, dn as ActivityNote, en as timerAt, et as WorkerTraceResolver, f as ExecutorMaterialization, fn as DEFAULT_STALL_AFTER_MS, g as Handle, gn as createActivityLog, h as ExecutorResult, hn as WorkerProgress, i as Budget, in as SessionTraceBox, it as workerTraceHeaders, j as RootSignal, k as RootHandle, l as ExecutorContext, ln as sandboxSessionTraceSource, m as ExecutorRegistry, mn as ScopeProgressInput, n as AgentExecutionRef, nn as waitUntil, nt as readWorkerTraceContext, o as ExecutionBindingReceipt, on as TraceSource, p as ExecutorNodeContext, pn as ExecutorProgress, q as TreeView, qt as WaitProbe, r as AgentSpec, rn as SessionMessageLike, rt as workerTraceEnv, s as Executor, sn as createPushTraceSource, t as Agent, tn as validateWaitSpec, tt as WorkerTraceSeamCarrier, u as ExecutorExecutionBinding, un as ActivityLog, v as MaterializedModelIdentity, w as ProfileMaterializationReceipt, x as NodeId, y as NoWinnerError, z as SpawnRejection } from "./types-B9KAen_0.js";
4
- import { $ as ToolLoopToolCall, C as WorktreeHarnessResult, K as RouterTransportConfig, Q as ToolLoopMessageRecord, S as WorktreeCommandResult, X as ToolLoopCompaction, Z as ToolLoopCompactionOptions, _ as createSteerableSandboxSession, a as ExecutorConfig, b as createInbox, c as RouterToolsSeam, d as createExecutor, f as createExecutorRegistry, g as SteerableSandboxSession, h as SteerableSandboxArgs, i as CliWorktreeSeam, l as SandboxSeam, m as SandboxSteeringOptions, n as CliSeam, o as ProviderSeam, p as DEFAULT_SANDBOX_STEERING_MAX_TURNS, q as ToolSpec, r as CliWorktreeBridgeSeam, s as RouterSeam, t as BridgeSeam, u as cliWorktreeExecutor, v as Inbox, w as WorktreeProfileMaterializationReceipt, x as WorktreeCheckRunner, y as InboxMessage } from "./runtime-aXvRThzL.js";
5
- import { A as providerAsSandboxClient, C as ProviderAsSandboxClientOptions, D as WorkspaceRequest, E as SandboxClientProviderOptions, F as createTangleSandboxExactProcessProvider, M as sandboxClientAsProvider, N as CreateTangleSandboxExactProcessProviderOptions, O as createAgentEnvironmentProviderRegistry, P as SandboxControlClient, S as PlacementInfo, T as ResourceRequest, _ as CheckpointRequest, a as AgentEnvironmentProviderRef, b as ExecResult, c as AgentEnvironmentStatus, d as AgentSession, f as AgentSessionRef, g as CheckpointRef, h as AgentTurnResult, i as AgentEnvironmentProvider, j as resolveAgentEnvironmentProvider, k as providerAsExecutor, l as AgentEnvironmentSummary, n as AgentEnvironmentCapabilities, o as AgentEnvironmentProviderRegistry, p as AgentSessionStatus, r as AgentEnvironmentEvent, s as AgentEnvironmentQuery, t as AgentEnvironment, u as AgentProfileRef, v as CreateAgentEnvironmentInput, w as ProviderExecutorOptions, x as ForkRequest, y as ExecRequest } from "./environment-provider-DlYw_pjo.js";
6
- import { a as StreamAgentTurnOptions, i as CollectedAgentTurn, n as AgentTurnInput, o as collectAgentTurn, r as AgentTurnUsage, s as streamAgentTurn, t as AgentTurnBackend } from "./stream-agent-turn-BXiMHdCf.js";
7
- export { type AcquireOptions, type ActivityLog, type ActivityNote, type Agent, type AgentEnvironment, type AgentEnvironmentCapabilities, type AgentEnvironmentEvent, type AgentEnvironmentProvider, type AgentEnvironmentProviderRef, type AgentEnvironmentProviderRegistry, type AgentEnvironmentQuery, type AgentEnvironmentStatus, type AgentEnvironmentSummary, type AgentExecutionRef, type AgentGraph, type AgentProfile, type AgentProfileRef, type AgentRunSpec, type AgentSession, type AgentSessionRef, type AgentSessionStatus, type AgentSpec, type AgentTurnBackend, type AgentTurnInput, type AgentTurnResult, type AgentTurnUsage, type AgenticOptions, type AgenticRunResult, type AgenticSurface, type AgenticTask, type AgenticTool, type AllWorkersStalledOptions, type AnalystFinding, type AnalystFindingEvent, type AnalystRegistry, type AnalyzeOnSettleRoute, type AnytimeReport, type AnytimeStrategySummary, type AnytimeTaskCurve, type ArtifactHandle, type AssertTraceDerivedFindings, type AuditIntentInput, type AuditIntentOptions, type AuthorStrategyOptions, type AuthoredHarness, type AuthoredProfile, type AuthoredStrategy, type AuthorizeDownMessage, type AuthorizedDownMessage, type AuthorizedSpawn, type AuthorizedSpawnContext, type AxisScoresOf, type BenchmarkCell, type BenchmarkConfig, type BenchmarkLift, type BenchmarkReport, type BenchmarkStrategySummary, type BenchmarkTaskRow, type BridgeSeam, type Budget, type BudgetPool, type BudgetPoolRestore, type BudgetReadout, type BusEvent, type BusRecord, type BusStats, type ChampionPick, type ChampionPolicy, type ChatCompletionsTransport, type ChatSessionStore, type ChatTransportExecutorOptions, type ChatTransportTool, type ChatWorkerSeamOptions, type CheckExecChannel, type CheckOutcome, type CheckRunContext, type CheckRunner, type CheckSource, type CheckSourceCtx, type CheckpointCapableBox, type CheckpointRef, type CheckpointRequest, type CliSeam, type CliWorktreeBridgeSeam, type CliWorktreeSeam, type CollectedAgentTurn, type CombinatorShape, type CompletionAnalyst, type CompletionEvidence, type CompletionPolicy, type CompletionVerdict, type ConcurrencyCaps, type ContinuationInstruction, type ContinuityMode, type CoordinationBinding, type CoordinationDeliveryEvidence, type CoordinationEvent, type CoordinationLog, type CoordinationMcpHandle, type CoordinationOwnerId, type CopyOptions, type Corpus, type CorpusFilter, type CorpusReadbackOptions, type CorpusRecord, type CreateAgentEnvironmentInput, type CreateSandboxOptions, type CreateScopeAnalystOptions, type CreateTangleSandboxExactProcessProviderOptions, type CriuCapableClient, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_STALL_AFTER_MS, type DefaultVerdict, type DefinePersona, type DefinePersonaInput, type DefinedLeaderboard, type DelegateOptions, type Deliverable, type DeliverableResolutionInput, type DeliverableSpec, type DeliveredOutput, type DispatchReport, type DispatchStopReason, type DispatchUnit, type DownMessageAuthorizationInput, type DownMessageDeliveryAttempt, type DownMessageDeliveryOutcome, type DownMessageEvent, type DriveHarness, type DriveHarnessOwnerContext, type Driver, type DriverAttemptRecord, type DriverAttemptStop, DriverAttemptsExhaustedError, type DriverProgressMark, type DriverRetryPolicy, EVIDENCE_MAX_CHARS, type EdgeDeliveryOutcome, type EdgeTraversal, type Environment, type EqualKArm, type EqualKOnCost, type EqualKOnCostOptions, type EqualKVerdict, type EventBus, type EvolutionArchiveNode, type EvolutionAuthor, type EvolutionBandInfo, type EvolutionCandidate, type EvolutionGeneration, type EvolutionReport, type ExecCtx, type ExecRequest, type ExecResult, type ExecutionBindingReceipt, type Executor, type ExecutorAccounting, type ExecutorConfig, type ExecutorContext, type ExecutorExecutionBinding, type ExecutorFactory, type ExecutorMaterialization, type ExecutorNodeContext, type ExecutorProgress, type ExecutorRegistry, type ExecutorResult, type ExecutorResultMapping, type Fanout, type FanoutOptions, type FanoutSynthesis, type FanoutWinnerSelector, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, type FinalizeContext, type FinalizerSettled, type FlatWidenGate, type ForkCapableBox, type ForkRequest, type GitWorkspaceOptions, type GraphEdge, GraphEdgeCapError, type GraphNode, type GraphResult, type GroupOf, type Handle, type HarvestCorpusOptions, type HarvestFailure, type HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, type InMemoryRunContext, type InMemoryRunContextOptions, InMemorySpawnJournal, type InProcessOnPrompt, type InProcessPromptCtx, type InProcessSandboxClientOptions, type Inbox, type InboxMessage, type IntentAudit, type Interval, type Iteration, type KeyProvider, type Leaderboard, type LeaderboardBenchScore, type LeaderboardBenchTask, type LeaderboardBenchmarkAdapter, type LeaderboardFlagSpec, type LeaderboardIterationInfo, type LeaderboardOptions, type LeaderboardRow, type LeaderboardRunContext, type LeaderboardScenario, type LeaderboardScore, type LeaderboardSpec, type LocalMcpMaterialization, type LocalSandboxClientOptions, type LoopCampaignDispatchOptions, type LoopDecisionPayload, type LoopDispatchOptions, type LoopEndedPayload, type LoopIterationDispatchPayload, type LoopIterationEndedPayload, type LoopIterationStartedPayload, type LoopLineageOptions, type LoopOptionsForDispatch, type LoopPlanDescription, type LoopPlanPayload, type LoopResult, type LoopSandboxPlacement, type LoopShape, type LoopStartedPayload, type LoopTeardownFailedPayload, type LoopTokenUsage, type LoopTraceEmitter, type LoopTraceEvent, type LoopUntil, type LoopUntilSpec, type LoopUntilState, type LoopWinner, type MakeWorkerAgent, type MaterializeLocalMcpOptions, type MaterializedExecutionIdentity, type MaterializedModelIdentity, type McpEndpoint, type McpEnvironmentOptions, McpSpawnFault, type McpToolDescriptor, type MountManifestEntry, type MountRecorder, NOTE_MAX_CHARS, type NativeContextContinuationExecution, type NativeContextContinuationInput, type NoProgressForOptions, type NoWinnerError, type NodeExecutionIdentity, type NodeId, type NodeSnapshot, type NodeStatus, type Observation, type ObserveInput, type ObserveOptions, type ObserveSupervisorNodeEvent, type OpenSandboxRunBeforeStartContext, type OpenSandboxRunOptions, type OpenSandboxRunPromptOptions, type Outcome, type OutputAdapter, type PairwiseOptions, type PairwiseVerdict, type Panel, type PanelJudge, type PanelSpec, type PanelVerdict, type PatchDeliverableOptions, type PendingWait, type Persona, type PersonaContext, type PersonaExecutors, type Pipeline, type PipelineStage, type PlacementInfo, type PlateauOptions, type PriorCoordination, type ProfileKeyOf, type ProfileMaterializationReceipt, type ProfileRichness, type ProfileRichnessThresholds, type ProgressSample, type ProgressTracker, type ProgressTrackerOptions, type ProgressView, type PromotionGateOptions, type PromotionVerdict, type PromptHandle, type PromptRegistry, type ProviderAsSandboxClientOptions, type ProviderExecutorOptions, type ProviderSeam, type PublishOptions, type ReconnectRetainedRunOptions, type RegisteredPrompt, type RegistryAnalyzeProjection, type RenderCorpusToInstructions, type RenderCorpusToInstructionsOptions, type RepairStop, type ReproductionCheck, type ReservationRejection, type ReservationTicket, type ResolveDriveHarness, type ResolveSandboxClientOptions, type ResolveSupervisorTools, type ResolvedMcpServerLaunch, type ResolvedSupervisorProfile, type ResourceRequest, type Restart, type ResultBlobStore, type ResumedKeyState, type ResumedWork, type RetainedRunCancelOptions, type RetainedRunCancellation, type RetainedRunEffect, type RetainedRunEventOptions, type RetainedRunHandle, type RetainedRunReplayPoint, type RetainedRunSnapshot, type RollingDispatchOptions, type RootHandle, type RootMaterialization, type RootSignal, type RouterSeam, type RouterToolsSeam, type RouterTransportConfig, type RunAgentRoundsOptions, type RunAgenticOptions, type RunContext, type RunGraphOptions, type RunPersonified, type RunPersonifiedOptions, type RunProvenance, type Runtime, type SandboxCapabilities, type SandboxClient, type SandboxClientProviderOptions, type SandboxControlClient, type SandboxEvent, type SandboxInstance, type SandboxLineage, type SandboxLineageHandle, type SandboxRun, SandboxRunAbortError, type SandboxSeam, type SandboxSteeringOptions, type SandboxToolPartState, type Scope, type ScopeAnalyst, type ScopeAnalyzeInput, type ScopeArgs, type ScopeProgressInput, type ScopeWidenGate, type ScoreOf, type SelectionReceipt, type SessionCapableBox, type SessionMessageLike, type SessionTraceBox, type Settled, type ShapeBudget, type ShapeContext, type ShapeRegistry, type Shell, type ShotSpec, type SpawnEvent, type SpawnForest, type SpawnForestEvent, type SpawnForestInDoubtNode, type SpawnForestMissingTree, type SpawnForestNode, type SpawnForestTree, type SpawnJournal, type SpawnOpts, type SpawnPrior, type SpawnRejection, type Spend, type SpendChannel, type SpendGap, type StartRetainedRunOptions, type StdioMcpConnection, type StdioMcpServerSpec, type SteerContext, type SteerableRootHandle, type SteerableSandboxArgs, type SteerableSandboxSession, type StopDecision, type StopRule, type Strategy, type StrategyArtifacts, type StrategyCtx, type StrategyEvolutionConfig, type StrategyMessage, type StrategyResult, type StrategyShotResult, type StreamAgentTurnOptions, type StructuralRolloutConfig, type StructuralRolloutMessage, type StructuralRolloutPolicy, type StructuralRolloutResult, type SuperviseDispatchOptions, type SuperviseOptions, type SuperviseOptionsForDispatch, type SuperviseRegistry, type SuperviseRegistryTable, type SuperviseSurfaceOptions, type SuperviseSurfaceResult, type SupervisedResult, type Supervisor, type SupervisorAgentDeps, type SupervisorFinalizer, type SupervisorNodeContext, type SupervisorNodeContextSeed, type SupervisorOpts, type SupervisorProfile, type SupervisorSpanAttributes, type SupervisorSpanOptions, type SupervisorSpanOutcome, type SupervisorSpanRecorder, type SupervisorToolDescriptor, type SupervisorToolInvocationContext, type SurfaceScore, type SurfaceWorkerConfig, type SurfaceWorkerOut, type ToolLoopCompaction, type ToolLoopCompactionOptions, type ToolLoopMessageRecord, type ToolLoopToolCall, type ToolSpec, type ToolStepInput, type TraceSource, type TrajectoryAnalysis, type TrajectoryNode, type TrajectoryReport, type TrajectoryReportFn, type TrajectoryReportOptions, type TraversalContinuity, type TreeView, type TurnResult, type UnknownMaterializationReason, type UntrackedCopyStats, type UsageEvent, VERIFY_TAIL_CHARS, type ValidationCtx, type Validator, type VerifierEnvironmentOptions, type Verify, type VerifySpec, type VisibleCheck, WORKER_TOOL_TRACE_SCHEMA_VERSION, type WaitOpts, type WaitOutcome, type WaitProbe, type WaitProbeRegistry, type WaitRejection, type WaitSpec, type WatchTraceOptions, type WaterfallCollector, type WaterfallReport, type WaterfallSpan, type Widen, type WidenDecision, type WidenGate, type WidenLineage, type WidenSpec, type WinnerStrategy, type WorkerEvidenceInput, type WorkerProgress, type WorkerResumeContext, type WorkerSpawnContext, type WorkerSteerRequest, type WorkerToolTraceArtifact, type WorkerTraceEvidence, type WorkerTraceResolver, type WorkerTraceSeamCarrier, type WorkerTraceUnavailableReason, type WorkerWatchOptions, type Workspace, type WorkspaceCommit, type WorkspaceRequest, type WorkspaceRun, type WorktreeCheckRunner, type WorktreeCliExecutorOptions, type WorktreeCommandResult, type WorktreeFanoutOptions, type WorktreeHarnessResult, type WorktreePatchArtifact, type WorktreeProfileMaterializationReceipt, acquireSandbox, adaptiveRefine, allOf, allWorkersStalled, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertCoordinationBinding, assertModelAllowed, assertProfileModelsAllowed, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, auditIntent, authorStrategy, bestDelivered, bestSoFar, breadthStrategy, buildSteerContext, builtinShapes, canDisplace, canonicalFindingEvent, captureWorkerTraceEvidence, chatTransportExecutor, chatWorkerSeam, classifyDriverFailure, cliWorktreeExecutor, closingWorkerNote, collectAgentTurn, collectDelivered, compareCheckOutcomes, completionAuthorizes, composeCheckSources, composeWorkerEvidence, computeFindingId, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createEventBus, createExecutor, createExecutorRegistry, createFileRunContext, createInMemoryRunContext, createInbox, createMcpEnvironment, createOpenInferenceFileExporter, createOtelExporter, createProgressTracker, createPromptRegistry, createPushTraceSource, createRootHandle, createSandboxLineage, createSandboxToolPartState, createScope, createScopeAnalyst, createShapeRegistry, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaitProbes, createWaterfallCollector, createWorktreeCliExecutor, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, discriminatingMeans, dumbContinuationFailPrompt, dumbContinuationPassPrompt, effectiveConcurrency, envKeyProvider, equalKOnCost, extractLlmCallEvent, failuresAnalyst, fanout, filterAuthoredAsserts, finalizeBestDelivered, flatWidenGate, formatPromptHandle, freeSlots, gateOnDeliverable, gitWorkspace, harvestCorpus, inProcessSandboxClient, inlineSandboxClient, isWaitOutcome, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, legacySupervisorRunsRoot, loadSpawnForest, localSandboxClient, localShell, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, normalizeAnalyzeOnSettle, observe, officialChecksFromMeta, openSandboxRun, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, patchDelivered, pendingWaits, pickBestDelivered, pickChampion, pipeline, plateau, plateauLength, pollFor, printBenchmarkReport, probeSandboxCapabilities, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promotionGate, promptHandle, providerAsExecutor, providerAsSandboxClient, queueOf, readWorkerProgress, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runFinalizer, runGraph, runInWorkspace, runPersonified, runStrategyEvolution, runTree, safeWorkerFile, sample, sampleFromSettled, sampleThenRefine, sandboxCheckRunner, sandboxClientAsProvider, sandboxSessionTraceSource, sanitizeMcpToolSchema, secretEnvOfMcpServer, selectBestIndex, selectChampion, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, spendFromUsageEvents, startRetainedRun, stopSentinel, strategyAuthorContract, strategyAuthorSystemPrompt, streamAgentTurn, structuralRollout, sumSandboxUsage, supervise, superviseDispatch, superviseSurface, supervisorAgent, supervisorInstructions, supervisorPolicyPrompt, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, timerAt, trajectoryReport, validateWaitSpec, verify, visibleCheckScore, waitUntil, watchTrace, widen, withUntrackedArtifacts, workerControlLogFile, workerFromBackend, workerInboxFile, workerInboxFileFromEventDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
2
+ import { $ as legacySupervisorRunsRoot, $a as ResolveDriveHarness, $c as ScoreOf, $i as BenchmarkLift, $n as selectBestIndex, $o as classifyDriverFailure, $r as AcquireOptions, $s as ScopeAnalyzeInput, $t as rollingDispatch, A as GitWorkspaceOptions, Aa as LoopCampaignDispatchOptions, Ac as LeaderboardIterationInfo, Af as materializeTreeView, Ai as FileCorpus, Al as CoordinationEvent, An as supervisorInstructions, Ao as createProgressTracker, Ar as Deliverable, As as CorpusFilter, At as runGraph, B as analyzeTrace, Ba as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, Bc as completionAuthorizes, Bi as widen, Bn as StructuralRolloutPolicy, Bo as FinalizeContext, Br as SandboxLineage, Bs as FlatWidenGate, Bt as formatPromptHandle, C as closingWorkerNote, Ca as breadthStrategy, Cc as ShapeContext, Cf as SpawnForest, Ci as equalKOnCost, Cl as AnalystFindingEvent, Cn as AuthoredProfile, Co as ProgressTrackerOptions, Cr as MaterializeLocalMcpOptions, Cs as ObserveOptions, Ct as GraphEdgeCapError, D as UntrackedCopyStats, Da as runAgentic, Dc as LeaderboardBenchTask, Df as SpawnForestNode, Di as registerShape, Dl as AuthorizedDownMessage, Dn as assessAuthoredProfile, Do as allOf, Dr as StdioMcpServerSpec, Ds as AssertTraceDerivedFindings, E as CopyOptions, Ea as refine, Ec as LeaderboardBenchScore, Ef as SpawnForestMissingTree, Ei as createShapeRegistry, El as AuthorizeDownMessage, En as asAuthoredProfile, Eo as StopRule, Er as StdioMcpConnection, Es as renderReport, Et as RunGraphOptions, F as gitWorkspace, Fa as loopCampaignDispatch, Fc as defineLeaderboard, Fi as loopUntil, Fl as DownMessageDeliveryAttempt, Fn as CheckSource, Fo as SupervisorSpanOptions, Fr as SandboxRunAbortError, Fs as EqualKVerdict, Ft as analyzesFindingsReportPrompt, G as workerTraceAnalysisStore, Gc as GroupOf, Gi as createScopeAnalyst, Gn as composeCheckSources, Go as pickBestDelivered, Gr as createSandboxToolPartState, Gs as PanelJudge, Gt as ConcurrencyCaps, H as WorkerToolTraceArtifact, Ha as SuperviseOptions, Hc as sentinelCompletion, Hi as RegistryAnalyzeProjection, Hn as VisibleCheck, Ho as SupervisorFinalizer, Hr as SessionCapableBox, Hs as LoopUntilSpec, Ht as naiveContinuationPrompt, I as jjWorkspace, Ia as loopDispatch, Ic as CompletionAnalyst, Ii as panel, Il as DownMessageDeliveryOutcome, In as CheckSourceCtx, Io as SupervisorSpanOutcome, Ir as TurnResult, Is as Fanout, It as createPromptRegistry, J as ScopeArgs, Ja as workerFromBackend, Jc as LeaderboardOptions, Ji as McpEnvironmentOptions, Jl as WorkerSpawnContext, Jn as filterAuthoredAsserts, Jo as DriverAttemptRecord, Jr as mapSandboxToolEvent, Js as Pipeline, Jt as DispatchUnit, K as createRootHandle, Ka as supervise, Kc as Interval, Ki as registryScopeAnalyst, Kn as defaultExtractCandidate, Ko as runFinalizer, Kr as extractLlmCallEvent, Ks as PanelSpec, Kt as DispatchReport, L as localShell, La as superviseDispatch, Lc as CompletionEvidence, Li as pipeline, Ll as DownMessageEvent, Ln as RepairStop, Lo as SupervisorSpanRecorder, Lr as openSandboxRun, Ls as FanoutOptions, Lt as delegatesWorkerBriefPrompt, M as Workspace, Ma as LoopOptionsForDispatch, Mc as LeaderboardScenario, Mf as replaySpawnTree, Mi as renderCorpusToInstructions, Mn as CheckOutcome, Mo as plateau, Mr as OpenSandboxRunOptions, Ms as EqualKArm, Mt as PromptHandle, N as WorkspaceCommit, Na as SuperviseDispatchOptions, Nc as LeaderboardScore, Nf as contentAddress, Ni as fanout, Nl as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Nn as CheckRunContext, No as sampleFromSettled, Nr as OpenSandboxRunPromptOptions, Ns as EqualKOnCost, Nt as PromptRegistry, O as copyUntrackedIntoClone, Oa as sample, Oc as LeaderboardBenchmarkAdapter, Of as SpawnForestTree, Oi as definePersona, Ol as ContinuationInstruction, On as defaultProfileRichnessThresholds, Oo as allWorkersStalled, Or as connectStdioMcp, Os as CombinatorShape, Ot as TraversalContinuity, P as WorkspaceRun, Pa as SuperviseOptionsForDispatch, Pc as LeaderboardSpec, Pi as flatWidenGate, Pl as DownMessageAuthorizationInput, Pn as CheckRunner, Po as SupervisorSpanAttributes, Pr as SandboxRun, Ps as EqualKOnCostOptions, Pt as RegisteredPrompt, Q as legacySupervisorRunDir, Qa as ObserveSupervisorNodeEvent, Qc as ProfileKeyOf, Qi as BenchmarkConfig, Ql as normalizeAnalyzeOnSettle, Qn as sandboxCheckRunner, Qo as DriverRetryPolicy, Qr as probeSandboxCapabilities, Qs as ScopeAnalyst, Qt as queueOf, R as runInWorkspace, Ra as AuthorizedSpawn, Rc as CompletionPolicy, Ri as selectValidWinner, Rl as MakeWorkerAgent, Rn as StructuralRolloutConfig, Ro as createSupervisorSpanRecorder, Rr as CheckpointCapableBox, Rs as FanoutSynthesis, Rt as dumbContinuationFailPrompt, S as WorkerEvidenceInput, Sa as adaptiveRefine, Sc as ShapeBudget, Sf as InMemorySpawnJournal, Si as assertProfileModelsAllowed, Sl as createWaterfallCollector, Sn as spendFromUsageEvents, So as ProgressTracker, Sr as LocalMcpMaterialization, Ss as ObserveInput, St as GraphEdge, T as settledWorkerOut, Ta as depthStrategy, Tc as DefinedLeaderboard, Tf as SpawnForestInDoubtNode, Ti as builtinShapes, Tl as AnalyzeOnSettleRoute, Tn as ProfileRichnessThresholds, To as StopDecision, Tr as McpToolDescriptor, Ts as observe, Tt as GraphResult, U as captureWorkerTraceEvidence, Ua as SuperviseRegistry, Uc as stopSentinel, Ui as assertTraceDerivedFindings, Un as canDisplace, Uo as bestDelivered, Ur as createSandboxLineage, Us as LoopUntilState, Ut as promptHandle, V as WORKER_TOOL_TRACE_SCHEMA_VERSION, Va as DeliverableResolutionInput, Vc as deterministicCompletion, Vi as CreateScopeAnalystOptions, Vn as StructuralRolloutResult, Vo as FinalizerSettled, Vr as SandboxLineageHandle, Vs as LoopUntil, Vt as kernelPromptRegistry, W as parseWorkerToolTraceArtifact, Wa as SuperviseRegistryTable, Wc as AxisScoresOf, Wi as buildSteerContext, Wn as compareCheckOutcomes, Wo as collectDelivered, Wr as SandboxToolPartState, Ws as Panel, Wt as supervisorPolicyPrompt, X as settledToIteration, Xa as DriveHarness, Xc as PairwiseOptions, Xi as sanitizeMcpToolSchema, Xl as canonicalFindingEvent, Xn as officialChecksFromMeta, Xo as DriverAttemptsExhaustedError, Xr as CriuCapableClient, Xs as RenderCorpusToInstructions, Xt as effectiveConcurrency, Y as createScope, Ya as CoordinationBinding, Yc as LeaderboardRow, Yi as createMcpEnvironment, Yl as WorkerWatchOptions, Yn as modelAuthoredChecks, Yo as DriverAttemptStop, Yr as sumSandboxUsage, Ys as PipelineStage, Yt as RollingDispatchOptions, Z as WorkerSteerRequest, Za as DriveHarnessOwnerContext, Zc as PairwiseVerdict, Zi as BenchmarkCell, Zn as resolveEntrySymbol, Zo as DriverProgressMark, Zr as SandboxCapabilities, Zs as RenderCorpusToInstructionsOptions, Zt as freeSlots, _ as WorktreeFanoutOptions, _a as StrategyCtx, _c as Persona, _f as gateOnDeliverable, _i as PromotionVerdict, _l as plateauLength, _n as BudgetPoolRestore, _o as PriorCoordination, _r as AuthoredStrategy, _s as HarvestCorpusOptions, _t as WorktreePatchArtifact, a as SandboxInstance, aa as runBenchmark, ac as TrajectoryReportOptions, ai as ReconnectRetainedRunOptions, al as renderPairwiseMarkdown, ao as SupervisorNodeContextSeed, ar as EvolutionAuthor, as as KeyProvider, at as workerControlLogFile, b as NOTE_MAX_CHARS, ba as StrategyShotResult, bc as RunPersonified, bf as FileSpawnJournal, bi as profileOptimizerModelCall, bl as WaterfallReport, bn as ReservationTicket, bo as PlateauOptions, br as strategyAuthorContract, bs as harvestCorpus, bt as EdgeDeliveryOutcome, c as VerifierEnvironmentOptions, ca as AgenticSurface, cc as Widen, cf as BusStats, ci as RetainedRunEffect, cl as IntentAudit, cn as ChatCompletionsTransport, co as SupervisorToolInvocationContext, cr as EvolutionGeneration, cs as mcpSecretEnvMetadataKey, ct as writeWorkerSteer, d as SuperviseSurfaceResult, da as ArtifactHandle, dc as WidenSpec, df as createEventBus, di as RetainedRunReplayPoint, dl as AnytimeReport, dn as ChatTransportTool, do as supervisorAgent, dr as StrategyEvolutionConfig, ds as secretEnvOfMcpServer, dt as RunContext, ea as BenchmarkReport, ec as ScopeWidenGate, ei as acquireSandbox, el as leaderboard, en as DelegateOptions, eo as ResolveSupervisorTools, er as structuralRollout, es as RunAgentRoundsOptions, et as readWorkerSteerRequests, f as SurfaceWorkerConfig, fa as CorpusReadbackOptions, fc as WinnerStrategy, ff as WatchTraceOptions, fi as RetainedRunSnapshot, fl as AnytimeStrategySummary, fn as ChatWorkerSeamOptions, fr as discriminatingMeans, fs as inlineSandboxClient, ft as createFileRunContext, g as AuthoredHarness, ga as StrategyArtifacts, gc as Outcome, gf as ExecutorResultMapping, gi as PromotionGateOptions, gl as bestSoFar, gn as BudgetPool, go as FileCoordinationLog, gr as AuthorStrategyOptions, gs as inProcessSandboxClient, gt as WorktreeCliExecutorOptions, h as superviseSurface, ha as Strategy, hc as LoopShape, hf as DeliverableSpec, hi as resolveSandboxClient, hl as areaUnderCurve, hn as createChatSessionStore, ho as CoordinationOwnerId, hr as selectChampion, hs as InProcessSandboxClientOptions, ht as patchDelivered, i as SandboxEvent, ia as printBenchmarkReport, ic as TrajectoryReportFn, ii as NativeContextContinuationInput, il as renderLeaderboardSvg, in as serveCoordinationMcp, io as SupervisorNodeContext, ir as EvolutionArchiveNode, is as localSandboxClient, it as supervisorWorkersDir, j as Shell, ja as LoopDispatchOptions, jc as LeaderboardRunContext, jf as pendingWaits, ji as InMemoryCorpus, jn as CheckExecChannel, jo as noProgressFor, jr as OpenSandboxRunBeforeStartContext, js as CorpusRecord, k as withUntrackedArtifacts, ka as sampleThenRefine, kc as LeaderboardFlagSpec, kf as loadSpawnForest, ki as runPersonified, kl as ContinuityMode, kn as profileRichnessFinding, ko as anyOf, kr as materializeLocalMcp, ks as Corpus, kt as defaultEdgeTraversalCap, l as createVerifierEnvironment, la as AgenticTask, lc as WidenDecision, lf as EventBus, li as RetainedRunEventOptions, ll as auditIntent, ln as ChatSessionStore, lo as assertCoordinationBinding, lr as EvolutionReport, ls as resolveMcpServerLaunch, lt as InMemoryRunContext, m as failuresAnalyst, ma as ShotSpec, mc as DefinePersonaInput, mf as watchTrace, mi as ResolveSandboxClientOptions, ml as anytimeReport, mn as chatWorkerSeam, mo as CoordinationLog, mr as runStrategyEvolution, ms as InProcessPromptCtx, mt as PatchDeliverableOptions, n as AnalystFinding, na as BenchmarkTaskRow, nc as TrajectoryNode, ni as startRetainedRun, nl as renderLeaderboardHtml, nn as delegate, no as SupervisorAgentDeps, nr as ChampionPick, ns as runAgentRounds, nt as supervisorRunDir, o as computeFindingId, oa as AgenticOptions, oc as Verify, of as BusEvent, oi as RetainedRunCancelOptions, ol as AuditIntentInput, oo as SupervisorProfile, or as EvolutionBandInfo, os as ResolvedMcpServerLaunch, ot as workerInboxFile, p as SurfaceWorkerOut, pa as RunAgenticOptions, pc as DefinePersona, pf as defaultToolDetectors, pi as StartRetainedRunOptions, pl as AnytimeTaskCurve, pn as chatTransportExecutor, po as CoordinationDeliveryEvidence, pr as pickChampion, ps as InProcessOnPrompt, pt as createInMemoryRunContext, q as createSupervisor, qc as Leaderboard, qi as McpEndpoint, ql as WorkerResumeContext, qn as defaultStructuralRolloutPolicy, qo as runTree, qr as mapSandboxEvent, qs as PanelVerdict, qt as DispatchStopReason, r as CreateSandboxOptions, ra as Environment, rc as TrajectoryReport, ri as NativeContextContinuationExecution, rl as renderLeaderboardMarkdown, rn as CoordinationMcpHandle, rr as ChampionPolicy, rs as LocalSandboxClientOptions, rt as supervisorRunsRoot, s as makeFinding, sa as AgenticRunResult, sc as VerifySpec, sf as BusRecord, si as RetainedRunCancellation, sl as AuditIntentOptions, sn as finalizeBestDelivered, so as SupervisorToolDescriptor, sr as EvolutionCandidate, ss as envKeyProvider, st as workerInboxFileFromEventDir, t as AgentProfile, ta as BenchmarkStrategySummary, tc as SteerContext, ti as reconnectRetainedRun, tl as pairwiseSignificance, tn as defaultDelegateBudget, to as ResolvedSupervisorProfile, tr as visibleCheckScore, ts as defaultSelectWinner, tt as safeWorkerFile, u as SuperviseSurfaceOptions, ua as AgenticTool, uc as WidenLineage, uf as PublishOptions, ui as RetainedRunHandle, ul as defaultAuditorInstruction, un as ChatTransportExecutorOptions, uo as resolveSupervisorProfile, ur as ReproductionCheck, us as resolveSecretEnv, ut as InMemoryRunContextOptions, v as worktreeFanout, va as StrategyMessage, vc as PersonaContext, vf as mapExecutorResult, vi as promotionGate, vl as renderAnytimeTable, vn as BudgetReadout, vo as AllWorkersStalledOptions, vr as assertStrategyContract, vs as HarvestFailure, vt as createWorktreeCliExecutor, w as composeWorkerEvidence, wa as defineStrategy, wc as ShapeRegistry, wf as SpawnForestEvent, wi as trajectoryReport, wl as AnalystRegistry, wn as ProfileRichness, wo as ProgressView, wr as McpSpawnFault, ws as defaultAnalystInstruction, wt as GraphNode, x as VERIFY_TAIL_CHARS, xa as SurfaceScore, xc as RunPersonifiedOptions, xf as InMemoryResultBlobStore, xi as assertModelAllowed, xl as WaterfallSpan, xn as createBudgetPool, xo as ProgressSample, xr as strategyAuthorSystemPrompt, xs as Observation, xt as EdgeTraversal, y as EVIDENCE_MAX_CHARS, ya as StrategyResult, yc as PersonaExecutors, yf as FileResultBlobStore, yi as profileChatClient, yl as WaterfallCollector, yn as ReservationRejection, yo as NoProgressForOptions, yr as authorStrategy, ys as HarvestReport, yt as AgentGraph, z as TrajectoryAnalysis, za as AuthorizedSpawnContext, zc as CompletionVerdict, zi as verify, zn as StructuralRolloutMessage, zo as DeliveredOutput, zr as ForkCapableBox, zs as FanoutWinnerSelector, zt as dumbContinuationPassPrompt } from "./index-DixXnx07.js";
3
+ import { $ as WorkerTraceEvidence, $t as isWaitOutcome, A as RootMaterialization, B as SpawnRejection, C as NodeStatus, D as ResumedKeyState, Dt as createOtelExporter, E as ResultBlobStore, Et as createOpenInferenceFileExporter, F as Settled, G as SupervisedResult, H as SpendChannel, I as SpawnEvent, J as TreeView, Jt as WaitProbe, K as Supervisor, Kt as PendingWait, L as SpawnJournal, M as RootSignal, N as Runtime, O as ResumedWork, P as Scope, Q as WidenGate, Qt as createWaitProbes, R as SpawnOpts, S as NodeSnapshot, T as Restart, U as SpendGap, V as Spend, W as SteerableRootHandle, X as UsageEvent, Xt as WaitRejection, Y as UnknownMaterializationReason, Yt as WaitProbeRegistry, Z as WaitOpts, Zt as WaitSpec, _ as MaterializedExecutionIdentity, _n as createActivityLog, an as SessionTraceBox, at as workerTraceHeaders, b as NodeExecutionIdentity, c as ExecutorAccounting, cn as createPushTraceSource, d as ExecutorFactory, dn as ActivityLog, en as pollFor, et as WorkerTraceUnavailableReason, f as ExecutorMaterialization, fn as ActivityNote, g as Handle, gn as WorkerProgress, h as ExecutorResult, hn as ScopeProgressInput, i as Budget, in as SessionMessageLike, it as workerTraceEnv, j as RootProviderModelEvidence, k as RootHandle, l as ExecutorContext, ln as decodeToolPart, m as ExecutorRegistry, mn as ExecutorProgress, n as AgentExecutionRef, nn as validateWaitSpec, nt as WorkerTraceSeamCarrier, o as ExecutionBindingReceipt, on as ToolStepInput, ot as workerTraceSeamKey, p as ExecutorNodeContext, pn as DEFAULT_STALL_AFTER_MS, q as SupervisorOpts, qt as WaitOutcome, r as AgentSpec, rn as waitUntil, rt as readWorkerTraceContext, s as Executor, sn as TraceSource, t as Agent, tn as timerAt, tt as WorkerTraceResolver, u as ExecutorExecutionBinding, un as sandboxSessionTraceSource, v as MaterializedModelIdentity, vn as readWorkerProgress, w as ProfileMaterializationReceipt, x as NodeId, y as NoWinnerError, z as SpawnPrior } from "./types-BjUQODeG.js";
4
+ import { $ as ToolLoopToolCall, C as WorktreeHarnessResult, K as RouterTransportConfig, Q as ToolLoopMessageRecord, S as WorktreeCommandResult, X as ToolLoopCompaction, Z as ToolLoopCompactionOptions, _ as createSteerableSandboxSession, a as ExecutorConfig, b as createInbox, c as RouterToolsSeam, d as createExecutor, f as createExecutorRegistry, g as SteerableSandboxSession, h as SteerableSandboxArgs, i as CliWorktreeSeam, l as SandboxSeam, m as SandboxSteeringOptions, n as CliSeam, o as ProviderSeam, p as DEFAULT_SANDBOX_STEERING_MAX_TURNS, q as ToolSpec, r as CliWorktreeBridgeSeam, s as RouterSeam, t as BridgeSeam, u as cliWorktreeExecutor, v as Inbox, w as WorktreeProfileMaterializationReceipt, x as WorktreeCheckRunner, y as InboxMessage } from "./runtime-CKk_poJ-.js";
5
+ import { A as providerAsSandboxClient, C as ProviderAsSandboxClientOptions, D as WorkspaceRequest, E as SandboxClientProviderOptions, F as createTangleSandboxExactProcessProvider, M as sandboxClientAsProvider, N as CreateTangleSandboxExactProcessProviderOptions, O as createAgentEnvironmentProviderRegistry, P as SandboxControlClient, S as PlacementInfo, T as ResourceRequest, _ as CheckpointRequest, a as AgentEnvironmentProviderRef, b as ExecResult, c as AgentEnvironmentStatus, d as AgentSession, f as AgentSessionRef, g as CheckpointRef, h as AgentTurnResult, i as AgentEnvironmentProvider, j as resolveAgentEnvironmentProvider, k as providerAsExecutor, l as AgentEnvironmentSummary, n as AgentEnvironmentCapabilities, o as AgentEnvironmentProviderRegistry, p as AgentSessionStatus, r as AgentEnvironmentEvent, s as AgentEnvironmentQuery, t as AgentEnvironment, u as AgentProfileRef, v as CreateAgentEnvironmentInput, w as ProviderExecutorOptions, x as ForkRequest, y as ExecRequest } from "./environment-provider-CkSDxRZd.js";
6
+ import { a as StreamAgentTurnOptions, i as CollectedAgentTurn, n as AgentTurnInput, o as collectAgentTurn, r as AgentTurnUsage, s as streamAgentTurn, t as AgentTurnBackend } from "./stream-agent-turn-By46GZlo.js";
7
+ export { type AcquireOptions, type ActivityLog, type ActivityNote, type Agent, type AgentEnvironment, type AgentEnvironmentCapabilities, type AgentEnvironmentEvent, type AgentEnvironmentProvider, type AgentEnvironmentProviderRef, type AgentEnvironmentProviderRegistry, type AgentEnvironmentQuery, type AgentEnvironmentStatus, type AgentEnvironmentSummary, type AgentExecutionRef, type AgentGraph, type AgentProfile, type AgentProfileRef, type AgentRunSpec, type AgentSession, type AgentSessionRef, type AgentSessionStatus, type AgentSpec, type AgentTurnBackend, type AgentTurnInput, type AgentTurnResult, type AgentTurnUsage, type AgenticOptions, type AgenticRunResult, type AgenticSurface, type AgenticTask, type AgenticTool, type AllWorkersStalledOptions, type AnalystFinding, type AnalystFindingEvent, type AnalystRegistry, type AnalyzeOnSettleRoute, type AnytimeReport, type AnytimeStrategySummary, type AnytimeTaskCurve, type ArtifactHandle, type AssertTraceDerivedFindings, type AuditIntentInput, type AuditIntentOptions, type AuthorStrategyOptions, type AuthoredHarness, type AuthoredProfile, type AuthoredStrategy, type AuthorizeDownMessage, type AuthorizedDownMessage, type AuthorizedSpawn, type AuthorizedSpawnContext, type AxisScoresOf, type BenchmarkCell, type BenchmarkConfig, type BenchmarkLift, type BenchmarkReport, type BenchmarkStrategySummary, type BenchmarkTaskRow, type BridgeSeam, type Budget, type BudgetPool, type BudgetPoolRestore, type BudgetReadout, type BusEvent, type BusRecord, type BusStats, type ChampionPick, type ChampionPolicy, type ChatCompletionsTransport, type ChatSessionStore, type ChatTransportExecutorOptions, type ChatTransportTool, type ChatWorkerSeamOptions, type CheckExecChannel, type CheckOutcome, type CheckRunContext, type CheckRunner, type CheckSource, type CheckSourceCtx, type CheckpointCapableBox, type CheckpointRef, type CheckpointRequest, type CliSeam, type CliWorktreeBridgeSeam, type CliWorktreeSeam, type CollectedAgentTurn, type CombinatorShape, type CompletionAnalyst, type CompletionEvidence, type CompletionPolicy, type CompletionVerdict, type ConcurrencyCaps, type ContinuationInstruction, type ContinuityMode, type CoordinationBinding, type CoordinationDeliveryEvidence, type CoordinationEvent, type CoordinationLog, type CoordinationMcpHandle, type CoordinationOwnerId, type CopyOptions, type Corpus, type CorpusFilter, type CorpusReadbackOptions, type CorpusRecord, type CreateAgentEnvironmentInput, type CreateSandboxOptions, type CreateScopeAnalystOptions, type CreateTangleSandboxExactProcessProviderOptions, type CriuCapableClient, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_STALL_AFTER_MS, type DefaultVerdict, type DefinePersona, type DefinePersonaInput, type DefinedLeaderboard, type DelegateOptions, type Deliverable, type DeliverableResolutionInput, type DeliverableSpec, type DeliveredOutput, type DispatchReport, type DispatchStopReason, type DispatchUnit, type DownMessageAuthorizationInput, type DownMessageDeliveryAttempt, type DownMessageDeliveryOutcome, type DownMessageEvent, type DriveHarness, type DriveHarnessOwnerContext, type Driver, type DriverAttemptRecord, type DriverAttemptStop, DriverAttemptsExhaustedError, type DriverProgressMark, type DriverRetryPolicy, EVIDENCE_MAX_CHARS, type EdgeDeliveryOutcome, type EdgeTraversal, type Environment, type EqualKArm, type EqualKOnCost, type EqualKOnCostOptions, type EqualKVerdict, type EventBus, type EvolutionArchiveNode, type EvolutionAuthor, type EvolutionBandInfo, type EvolutionCandidate, type EvolutionGeneration, type EvolutionReport, type ExecCtx, type ExecRequest, type ExecResult, type ExecutionBindingReceipt, type Executor, type ExecutorAccounting, type ExecutorConfig, type ExecutorContext, type ExecutorExecutionBinding, type ExecutorFactory, type ExecutorMaterialization, type ExecutorNodeContext, type ExecutorProgress, type ExecutorRegistry, type ExecutorResult, type ExecutorResultMapping, type Fanout, type FanoutOptions, type FanoutSynthesis, type FanoutWinnerSelector, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, type FinalizeContext, type FinalizerSettled, type FlatWidenGate, type ForkCapableBox, type ForkRequest, type GitWorkspaceOptions, type GraphEdge, GraphEdgeCapError, type GraphNode, type GraphResult, type GroupOf, type Handle, type HarvestCorpusOptions, type HarvestFailure, type HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, type InMemoryRunContext, type InMemoryRunContextOptions, InMemorySpawnJournal, type InProcessOnPrompt, type InProcessPromptCtx, type InProcessSandboxClientOptions, type Inbox, type InboxMessage, type IntentAudit, type Interval, type Iteration, type KeyProvider, type Leaderboard, type LeaderboardBenchScore, type LeaderboardBenchTask, type LeaderboardBenchmarkAdapter, type LeaderboardFlagSpec, type LeaderboardIterationInfo, type LeaderboardOptions, type LeaderboardRow, type LeaderboardRunContext, type LeaderboardScenario, type LeaderboardScore, type LeaderboardSpec, type LocalMcpMaterialization, type LocalSandboxClientOptions, type LoopCampaignDispatchOptions, type LoopDecisionPayload, type LoopDispatchOptions, type LoopEndedPayload, type LoopIterationDispatchPayload, type LoopIterationEndedPayload, type LoopIterationStartedPayload, type LoopLineageOptions, type LoopOptionsForDispatch, type LoopPlanDescription, type LoopPlanPayload, type LoopResult, type LoopSandboxPlacement, type LoopShape, type LoopStartedPayload, type LoopTeardownFailedPayload, type LoopTokenUsage, type LoopTraceEmitter, type LoopTraceEvent, type LoopUntil, type LoopUntilSpec, type LoopUntilState, type LoopWinner, type MakeWorkerAgent, type MaterializeLocalMcpOptions, type MaterializedExecutionIdentity, type MaterializedModelIdentity, type McpEndpoint, type McpEnvironmentOptions, McpSpawnFault, type McpToolDescriptor, type MountManifestEntry, type MountRecorder, NOTE_MAX_CHARS, type NativeContextContinuationExecution, type NativeContextContinuationInput, type NoProgressForOptions, type NoWinnerError, type NodeExecutionIdentity, type NodeId, type NodeSnapshot, type NodeStatus, type Observation, type ObserveInput, type ObserveOptions, type ObserveSupervisorNodeEvent, type OpenSandboxRunBeforeStartContext, type OpenSandboxRunOptions, type OpenSandboxRunPromptOptions, type Outcome, type OutputAdapter, type PairwiseOptions, type PairwiseVerdict, type Panel, type PanelJudge, type PanelSpec, type PanelVerdict, type PatchDeliverableOptions, type PendingWait, type Persona, type PersonaContext, type PersonaExecutors, type Pipeline, type PipelineStage, type PlacementInfo, type PlateauOptions, type PriorCoordination, type ProfileKeyOf, type ProfileMaterializationReceipt, type ProfileRichness, type ProfileRichnessThresholds, type ProgressSample, type ProgressTracker, type ProgressTrackerOptions, type ProgressView, type PromotionGateOptions, type PromotionVerdict, type PromptHandle, type PromptRegistry, type ProviderAsSandboxClientOptions, type ProviderExecutorOptions, type ProviderSeam, type PublishOptions, type ReconnectRetainedRunOptions, type RegisteredPrompt, type RegistryAnalyzeProjection, type RenderCorpusToInstructions, type RenderCorpusToInstructionsOptions, type RepairStop, type ReproductionCheck, type ReservationRejection, type ReservationTicket, type ResolveDriveHarness, type ResolveSandboxClientOptions, type ResolveSupervisorTools, type ResolvedMcpServerLaunch, type ResolvedSupervisorProfile, type ResourceRequest, type Restart, type ResultBlobStore, type ResumedKeyState, type ResumedWork, type RetainedRunCancelOptions, type RetainedRunCancellation, type RetainedRunEffect, type RetainedRunEventOptions, type RetainedRunHandle, type RetainedRunReplayPoint, type RetainedRunSnapshot, type RollingDispatchOptions, type RootHandle, type RootMaterialization, type RootProviderModelEvidence, type RootSignal, type RouterSeam, type RouterToolsSeam, type RouterTransportConfig, type RunAgentRoundsOptions, type RunAgenticOptions, type RunContext, type RunGraphOptions, type RunPersonified, type RunPersonifiedOptions, type RunProvenance, type Runtime, type SandboxCapabilities, type SandboxClient, type SandboxClientProviderOptions, type SandboxControlClient, type SandboxEvent, type SandboxInstance, type SandboxLineage, type SandboxLineageHandle, type SandboxRun, SandboxRunAbortError, type SandboxSeam, type SandboxSteeringOptions, type SandboxToolPartState, type Scope, type ScopeAnalyst, type ScopeAnalyzeInput, type ScopeArgs, type ScopeProgressInput, type ScopeWidenGate, type ScoreOf, type SelectionReceipt, type SessionCapableBox, type SessionMessageLike, type SessionTraceBox, type Settled, type ShapeBudget, type ShapeContext, type ShapeRegistry, type Shell, type ShotSpec, type SpawnEvent, type SpawnForest, type SpawnForestEvent, type SpawnForestInDoubtNode, type SpawnForestMissingTree, type SpawnForestNode, type SpawnForestTree, type SpawnJournal, type SpawnOpts, type SpawnPrior, type SpawnRejection, type Spend, type SpendChannel, type SpendGap, type StartRetainedRunOptions, type StdioMcpConnection, type StdioMcpServerSpec, type SteerContext, type SteerableRootHandle, type SteerableSandboxArgs, type SteerableSandboxSession, type StopDecision, type StopRule, type Strategy, type StrategyArtifacts, type StrategyCtx, type StrategyEvolutionConfig, type StrategyMessage, type StrategyResult, type StrategyShotResult, type StreamAgentTurnOptions, type StructuralRolloutConfig, type StructuralRolloutMessage, type StructuralRolloutPolicy, type StructuralRolloutResult, type SuperviseDispatchOptions, type SuperviseOptions, type SuperviseOptionsForDispatch, type SuperviseRegistry, type SuperviseRegistryTable, type SuperviseSurfaceOptions, type SuperviseSurfaceResult, type SupervisedResult, type Supervisor, type SupervisorAgentDeps, type SupervisorFinalizer, type SupervisorNodeContext, type SupervisorNodeContextSeed, type SupervisorOpts, type SupervisorProfile, type SupervisorSpanAttributes, type SupervisorSpanOptions, type SupervisorSpanOutcome, type SupervisorSpanRecorder, type SupervisorToolDescriptor, type SupervisorToolInvocationContext, type SurfaceScore, type SurfaceWorkerConfig, type SurfaceWorkerOut, type ToolLoopCompaction, type ToolLoopCompactionOptions, type ToolLoopMessageRecord, type ToolLoopToolCall, type ToolSpec, type ToolStepInput, type TraceSource, type TrajectoryAnalysis, type TrajectoryNode, type TrajectoryReport, type TrajectoryReportFn, type TrajectoryReportOptions, type TraversalContinuity, type TreeView, type TurnResult, type UnknownMaterializationReason, type UntrackedCopyStats, type UsageEvent, VERIFY_TAIL_CHARS, type ValidationCtx, type Validator, type VerifierEnvironmentOptions, type Verify, type VerifySpec, type VisibleCheck, WORKER_TOOL_TRACE_SCHEMA_VERSION, type WaitOpts, type WaitOutcome, type WaitProbe, type WaitProbeRegistry, type WaitRejection, type WaitSpec, type WatchTraceOptions, type WaterfallCollector, type WaterfallReport, type WaterfallSpan, type Widen, type WidenDecision, type WidenGate, type WidenLineage, type WidenSpec, type WinnerStrategy, type WorkerEvidenceInput, type WorkerProgress, type WorkerResumeContext, type WorkerSpawnContext, type WorkerSteerRequest, type WorkerToolTraceArtifact, type WorkerTraceEvidence, type WorkerTraceResolver, type WorkerTraceSeamCarrier, type WorkerTraceUnavailableReason, type WorkerWatchOptions, type Workspace, type WorkspaceCommit, type WorkspaceRequest, type WorkspaceRun, type WorktreeCheckRunner, type WorktreeCliExecutorOptions, type WorktreeCommandResult, type WorktreeFanoutOptions, type WorktreeHarnessResult, type WorktreePatchArtifact, type WorktreeProfileMaterializationReceipt, acquireSandbox, adaptiveRefine, allOf, allWorkersStalled, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertCoordinationBinding, assertModelAllowed, assertProfileModelsAllowed, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, auditIntent, authorStrategy, bestDelivered, bestSoFar, breadthStrategy, buildSteerContext, builtinShapes, canDisplace, canonicalFindingEvent, captureWorkerTraceEvidence, chatTransportExecutor, chatWorkerSeam, classifyDriverFailure, cliWorktreeExecutor, closingWorkerNote, collectAgentTurn, collectDelivered, compareCheckOutcomes, completionAuthorizes, composeCheckSources, composeWorkerEvidence, computeFindingId, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createEventBus, createExecutor, createExecutorRegistry, createFileRunContext, createInMemoryRunContext, createInbox, createMcpEnvironment, createOpenInferenceFileExporter, createOtelExporter, createProgressTracker, createPromptRegistry, createPushTraceSource, createRootHandle, createSandboxLineage, createSandboxToolPartState, createScope, createScopeAnalyst, createShapeRegistry, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaitProbes, createWaterfallCollector, createWorktreeCliExecutor, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, discriminatingMeans, dumbContinuationFailPrompt, dumbContinuationPassPrompt, effectiveConcurrency, envKeyProvider, equalKOnCost, extractLlmCallEvent, failuresAnalyst, fanout, filterAuthoredAsserts, finalizeBestDelivered, flatWidenGate, formatPromptHandle, freeSlots, gateOnDeliverable, gitWorkspace, harvestCorpus, inProcessSandboxClient, inlineSandboxClient, isWaitOutcome, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, legacySupervisorRunsRoot, loadSpawnForest, localSandboxClient, localShell, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, normalizeAnalyzeOnSettle, observe, officialChecksFromMeta, openSandboxRun, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, patchDelivered, pendingWaits, pickBestDelivered, pickChampion, pipeline, plateau, plateauLength, pollFor, printBenchmarkReport, probeSandboxCapabilities, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promotionGate, promptHandle, providerAsExecutor, providerAsSandboxClient, queueOf, readWorkerProgress, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runFinalizer, runGraph, runInWorkspace, runPersonified, runStrategyEvolution, runTree, safeWorkerFile, sample, sampleFromSettled, sampleThenRefine, sandboxCheckRunner, sandboxClientAsProvider, sandboxSessionTraceSource, sanitizeMcpToolSchema, secretEnvOfMcpServer, selectBestIndex, selectChampion, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, spendFromUsageEvents, startRetainedRun, stopSentinel, strategyAuthorContract, strategyAuthorSystemPrompt, streamAgentTurn, structuralRollout, sumSandboxUsage, supervise, superviseDispatch, superviseSurface, supervisorAgent, supervisorInstructions, supervisorPolicyPrompt, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, timerAt, trajectoryReport, validateWaitSpec, verify, visibleCheckScore, waitUntil, watchTrace, widen, withUntrackedArtifacts, workerControlLogFile, workerFromBackend, workerInboxFile, workerInboxFileFromEventDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
package/dist/kernel.js CHANGED
@@ -1,13 +1,13 @@
1
- import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-BxwZJVfZ.js";
1
+ import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-Bo5ZSAUR.js";
2
2
  import { _ as captureWorkerTraceEvidence, a as loadSpawnForest, b as workerTraceAnalysisStore, c as replaySpawnTree, g as WORKER_TOOL_TRACE_SCHEMA_VERSION, i as InMemorySpawnJournal, n as FileSpawnJournal, o as materializeTreeView, r as InMemoryResultBlobStore, s as pendingWaits, t as FileResultBlobStore, x as contentAddress, y as parseWorkerToolTraceArtifact } from "./spawn-journal-Cd5L-Ie9.js";
3
3
  import { i as mapSandboxToolEvent, n as extractLlmCallEvent, o as sumSandboxUsage, r as mapSandboxEvent, t as createSandboxToolPartState } from "./sandbox-events-vIwmuPdl.js";
4
4
  import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-mWSoToiQ.js";
5
- import { $ as runAgentRounds, B as workerTraceHeaders, C as queueOf, G as decodeToolPart, H as DEFAULT_SANDBOX_STEERING_MAX_TURNS, I as createWorktreeCliExecutor, J as createActivityLog, K as sandboxSessionTraceSource, M as cliWorktreeExecutor, N as createExecutor, O as createBudgetPool, P as createExecutorRegistry, Q as defaultSelectWinner, R as readWorkerTraceContext, S as freeSlots, U as createSteerableSandboxSession, V as workerTraceSeamKey, W as createPushTraceSource, X as createInbox, Y as readWorkerProgress, _ as pollFor, a as pickBestDelivered, b as waitUntil, et as createSandboxLineage, g as isWaitOutcome, h as createWaitProbes, i as collectDelivered, k as spendFromUsageEvents, m as settledToIteration, mt as createOtelExporter, n as createSupervisor, nt as acquireSandbox, o as runFinalizer, pt as createOpenInferenceFileExporter, q as DEFAULT_STALL_AFTER_MS, r as bestDelivered, s as runTree, t as createRootHandle, tt as probeSandboxCapabilities, u as createScope, v as timerAt, w as rollingDispatch, x as effectiveConcurrency, y as validateWaitSpec, z as workerTraceEnv } from "./supervisor-DlVTwwJb.js";
5
+ import { $ as runAgentRounds, B as workerTraceHeaders, C as queueOf, G as decodeToolPart, H as DEFAULT_SANDBOX_STEERING_MAX_TURNS, I as createWorktreeCliExecutor, J as createActivityLog, K as sandboxSessionTraceSource, M as cliWorktreeExecutor, N as createExecutor, O as createBudgetPool, P as createExecutorRegistry, Q as defaultSelectWinner, R as readWorkerTraceContext, S as freeSlots, U as createSteerableSandboxSession, V as workerTraceSeamKey, W as createPushTraceSource, X as createInbox, Y as readWorkerProgress, _ as pollFor, a as pickBestDelivered, b as waitUntil, et as createSandboxLineage, g as isWaitOutcome, h as createWaitProbes, i as collectDelivered, k as spendFromUsageEvents, m as settledToIteration, mt as createOtelExporter, n as createSupervisor, nt as acquireSandbox, o as runFinalizer, pt as createOpenInferenceFileExporter, q as DEFAULT_STALL_AFTER_MS, r as bestDelivered, s as runTree, t as createRootHandle, tt as probeSandboxCapabilities, u as createScope, v as timerAt, w as rollingDispatch, x as effectiveConcurrency, y as validateWaitSpec, z as workerTraceEnv } from "./supervisor-BTuNGicF.js";
6
6
  import { a as sandboxClientAsProvider, i as resolveAgentEnvironmentProvider, n as providerAsExecutor, o as createTangleSandboxExactProcessProvider, r as providerAsSandboxClient, t as createAgentEnvironmentProviderRegistry } from "./environment-provider-mDsjfGjY.js";
7
- import { C as observe, E as profileOptimizerModelCall, S as defaultAnalystInstruction, T as profileChatClient, _ as depthStrategy, a as defaultStructuralRolloutPolicy, b as sample, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as defineStrategy, h as breadthStrategy, i as defaultExtractCandidate, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, v as refine, w as renderReport, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-Dq0j-JHl.js";
8
- import { $ as loopUntil, A as assertStrategyContract, At as McpSpawnFault, B as promotionGate, C as chatTransportExecutor, Ct as pairwiseSignificance, D as pickChampion, Dt as renderPairwiseMarkdown, E as discriminatingMeans, Et as renderLeaderboardSvg, F as openSandboxRun, Ft as envKeyProvider, G as builtinShapes, H as trajectoryReport, I as printBenchmarkReport, It as mcpSecretEnvMetadataKey, J as FileCorpus, K as createShapeRegistry, L as runBenchmark, Lt as resolveMcpServerLaunch, M as strategyAuthorContract, Mt as materializeLocalMcp, N as strategyAuthorSystemPrompt, Nt as createMcpEnvironment, O as runStrategyEvolution, Ot as auditIntent, P as SandboxRunAbortError, Pt as sanitizeMcpToolSchema, Q as flatWidenGate, R as reconnectRetainedRun, Rt as resolveSecretEnv, St as leaderboard, T as createChatSessionStore, Tt as renderLeaderboardMarkdown, U as definePersona, V as equalKOnCost, W as runPersonified, X as renderCorpusToInstructions, Y as InMemoryCorpus, Z as fanout, _ as settledWorkerOut, _t as superviseDispatch, a as localShell, at as assertTraceDerivedFindings, b as analyzeTrace, bt as sentinelCompletion, c as createVerifierEnvironment, ct as registryScopeAnalyst, d as worktreeFanout, dt as defineLeaderboard, et as panel, f as EVIDENCE_MAX_CHARS, ft as resolveSandboxClient, g as composeWorkerEvidence, gt as loopDispatch, h as closingWorkerNote, ht as loopCampaignDispatch, i as jjWorkspace, it as widen, j as authorStrategy, jt as connectStdioMcp, k as selectChampion, kt as defaultAuditorInstruction, l as failuresAnalyst, lt as inProcessSandboxClient, m as VERIFY_TAIL_CHARS, mt as inlineSandboxClient, n as makeFinding, nt as selectValidWinner, o as runInWorkspace, ot as buildSteerContext, p as NOTE_MAX_CHARS, pt as localSandboxClient, q as registerShape, r as gitWorkspace, rt as verify, s as createWaterfallCollector, st as createScopeAnalyst, t as computeFindingId, tt as pipeline, u as superviseSurface, ut as harvestCorpus, v as copyUntrackedIntoClone, vt as completionAuthorizes, w as chatWorkerSeam, wt as renderLeaderboardHtml, x as patchDelivered, xt as stopSentinel, y as withUntrackedArtifacts, yt as deterministicCompletion, z as startRetainedRun, zt as secretEnvOfMcpServer } from "./runtime-YuPbrgG1.js";
9
- import { At as defaultToolDetectors, Ct as plateauLength, Et as canonicalFindingEvent, Ft as createSupervisorSpanRecorder, It as gateOnDeliverable, Lt as mapExecutorResult, Mt as createFileRunContext, Nt as createInMemoryRunContext, Ot as normalizeAnalyzeOnSettle, Pt as FileCoordinationLog, St as bestSoFar, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, X as delegate, Y as defaultDelegateBudget, _ as promptHandle, _t as noProgressFor, a as assertCoordinationBinding, b as classifyDriverFailure, bt as anytimeReport, d as delegatesWorkerBriefPrompt, f as dumbContinuationFailPrompt, ft as finalizeBestDelivered, g as naiveContinuationPrompt, gt as createProgressTracker, h as kernelPromptRegistry, ht as anyOf, i as workerFromBackend, jt as watchTrace, kt as createEventBus, l as analyzesFindingsReportPrompt, m as formatPromptHandle, mt as allWorkersStalled, n as supervise, o as resolveSupervisorProfile, p as dumbContinuationPassPrompt, pt as allOf, s as supervisorAgent, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as createPromptRegistry, v as supervisorPolicyPrompt, vt as plateau, wt as renderAnytimeTable, x as serveCoordinationMcp, xt as areaUnderCurve, y as DriverAttemptsExhaustedError, yt as sampleFromSettled } from "./supervise-BDj-uFfb.js";
10
- import { a as supervisorInstructions, i as profileRichnessFinding, n as assessAuthoredProfile, r as defaultProfileRichnessThresholds, t as asAuthoredProfile } from "./authoring-WS1l0lU1.js";
11
- import { n as defaultEdgeTraversalCap, r as runGraph, t as GraphEdgeCapError } from "./graph-B9hFN-zX.js";
7
+ import { C as observe, E as profileOptimizerModelCall, S as defaultAnalystInstruction, T as profileChatClient, _ as depthStrategy, a as defaultStructuralRolloutPolicy, b as sample, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as defineStrategy, h as breadthStrategy, i as defaultExtractCandidate, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, v as refine, w as renderReport, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-DGkq_Grt.js";
8
+ import { $ as loopUntil, A as assertStrategyContract, At as McpSpawnFault, B as promotionGate, C as chatTransportExecutor, Ct as pairwiseSignificance, D as pickChampion, Dt as renderPairwiseMarkdown, E as discriminatingMeans, Et as renderLeaderboardSvg, F as openSandboxRun, Ft as envKeyProvider, G as builtinShapes, H as trajectoryReport, I as printBenchmarkReport, It as mcpSecretEnvMetadataKey, J as FileCorpus, K as createShapeRegistry, L as runBenchmark, Lt as resolveMcpServerLaunch, M as strategyAuthorContract, Mt as materializeLocalMcp, N as strategyAuthorSystemPrompt, Nt as createMcpEnvironment, O as runStrategyEvolution, Ot as auditIntent, P as SandboxRunAbortError, Pt as sanitizeMcpToolSchema, Q as flatWidenGate, R as reconnectRetainedRun, Rt as resolveSecretEnv, St as leaderboard, T as createChatSessionStore, Tt as renderLeaderboardMarkdown, U as definePersona, V as equalKOnCost, W as runPersonified, X as renderCorpusToInstructions, Y as InMemoryCorpus, Z as fanout, _ as settledWorkerOut, _t as superviseDispatch, a as localShell, at as assertTraceDerivedFindings, b as analyzeTrace, bt as sentinelCompletion, c as createVerifierEnvironment, ct as registryScopeAnalyst, d as worktreeFanout, dt as defineLeaderboard, et as panel, f as EVIDENCE_MAX_CHARS, ft as resolveSandboxClient, g as composeWorkerEvidence, gt as loopDispatch, h as closingWorkerNote, ht as loopCampaignDispatch, i as jjWorkspace, it as widen, j as authorStrategy, jt as connectStdioMcp, k as selectChampion, kt as defaultAuditorInstruction, l as failuresAnalyst, lt as inProcessSandboxClient, m as VERIFY_TAIL_CHARS, mt as inlineSandboxClient, n as makeFinding, nt as selectValidWinner, o as runInWorkspace, ot as buildSteerContext, p as NOTE_MAX_CHARS, pt as localSandboxClient, q as registerShape, r as gitWorkspace, rt as verify, s as createWaterfallCollector, st as createScopeAnalyst, t as computeFindingId, tt as pipeline, u as superviseSurface, ut as harvestCorpus, v as copyUntrackedIntoClone, vt as completionAuthorizes, w as chatWorkerSeam, wt as renderLeaderboardHtml, x as patchDelivered, xt as stopSentinel, y as withUntrackedArtifacts, yt as deterministicCompletion, z as startRetainedRun, zt as secretEnvOfMcpServer } from "./runtime-BeBAzfnW.js";
9
+ import { At as defaultToolDetectors, Ct as plateauLength, Et as canonicalFindingEvent, Ft as createSupervisorSpanRecorder, It as gateOnDeliverable, Lt as mapExecutorResult, Mt as createFileRunContext, Nt as createInMemoryRunContext, Ot as normalizeAnalyzeOnSettle, Pt as FileCoordinationLog, St as bestSoFar, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, X as delegate, Y as defaultDelegateBudget, _ as promptHandle, _t as noProgressFor, a as assertCoordinationBinding, b as classifyDriverFailure, bt as anytimeReport, d as delegatesWorkerBriefPrompt, f as dumbContinuationFailPrompt, ft as finalizeBestDelivered, g as naiveContinuationPrompt, gt as createProgressTracker, h as kernelPromptRegistry, ht as anyOf, i as workerFromBackend, jt as watchTrace, kt as createEventBus, l as analyzesFindingsReportPrompt, m as formatPromptHandle, mt as allWorkersStalled, n as supervise, o as resolveSupervisorProfile, p as dumbContinuationPassPrompt, pt as allOf, s as supervisorAgent, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as createPromptRegistry, v as supervisorPolicyPrompt, vt as plateau, wt as renderAnytimeTable, x as serveCoordinationMcp, xt as areaUnderCurve, y as DriverAttemptsExhaustedError, yt as sampleFromSettled } from "./supervise-B2fTctMn.js";
10
+ import { a as supervisorInstructions, i as profileRichnessFinding, n as assessAuthoredProfile, r as defaultProfileRichnessThresholds, t as asAuthoredProfile } from "./authoring-sf0VpHlY.js";
11
+ import { n as defaultEdgeTraversalCap, r as runGraph, t as GraphEdgeCapError } from "./graph-DjTw-HMK.js";
12
12
  import { a as supervisorRunDir, c as workerControlLogFile, d as writeWorkerSteer, i as safeWorkerFile, l as workerInboxFile, n as legacySupervisorRunsRoot, o as supervisorRunsRoot, r as readWorkerSteerRequests, s as supervisorWorkersDir, t as legacySupervisorRunDir, u as workerInboxFileFromEventDir } from "./run-layout-CeJsEAom.js";
13
13
  export { DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_STALL_AFTER_MS, DriverAttemptsExhaustedError, EVIDENCE_MAX_CHARS, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, GraphEdgeCapError, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, McpSpawnFault, NOTE_MAX_CHARS, SandboxRunAbortError, VERIFY_TAIL_CHARS, WORKER_TOOL_TRACE_SCHEMA_VERSION, acquireSandbox, adaptiveRefine, allOf, allWorkersStalled, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertCoordinationBinding, assertModelAllowed, assertProfileModelsAllowed, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, auditIntent, authorStrategy, bestDelivered, bestSoFar, breadthStrategy, buildSteerContext, builtinShapes, canDisplace, canonicalFindingEvent, captureWorkerTraceEvidence, chatTransportExecutor, chatWorkerSeam, classifyDriverFailure, cliWorktreeExecutor, closingWorkerNote, collectAgentTurn, collectDelivered, compareCheckOutcomes, completionAuthorizes, composeCheckSources, composeWorkerEvidence, computeFindingId, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createEventBus, createExecutor, createExecutorRegistry, createFileRunContext, createInMemoryRunContext, createInbox, createMcpEnvironment, createOpenInferenceFileExporter, createOtelExporter, createProgressTracker, createPromptRegistry, createPushTraceSource, createRootHandle, createSandboxLineage, createSandboxToolPartState, createScope, createScopeAnalyst, createShapeRegistry, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaitProbes, createWaterfallCollector, createWorktreeCliExecutor, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, discriminatingMeans, dumbContinuationFailPrompt, dumbContinuationPassPrompt, effectiveConcurrency, envKeyProvider, equalKOnCost, extractLlmCallEvent, failuresAnalyst, fanout, filterAuthoredAsserts, finalizeBestDelivered, flatWidenGate, formatPromptHandle, freeSlots, gateOnDeliverable, gitWorkspace, harvestCorpus, inProcessSandboxClient, inlineSandboxClient, isWaitOutcome, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, legacySupervisorRunsRoot, loadSpawnForest, localSandboxClient, localShell, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, normalizeAnalyzeOnSettle, observe, officialChecksFromMeta, openSandboxRun, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, patchDelivered, pendingWaits, pickBestDelivered, pickChampion, pipeline, plateau, plateauLength, pollFor, printBenchmarkReport, probeSandboxCapabilities, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promotionGate, promptHandle, providerAsExecutor, providerAsSandboxClient, queueOf, readWorkerProgress, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runFinalizer, runGraph, runInWorkspace, runPersonified, runStrategyEvolution, runTree, safeWorkerFile, sample, sampleFromSettled, sampleThenRefine, sandboxCheckRunner, sandboxClientAsProvider, sandboxSessionTraceSource, sanitizeMcpToolSchema, secretEnvOfMcpServer, selectBestIndex, selectChampion, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, spendFromUsageEvents, startRetainedRun, stopSentinel, strategyAuthorContract, strategyAuthorSystemPrompt, streamAgentTurn, structuralRollout, sumSandboxUsage, supervise, superviseDispatch, superviseSurface, supervisorAgent, supervisorInstructions, supervisorPolicyPrompt, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, timerAt, trajectoryReport, validateWaitSpec, verify, visibleCheckScore, waitUntil, watchTrace, widen, withUntrackedArtifacts, workerControlLogFile, workerFromBackend, workerInboxFile, workerInboxFileFromEventDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
@@ -1,9 +1,9 @@
1
1
  import { a as persistCandidateOutputArtifact, ct as omitTopLevelDigest, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact } from "./prepare-BQ82nG06.js";
2
2
  import { i as sealAgentCandidateBundle, t as captureAgentCandidateWorkspace } from "./workspace-archive-CGcXL3zA.js";
3
3
  import { t as assertExecutableAgentProfile } from "./model-policy-mWSoToiQ.js";
4
- import { t as createAgentImprovementActivationResult } from "./activation-DFJBEC62.js";
4
+ import { t as createAgentImprovementActivationResult } from "./activation-U2mou_hT.js";
5
5
  import { t as RESEARCHER_SYSTEM_PROMPT } from "./researcher-CYmr4VJy.js";
6
- import { n as supervise } from "./supervise-BDj-uFfb.js";
6
+ import { n as supervise } from "./supervise-B2fTctMn.js";
7
7
  import { agentCandidateKnowledgeSchema, agentProfileSchema, sha256DigestSchema } from "@tangle-network/agent-interface";
8
8
  import { realpath } from "node:fs/promises";
9
9
  import { evaluateKnowledgeBaseReadiness, fromAgentCandidateKnowledgeRef, improveKnowledgeBase, knowledgeImprovementCandidateRef, loadKnowledgeImprovementActivationResult, promoteKnowledgeCandidate, restoreKnowledgeCandidateBaseline, toAgentCandidateKnowledgeRef, withKnowledgeImprovementComparison } from "@tangle-network/agent-knowledge";
@@ -432,4 +432,4 @@ function addSpent(target, result) {
432
432
  //#endregion
433
433
  export { createSupervisedKnowledgeUpdater as a, runSupervisedKnowledgeUpdate as c, RESEARCH_SUPERVISOR_SYSTEM_PROMPT as i, createKnowledgeImprovementActivationExecutor as l, createAgentKnowledgeReadinessCheck as n, formatSupervisedKnowledgeTask as o, runKnowledgeImprovementJob as r, knowledgeReadinessDeliverable as s, buildKnowledgeImprovementExperimentBundles as t };
434
434
 
435
- //# sourceMappingURL=knowledge-By_lZ80W.js.map
435
+ //# sourceMappingURL=knowledge-DV8PEBph.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge-By_lZ80W.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { RESEARCHER_SYSTEM_PROMPT } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n /** Caller-owned exact supervisor harness/provider/model identity. */\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const exactSupervisor = agentProfileSchema.parse(options.supervisorProfile) as SupervisorProfile\n assertExecutableAgentProfile(exactSupervisor, 'runSupervisedKnowledgeUpdate')\n const baseInstructions = exactSupervisor.prompt?.systemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = RESEARCHER_SYSTEM_PROMPT\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n ...exactSupervisor,\n prompt: { ...exactSupervisor.prompt, systemPrompt },\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorProfile,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n supervisorProfile,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAAS,KAAA;EAChD;EACA,YAAY,OAAO,eAAe;GAChC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,mEAAmE;GAErF,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,IAAI,UAAU,SAAS,OAAO,UAAU;GAExC,MAAM,kBAAkB;IACtB,MAAM,QAAQ;IACd,WAAW,UAAU;IACrB,YAAY;KACV,YAAY,WAAW;KACvB,aAAa,WAAW;KACxB,UAAU,QAAQ;KAClB,eAAe,YACb,UAAU,OACR,yBAAyB,SAAS,WAAW,WAAW,WAAW,MAAM,CAC3E;IACJ;IACA,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;IACtD,GAAI,QAAQ,eAAe,KAAA,IA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
+ {"version":3,"file":"knowledge-DV8PEBph.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { RESEARCHER_SYSTEM_PROMPT } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n /** Caller-owned exact supervisor harness/provider/model identity. */\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const exactSupervisor = agentProfileSchema.parse(options.supervisorProfile) as SupervisorProfile\n assertExecutableAgentProfile(exactSupervisor, 'runSupervisedKnowledgeUpdate')\n const baseInstructions = exactSupervisor.prompt?.systemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = RESEARCHER_SYSTEM_PROMPT\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n ...exactSupervisor,\n prompt: { ...exactSupervisor.prompt, systemPrompt },\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorProfile,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n supervisorProfile,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAAS,KAAA;EAChD;EACA,YAAY,OAAO,eAAe;GAChC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,mEAAmE;GAErF,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,IAAI,UAAU,SAAS,OAAO,UAAU;GAExC,MAAM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;EAAG,UAAU;EAAM,KAAK;EAAG,IAAI;CAAE;AACzF;AAEA,SAAS,SACP,QACA,QACM;CACN,MAAM,QAAQ,OAAO;CACrB,OAAO,cAAc,MAAM;CAC3B,OAAO,eAAe,MAAM,OAAO;CACnC,OAAO,gBAAgB,MAAM,OAAO;CACpC,OAAO,WAAW,OAAO,YAAY,MAAM,aAAa;CACxD,OAAO,OAAO,MAAM;CACpB,OAAO,MAAM,MAAM;AACrB"}
@@ -1,2 +1,2 @@
1
- import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-CcpNgmQY.js";
1
+ import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-BsrFZu0N.js";
2
2
  export { type AgentKnowledgeReadinessCheckOptions, type CreateKnowledgeImprovementActivationExecutorOptions, type KnowledgeImprovementActivationExecutor, type KnowledgeImprovementCandidatePair, type KnowledgeImprovementExperimentBundles, type KnowledgeImprovementJobMeasurement, type KnowledgeImprovementJobResult, type KnowledgeReadinessCheck, type KnowledgeReadinessCheckInput, type KnowledgeReadinessCheckResult, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, type RunKnowledgeImprovementJobOptions, type SupervisedKnowledgeUpdateInput, type SupervisedKnowledgeUpdateOptions, type SupervisedKnowledgeUpdateResult, type SupervisedKnowledgeUpdater, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
package/dist/knowledge.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-By_lZ80W.js";
1
+ import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-DV8PEBph.js";
2
2
  export { RESEARCH_SUPERVISOR_SYSTEM_PROMPT, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
@@ -1,6 +1,6 @@
1
1
  import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
2
- import { _ as WorktreeFanoutOptions, _t as WorktreePatchArtifact, fc as WinnerStrategy, g as AuthoredHarness } from "./index-D9dVsozT.js";
3
- import { i as Budget } from "./types-B9KAen_0.js";
2
+ import { _ as WorktreeFanoutOptions, _t as WorktreePatchArtifact, fc as WinnerStrategy, g as AuthoredHarness } from "./index-DixXnx07.js";
3
+ import { i as Budget } from "./types-BjUQODeG.js";
4
4
  import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
5
5
  import { AgentProfile } from "@tangle-network/agent-interface";
6
6
  //#region src/loop-runner.d.ts
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
162
162
  };
163
163
  //#endregion
164
164
  export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
165
- //# sourceMappingURL=loop-runner-bin-D9OAFkP_.d.ts.map
165
+ //# sourceMappingURL=loop-runner-bin-BqJGlXju.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { i as ConfigError } from "./errors-DEAvWQPy.js";
2
- import { P as createExecutorRegistry } from "./supervisor-DlVTwwJb.js";
3
- import { U as definePersona, W as runPersonified, d as worktreeFanout } from "./runtime-YuPbrgG1.js";
2
+ import { P as createExecutorRegistry } from "./supervisor-BTuNGicF.js";
3
+ import { U as definePersona, W as runPersonified, d as worktreeFanout } from "./runtime-BeBAzfnW.js";
4
4
  import { t as runAnalystLoop } from "./analyst-loop-CBiT-ev1.js";
5
5
  import { t as createKbGate } from "./kb-gate-DpaSwXVx.js";
6
6
  //#region src/loop-runner.ts
@@ -243,4 +243,4 @@ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main()
243
243
  //#endregion
244
244
  export { isDelegatedLoopMode as a, worktreeLoopRunner as c, auditLoopRunner as i, runLoopRunnerCli as n, researchLoopRunner as o, DELEGATED_LOOP_MODES as r, runDelegatedLoop as s, parseLoopRunnerArgv as t };
245
245
 
246
- //# sourceMappingURL=loop-runner-bin-CjsTZUVS.js.map
246
+ //# sourceMappingURL=loop-runner-bin-C1G7gPX0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-CjsTZUVS.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,K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,SAAS,OAAO,KAAsB;CACpC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;AAGA,eAAe,OAAsB;CACnC,MAAM,EAAE,MAAM,WAAW,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC;CAClE,IAAI,CAAC,QAAQ,CAAC,QAAQ;EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
1
+ {"version":3,"file":"loop-runner-bin-C1G7gPX0.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,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