@tangle-network/agent-runtime 0.104.0 → 0.106.0

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 (217) hide show
  1. package/README.md +176 -42
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1134
  40. package/dist/index.js +2134 -1972
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +776 -888
  43. package/dist/intelligence.js +1466 -1410
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -17
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -437
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +150 -147
  84. package/dist/primeintellect/index.js +626 -1004
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +43 -55
  130. package/skills/build-with-agent-runtime/SKILL.md +16 -9
  131. package/skills/loop-writer/SKILL.md +1 -1
  132. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  133. package/dist/analyst-loop.js.map +0 -1
  134. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  135. package/dist/candidate-execution/index.js.map +0 -1
  136. package/dist/chunk-2KGAN2HM.js +0 -1256
  137. package/dist/chunk-2KGAN2HM.js.map +0 -1
  138. package/dist/chunk-2QJSNOGK.js +0 -48
  139. package/dist/chunk-2QJSNOGK.js.map +0 -1
  140. package/dist/chunk-2UABGGUB.js +0 -474
  141. package/dist/chunk-2UABGGUB.js.map +0 -1
  142. package/dist/chunk-2VZYRB55.js +0 -834
  143. package/dist/chunk-2VZYRB55.js.map +0 -1
  144. package/dist/chunk-2X65HYMI.js +0 -3526
  145. package/dist/chunk-2X65HYMI.js.map +0 -1
  146. package/dist/chunk-3MDZX7YU.js +0 -125
  147. package/dist/chunk-3MDZX7YU.js.map +0 -1
  148. package/dist/chunk-3PPVCS75.js +0 -199
  149. package/dist/chunk-3PPVCS75.js.map +0 -1
  150. package/dist/chunk-5HNDYWUT.js +0 -6424
  151. package/dist/chunk-5HNDYWUT.js.map +0 -1
  152. package/dist/chunk-5IBQAPVB.js +0 -29
  153. package/dist/chunk-5IBQAPVB.js.map +0 -1
  154. package/dist/chunk-5QOB7H74.js +0 -387
  155. package/dist/chunk-5QOB7H74.js.map +0 -1
  156. package/dist/chunk-ATDFUJYI.js +0 -4728
  157. package/dist/chunk-ATDFUJYI.js.map +0 -1
  158. package/dist/chunk-B7K7V22Y.js +0 -699
  159. package/dist/chunk-B7K7V22Y.js.map +0 -1
  160. package/dist/chunk-DPEUKJRO.js +0 -27
  161. package/dist/chunk-DPEUKJRO.js.map +0 -1
  162. package/dist/chunk-FD2MBMOH.js +0 -494
  163. package/dist/chunk-FD2MBMOH.js.map +0 -1
  164. package/dist/chunk-FJI3EXU3.js +0 -2402
  165. package/dist/chunk-FJI3EXU3.js.map +0 -1
  166. package/dist/chunk-HAO4CXHP.js +0 -200
  167. package/dist/chunk-HAO4CXHP.js.map +0 -1
  168. package/dist/chunk-ISPWRSEC.js +0 -408
  169. package/dist/chunk-ISPWRSEC.js.map +0 -1
  170. package/dist/chunk-KRBFHMV6.js +0 -1228
  171. package/dist/chunk-KRBFHMV6.js.map +0 -1
  172. package/dist/chunk-L5DST3QC.js +0 -351
  173. package/dist/chunk-L5DST3QC.js.map +0 -1
  174. package/dist/chunk-M22PL4GH.js +0 -171
  175. package/dist/chunk-M22PL4GH.js.map +0 -1
  176. package/dist/chunk-NURIQBJQ.js +0 -72
  177. package/dist/chunk-NURIQBJQ.js.map +0 -1
  178. package/dist/chunk-PZZKQVQV.js +0 -52
  179. package/dist/chunk-PZZKQVQV.js.map +0 -1
  180. package/dist/chunk-Q2JSAVQ3.js +0 -671
  181. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  182. package/dist/chunk-SBTWKPVR.js +0 -5576
  183. package/dist/chunk-SBTWKPVR.js.map +0 -1
  184. package/dist/chunk-SGKPNBXE.js +0 -60
  185. package/dist/chunk-SGKPNBXE.js.map +0 -1
  186. package/dist/chunk-SNSMRT6H.js +0 -680
  187. package/dist/chunk-SNSMRT6H.js.map +0 -1
  188. package/dist/chunk-STJEHM5F.js +0 -1338
  189. package/dist/chunk-STJEHM5F.js.map +0 -1
  190. package/dist/chunk-UPWGXKXB.js +0 -254
  191. package/dist/chunk-UPWGXKXB.js.map +0 -1
  192. package/dist/chunk-YEJR7IXO.js +0 -68
  193. package/dist/chunk-YEJR7IXO.js.map +0 -1
  194. package/dist/chunk-ZXICDSAK.js +0 -907
  195. package/dist/chunk-ZXICDSAK.js.map +0 -1
  196. package/dist/completion-gate-Bv47cOnn.d.ts +0 -256
  197. package/dist/conversation.js.map +0 -1
  198. package/dist/coordination-CxtzMxSM.d.ts +0 -2570
  199. package/dist/environment-provider.js.map +0 -1
  200. package/dist/improve--2A0gK1-.d.ts +0 -440
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-CtK9dSny.d.ts +0 -175
  204. package/dist/loop-runner-bin-DUOGtvOl.d.ts +0 -207
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-DzkUY3HQ.d.ts +0 -271
  209. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  210. package/dist/structural-rollout-C4mabf87.d.ts +0 -446
  211. package/dist/supervise-7q9F5brx.d.ts +0 -379
  212. package/dist/types-BCoemcXU.d.ts +0 -802
  213. package/dist/types-BwoZWq-i.d.ts +0 -510
  214. package/dist/types-Cbp72qyu.d.ts +0 -491
  215. package/dist/types-CmYCMbFT.d.ts +0 -203
  216. package/dist/types-CvNwMzQt.d.ts +0 -957
  217. package/dist/worktree-fanout-WsOzt8qu.d.ts +0 -999
package/dist/index.d.ts CHANGED
@@ -1,1134 +1,14 @@
1
- import { AgentEvalError, AnalystFinding, KnowledgeReadinessReport, RunRecord, ControlEvalResult } from '@tangle-network/agent-eval';
2
- export { AgentEvalError, AgentEvalErrorCode, ConfigError, ControlBudget, ControlDecision, ControlEvalResult, ControlRunResult, ControlStep, DataAcquisitionPlan, JudgeError, KnowledgeReadinessReport, KnowledgeRequirement, NotFoundError, RunRecord, ValidationError } from '@tangle-network/agent-eval';
3
- import { c as createOpenAICompatibleBackend } from './backends-BO4Jqoe2.js';
4
- export { a as createIterableBackend, b as createSandboxPromptBackend } from './backends-BO4Jqoe2.js';
5
- export { AGENT_CANDIDATE_EXECUTION_SUPPORT, AgentCandidateBundleInput, AgentCandidateCodeSource, AgentCandidateCodeSurfaceSource, AgentCandidateProfileSource, AgentCandidateWorkspaceArchiveLimits, BuildAgentCandidateBundleInput, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CaptureAgentCandidateWorkspaceOptions, CapturedAgentCandidateWorkspace, CreateAgentCandidateWorkspacePortOptions, DisposePreparedAgentCandidateOptions, ExactProcessCandidateExecutorOptions, FileAgentCandidateExecutionClaimStore, FileAgentCandidateExecutionClaimStoreOptions, RecoverExpiredAgentCandidateOptions, buildAgentCandidateBundle, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, createAgentCandidateWorkspacePort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, persistCandidateOutputArtifact, recoverExpiredAgentCandidateExecution, sealAgentCandidateBundle, verifyAgentCandidateBundle } from './candidate-execution/index.js';
6
- export { a as AgentCandidateExecutionAttemptRecord, b as AgentCandidateExecutionAttemptRef, c as AgentCandidateExecutionClaim, d as AgentCandidateExecutionClaimResult, A as AgentCandidateExecutionClaimStore, e as AgentCandidateExecutionCleanupHandles, f as AgentCandidateExecutionFailureClass, g as AgentCandidateExecutionFinishResult, h as AgentCandidateExecutionLease, i as AgentCandidateExecutionPhase, j as AgentCandidateExecutionPhaseResult, k as AgentCandidateExecutionRecoveryEvidence, l as AgentCandidateExecutionStageResult, m as AgentCandidateExecutionTerminalRecord, n as AgentCandidateExecutionTerminalResult, o as AgentCandidateModelGrantActivateInput, q as AgentCandidateModelGrantClient, r as AgentCandidateModelGrantReservation, s as AgentCandidateModelGrantReserveInput, t as AgentCandidateModelGrantSettleInput, u as AgentCandidatePreparationEvidence, v as AgentCandidateRetryRejection, C as CreateProtectedAgentCandidateModelPortOptions, E as ExecutePreparedAgentCandidateOptions, I as InMemoryAgentCandidateExecutionClaimStore, P as PrepareAgentCandidateExecutionOptions, w as applyExactAgentProfileDiff, x as assertCandidateProfileBinding, y as createProtectedAgentCandidateModelPort, z as executePreparedAgentCandidate, B as parseExactAgentProfile, D as parseExactAgentProfileDiff, F as prepareAgentCandidateExecution } from './protected-model-port-DzkUY3HQ.js';
7
- export { j as AgentCandidateArtifactPort, a as AgentCandidateBenchmarkGraderPort, k as AgentCandidateContainerPort, e as AgentCandidateExecutionPorts, l as AgentCandidateExecutorFinalCapture, m as AgentCandidateExecutorMemoryCapture, A as AgentCandidateExecutorPort, n as AgentCandidateExecutorProfileFile, o as AgentCandidateExecutorRequest, p as AgentCandidateExecutorStopRequest, q as AgentCandidateExecutorTaskOutcomeCapture, r as AgentCandidateExecutorWorkspaceFile, s as AgentCandidateExecutorWorkspaceInput, t as AgentCandidateMemoryPort, u as AgentCandidateMemoryResetResult, v as AgentCandidateModelLimits, f as AgentCandidateModelPort, b as AgentCandidateOutputArtifactPort, w as AgentCandidateOutputPurpose, h as AgentCandidateProtectedModelActivation, g as AgentCandidateProtectedModelReservation, i as AgentCandidateProtectedModelSettlement, x as AgentCandidateProtectedRunCapture, y as AgentCandidateRepositoryPort, c as AgentCandidateRunFinalization, d as AgentCandidateTaskExecution, z as AgentCandidateVerificationPorts, B as AgentCandidateWorkspacePort, C as CANDIDATE_TRACE_ENV, D as CANDIDATE_TRACE_TAGS, E as CanonicalCandidateDocument, P as PreparedAgentCandidateExecution, F as PreparedAgentCandidateInstruction, G as PreparedAgentCandidateKnowledge, H as PreparedAgentCandidateLaunch, I as PreparedAgentCandidateTrace, R as ResolvedAgentCandidateContainer, V as VerifiedAgentCandidate, J as VerifiedAgentCandidateTaskOutcome } from './types-Cbp72qyu.js';
8
- export { AuthSource, BackendCallPolicy, CircuitBreakerConfig, CircuitBreakerState, CircuitOpenError, Conversation, ConversationDriveState, ConversationJournal, ConversationJournalEntry, ConversationParticipant, ConversationPolicy, ConversationResult, ConversationStreamEvent, ConversationTurn, D1DatabaseLike, D1StmtLike, DEFAULT_MAX_DEPTH, DeadlineExceededError, FORWARD_HEADERS, FileConversationJournal, ForwardHeaderName, HaltContext, HaltPredicate, HaltReason, HaltSignal, InMemoryConversationJournal, PersonaConversationResult, PersonaDriver, PropagatedHeaders, RetryBackoff, RetryableErrorPredicate, RunConversationOptions, RunPersonaConfig, RunPersonaConversationOptions, SqlAdapter, SqlConversationJournal, TurnOrder, buildForwardHeaders, computeBackoff, createConversationBackend, d1ToSqlAdapter, defaultIsRetryable, defineConversation, isDepthExceeded, makePerAttemptSignal, readDepth, runConversation, runConversationStream, runPersonaConversation, runPersonaDispatch, sleep, slugifySpeaker, turnId } from './conversation.js';
9
- import { V as Verifier, C as CandidateGenerator } from './improve--2A0gK1-.js';
10
- export { A as AGENTIC_PROFILE_RESOURCE_ROOT, b as AgenticGeneratorOptions, c as AgenticGeneratorShotDisposition, d as AgenticGeneratorShotExecution, e as AgenticGeneratorShotReceipt, f as ImproveCodeOptions, I as ImproveOptions, a as ImproveResult, g as ImproveSkillsOptions, h as ImproveSurface, i as ImprovementCandidate, j as ImprovementDriverOptions, M as ManagedImprovementDriver, k as VerifyResult, l as agenticGenerator, m as commandVerifier, n as defaultBuildPrompt, o as improve, p as improvementDriver } from './improve--2A0gK1-.js';
11
- import { ProposeContext, SurfaceProposer, MutableSurface } from '@tangle-network/agent-eval/campaign';
12
- import { L as LocalHarness, r as runLocalHarness } from './local-harness-CtK9dSny.js';
13
- import { T as ToolLoopChat, c as RuntimeTelemetryOptions } from './sanitize-DEbPNtyI.js';
14
- export { d as RuntimeEventCollector, e as RuntimeStreamEventCollector, S as SanitizedKnowledgeReadinessReport, f as createRuntimeEventCollector, g as createRuntimeStreamEventCollector, s as sanitizeAgentRuntimeEvent, h as sanitizeKnowledgeReadinessReport, i as sanitizeRuntimeStreamEvent } from './sanitize-DEbPNtyI.js';
15
- import { AgentProfile, AgentProfileDiff } from '@tangle-network/agent-interface';
16
- export { AgentCandidateBenchmarkGraderIdentity } from '@tangle-network/agent-interface';
17
- import { Scenario, SelfImproveOptions } from '@tangle-network/agent-eval/contract';
18
- import { S as SurfaceImprovementEdit } from './improvement-adapter-HAZz-7vK.js';
19
- import { I as ImprovementProposalSource } from './types-CmYCMbFT.js';
20
- import { S as StructuralRolloutPolicy } from './structural-rollout-C4mabf87.js';
21
- export { AgentKnowledgeReadinessCheckOptions, CreateKnowledgeImprovementActivationExecutorOptions, KnowledgeImprovementActivationExecutor, KnowledgeImprovementCandidatePair, KnowledgeImprovementExperimentBundles, KnowledgeImprovementJobMeasurement, KnowledgeImprovementJobResult, KnowledgeReadinessCheck, KnowledgeReadinessCheckInput, KnowledgeReadinessCheckResult, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, RunKnowledgeImprovementJobOptions, SupervisedKnowledgeUpdateInput, SupervisedKnowledgeUpdateOptions, SupervisedKnowledgeUpdateResult, SupervisedKnowledgeUpdater, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate } from './knowledge.js';
22
- export { D as DELEGATED_LOOP_MODES, a as DelegatedLoopMode, b as DelegatedLoopRegistry, c as DelegatedLoopResult, d as DelegatedLoopRunner, L as LoopRunnerCliArgs, e as LoopRunnerCliResult, R as ResearchLoopResult, f as ResearchLoopRunnerOptions, g as RunDelegatedLoopOptions, V as VetoedFact, W as WorktreeLoopRunnerOptions, h as auditLoopRunner, i as isDelegatedLoopMode, p as parseLoopRunnerArgv, r as researchLoopRunner, j as runDelegatedLoop, k as runLoopRunnerCli, s as selfImproveLoopRunner, w as worktreeLoopRunner } from './loop-runner-bin-DUOGtvOl.js';
23
- export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from './openai-tools-fnj6SRVg.js';
24
- export { b1 as EvalRunEvent, b2 as EvalRunGeneration, b3 as EvalRunsExportConfig, b4 as EvalRunsExportResult, b5 as INTELLIGENCE_WIRE_VERSION, b6 as LoopSpanNode, b7 as OtelAttribute, b8 as OtelExportConfig, b9 as OtelExporter, ba as OtelSpan, bb as RuntimeEventOtelOptions, bc as buildLoopOtelSpans, bd as buildLoopSpanNodes, be as buildRuntimeEventOtelSpans, bf as createOtelExporter, bg as exportEvalRuns, bh as loopEventToOtelSpan } from './coordination-CxtzMxSM.js';
25
- import { K as KnowledgeReadinessDecision, A as AgentBackendInput, c as AgentExecutionBackend, h as RunAgentTaskOptions, i as AgentTaskRunResult, j as RunAgentTaskStreamOptions, R as RuntimeStreamEvent, k as RuntimeSessionStore, l as RuntimeSession } from './types-BwoZWq-i.js';
26
- export { m as AgentAdapter, d as AgentBackendContext, n as AgentKnowledgeProvider, e as AgentRuntimeEvent, o as AgentRuntimeEventSink, p as AgentTaskContext, g as AgentTaskSpec, f as AgentTaskStatus, B as BackendErrorDetail, b as OpenAIChatResponseFormat, O as OpenAIChatTool, a as OpenAIChatToolChoice } from './types-BwoZWq-i.js';
27
- import { R as RuntimeHooks } from './types-BCoemcXU.js';
28
- export { d as RuntimeDecisionEvidenceRef, e as RuntimeDecisionKind, f as RuntimeDecisionPoint, g as RuntimeHookContext, h as RuntimeHookErrorContext, i as RuntimeHookEvent, j as RuntimeHookPhase, k as RuntimeHookTarget, l as RuntimeRunHandle, m as RuntimeRunPersistenceAdapter, n as RuntimeRunRow, o as composeRuntimeHooks, p as defineRuntimeHooks, q as notifyRuntimeDecisionPoint, r as notifyRuntimeHookEvent, s as startRuntimeRun } from './types-BCoemcXU.js';
29
- import '@tangle-network/agent-interface/environment-provider';
30
- import 'node:child_process';
31
- import './worktree-fanout-WsOzt8qu.js';
32
- import './types-CvNwMzQt.js';
33
- import '@tangle-network/sandbox';
34
- import './completion-gate-Bv47cOnn.js';
35
- import '@tangle-network/agent-profile-materialize';
36
- import '@tangle-network/agent-knowledge';
37
- import './activation-Cm-9MMX1.js';
38
- import './supervise-7q9F5brx.js';
39
- import './kb-gate-CwHO0vz6.js';
40
- import './substrate-Dyiqmd3o.js';
41
- import './environment-provider.js';
42
-
43
- /**
44
- * `handleChatTurn` — framework-neutral chat-turn HTTP orchestrator.
45
- * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`
46
- * lifecycle vocabulary, and the persist / post-process / trace-flush
47
- * hook order. Returns a `ReadableStream` body the product hands to its
48
- * platform `Response`.
49
- *
50
- * Execution durability is the substrate's concern: `box.streamPrompt`
51
- * auto-reconnects in-call; cross-process reconnect via `X-Execution-ID`
52
- * is the product's job. The producer this engine wraps already speaks
53
- * that protocol — the engine just frames the events.
54
- *
55
- * Hooks (`ChatTurnHooks`):
56
- * - `produce` — build the backend event stream
57
- * - `persistAssistantMessage` — write the assistant turn to the product DB
58
- * - `onTurnComplete?` — post-process (proposals, citations, …)
59
- * - `onEvent?` — per-event side channel (e.g. DO broadcast)
60
- * - `transformFinalText?` — pre-persist transform (e.g. PII redact)
61
- * - `traceFlush?` — handed to waitUntil so OTLP export lands
62
- *
63
- * Framework neutrality: takes already-resolved values (`identity` tuple,
64
- * a `waitUntil`), never a `Request` or a `Context`. The product's thin
65
- * route adapter does auth + parse + access-control, then calls
66
- * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.
67
- */
68
- /** The NDJSON line protocol every product chat client already speaks. */
69
- interface ChatStreamEvent {
70
- type: string;
71
- data?: Record<string, unknown>;
72
- }
73
- /** Identity of a chat turn. `tenantId` is the workspace id for workspace-
74
- * scoped products and the user id for session-scoped products. */
75
- interface ChatTurnIdentity {
76
- tenantId: string;
77
- /** Thread / session id. */
78
- sessionId: string;
79
- userId: string;
80
- /** Monotonic 0-based turn index within the session. */
81
- turnIndex: number;
82
- }
83
- /** The live side of a turn — what the product's `produce` hook returns. */
84
- interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {
85
- /** The turn's event stream. Forwarded verbatim to the caller. */
86
- stream: AsyncGenerator<TEvent, void, unknown>;
87
- /** The turn's final assistant text. Read once, after `stream` drains. */
88
- finalText(): string;
89
- }
90
- interface ChatTurnHooks {
91
- /** Build the backend stream. The engine forwards events verbatim and
92
- * reads `finalText()` once the stream drains. */
93
- produce(): ChatTurnProducer;
94
- /** Persist the assistant message to the product's own store. Called
95
- * once, after drain, with the assembled (transform-applied) text. */
96
- persistAssistantMessage(input: {
97
- identity: ChatTurnIdentity;
98
- finalText: string;
99
- }): Promise<void>;
100
- /** Optional post-processing (proposals, citations, credit metering …).
101
- * Errors are swallowed + logged — post-process must never fail a turn
102
- * that already streamed successfully. */
103
- onTurnComplete?(input: {
104
- identity: ChatTurnIdentity;
105
- finalText: string;
106
- }): Promise<void>;
107
- /** Optional per-event side channel (e.g. DO broadcast). Runs for every
108
- * emitted event, lifecycle envelope included. Errors swallowed — a
109
- * broadcast failure must not break the chat stream. */
110
- onEvent?(event: ChatStreamEvent): void | Promise<void>;
111
- /** Optional pre-persist transform of the final text (e.g. PII
112
- * redaction). Affects only what is persisted; the live stream is
113
- * never altered. */
114
- transformFinalText?(text: string): string | Promise<string>;
115
- /** Optional trace flush — resolves when OTLP export completes. Handed
116
- * to `waitUntil` so the worker isolate stays alive for the POST. */
117
- traceFlush?(): Promise<void>;
118
- }
119
- interface RunChatTurnInput {
120
- identity: ChatTurnIdentity;
121
- hooks: ChatTurnHooks;
122
- /** Worker liveness hook. When omitted, trace flush is awaited inline
123
- * before the stream closes. */
124
- waitUntil?: (p: Promise<unknown>) => void;
125
- /** Structured logger for swallowed hook errors. Defaults to
126
- * `console.error` so failures surface without product wiring. */
127
- log?: (message: string, meta?: Record<string, unknown>) => void;
128
- }
129
- interface ChatTurnResult {
130
- /** NDJSON body — return this as the platform `Response` body. */
131
- body: ReadableStream<Uint8Array>;
132
- /** Content type for the response. */
133
- contentType: 'application/x-ndjson';
134
- }
135
- /**
136
- * Run one chat turn. Returns immediately with a `ReadableStream` body;
137
- * the turn executes as the body is pulled. Never rejects — backend
138
- * failures surface as `error` + `session.run.failed` events.
139
- */
140
- declare function handleChatTurn(input: RunChatTurnInput): ChatTurnResult;
141
-
142
- /**
143
- * Derive a stable executionId from the run identity. The same
144
- * `(projectId, sessionId, turnIndex)` tuple yields the same id — so a
145
- * client retry of the same turn lands on the same substrate execution
146
- * and the orchestrator's buffer replays instead of starting a second
147
- * prompt.
148
- *
149
- * Format is readable, not hashed: operators grepping orchestrator logs
150
- * for `gtm-agent:thread-abc:3` find the run without translating an
151
- * opaque id. Substrate executionIds are not a secrecy boundary.
152
- *
153
- * Wire integration:
154
- * - Sandbox PromptOptions accepts `executionId` and `lastEventId`.
155
- * Products pass this id to make cross-process reconnect land on the
156
- * same substrate execution instead of spawning a duplicate run.
157
- */
158
- declare function deriveExecutionId(input: {
159
- projectId: string;
160
- sessionId: string;
161
- turnIndex: number;
162
- }): string;
163
-
164
- /**
165
- *
166
- * Error taxonomy for `@tangle-network/agent-runtime`.
167
- *
168
- * Public contract: every error this package throws as part of its consumer-
169
- * facing API either extends `AgentEvalError` (re-exported here for ergonomic
170
- * `instanceof` checks at the runtime boundary) or extends one of the
171
- * runtime-specific subclasses below.
172
- *
173
- * Internal invariant guards (`throw new Error('this should never happen')`)
174
- * remain plain `Error` — they are programmer-mistake assertions, not
175
- * consumer-catchable contract failures.
176
- *
177
- * Subclassing strategy: where a runtime-specific failure maps cleanly to an
178
- * agent-eval code (validation, config, not_found), we re-use the agent-eval
179
- * subclass. Runtime-only failure modes (session resume against the wrong
180
- * backend, backend transport errors) get fresh subclasses that still carry an
181
- * `AgentEvalErrorCode` so cross-package handlers can pattern-match without
182
- * importing the runtime.
183
- *
184
- * @stable
185
- */
186
-
187
- /**
188
- *
189
- * A backend transport call (HTTP, gRPC, sidecar IPC) failed with a non-success
190
- * status. Distinct from `JudgeError` (which is structural / unrecoverable)
191
- * because backend failures are sometimes retryable and consumers may want to
192
- * branch on the upstream status code.
193
- *
194
- * @stable
195
- */
196
- declare class BackendTransportError extends AgentEvalError {
197
- readonly backend: string;
198
- readonly status?: number;
199
- /**
200
- * Truncated upstream response body (≤2 KiB) when available. Diagnostic
201
- * only — surfaces in `backend_error.error.body` and `final.error.body`
202
- * so operators can see "free_tier_limit", "invalid_api_key", etc. without
203
- * cracking the log line open.
204
- */
205
- readonly body?: string;
206
- constructor(backend: string, message: string, options?: {
207
- cause?: unknown;
208
- status?: number;
209
- body?: string;
210
- });
211
- }
212
- /**
213
- *
214
- * A runtime-run lifecycle method was called in an order the state machine does
215
- * not allow: `persist()` before `complete()`, `complete()` twice, etc.
216
- *
217
- * @stable
218
- */
219
- declare class RuntimeRunStateError extends AgentEvalError {
220
- constructor(message: string, options?: {
221
- cause?: unknown;
222
- });
223
- }
224
- /**
225
- *
226
- * The dynamic-loop planner returned an unusable topology move — the LLM emitted
227
- * no parseable envelope, an unknown `kind`, or a structurally-invalid move
228
- * (e.g. a fanout with zero tasks). This is a structural failure of the
229
- * agent-authored topology, not a config mistake: the planner ran but its output
230
- * cannot drive the kernel. Carries `validation` so cross-package handlers can
231
- * pattern-match without importing the runtime. Fail loud — never substitute a
232
- * default move, or the loop silently runs a topology nobody chose.
233
- *
234
- * @stable
235
- */
236
- declare class PlannerError extends AgentEvalError {
237
- constructor(message: string, options?: {
238
- cause?: unknown;
239
- });
240
- }
241
-
242
- /**
243
- * Build-prompt starting points for the two buildable artifact types. There is
244
- * NO `toolGenerator`/`mcpGenerator` wrapper — the factory is `agenticGenerator`
245
- * + a verifier (docs/artifact-lifecycle-frontier.md), so a tool or an MCP
246
- * server is built by composing the pieces directly:
247
- *
248
- * // a tool:
249
- * agenticGenerator({ buildPrompt: toolBuildPrompt, verify: commandVerifier('pnpm', ['test']) })
250
- * // an MCP server:
251
- * agenticGenerator({ buildPrompt: mcpBuildPrompt, verify: mcpServeVerifier({ command: 'node', args: ['server.mjs'] }) })
252
- *
253
- * These are the only type-specific bit (the phrasing that points the agent at a
254
- * tool vs. an MCP); the worktree, resume-on-failure loop, and improvement-loop
255
- * wrapper are shared. MCP is the load-bearing target — it is how a harness
256
- * acquires tools; raw tools matter where we control the loader.
257
- */
258
-
259
- type FindingsArg = {
260
- report: unknown;
261
- findings: AnalystFinding[];
262
- };
263
- /** Render findings as the ranked-evidence block every build prompt ends with. */
264
- declare function findingLines(findings: AnalystFinding[]): string[];
265
- /** Build the starting instruction for a coder agent tasked with implementing a new tool. */
266
- declare function toolBuildPrompt(args: FindingsArg): string;
267
- /** Build the starting instruction for a coder agent tasked with implementing a new MCP server. */
268
- declare function mcpBuildPrompt(args: FindingsArg): string;
269
-
270
- /**
271
- * Campaign `spans.jsonl` → OTLP-flat JSONL — the missing converter between
272
- * what the substrate RECORDS and what its trace analysts READ.
273
- *
274
- * agent-eval's `runCampaign` durably records one `spans.jsonl` per cell
275
- * (`defaultBuildTraceWriter`): flat records
276
- * `{ name, cellId, startMs, durationMs?, ...attributes }` with no trace/span
277
- * ids. Its trace consumers (`OtlpFileTraceStore`, the trace-analyst registry,
278
- * `haloProposer`/`traceAnalystProposer` via `resolveTraces`) read OTLP-flat
279
- * JSONL (`trace_id`/`span_id`/ISO times/status/attributes — the shape
280
- * `projectOtlpFlatLine` parses). Nothing shipped converts between the two, so
281
- * the traces real optimization runs write could never reach the trace-native
282
- * proposers. This module is that wire adapter:
283
- *
284
- * - {@link campaignCellSpansToOtlp} — one cell's `spans.jsonl` content →
285
- * OTLP lines (a per-cell root AGENT anchor span + one child per record).
286
- * - {@link convertCampaignDirToOtlp} — walk any campaign run/generation dir
287
- * for `spans.jsonl` files and concatenate their OTLP lines.
288
- * - {@link campaignTraceResolver} — the `resolveTraces` implementation for
289
- * `traceAnalystProposer`/`haloProposer`: proposing generation g reads the
290
- * traces the loop just recorded (`gen-<g-1>`, or `baseline` for g = 0)
291
- * under the same `runDir` handed to `improve()`/`selfImprove()`.
292
- *
293
- * Trace identity: one trace per CELL, keyed on the cell's on-disk path — the
294
- * same sanitized `cellId` recurs across the baseline and every candidate
295
- * campaign, so folding the id alone would merge distinct runs into one trace.
296
- * Ids are deterministic FNV-1a folds to OTLP's 32/16-hex width, so re-converts
297
- * are stable and byte-identical.
298
- */
299
-
300
- interface CampaignOtlpOptions {
301
- /** OTLP `service.name` on every emitted span. Default `'campaign'`. */
302
- serviceName?: string;
303
- }
304
- /**
305
- * Convert ONE cell's `spans.jsonl` content to OTLP-flat JSONL lines.
306
- * `cellKey` is the identity the trace id folds from — pass the cell's on-disk
307
- * path (unique per campaign); `cellId` is the display/attribute label.
308
- * Returns `[]` for empty/recordless content (a dispatch that never touched
309
- * `ctx.trace`/`ctx.cost` writes an empty file — that is data, not an error).
310
- */
311
- declare function campaignCellSpansToOtlp(content: string, cell: {
312
- cellId: string;
313
- cellKey?: string;
314
- }, opts?: CampaignOtlpOptions): string[];
315
- /**
316
- * Walk `dir` (a campaign run dir, a generation dir, or a whole `selfImprove`
317
- * run root) for `spans.jsonl` files and return their concatenated OTLP-flat
318
- * JSONL — the exact string the `resolveTraces` contract expects. `''` when no
319
- * spans exist (the proposers fail loud on empty by design).
320
- */
321
- declare function convertCampaignDirToOtlp(dir: string, opts?: CampaignOtlpOptions): string;
322
- interface CampaignTraceResolverOptions extends CampaignOtlpOptions {
323
- /** The `selfImprove`/`improve()` run root — the SAME `runDir` the loop
324
- * records under (`<runDir>/baseline/...`, `<runDir>/gen-<g>/candidate-<i>/...`).
325
- * Must be a real path; a `mem://` run records nothing to resolve. */
326
- runDir: string;
327
- }
328
- /**
329
- * Build the `resolveTraces` function `traceAnalystProposer`/`haloProposer`
330
- * take: proposing generation g reads the traces of the campaigns the loop just
331
- * scored — `gen-<g-1>` (or `baseline` when g = 0), falling back to every trace
332
- * under the run root when that directory has none (e.g. a caller pointing at a
333
- * single campaign dir rather than a loop root).
334
- *
335
- * traceAnalystProposer({ ..., resolveTraces: campaignTraceResolver({ runDir }) })
336
- */
337
- declare function campaignTraceResolver(opts: CampaignTraceResolverOptions): (ctx: Pick<ProposeContext, 'generation'>) => string;
338
-
339
- /**
340
- * `driverLoopGenerator` — the driver→worker `CandidateGenerator`: the build
341
- * loop run by the ATOM instead of the canned respawn.
342
- *
343
- * `agenticGenerator` steers with three hardcoded conditions picking a canned
344
- * note (`EMPTY_TREE_NOTE` / `failureNote`) and respawns. This generator swaps
345
- * that respawn brain for a real driver: an LLM on the canonical tool-loop seam
346
- * (`runBrainLoop` + `ToolLoopChat` — the exact loop `driverAgent` runs its
347
- * brain on) that AUTHORS each worker instruction, OBSERVES what the session
348
- * actually produced (diff, files, verifier output), RATES it, and DECIDES
349
- * refine / re-scope / decompose — prompted with the senior scientific-method
350
- * doctrine (`buildDriverSystem`).
351
- *
352
- * The worker stays the proven primitive: `runLocalHarness` in the candidate
353
- * worktree, same as `agenticGenerator` — only the brain between sessions
354
- * changes. The worktree machinery (`worktreeBuildCandidate`) and verifiers
355
- * (`commandVerifier` / `mcpServeVerifier`) are reused verbatim.
356
- *
357
- * Completion-oracle invariant (the supervisor doctrine, kept): the driver's
358
- * prose NEVER decides the outcome. After the loop, code re-checks ground
359
- * truth — tree dirty, raw-trace evidence present, verifier green — and only
360
- * that decides `applied`. A driver that claims success over a failing verifier
361
- * produces a discarded candidate, not a shipped one.
362
- *
363
- * @experimental
364
- */
365
-
366
- interface DriverLoopGeneratorOptions {
367
- /** The driver-LLM seam — ONE inference turn over the conversation + tool specs (the canonical
368
- * `ToolLoopChat`, same seam as `driverAgent`): `routerBrain(cfg)` in production, a scripted
369
- * mock in tests. */
370
- brain: ToolLoopChat;
371
- /** Local coding harness the driver's worker sessions run in the worktree. Default `claude`. */
372
- harness?: LocalHarness;
373
- /** Per-worker-session wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */
374
- timeoutMs?: number;
375
- /** Build the driver's task briefing (domain framing + method + findings) — the same senior
376
- * prompt the worker path uses (`toolBuildPrompt` / `mcpBuildPrompt`). The driver reads it and
377
- * folds what each worker needs into its instruction. Default `defaultBuildPrompt`. */
378
- buildPrompt?: (args: {
379
- report: unknown;
380
- findings: AnalystFinding[];
381
- }) => string;
382
- /** Verify the worktree (the intrinsic check). Exposed to the driver as `run_verifier` AND
383
- * re-run by code as the final keep/discard gate. Omitted ⇒ the final gate is dirty-tree only
384
- * (legacy `agenticGenerator` behavior sans verifier). */
385
- verify?: Verifier;
386
- /** Max driver inference turns. Default `max(8, 2 + maxShots * 3)` — room for one
387
- * observe/rate/decide cycle per worker session plus orientation. */
388
- maxTurns?: number;
389
- /** The research seam (adopt-not-build): when set, the driver gets a
390
- * `research{query}` tool + the `researchDriverNote` doctrine, so it can
391
- * discover an EXISTING external MCP instead of building one. Wire a real
392
- * web/search backend here — none is provisioned by default (the build
393
- * harness has no live web access yet; flagged). */
394
- research?: (query: string) => Promise<string>;
395
- /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */
396
- runHarness?: typeof runLocalHarness;
397
- /** Test seam — inject the worktree diff reader (defaults to `git diff` in the worktree). */
398
- readDiff?: (worktreePath: string) => string;
399
- /** Test seam — inject the changed-paths reader (defaults to `git status --porcelain`). */
400
- changedPaths?: (worktreePath: string) => string[];
401
- }
402
- /** Driver→worker `CandidateGenerator`: an LLM driver on the canonical tool-loop authors, observes, rates, and steers coding-harness sessions in the worktree until the verifier passes or the session budget is spent. */
403
- declare function driverLoopGenerator(opts: DriverLoopGeneratorOptions): CandidateGenerator;
404
-
405
- /**
406
- * Typed-findings accessor — the one place `unknown[]` findings become
407
- * `AnalystFinding[]`.
408
- *
409
- * agent-eval's `ProposeContext.findings` is `TFindings[] = unknown[]` on the
410
- * wire: the loop threads whatever the previous `analyzeGeneration` producer (or
411
- * the caller's static seed) returned. Consumers that need the typed envelope
412
- * (`claim`/`severity`/`recommended_action`) were down-casting with a bare
413
- * `as AnalystFinding[]` — a lie at runtime whenever the seed was a raw string
414
- * or an ad-hoc digest, which then rendered `undefined` into build prompts.
415
- *
416
- * `toAnalystFindings` replaces that cast: real findings pass through
417
- * unchanged (structural guard, fail-closed), and non-conforming values are
418
- * LIFTED into a real `AnalystFinding` envelope via `makeFinding` — the most
419
- * actionable text becomes the claim, the original value rides in `metadata.raw`
420
- * — so everything downstream of the accessor handles exactly one shape.
421
- */
422
-
423
- /** Analyst id stamped on findings lifted from untyped seed values. */
424
- declare const LIFTED_FINDING_ANALYST_ID = "lifted-seed";
425
- /** Structural guard for the schema-versioned `AnalystFinding` envelope.
426
- * Strict on the identity fields `makeFinding` always populates — a partial
427
- * look-alike is lifted (re-enveloped), not trusted. */
428
- declare function isAnalystFinding(value: unknown): value is AnalystFinding;
429
- interface ToAnalystFindingsOptions {
430
- /** `analyst_id` stamped on lifted (non-conforming) values.
431
- * Default {@link LIFTED_FINDING_ANALYST_ID}. */
432
- analystId?: string;
433
- /** `area` stamped on lifted values. Default `'seed'`. */
434
- area?: string;
435
- }
436
- /**
437
- * Normalize a mixed `unknown[]` findings array to `AnalystFinding[]`:
438
- * conforming findings pass through by reference; strings and finding-ish
439
- * objects are lifted into envelopes (claim = most actionable text, original
440
- * value under `metadata.raw`); values with no extractable text are dropped.
441
- * Never throws — a malformed seed must not kill a proposal round.
442
- */
443
- declare function toAnalystFindings(findings: readonly unknown[], opts?: ToAnalystFindingsOptions): AnalystFinding[];
444
-
445
- /**
446
- * `mcpServeVerifier` — the intrinsic verifier for a built MCP server: the
447
- * boot-and-probe checker named in docs/artifact-lifecycle-frontier.md. A
448
- * generated MCP server is only a candidate if it actually *serves* — so this
449
- * boots it over stdio (the default local MCP transport) and runs the real
450
- * handshake: `initialize` → `notifications/initialized` → `tools/list`, and
451
- * asserts the server answers with at least `minTools` tools.
452
- *
453
- * The spawn + handshake is the SHARED same-host stdio connection
454
- * (`connectStdioMcp`) — the same code path that later serves the built server
455
- * LIVE to a scored run (`materializeLocalMcp`), so "verified it serves" and
456
- * "served while scored" can never drift apart.
457
- *
458
- * Outcomes follow the `Verifier` contract: a server that fails to start, exits
459
- * early, errors the handshake, times out, or exposes no tools is a FAILED
460
- * candidate (`{ok:false}`, fed back into the next generation shot); a missing
461
- * start binary or spawn fault THROWS (a setup bug, never a silent fallback).
462
- */
463
-
464
- interface McpServeSpec {
465
- /** Command that starts the built MCP server in the worktree (stdio transport). */
466
- command: string;
467
- args?: string[];
468
- /** Extra env for the server process (merged over `process.env`). */
469
- env?: Record<string, string>;
470
- /** Handshake timeout (ms). Default 30s. */
471
- timeoutMs?: number;
472
- /** Minimum tools the server must expose to pass. Default 1. */
473
- minTools?: number;
474
- }
475
- /** Build a `Verifier` that boots a generated MCP server over stdio and checks it exposes tools. */
476
- declare function mcpServeVerifier(spec: McpServeSpec): Verifier;
477
-
478
- /**
479
- * The senior scientific-method optimizer doctrine — the ONE substantial prompt
480
- * core shared by every builder/author surface (tool build, MCP build, codebase
481
- * improvement, strategy authoring) and by the driver that steers build workers
482
- * (`driverLoopGenerator`).
483
- *
484
- * Seeded from the proven senior prompts rather than invented: GEPA's
485
- * `REFLECTION_SYSTEM` (localize → diagnose → minimal generalizable fix →
486
- * preserve what works), the /evolve loop (one hypothesis with a mechanism and a
487
- * falsifiable prediction; attack the largest measured gap first), /pursue (one
488
- * coherent change set, no partial scaffolding), and the self-improving-loop /
489
- * supervisor doctrine (a keep is decided by a real check, never by the author;
490
- * observe → rate → decide). Generalized from "mutate a prompt string" to
491
- * "build a code surface a held-out measurement will grade".
492
- */
493
- /**
494
- * The shared method block every build/author prompt embeds. Domain framing
495
- * (what a tool/MCP/codebase-edit deliverable looks like) wraps around it; this
496
- * is the process itself.
497
- */
498
- declare const optimizerMethod: string;
499
- /**
500
- * The driver's stance for `driverLoopGenerator` — the build-domain instance of
501
- * the supervisor doctrine (observe → rate → decide; refine / re-scope /
502
- * decompose; the check decides delivery, never the driver's prose).
503
- */
504
- declare const buildDriverSystem: string;
505
- /**
506
- * The driver's ADOPT-not-build doctrine, appended to `buildDriverSystem` when
507
- * a `research` tool is wired into the loop (`DriverLoopGeneratorOptions.
508
- * research`). Kept separate so a driver WITHOUT the tool is never told to
509
- * call a tool it does not have.
510
- */
511
- declare const researchDriverNote: string;
512
- /**
513
- * The senior authoring process for `authorStrategy` — the same method, shaped
514
- * to the strategy contract (author-blind, conserved budget, one module out).
515
- */
516
- declare const strategyAuthorMethod: string;
517
-
518
- type ProfileDiffProposerContext<TFindings = unknown> = ProposeContext<TFindings> & {
519
- profile: AgentProfile;
520
- };
521
- interface ProfileDiffProposerOptions<TFindings = unknown> {
522
- proposeDiffs(context: ProfileDiffProposerContext<TFindings>): Promise<readonly AgentProfileDiff[]> | readonly AgentProfileDiff[];
523
- }
524
- /**
525
- * Turn exact AgentProfileDiffs from any source into full profile candidates for
526
- * the shared optimization loop. Research, catalogs, humans, and trace miners
527
- * differ only in `proposeDiffs`; measurement and promotion stay identical.
528
- */
529
- declare function profileDiffProposer<TFindings = unknown>(options: ProfileDiffProposerOptions<TFindings>): SurfaceProposer<TFindings>;
530
-
531
- /**
532
- *
533
- * `rawTraceDistiller` — the meta-harness `analyzeGeneration` producer.
534
- *
535
- * The default `generationFailureDistiller` (in `improve.ts`) COMPRESSES each
536
- * generation's failing cells into ~1500-char structured findings before the next
537
- * proposal round. That is the ACE-style recipe: a small summary is the proposer's
538
- * whole view of what went wrong. This producer does the opposite — the
539
- * meta-harness recipe (yoonholee.com/meta-harness): it does NOT summarize. It
540
- * points the coding-agent proposer at the generation's RAW run traces already on
541
- * disk under `runDir` — the durable per-cell `spans.jsonl` event logs,
542
- * `cached-result.json` scores, and any artifacts the substrate persisted — and
543
- * instructs the agent to `grep`/`cat`/`ls` them to diagnose the failures itself
544
- * (up to the harness's full context, ~millions of tokens, vs a ~1500-char digest).
545
- *
546
- * It emits `AnalystFinding[]` so it drops into the SAME `opts.analyzeGeneration`
547
- * slot the default distiller uses, and renders through the same
548
- * `agenticGenerator` prompt path (`claim` + `recommended_action`). The findings
549
- * carry ABSOLUTE paths — the coding harness runs with `cwd` = a candidate
550
- * worktree, so a relative `runDir` would be uncattable from there.
551
- *
552
- * Runtime layout it reads (written by agent-eval's optimization loop):
553
- *
554
- * <runDir>/gen-<N>/ ← the generation dir (input.runDir)
555
- * candidate-<i>/ ← one candidate campaign (campaign.runDir)
556
- * <sanitized cellId>/ ← one scenario×rep cell
557
- * spans.jsonl ← the raw trace (event/span log)
558
- * cached-result.json ← the cell's score + artifact ref
559
- * <artifacts…> ← whatever the dispatch wrote
560
- *
561
- * @experimental
562
- */
563
-
564
- interface RawTraceDistillerOptions {
565
- /** Anchor the emitted paths at this run root instead of the generation `runDir`
566
- * the loop passes in. Normally unset — each call points at that generation's
567
- * own directory (`input.runDir`). Pass an absolute path when you construct the
568
- * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */
569
- runDir?: string;
570
- /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */
571
- maxCandidates?: number;
572
- /** Max failing cells to enumerate per candidate before collapsing the rest into
573
- * an "ls the candidate dir" pointer. Default 8. */
574
- maxCellsPerCandidate?: number;
575
- /** Max concrete file paths to list per cell (the agent can always `ls` the dir
576
- * for the rest). Default 24. */
577
- maxFilesPerCell?: number;
578
- /** Findings to fall back to when the generation had NO failing cells, so a
579
- * clean round never wipes the proposer's steering context. Mirrors the default
580
- * distiller's static-seed fallback. Default: a single instruction finding. */
581
- fallbackFindings?: unknown[];
582
- }
583
- /**
584
- * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE
585
- * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a
586
- * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.
587
- *
588
- * Drop-in for `opts.analyzeGeneration` on `improve()` / `selfImprove()`:
589
- *
590
- * await improve(profile, seedFindings, {
591
- * surface: 'code',
592
- * code: { repoRoot },
593
- * runDir: '/abs/run', // MUST be a real path — the traces live here
594
- * analyzeGeneration: rawTraceDistiller(),
595
- * scenarios, judge, agent,
596
- * })
597
- */
598
- declare function rawTraceDistiller<TScenario extends Scenario = Scenario, TArtifact = unknown>(options?: RawTraceDistillerOptions): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']>;
599
-
600
- /**
601
- *
602
- * `reflectiveGenerator` — the cheap, no-sandbox `CandidateGenerator`. It drafts
603
- * surface edits via the existing improvement proposer (`proposeFromFindings`,
604
- * one LLM patch per finding) and applies them as ONE coherent improvement into
605
- * the candidate worktree. `maxShots` is ignored — reflection is single-shot by
606
- * construction (the patches are already drafted).
607
- *
608
- * This is the `shots=1, sandbox=off` setting of the one improvement driver.
609
- * The `agenticGenerator` (a multi-shot verify-in-session loop) is the
610
- * `shots=N` setting — both plug into the same `improvementDriver`.
611
- *
612
- * @experimental
613
- */
614
-
615
- interface ReflectiveGeneratorOptions {
616
- improvementProposalSource: ImprovementProposalSource<SurfaceImprovementEdit>;
617
- }
618
- /** Cheap no-sandbox `CandidateGenerator` (the `shots=1` setting): draft surface edits via the improvement adapter and apply them as one coherent candidate. */
619
- declare function reflectiveGenerator(opts: ReflectiveGeneratorOptions): CandidateGenerator;
620
-
621
- /**
622
- * `rolloutPolicyProposer` — the `'rollout-policy'` surface for `improve()`: the
623
- * inference-time `StructuralRolloutPolicy` dials { k, repairRounds, testgen } as a
624
- * held-out-gated optimizable surface.
625
- *
626
- * Why this seam: agent-eval's loop contract is already generic — `MutableSurface`
627
- * admits any string, documented as "serialized tool config" — so the policy rides
628
- * the SAME serialize→propose→gate→parse-back cycle the tools/mcp/hooks surfaces
629
- * use. No agent-eval changes; the only net-new piece is this proposer.
630
- *
631
- * Why deterministic: prompt-wording proposals are a measured zero on this stack,
632
- * and the policy space is tiny and fully enumerable. The proposer emits bounded
633
- * single-dial neighbors (k±2 in [1,10], repairRounds±1 in [0,3], testgen±3 in
634
- * [0,10], ≤4 per generation) and lets the held-out gate do ALL the deciding — an
635
- * LLM proposer would add cost and nondeterminism with nothing to reason about.
636
- *
637
- * Persistence: the policy lives in `profile.extensions['structural-rollout']`
638
- * (AgentProfile's designed slot for runtime-specific config). A gated winner is
639
- * written back there by `improve()`, the same profile-field write-back every other
640
- * config surface gets; `structuralRolloutPolicyFromProfile` is the read side a
641
- * runtime caller feeds to `structuralRollout({ policy })`.
642
- *
643
- * @experimental
644
- */
645
-
646
- /** The profile extensions namespace the policy persists under. */
647
- declare const ROLLOUT_POLICY_EXTENSION = "structural-rollout";
648
- /** Proposal bounds per dial. These are the SEARCH bounds (what the proposer may
649
- * explore), chosen so every reachable value is a measured-sane recipe: k=1 is the
650
- * low-compute preset, testgen=0 disables check authoring, repairRounds caps where
651
- * the measured increment flattens (+1–3pp beyond round 2). */
652
- declare const ROLLOUT_POLICY_BOUNDS: {
653
- readonly k: {
654
- readonly min: 1;
655
- readonly max: 10;
656
- readonly step: 2;
657
- };
658
- readonly repairRounds: {
659
- readonly min: 0;
660
- readonly max: 3;
661
- readonly step: 1;
662
- };
663
- readonly testgen: {
664
- readonly min: 0;
665
- readonly max: 10;
666
- readonly step: 3;
667
- };
668
- };
669
- /** Parse a serialized policy surface. Defensive by design — the proposer reads
670
- * `ctx.currentSurface`, which the loop types as `string | CodeSurface`. Returns
671
- * `undefined` (never throws) for non-strings, malformed JSON, or a shape that
672
- * violates the policy's own invariants: the no-op signal. Unknown dials are
673
- * dropped; `diverse`/`temperature` ride through untouched (the proposer never
674
- * mutates them — `diverse` is a measured paired null). */
675
- declare function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined;
676
- /** Normalize an untyped policy bag (a parsed surface or a profile extension) into
677
- * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any
678
- * present dial violates the policy invariants (mirrors `resolvePolicy`: integer
679
- * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as "not
680
- * configured", never as a fabricated recipe. */
681
- declare function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined;
682
- /** Stable serialization — dial order is fixed so identical policies produce
683
- * identical surfaces (the loop dedupes/hashes candidates by surface content). */
684
- declare function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string;
685
- /** Read the persisted policy off the profile. `undefined` when the profile does
686
- * not opt into structural rollout — the improve() surface no-ops then, because
687
- * tuning dials nothing consumes would ship dead config. */
688
- declare function structuralRolloutPolicyFromProfile(profile: AgentProfile): StructuralRolloutPolicy | undefined;
689
- /** Persist a policy into the profile's extensions namespace. Shallow copy; never
690
- * mutates the input profile (the applyWinnerToProfile contract). */
691
- declare function applyRolloutPolicyToProfile(profile: AgentProfile, policy: StructuralRolloutPolicy): AgentProfile;
692
- /** All bounded single-dial neighbors of `policy`, in a fixed priority order: k
693
- * first (selection breadth carries 85–92% of the measured effect), then
694
- * repairRounds, then testgen. Steps clamp to the dial's bounds; clamped-to-no-op
695
- * and duplicate policies are dropped. */
696
- declare function enumerateNeighborPolicies(policy: StructuralRolloutPolicy): StructuralRolloutPolicy[];
697
- /**
698
- * The deterministic `SurfaceProposer` for the `'rollout-policy'` surface.
699
- *
700
- * Each generation: parse the current policy surface, enumerate its bounded
701
- * single-dial neighbors, and return at most `min(populationSize, 4)` of them,
702
- * rotating the enumeration window by generation so successive generations explore
703
- * different neighbors when nothing promoted. Proposes NOTHING when the surface
704
- * carries no policy (the profile never opted in) — an empty proposal is the
705
- * loop-native no-op, mirroring `improvementDriver`'s no-findings behavior.
706
- */
707
- declare function rolloutPolicyProposer(): SurfaceProposer;
708
-
709
- /**
710
- *
711
- * Chat-model resolution + catalog validation — the shared primitive every
712
- * product chat handler needs and was, until now, hand-rolling. Lifts the
713
- * router `/v1/models` fetch, the fail-closed id validation, and the
714
- * precedence resolver out of four near-identical per-repo copies.
715
- *
716
- * Policy-free by design: callers pass their own precedence order
717
- * (`resolveChatModel`) and their own known-good `allowlist`
718
- * (`validateChatModelId`), so each product keeps its resolution policy while
719
- * sharing the catalog fetch, the malformed-id guard, and the fail-closed
720
- * admission rule. No React, no `process.env` assumption — `env` is an
721
- * explicit narrow record so this runs unchanged in Node and in Workers.
722
- *
723
- * @stable
724
- */
725
- /**
726
- * A model entry as returned by the Tangle Router `/v1/models` endpoint.
727
- * Intentionally minimal — only the fields resolution + validation read.
728
- */
729
- interface ModelInfo {
730
- id: string;
731
- name?: string;
732
- description?: string;
733
- /** Provider slug, when the router exposes it (`provider` or `_provider`). */
734
- provider?: string;
735
- _provider?: string;
736
- architecture?: {
737
- modality?: string;
738
- input_modalities?: string[];
739
- output_modalities?: string[];
740
- };
741
- }
742
- /** Env keys the router base URL is resolved from. */
743
- interface RouterEnv {
744
- TANGLE_ROUTER_URL?: string;
745
- TANGLE_ROUTER_BASE_URL?: string;
746
- }
747
- /** Default Tangle Router base URL used when no env override is set. */
748
- declare const DEFAULT_ROUTER_BASE_URL = "https://router.tangle.tools";
749
- /** Resolve the router base URL from env, normalised — no trailing `/v1` or `/`. */
750
- declare function resolveRouterBaseUrl(env?: RouterEnv): string;
751
- /**
752
- * Fetch the model catalog from the router's `/v1/models`. Throws on a non-2xx
753
- * response — callers decide whether to fail open (empty catalog) or closed.
754
- */
755
- declare function getModels(routerBaseUrl?: string): Promise<ModelInfo[]>;
756
- /** Trim a candidate model id; `undefined` for non-strings and blanks. */
757
- declare function cleanModelId(value: unknown): string | undefined;
758
- interface ChatModelCandidate {
759
- /** Stable label for telemetry — e.g. `request`, `workspace`, `env`. */
760
- source: string;
761
- model: string | undefined;
762
- }
763
- interface ResolvedChatModel {
764
- source: string;
765
- model: string;
766
- }
767
- /**
768
- * Resolve a chat model by precedence: the first candidate carrying a
769
- * non-blank model wins, else `fallback`. The caller owns the precedence
770
- * order, so each product keeps its own policy (request → workspace → env,
771
- * etc.) while the first-non-blank logic and the telemetry shape stay shared.
772
- */
773
- declare function resolveChatModel(candidates: ChatModelCandidate[], fallback: ResolvedChatModel): ResolvedChatModel;
774
- type ChatModelValidation = {
775
- succeeded: true;
776
- value: string;
777
- } | {
778
- succeeded: false;
779
- error: string;
780
- };
781
- /**
782
- * Validate a caller-supplied chat-model id. Rejects non-strings, malformed
783
- * ids, and ids absent from both the caller's `allowlist` and the live router
784
- * catalog. Fails closed: when the catalog cannot be fetched, an unverifiable
785
- * id is rejected rather than admitted — a bad model never reaches the agent.
786
- */
787
- declare function validateChatModelId(modelId: unknown, options?: {
788
- /**
789
- * Known-good ids that skip the catalog round trip — e.g. the product's
790
- * default model plus any env-configured ids.
791
- */
792
- allowlist?: string[];
793
- routerBaseUrl?: string;
794
- /** Injectable catalog loader — overridden in tests. */
795
- loadModels?: (routerBaseUrl: string) => Promise<ModelInfo[]>;
796
- }): Promise<ChatModelValidation>;
797
-
798
- /**
799
- *
800
- * Pure readiness-decision helper. Maps a `KnowledgeReadinessReport` from
801
- * `@tangle-network/agent-eval` to a three-state branch (`ready` / `blocked` /
802
- * `caveat`) the runtime, route handlers, and UI shells can all switch on.
803
- *
804
- * Default `minimumScore` of 0.7 mirrors the readiness scoring scale in
805
- * agent-eval; callers tightening or loosening this should keep it consistent
806
- * across all entry points for the same product so the UI / metrics agree on
807
- * what "caveat" means.
808
- *
809
- * @stable
810
- */
811
-
812
- /**
813
- * Map a `KnowledgeReadinessReport` to a three-state branch (`ready` / `blocked` / `caveat`) the runtime, route handlers, and UI shells all switch on.
814
- *
815
- * @stable
816
- */
817
- declare function decideKnowledgeReadiness(report: KnowledgeReadinessReport, options?: {
818
- minimumScore?: number;
819
- }): KnowledgeReadinessDecision;
820
-
821
- /**
822
- * The product-facing backend selector for `runChatThroughRuntime` /
823
- * `runAgentTaskStream`: one call turns a `--backend {router,tcloud,cli-bridge,
824
- * sandbox}` choice into the `AgentExecutionBackend` the chat leg runs on.
825
- *
826
- * It is the `AgentExecutionBackend` sibling of `resolveSandboxClient` (which
827
- * resolves the `SandboxClient` a `runAgentRounds` drives). Both exist for the same
828
- * reason: every in-process eval product hand-rolled the identical
829
- * "`backend-name` → `createOpenAICompatibleBackend`" branch, and the copies
830
- * drift. This is the single generic resolver they share.
831
- *
832
- * - `router` / `tcloud` / `cli-bridge` → OpenAI-compatible chat completions.
833
- * All three speak `POST {baseUrl}/chat/completions` in OpenAI's SSE shape —
834
- * the router (a.k.a. tcloud) IS that endpoint, and cli-bridge fronts a
835
- * harness CLI behind the same protocol at its own `/v1`. They differ only
836
- * in `baseUrl` / `apiKey` and the `kind` label a product wants on its
837
- * traces. cli-bridge REQUIRES `model` in the request body, so it MUST route
838
- * through `createOpenAICompatibleBackend` (which sends it), never a
839
- * transport that drops the field.
840
- * - `sandbox` → the caller's own domain backend. The sandbox variant carries
841
- * product specifics (system prompt, workspace id, in-box D1 executor) that
842
- * do NOT belong in the substrate, so the product passes a `sandboxBackend()`
843
- * seam that this resolver simply invokes.
844
- *
845
- * This resolver is PURE backend selection. Product concerns — credit hard-cuts,
846
- * fetch-capture shims, D1 platform wiring — stay as product-side WRAPPERS
847
- * around the returned backend. The OpenAI-compat passthrough fields (`tools`,
848
- * `toolChoice`, `responseFormat`, `temperature`, `maxTokens`, `fetchImpl`,
849
- * `retry`) are forwarded verbatim so a product can advertise its app tools,
850
- * preserve generation settings, or install a capturing fetch without
851
- * re-opening the branch this consolidation closes.
852
- */
853
-
854
- /** The transport a chat backend runs on. */
855
- type AgentBackendKind = 'router' | 'tcloud' | 'cli-bridge' | 'sandbox';
856
- /**
857
- * OpenAI-compat passthrough forwarded to `createOpenAICompatibleBackend` for
858
- * the `router` / `tcloud` / `cli-bridge` kinds. Mirrors that factory's optional
859
- * inputs so a product keeps its tool advertising / capture-fetch without
860
- * re-implementing the backend branch.
861
- */
862
- type OpenAICompatPassthrough = Pick<Parameters<typeof createOpenAICompatibleBackend>[0], 'tools' | 'toolChoice' | 'responseFormat' | 'temperature' | 'maxTokens' | 'fetchImpl' | 'retry'>;
863
- interface ResolveAgentBackendOptions<TInput extends AgentBackendInput = AgentBackendInput> extends OpenAICompatPassthrough {
864
- /** The chat transport to resolve. */
865
- kind: AgentBackendKind;
866
- /**
867
- * Bearer credential for the OpenAI-compat kinds. Empty string is valid for a
868
- * loopback-anonymous cli-bridge; a `router`/`tcloud` route with an empty key
869
- * is a caller bug the product surfaces before calling in.
870
- */
871
- apiKey: string;
872
- /** Base URL for the OpenAI-compat kinds. cli-bridge's is its `/v1`. */
873
- baseUrl: string;
874
- /** Model id sent on every request. cli-bridge rejects a request without it. */
875
- model: string;
876
- /** `kind` label stamped on the resolved backend + its traces. Defaults to `kind`. */
877
- label?: string;
878
- /**
879
- * `sandbox` kind: the product's own domain backend. Required for that kind —
880
- * the substrate owns no product sandbox shape, so a `sandbox` resolution with
881
- * no seam is a caller bug, not a silent fallback.
882
- */
883
- sandboxBackend?: () => AgentExecutionBackend<TInput>;
884
- }
885
- /**
886
- * Resolve the `AgentExecutionBackend` for the chosen `kind`. Reuse this instead
887
- * of hand-rolling the `createOpenAICompatibleBackend` branch in each product.
888
- */
889
- declare function resolveAgentBackend<TInput extends AgentBackendInput = AgentBackendInput>(opts: ResolveAgentBackendOptions<TInput>): AgentExecutionBackend<TInput>;
890
-
891
- /**
892
- *
893
- * The two top-level entry points:
894
- *
895
- * - `runAgentTask` — single-shot lifecycle for adapter-driven tasks.
896
- * - `runAgentTaskStream` — streaming lifecycle that delegates execution to an
897
- * `AgentExecutionBackend` (model API, sandbox, or custom iterable).
898
- *
899
- * Both gate the run on `KnowledgeReadinessReport` from `agent-eval`, emit the
900
- * same lifecycle event vocabulary (under different shapes — see `types.ts`),
901
- * and route session lifecycle through a pluggable `RuntimeSessionStore`.
902
- *
903
- * @stable
904
- */
905
-
906
- /** Stamp cross-cutting defaults onto adapter-projected RunRecords without
907
- * overriding anything the adapter set explicitly:
908
- * - `scenarioId` — the run's scenario, when the record omits one.
909
- * - `failureClass` — the control layer's failure classification promoted
910
- * onto the canonical cross-agent key, but ONLY when it's a real taxonomy
911
- * class. This is what lets the substrate aggregate failures across every
912
- * agent in one vocabulary instead of per-agent ad-hoc strings. */
913
- declare function applyRunRecordDefaults(records: RunRecord[], scenarioId: string, controlFailureClass: string | undefined): RunRecord[];
914
-
915
- /**
916
- * Single-shot task lifecycle for adapter-driven tasks: readiness-gated, emits the runtime lifecycle event vocabulary, session-store pluggable.
917
- *
918
- * @stable
919
- */
920
- declare function runAgentTask<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult>(options: RunAgentTaskOptions<TState, TAction, TActionResult, TEval>): Promise<AgentTaskRunResult<TState, TAction, TActionResult, TEval>>;
921
- /**
922
- * Streaming task lifecycle: delegates execution to an `AgentExecutionBackend` (model API, sandbox, or custom iterable) and yields lifecycle events as they happen.
923
- *
924
- * @stable
925
- */
926
- declare function runAgentTaskStream<TInput extends AgentBackendInput = AgentBackendInput>(options: RunAgentTaskStreamOptions<TInput>): AsyncIterable<RuntimeStreamEvent>;
927
-
928
- /**
929
- *
930
- * Session helpers + an in-memory `RuntimeSessionStore` implementation suitable
931
- * for tests, scratch processes, and per-request scratch storage in serverless
932
- * runtimes. Durable stores (D1, postgres, Durable Objects) implement the same
933
- * interface from `./types`.
934
- *
935
- * @stable
936
- */
937
-
938
- /** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */
939
- declare class InMemoryRuntimeSessionStore implements RuntimeSessionStore {
940
- private readonly sessions;
941
- private readonly events;
942
- get(sessionId: string): RuntimeSession | undefined;
943
- put(session: RuntimeSession): void;
944
- appendEvent(sessionId: string, event: RuntimeStreamEvent): void;
945
- listEvents(sessionId: string): RuntimeStreamEvent[];
946
- }
947
-
948
- /**
949
- *
950
- * Server-Sent Events serialization for runtime telemetry streams.
951
- *
952
- * Newline-safe by construction: any newline in `id` or `event` is collapsed to
953
- * a space (browsers terminate fields on newline), and multi-line `data`
954
- * payloads are split into one `data:` line per source line so JSON.stringify
955
- * output transports cleanly.
956
- *
957
- * @stable
958
- */
959
-
960
- /** @stable */
961
- interface ServerSentEventOptions {
962
- event?: string;
963
- id?: string;
964
- retry?: number;
965
- }
966
- /** Serialize a `KnowledgeReadinessReport` as a Server-Sent Event string. @stable */
967
- declare function readinessServerSentEvent(report: KnowledgeReadinessReport, options?: RuntimeTelemetryOptions & ServerSentEventOptions): string;
968
- /** Serialize a `RuntimeStreamEvent` as a Server-Sent Event string. @stable */
969
- declare function runtimeStreamServerSentEvent(event: RuntimeStreamEvent, options?: RuntimeTelemetryOptions & ServerSentEventOptions): string;
970
-
971
- /**
972
- * Bounded turn-level tool-dispatch loop.
973
- *
974
- * `runAgentTaskStream` runs ONE model turn; `runAgentRounds` orchestrates DELEGATED
975
- * multi-agent topologies (refine / fanout-vote). Neither is the everyday
976
- * interactive shape: a chat turn where the model may emit tool calls, each is
977
- * executed, the results are folded back, and the turn re-runs until the model
978
- * stops (or a turn cap). Every agent app hand-rolls that loop — this is it,
979
- * as a reusable primitive.
980
- *
981
- * Substrate-neutral by design: the caller supplies `streamTurn` (wrapping
982
- * whatever backend / `runAgentTaskStream` it uses) and `executeToolCall`
983
- * (routing to its executors). This module owns the LOOP; the caller owns the
984
- * model and the executors. `Raw` (streaming variant) is the caller's own
985
- * event type. The only imported contract is the runtime hook type: hooks are
986
- * execution-scoped observers, not part of the agent profile.
987
- */
988
-
989
- interface ToolLoopCall {
990
- toolCallId?: string;
991
- toolName: string;
992
- args: Record<string, unknown>;
993
- }
994
- /** Outcome of one tool dispatch — structurally compatible with a hub/integration
995
- * tool-outcome union, so callers can fold either through the loop. */
996
- type ToolCallOutcome = {
997
- ok: true;
998
- result: unknown;
999
- } | {
1000
- ok: false;
1001
- code: string;
1002
- message: string;
1003
- status?: number;
1004
- };
1005
- /** One OpenAI-shaped tool-call entry carried on an assistant message. */
1006
- interface ToolLoopAssistantToolCall {
1007
- id: string;
1008
- type: 'function';
1009
- function: {
1010
- name: string;
1011
- arguments: string;
1012
- };
1013
- }
1014
- /**
1015
- * A message in the running conversation the loop sends to `streamTurn`.
1016
- *
1017
- * The base `{ role, content }` covers `system` / `user` / plain `assistant`
1018
- * turns. Two optional fields carry the OpenAI function-calling contract so a
1019
- * strict model (Claude, and any OpenAI-compatible provider that validates tool
1020
- * history) reads its own tool use back instead of re-issuing the same call:
1021
- *
1022
- * - an assistant turn that emitted tool calls carries `tool_calls`, and its
1023
- * `content` is `null` when the turn was tool-only;
1024
- * - each tool result is its own `{ role: 'tool', tool_call_id, content }`
1025
- * message keyed to the call that produced it.
1026
- *
1027
- * Widening is additive: a `streamTurn` that reads only `role` + `content` still
1028
- * works; one that forwards the whole message to an OpenAI-compatible endpoint
1029
- * now sends correct tool history.
1030
- */
1031
- type ToolLoopMessage = {
1032
- role: string;
1033
- content: string | null;
1034
- tool_calls?: ToolLoopAssistantToolCall[];
1035
- tool_call_id?: string;
1036
- };
1037
- type ToolLoopEvent = {
1038
- type: 'text';
1039
- text: string;
1040
- } | {
1041
- type: 'tool_call';
1042
- call: ToolLoopCall;
1043
- } | {
1044
- type: 'other';
1045
- event: unknown;
1046
- };
1047
- /** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =
1048
- * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the
1049
- * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs
1050
- * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /
1051
- * resource outcomes — eval scoring must distinguish them from capability failure. */
1052
- type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget';
1053
- interface ToolLoopResult {
1054
- finalText: string;
1055
- toolResults: Array<{
1056
- call: ToolLoopCall;
1057
- label: string;
1058
- outcome: ToolCallOutcome;
1059
- }>;
1060
- turns: number;
1061
- stopReason: ToolLoopStopReason;
1062
- /** @deprecated Use `stopReason !== 'completed'` instead. */
1063
- cappedOut: boolean;
1064
- }
1065
- interface RunToolLoopOptions {
1066
- systemPrompt: string;
1067
- userMessage: string;
1068
- priorMessages?: ToolLoopMessage[];
1069
- streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>;
1070
- executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
1071
- isExecutableTool: (toolName: string) => boolean;
1072
- /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.
1073
- * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */
1074
- maxToolTurns?: number;
1075
- /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the
1076
- * loop stops with stopReason `deadline`. */
1077
- deadlineMs?: number;
1078
- /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
1079
- maxCostUsd?: number;
1080
- /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
1081
- costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
1082
- renderResult?: (label: string, outcome: ToolCallOutcome) => string;
1083
- labelFor?: (call: ToolLoopCall) => string;
1084
- runId?: string;
1085
- scenarioId?: string;
1086
- hooks?: RuntimeHooks;
1087
- }
1088
- /** Run the bounded tool loop and return the final text + every executed tool
1089
- * outcome. Awaitable — callers needing to stream events to a UI use
1090
- * {@link streamToolLoop}. */
1091
- declare function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult>;
1092
- type StreamToolLoopYield<Raw> = {
1093
- kind: 'event';
1094
- event: Raw;
1095
- } | {
1096
- kind: 'tool_result';
1097
- toolName: string;
1098
- toolCallId?: string;
1099
- label: string;
1100
- outcome: ToolCallOutcome;
1101
- } | {
1102
- kind: 'capped';
1103
- pending: number;
1104
- stopReason: Exclude<ToolLoopStopReason, 'completed'>;
1105
- };
1106
- interface StreamToolLoopOptions<Raw> {
1107
- systemPrompt: string;
1108
- userMessage: string;
1109
- priorMessages?: ToolLoopMessage[];
1110
- streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>;
1111
- extractText: (event: Raw) => string;
1112
- extractToolCall: (event: Raw) => ToolLoopCall | null;
1113
- isExecutableTool: (toolName: string) => boolean;
1114
- executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
1115
- /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */
1116
- maxToolTurns?: number;
1117
- /** Wall-clock deadline in ms since epoch (Date.now()-based). */
1118
- deadlineMs?: number;
1119
- /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
1120
- maxCostUsd?: number;
1121
- /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
1122
- costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
1123
- renderResult?: (label: string, outcome: ToolCallOutcome) => string;
1124
- labelFor?: (call: ToolLoopCall) => string;
1125
- runId?: string;
1126
- scenarioId?: string;
1127
- hooks?: RuntimeHooks;
1128
- }
1129
- /** Streaming bounded tool loop: yields each raw turn event (the caller maps +
1130
- * telemetries + re-emits it) and each executed `tool_result`; emits one
1131
- * `capped` if it stops for any non-completed reason with calls still pending. */
1132
- declare function streamToolLoop<Raw>(opts: StreamToolLoopOptions<Raw>): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown>;
1133
-
1134
- export { AgentBackendInput, type AgentBackendKind, AgentExecutionBackend, AgentTaskRunResult, BackendTransportError, type CampaignOtlpOptions, type CampaignTraceResolverOptions, CandidateGenerator, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, DEFAULT_ROUTER_BASE_URL, type DriverLoopGeneratorOptions, InMemoryRuntimeSessionStore, LIFTED_FINDING_ANALYST_ID, type McpServeSpec, type ModelInfo, PlannerError, type ProfileDiffProposerContext, type ProfileDiffProposerOptions, ROLLOUT_POLICY_BOUNDS, ROLLOUT_POLICY_EXTENSION, type RawTraceDistillerOptions, type ReflectiveGeneratorOptions, type ResolveAgentBackendOptions, type ResolvedChatModel, type RouterEnv, type RunChatTurnInput, type RunToolLoopOptions, RuntimeHooks, RuntimeRunStateError, RuntimeSessionStore, RuntimeStreamEvent, RuntimeTelemetryOptions, type StreamToolLoopOptions, type StreamToolLoopYield, type ToAnalystFindingsOptions, type ToolCallOutcome, type ToolLoopAssistantToolCall, type ToolLoopCall, type ToolLoopEvent, type ToolLoopMessage, type ToolLoopResult, type ToolLoopStopReason, Verifier, applyRolloutPolicyToProfile, applyRunRecordDefaults, buildDriverSystem, campaignCellSpansToOtlp, campaignTraceResolver, cleanModelId, convertCampaignDirToOtlp, createOpenAICompatibleBackend, decideKnowledgeReadiness, deriveExecutionId, driverLoopGenerator, enumerateNeighborPolicies, findingLines, getModels, handleChatTurn, isAnalystFinding, mcpBuildPrompt, mcpServeVerifier, normalizeRolloutPolicy, optimizerMethod, parseRolloutPolicy, profileDiffProposer, rawTraceDistiller, readinessServerSentEvent, reflectiveGenerator, researchDriverNote, resolveAgentBackend, resolveChatModel, resolveRouterBaseUrl, rolloutPolicyProposer, runAgentTask, runAgentTaskStream, runToolLoop, runtimeStreamServerSentEvent, serializeRolloutPolicy, strategyAuthorMethod, streamToolLoop, structuralRolloutPolicyFromProfile, toAnalystFindings, toolBuildPrompt, validateChatModelId };
1
+ import { _ as RunAgentTaskOptions, a as AgentKnowledgeProvider, b as RuntimeSessionStore, c as AgentTaskContext, d as AgentTaskStatus, f as BackendErrorDetail, g as OpenAIChatToolChoice, h as OpenAIChatTool, i as AgentExecutionBackend, l as AgentTaskRunResult, m as OpenAIChatResponseFormat, n as AgentBackendContext, o as AgentRuntimeEvent, p as KnowledgeReadinessDecision, r as AgentBackendInput, s as AgentRuntimeEventSink, t as AgentAdapter, u as AgentTaskSpec, v as RunAgentTaskStreamOptions, x as RuntimeStreamEvent, y as RuntimeSession } from "./types-C9j4qg6l.js";
2
+ import { A as RuntimeRunCompleteInput, B as RuntimeDecisionPoint, F as RuntimeRunRow, G as RuntimeHookTarget, H as RuntimeHookErrorContext, I as RuntimeRunStatus, J as defineRuntimeHooks, K as RuntimeHooks, L as startRuntimeRun, M as RuntimeRunHandle, N as RuntimeRunOptions, P as RuntimeRunPersistenceAdapter, R as RuntimeDecisionEvidenceRef, U as RuntimeHookEvent, V as RuntimeHookContext, W as RuntimeHookPhase, X as notifyRuntimeHookEvent, Y as notifyRuntimeDecisionPoint, j as RuntimeRunCost, q as composeRuntimeHooks, z as RuntimeDecisionKind } from "./types-BevOjfTY.js";
3
+ import { Bu as RuntimeRunStateError, Fu as BackendTransportError, Iu as ConfigError, Lu as JudgeError, Nu as AgentEvalError, Pu as AgentEvalErrorCode, Ru as NotFoundError, Vu as ValidationError, au as LoopSpanNode, cu as OtelExporter, du as buildLoopOtelSpans, eu as EvalRunEvent, fu as buildLoopSpanNodes, gu as loopEventToOtelSpan, hu as exportEvalRuns, iu as INTELLIGENCE_WIRE_VERSION, lu as OtelSpan, mu as createOtelExporter, nu as EvalRunsExportConfig, ou as OtelAttribute, pc as WorktreeCheckRunner, pu as buildRuntimeEventOtelSpans, ru as EvalRunsExportResult, su as OtelExportConfig, tu as EvalRunGeneration, uu as RuntimeEventOtelOptions, zu as PlannerError } from "./index-DruSKs3Z.js";
4
+ import { A as createRuntimeEventCollector, C as RuntimeEventCollector, D as RuntimeTelemetryOptions, E as RuntimeStreamEventSummary, M as sanitizeAgentRuntimeEvent, N as sanitizeKnowledgeReadinessReport, O as SanitizedKnowledgeReadinessReport, P as sanitizeRuntimeStreamEvent, T as RuntimeStreamEventSink, j as createRuntimeStreamEventCollector, k as SanitizedKnowledgeRequirement, w as RuntimeStreamEventCollector } from "./local-harness-Dh8PJ0ot.js";
5
+ import { C as AgentCandidateCodeSurfaceSource, D as AgentCandidateBundleInput, E as buildAgentCandidateBundle, O as sealAgentCandidateBundle, S as AgentCandidateCodeSource, T as BuildAgentCandidateBundleInput, _ as exactProcessProviderAsCandidateExecutor, a as captureAgentCandidateWorkspace, b as FileAgentCandidateExecutionClaimStore, c as AGENT_CANDIDATE_EXECUTION_SUPPORT, d as recoverExpiredAgentCandidateExecution, f as persistCandidateOutputArtifact, g as ExactProcessCandidateExecutorOptions, h as candidateKnowledgeExecutionPaths, i as CreateAgentCandidateWorkspacePortOptions, l as verifyAgentCandidateBundle, m as CANDIDATE_KNOWLEDGE_ROOT_ENV, n as CaptureAgentCandidateWorkspaceOptions, o as captureAgentCandidateWorkspaceFiles, p as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, r as CapturedAgentCandidateWorkspace, s as createAgentCandidateWorkspacePort, t as AgentCandidateWorkspaceArchiveLimits, u as RecoverExpiredAgentCandidateOptions, v as DisposePreparedAgentCandidateOptions, w as AgentCandidateProfileSource, x as FileAgentCandidateExecutionClaimStoreOptions, y as disposePreparedAgentCandidateExecution } from "./index-C-FYUuFG.js";
6
+ import { A as AgentCandidateExecutionTerminalRecord, C as AgentCandidateExecutionFailureClass, D as AgentCandidateExecutionPhaseResult, E as AgentCandidateExecutionPhase, F as candidateExecutionClaim, I as AgentCandidatePreparationEvidence, M as AgentCandidateRetryRejection, N as InMemoryAgentCandidateExecutionClaimStore, O as AgentCandidateExecutionRecoveryEvidence, P as InMemoryAgentCandidateExecutionClaimStoreOptions, S as AgentCandidateExecutionCleanupHandles, T as AgentCandidateExecutionLease, _ as AgentCandidateExecutionAttemptRecord, a as AgentCandidateModelGrantSettleInput, b as AgentCandidateExecutionClaimResult, c as applyExactAgentProfileDiff, d as parseExactAgentProfile, f as parseExactAgentProfileDiff, g as executePreparedAgentCandidate, h as ExecutePreparedAgentCandidateOptions, i as AgentCandidateModelGrantReserveInput, j as AgentCandidateExecutionTerminalResult, k as AgentCandidateExecutionStageResult, l as assertCandidateProfileBinding, m as prepareAgentCandidateExecution, n as AgentCandidateModelGrantClient, o as CreateProtectedAgentCandidateModelPortOptions, p as PrepareAgentCandidateExecutionOptions, r as AgentCandidateModelGrantReservation, s as createProtectedAgentCandidateModelPort, t as AgentCandidateModelGrantActivateInput, v as AgentCandidateExecutionAttemptRef, w as AgentCandidateExecutionFinishResult, x as AgentCandidateExecutionClaimStore, y as AgentCandidateExecutionClaim } from "./protected-model-port-BP6Z4eau.js";
7
+ import { A as CANDIDATE_TRACE_ENV, B as VerifiedAgentCandidate, C as AgentCandidateProtectedModelSettlement, D as AgentCandidateTaskExecution, E as AgentCandidateRunFinalization, F as PreparedAgentCandidateInstruction, I as PreparedAgentCandidateKnowledge, L as PreparedAgentCandidateLaunch, M as CanonicalCandidateDocument, N as PersistedTaskOutcomeEvidence, O as AgentCandidateVerificationPorts, P as PreparedAgentCandidateExecution, R as PreparedAgentCandidateTrace, S as AgentCandidateProtectedModelReservation, T as AgentCandidateRepositoryPort, V as VerifiedAgentCandidateTaskOutcome, _ as AgentCandidateModelLimits, a as AgentCandidateExecutionPorts, b as AgentCandidateOutputPurpose, c as AgentCandidateExecutorPort, d as AgentCandidateExecutorStopRequest, f as AgentCandidateExecutorTaskOutcomeCapture, g as AgentCandidateMemoryResetResult, h as AgentCandidateMemoryPort, i as AgentCandidateContainerPort, j as CANDIDATE_TRACE_TAGS, k as AgentCandidateWorkspacePort, l as AgentCandidateExecutorProfileFile, m as AgentCandidateExecutorWorkspaceInput, n as AgentCandidateBenchmarkGraderIdentity, o as AgentCandidateExecutorFinalCapture, p as AgentCandidateExecutorWorkspaceFile, r as AgentCandidateBenchmarkGraderPort, s as AgentCandidateExecutorMemoryCapture, t as AgentCandidateArtifactPort, u as AgentCandidateExecutorRequest, v as AgentCandidateModelPort, w as AgentCandidateProtectedRunCapture, x as AgentCandidateProtectedModelActivation, y as AgentCandidateOutputArtifactPort, z as ResolvedAgentCandidateContainer } from "./types-BaIpb0XT.js";
8
+ import { $ as sleep, A as RunConversationOptions, B as buildForwardHeaders, C as ConversationResult, D as HaltPredicate, E as HaltContext, F as InMemoryConversationJournal, G as CircuitBreakerState, H as readDepth, I as DEFAULT_MAX_DEPTH, J as RetryBackoff, K as CircuitOpenError, L as FORWARD_HEADERS, M as ConversationJournal, N as ConversationJournalEntry, O as HaltReason, P as FileConversationJournal, Q as makePerAttemptSignal, R as ForwardHeaderName, S as ConversationPolicy, T as ConversationTurn, U as BackendCallPolicy, V as isDepthExceeded, W as CircuitBreakerConfig, X as computeBackoff, Y as RetryableErrorPredicate, Z as defaultIsRetryable, _ as createConversationBackend, a as RunPersonaConfig, b as ConversationDriveState, c as runPersonaDispatch, d as D1DatabaseLike, f as D1StmtLike, g as defineConversation, h as d1ToSqlAdapter, i as PersonaDriver, j as TurnOrder, k as HaltSignal, l as runConversation, m as SqlConversationJournal, n as turnId, o as RunPersonaConversationOptions, p as SqlAdapter, q as DeadlineExceededError, r as PersonaConversationResult, s as runPersonaConversation, t as slugifySpeaker, u as runConversationStream, v as AuthSource, w as ConversationStreamEvent, x as ConversationParticipant, y as Conversation, z as PropagatedHeaders } from "./index-Efjb3nrQ.js";
9
+ import { $ as rawTraceDistiller, A as ResolveAgentBackendOptions, At as handleChatTurn, B as getModels, C as readinessServerSentEvent, Ct as deriveExecutionId, D as runAgentTask, Dt as ChatTurnProducer, E as applyRunRecordDefaults, Et as ChatTurnIdentity, F as DEFAULT_ROUTER_BASE_URL, G as applyRolloutPolicyToProfile, H as resolveRouterBaseUrl, I as ModelInfo, J as serializeRolloutPolicy, K as normalizeRolloutPolicy, L as ResolvedChatModel, M as decideKnowledgeReadiness, Mt as createIterableBackend, N as ChatModelCandidate, Nt as createOpenAICompatibleBackend, O as runAgentTaskStream, Ot as ChatTurnResult, P as ChatModelValidation, Pt as createSandboxPromptBackend, Q as RawTraceDistillerOptions, R as RouterEnv, S as ServerSentEventOptions, St as toolBuildPrompt, T as InMemoryRuntimeSessionStore, Tt as ChatTurnHooks, U as validateChatModelId, V as resolveChatModel, W as ROLLOUT_POLICY_EXTENSION, X as ReflectiveGeneratorOptions, Y as structuralRolloutPolicyFromProfile, Z as reflectiveGenerator, _ as ToolLoopMessage, _t as DriverLoopGeneratorOptions, a as ControlStep, at as OfficialOptimizerContextOptions, b as runToolLoop, bt as findingLines, c as KnowledgeRequirement, ct as OfficialSkillOptOptions, d as StreamToolLoopOptions, dt as McpServeSpec, et as buildDriverSystem, f as StreamToolLoopYield, ft as mcpServeVerifier, g as ToolLoopEvent, gt as toAnalystFindings, h as ToolLoopCall, ht as isAnalystFinding, i as ControlRunResult, it as OfficialGepaOptions, j as resolveAgentBackend, jt as BackendRetryPolicy, k as AgentBackendKind, kt as RunChatTurnInput, l as RunRecord, lt as officialGepa, m as ToolLoopAssistantToolCall, mt as ToAnalystFindingsOptions, n as ControlDecision, nt as researchDriverNote, o as DataAcquisitionPlan, ot as OfficialOptimizerUnavailableError, p as ToolCallOutcome, pt as LIFTED_FINDING_ANALYST_ID, q as parseRolloutPolicy, r as ControlEvalResult, rt as strategyAuthorMethod, s as KnowledgeReadinessReport, st as OfficialSensitiveCandidateInput, t as ControlBudget, tt as optimizerMethod, u as RunToolLoopOptions, ut as officialSkillOpt, v as ToolLoopResult, vt as driverLoopGenerator, w as runtimeStreamServerSentEvent, wt as ChatStreamEvent, x as streamToolLoop, xt as mcpBuildPrompt, y as ToolLoopStopReason, yt as BuildPromptFindingsInput, z as cleanModelId } from "./index-BGdxAwfO.js";
10
+ import { A as AGENTIC_PROFILE_RESOURCE_ROOT, B as CandidateGenerator, C as ImproveSkillsOptions, D as ImprovementProfileCandidate, E as ImprovementCodeCandidate, F as Verifier, I as VerifyResult, L as agenticGenerator, M as AgenticGeneratorShotDisposition, N as AgenticGeneratorShotExecution, O as DeepReadonly, P as AgenticGeneratorShotReceipt, R as commandVerifier, S as ImproveResult, T as ImprovementCandidate, _ as ImproveOptimizationRunOptions, a as ImproveCandidateValidationInput, b as ImproveProfileComponents, c as ImproveCodeResult, d as ImproveLineage, f as ImproveMethodContext, g as ImproveMethodSource, h as ImproveMethodResult, i as improve, j as AgenticGeneratorOptions, k as ReadonlyAgentProfile, l as ImproveCodeRunOptions, m as ImproveMethodOptions, o as ImproveCandidateValidator, p as ImproveMethodFactory, s as ImproveCodeOptions, u as ImproveCost, v as ImproveOptions, w as ImproveSurface, x as ImproveProfileSurface, y as ImproveProfileAgent, z as defaultBuildPrompt } from "./redact-kbIOjfjM.js";
11
+ 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-CbNM40xG.js";
12
+ import { _ as researchLoopRunner, a as DELEGATED_LOOP_MODES, c as DelegatedLoopResult, d as ResearchLoopRunnerOptions, f as RunDelegatedLoopOptions, g as isDelegatedLoopMode, h as auditLoopRunner, i as runLoopRunnerCli, l as DelegatedLoopRunner, m as WorktreeLoopRunnerOptions, n as LoopRunnerCliResult, o as DelegatedLoopMode, p as VetoedFact, r as parseLoopRunnerArgv, s as DelegatedLoopRegistry, t as LoopRunnerCliArgs, u as ResearchLoopResult, v as runDelegatedLoop, y as worktreeLoopRunner } from "./loop-runner-bin-BXsFEUcf.js";
13
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-B68JaOCx.js";
14
+ export { AGENTIC_PROFILE_RESOURCE_ROOT, AGENT_CANDIDATE_EXECUTION_SUPPORT, type AgentAdapter, type AgentBackendContext, type AgentBackendInput, type AgentBackendKind, type AgentCandidateArtifactPort, type AgentCandidateBenchmarkGraderIdentity, type AgentCandidateBenchmarkGraderPort, type AgentCandidateBundleInput, type AgentCandidateCodeSource, type AgentCandidateCodeSurfaceSource, type AgentCandidateContainerPort, type AgentCandidateExecutionAttemptRecord, type AgentCandidateExecutionAttemptRef, type AgentCandidateExecutionClaim, type AgentCandidateExecutionClaimResult, type AgentCandidateExecutionClaimStore, type AgentCandidateExecutionCleanupHandles, type AgentCandidateExecutionFailureClass, type AgentCandidateExecutionFinishResult, type AgentCandidateExecutionLease, type AgentCandidateExecutionPhase, type AgentCandidateExecutionPhaseResult, type AgentCandidateExecutionPorts, type AgentCandidateExecutionRecoveryEvidence, type AgentCandidateExecutionStageResult, type AgentCandidateExecutionTerminalRecord, type AgentCandidateExecutionTerminalResult, type AgentCandidateExecutorFinalCapture, type AgentCandidateExecutorMemoryCapture, type AgentCandidateExecutorPort, type AgentCandidateExecutorProfileFile, type AgentCandidateExecutorRequest, type AgentCandidateExecutorStopRequest, type AgentCandidateExecutorTaskOutcomeCapture, type AgentCandidateExecutorWorkspaceFile, type AgentCandidateExecutorWorkspaceInput, type AgentCandidateMemoryPort, type AgentCandidateMemoryResetResult, type AgentCandidateModelGrantActivateInput, type AgentCandidateModelGrantClient, type AgentCandidateModelGrantReservation, type AgentCandidateModelGrantReserveInput, type AgentCandidateModelGrantSettleInput, type AgentCandidateModelLimits, type AgentCandidateModelPort, type AgentCandidateOutputArtifactPort, type AgentCandidateOutputPurpose, type AgentCandidatePreparationEvidence, type AgentCandidateProfileSource, type AgentCandidateProtectedModelActivation, type AgentCandidateProtectedModelReservation, type AgentCandidateProtectedModelSettlement, type AgentCandidateProtectedRunCapture, type AgentCandidateRepositoryPort, type AgentCandidateRetryRejection, type AgentCandidateRunFinalization, type AgentCandidateTaskExecution, type AgentCandidateVerificationPorts, type AgentCandidateWorkspaceArchiveLimits, type AgentCandidateWorkspacePort, AgentEvalError, type AgentEvalErrorCode, type AgentExecutionBackend, type AgentKnowledgeProvider, type AgentKnowledgeReadinessCheckOptions, type AgentRuntimeEvent, type AgentRuntimeEventSink, type AgentTaskContext, type AgentTaskRunResult, type AgentTaskSpec, type AgentTaskStatus, type AgenticGeneratorOptions, type AgenticGeneratorShotDisposition, type AgenticGeneratorShotExecution, type AgenticGeneratorShotReceipt, type AuthSource, type BackendCallPolicy, type BackendErrorDetail, type BackendRetryPolicy, BackendTransportError, type BuildAgentCandidateBundleInput, type BuildPromptFindingsInput, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, type CandidateGenerator, type CanonicalCandidateDocument, type CaptureAgentCandidateWorkspaceOptions, type CapturedAgentCandidateWorkspace, type ChatModelCandidate, type ChatModelValidation, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, type CircuitBreakerConfig, CircuitBreakerState, CircuitOpenError, ConfigError, type ControlBudget, type ControlDecision, type ControlEvalResult, type ControlRunResult, type ControlStep, type Conversation, type ConversationDriveState, type ConversationJournal, type ConversationJournalEntry, type ConversationParticipant, type ConversationPolicy, type ConversationResult, type ConversationStreamEvent, type ConversationTurn, type CreateAgentCandidateWorkspacePortOptions, type CreateKnowledgeImprovementActivationExecutorOptions, type CreateProtectedAgentCandidateModelPortOptions, type D1DatabaseLike, type D1StmtLike, DEFAULT_MAX_DEPTH, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, type DataAcquisitionPlan, DeadlineExceededError, type DeepReadonly, type DelegatedLoopMode, type DelegatedLoopRegistry, type DelegatedLoopResult, type DelegatedLoopRunner, type DisposePreparedAgentCandidateOptions, type DriverLoopGeneratorOptions, type EvalRunEvent, type EvalRunGeneration, type EvalRunsExportConfig, type EvalRunsExportResult, type ExactProcessCandidateExecutorOptions, type ExecutePreparedAgentCandidateOptions, FORWARD_HEADERS, FileAgentCandidateExecutionClaimStore, type FileAgentCandidateExecutionClaimStoreOptions, FileConversationJournal, type ForwardHeaderName, type HaltContext, type HaltPredicate, type HaltReason, type HaltSignal, INTELLIGENCE_WIRE_VERSION, type ImproveCandidateValidationInput, type ImproveCandidateValidator, type ImproveCodeOptions, type ImproveCodeResult, type ImproveCodeRunOptions, type ImproveCost, type ImproveLineage, type ImproveMethodContext, type ImproveMethodFactory, type ImproveMethodOptions, type ImproveMethodResult, type ImproveMethodSource, type ImproveOptimizationRunOptions, type ImproveOptions, type ImproveProfileAgent, type ImproveProfileComponents, type ImproveProfileSurface, type ImproveResult, type ImproveSkillsOptions, type ImproveSurface, type ImprovementCandidate, type ImprovementCodeCandidate, type ImprovementProfileCandidate, InMemoryAgentCandidateExecutionClaimStore, type InMemoryAgentCandidateExecutionClaimStoreOptions, InMemoryConversationJournal, InMemoryRuntimeSessionStore, JudgeError, type KnowledgeImprovementActivationExecutor, type KnowledgeImprovementCandidatePair, type KnowledgeImprovementExperimentBundles, type KnowledgeImprovementJobMeasurement, type KnowledgeImprovementJobResult, type KnowledgeReadinessCheck, type KnowledgeReadinessCheckInput, type KnowledgeReadinessCheckResult, type KnowledgeReadinessDecision, type KnowledgeReadinessReport, type KnowledgeRequirement, LIFTED_FINDING_ANALYST_ID, type LoopRunnerCliArgs, type LoopRunnerCliResult, type LoopSpanNode, type McpServeSpec, type ModelInfo, NotFoundError, type OfficialGepaOptions, type OfficialOptimizerContextOptions, OfficialOptimizerUnavailableError, type OfficialSensitiveCandidateInput, type OfficialSkillOptOptions, type OpenAIChatResponseFormat, type OpenAIChatTool, type OpenAIChatToolChoice, type OtelAttribute, type OtelExportConfig, type OtelExporter, type OtelSpan, type PersistedTaskOutcomeEvidence, type PersonaConversationResult, type PersonaDriver, PlannerError, type PrepareAgentCandidateExecutionOptions, type PreparedAgentCandidateExecution, type PreparedAgentCandidateInstruction, type PreparedAgentCandidateKnowledge, type PreparedAgentCandidateLaunch, type PreparedAgentCandidateTrace, type PropagatedHeaders, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, type RawTraceDistillerOptions, type ReadonlyAgentProfile, type RecoverExpiredAgentCandidateOptions, type ReflectiveGeneratorOptions, type ResearchLoopResult, type ResearchLoopRunnerOptions, type ResolveAgentBackendOptions, type ResolvedAgentCandidateContainer, type ResolvedChatModel, type RetryBackoff, type RetryableErrorPredicate, type RouterEnv, type RunAgentTaskOptions, type RunAgentTaskStreamOptions, type RunChatTurnInput, type RunConversationOptions, type RunDelegatedLoopOptions, type RunKnowledgeImprovementJobOptions, type RunPersonaConfig, type RunPersonaConversationOptions, type RunRecord, type RunToolLoopOptions, type RuntimeDecisionEvidenceRef, type RuntimeDecisionKind, type RuntimeDecisionPoint, type RuntimeEventCollector, type RuntimeEventOtelOptions, type RuntimeHookContext, type RuntimeHookErrorContext, type RuntimeHookEvent, type RuntimeHookPhase, type RuntimeHookTarget, type RuntimeHooks, type RuntimeRunCompleteInput, type RuntimeRunCost, type RuntimeRunHandle, type RuntimeRunOptions, type RuntimeRunPersistenceAdapter, type RuntimeRunRow, RuntimeRunStateError, type RuntimeRunStatus, type RuntimeSession, type RuntimeSessionStore, type RuntimeStreamEvent, type RuntimeStreamEventCollector, type RuntimeStreamEventSink, type RuntimeStreamEventSummary, type RuntimeTelemetryOptions, type SanitizedKnowledgeReadinessReport, type SanitizedKnowledgeRequirement, type ServerSentEventOptions, type SqlAdapter, SqlConversationJournal, type StreamToolLoopOptions, type StreamToolLoopYield, type SupervisedKnowledgeUpdateInput, type SupervisedKnowledgeUpdateOptions, type SupervisedKnowledgeUpdateResult, type SupervisedKnowledgeUpdater, type ToAnalystFindingsOptions, type ToolCallOutcome, type ToolLoopAssistantToolCall, type ToolLoopCall, type ToolLoopEvent, type ToolLoopMessage, type ToolLoopResult, type ToolLoopStopReason, type TurnOrder, ValidationError, type VerifiedAgentCandidate, type VerifiedAgentCandidateTaskOutcome, type Verifier, type VerifyResult, type VetoedFact, type WorktreeCheckRunner, type WorktreeLoopRunnerOptions, agenticGenerator, applyExactAgentProfileDiff, applyRolloutPolicyToProfile, applyRunRecordDefaults, assertCandidateProfileBinding, auditLoopRunner, buildAgentCandidateBundle, buildDriverSystem, buildForwardHeaders, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, cleanModelId, commandVerifier, composeRuntimeHooks, computeBackoff, createAgentCandidateWorkspacePort, createAgentKnowledgeReadinessCheck, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenAICompatibleBackend, createOtelExporter, createProtectedAgentCandidateModelPort, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, defaultBuildPrompt, defaultIsRetryable, defineConversation, defineRuntimeHooks, deriveExecutionId, disposePreparedAgentCandidateExecution, driverLoopGenerator, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, exportEvalRuns, findingLines, formatSupervisedKnowledgeTask, getModels, handleChatTurn, improve, isAnalystFinding, isDelegatedLoopMode, isDepthExceeded, knowledgeReadinessDeliverable, loopEventToOtelSpan, makePerAttemptSignal, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, parseExactAgentProfile, parseExactAgentProfileDiff, parseLoopRunnerArgv, parseRolloutPolicy, persistCandidateOutputArtifact, prepareAgentCandidateExecution, rawTraceDistiller, readDepth, readinessServerSentEvent, recoverExpiredAgentCandidateExecution, reflectiveGenerator, researchDriverNote, researchLoopRunner, resolveAgentBackend, resolveChatModel, resolveRouterBaseUrl, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runToolLoop, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, sealAgentCandidateBundle, serializeRolloutPolicy, sleep, slugifySpeaker, startRuntimeRun, strategyAuthorMethod, streamToolLoop, structuralRolloutPolicyFromProfile, toAnalystFindings, toolBuildPrompt, turnId, validateChatModelId, verifyAgentCandidateBundle, worktreeLoopRunner };