@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
@@ -0,0 +1,838 @@
1
+ import { _ as RunAgentTaskOptions, b as RuntimeSessionStore, g as OpenAIChatToolChoice, h as OpenAIChatTool, i as AgentExecutionBackend, l as AgentTaskRunResult, m as OpenAIChatResponseFormat, n as AgentBackendContext, p as KnowledgeReadinessDecision, r as AgentBackendInput, v as RunAgentTaskStreamOptions, x as RuntimeStreamEvent, y as RuntimeSession } from "./types-C9j4qg6l.js";
2
+ import { i as SurfaceImprovementEdit } from "./improvement-adapter-Cr5TBSji.js";
3
+ import { o as ImprovementProposalSource } from "./types-Cja5OTGh.js";
4
+ import { K as RuntimeHooks } from "./types-BevOjfTY.js";
5
+ import { Iu as ConfigError, en as StructuralRolloutPolicy } from "./index-DruSKs3Z.js";
6
+ import { D as RuntimeTelemetryOptions, c as runLocalHarness, i as LocalHarness, y as ToolLoopChat } from "./local-harness-Dh8PJ0ot.js";
7
+ import "./index-C-FYUuFG.js";
8
+ import "./index-Efjb3nrQ.js";
9
+ import { B as CandidateGenerator, F as Verifier, a as ImproveCandidateValidationInput, k as ReadonlyAgentProfile, p as ImproveMethodFactory, t as Redactor } from "./redact-kbIOjfjM.js";
10
+ import "./index-CbNM40xG.js";
11
+ import "./loop-runner-bin-BXsFEUcf.js";
12
+ import "./openai-tools-B68JaOCx.js";
13
+ import { AnalystFinding, ControlBudget as ControlBudget$1, ControlDecision as ControlDecision$1, ControlEvalResult, ControlEvalResult as ControlEvalResult$1, ControlRunResult as ControlRunResult$1, ControlStep as ControlStep$1, DataAcquisitionPlan as DataAcquisitionPlan$1, KnowledgeReadinessReport, KnowledgeReadinessReport as KnowledgeReadinessReport$1, KnowledgeRequirement as KnowledgeRequirement$1, RunRecord, RunRecord as RunRecord$1 } from "@tangle-network/agent-eval";
14
+ import { GepaOptimizationMethodConfig, SkillOptOptimizationMethodConfig } from "@tangle-network/agent-eval/campaign";
15
+ import { AgentProfile as AgentProfile$1 } from "@tangle-network/agent-interface";
16
+ import { MutableSurface, Scenario as Scenario$1, SelfImproveOptions } from "@tangle-network/agent-eval/contract";
17
+ //#region src/backends.d.ts
18
+ /** Wrap any custom async-iterable stream into a typed `AgentExecutionBackend`. @stable */
19
+ declare function createIterableBackend<TInput extends AgentBackendInput>(options: {
20
+ kind: string;
21
+ start?: AgentExecutionBackend<TInput>['start'];
22
+ resume?: AgentExecutionBackend<TInput>['resume'];
23
+ stream: AgentExecutionBackend<TInput>['stream'];
24
+ stop?: AgentExecutionBackend<TInput>['stop'];
25
+ }): AgentExecutionBackend<TInput>;
26
+ /** Build an `AgentExecutionBackend` backed by a sandbox/sidecar `streamPrompt` call. @stable */
27
+ declare function createSandboxPromptBackend<TBox, TInput extends AgentBackendInput = AgentBackendInput>(options: {
28
+ kind?: string;
29
+ getBox(input: TInput, context: Omit<AgentBackendContext, 'session'>): Promise<TBox> | TBox;
30
+ streamPrompt(box: TBox, message: string, context: AgentBackendContext): AsyncIterable<unknown>;
31
+ mapEvent?: (event: unknown, context: AgentBackendContext) => RuntimeStreamEvent | undefined;
32
+ getSessionId?: (box: TBox, input: TInput) => string | undefined;
33
+ }): AgentExecutionBackend<TInput>;
34
+ /** @stable */
35
+ /**
36
+ * Retry policy for transient transport errors (rate limits, upstream
37
+ * timeouts). Defaults to 5 attempts with exponential backoff starting at
38
+ * 1s, ±25% jitter, capped at 30s. Set `maxAttempts: 1` to disable retries.
39
+ *
40
+ * Retried status codes:
41
+ * - 408 Request Timeout
42
+ * - 425 Too Early
43
+ * - 429 Too Many Requests
44
+ * - 500 / 502 / 503 / 504 — upstream transient failures
45
+ *
46
+ * Hard failures (401, 403, 4xx other than the above) propagate immediately.
47
+ */
48
+ interface BackendRetryPolicy {
49
+ /** Total attempts including the first try. Default 5. */
50
+ maxAttempts?: number;
51
+ /** Initial backoff in ms before the second attempt. Default 1000. */
52
+ initialBackoffMs?: number;
53
+ /** Hard ceiling on backoff in ms. Default 30000. */
54
+ maxBackoffMs?: number;
55
+ /** Jitter fraction in [0, 1]. Default 0.25 (±25%). */
56
+ jitter?: number;
57
+ /** Status codes that trigger a retry. Default: 408, 425, 429, 500, 502, 503, 504. */
58
+ retryStatuses?: ReadonlyArray<number>;
59
+ /**
60
+ * Per-attempt wall-clock deadline in ms. If a single fetch attempt does
61
+ * not return headers within this window the attempt is aborted and
62
+ * retried. Default 120000 (2 min). Without this a hung upstream blocks
63
+ * the attempt indefinitely — observed in production as a 15-minute
64
+ * `fetch failed` that burned an entire eval persona. Set to 0 to disable.
65
+ */
66
+ requestTimeoutMs?: number;
67
+ }
68
+ /**
69
+ *
70
+ * OpenAI-compat streaming backend. Routes `runAgentTaskStream` through any
71
+ * `POST /chat/completions` endpoint that speaks OpenAI's SSE protocol —
72
+ * Tangle Router, OpenAI direct, OpenRouter, Groq, DeepSeek, Together. The
73
+ * router also fronts Anthropic models in Anthropic-native SSE shape; this
74
+ * backend handles both.
75
+ *
76
+ * ### Tool calls
77
+ *
78
+ * Pass `tools` (and optionally `toolChoice`) to forward an OpenAI Chat
79
+ * Completions `tools[]` array on every request. Streamed `tool_call` chunks
80
+ * are buffered until the model finalizes them (either `finish_reason:
81
+ * 'tool_calls'` for OpenAI shape or a `content_block_stop` for Anthropic
82
+ * `tool_use` blocks proxied through the router), then emitted as a single
83
+ * `tool_call` RuntimeStreamEvent with the assembled `args`.
84
+ *
85
+ * The backend does NOT execute tools — it surfaces calls for the caller's
86
+ * own dispatcher (typically the product's MCP / sandbox runtime) to fulfill
87
+ * and feed back as a subsequent `messages` turn. This keeps the transport
88
+ * thin and lets the agent host own tool dispatch policy.
89
+ *
90
+ * ### Fail-loud errors
91
+ *
92
+ * Non-success HTTP responses (4xx/5xx) and exhausted retry budgets throw
93
+ * `BackendTransportError` from inside the `stream()` generator. The runtime
94
+ * catches the throw, yields a `backend_error` with a typed `error` field
95
+ * (`kind`, `status`, truncated `body`) and a terminal `final` event with
96
+ * `status: 'failed'` carrying the same detail. Consumers MUST map
97
+ * `final.error` onto their `RunRecord.error` — silently treating an empty
98
+ * `finalText` as "agent produced nothing" hides credit exhaustion, auth
99
+ * failure, and upstream outages.
100
+ *
101
+ * @stable
102
+ */
103
+ declare function createOpenAICompatibleBackend<TInput extends AgentBackendInput = AgentBackendInput>(options: {
104
+ apiKey: string;
105
+ baseUrl: string;
106
+ model: string;
107
+ kind?: string;
108
+ /**
109
+ * OpenAI Chat Completions `tools[]` definitions surfaced to the model on
110
+ * every request. Omit to send a tool-free request (existing behavior).
111
+ * The runtime makes no assumption about the dispatcher — calls stream out
112
+ * as `tool_call` events and the caller is responsible for executing them
113
+ * and feeding `tool_result` messages back on a follow-up turn.
114
+ */
115
+ tools?: ReadonlyArray<OpenAIChatTool>;
116
+ /**
117
+ * OpenAI Chat Completions `tool_choice`. Default `undefined` (request
118
+ * omits the field; provider falls back to its own default — typically
119
+ * `'auto'`).
120
+ */
121
+ toolChoice?: OpenAIChatToolChoice;
122
+ /**
123
+ * OpenAI Chat Completions `response_format`. Omit for provider default text.
124
+ */
125
+ responseFormat?: OpenAIChatResponseFormat;
126
+ /** OpenAI Chat Completions `temperature`. Omit for provider default. */
127
+ temperature?: number;
128
+ /** Maximum completion tokens, sent as OpenAI-compatible `max_tokens`. Omit for provider default. */
129
+ maxTokens?: number;
130
+ fetchImpl?: typeof fetch;
131
+ retry?: BackendRetryPolicy;
132
+ }): AgentExecutionBackend<TInput>;
133
+ //#endregion
134
+ //#region src/durable/chat-engine.d.ts
135
+ /**
136
+ * `handleChatTurn` — framework-neutral chat-turn HTTP orchestrator.
137
+ * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`
138
+ * lifecycle vocabulary, and the persist / post-process / trace-flush
139
+ * hook order. Returns a `ReadableStream` body the product hands to its
140
+ * platform `Response`.
141
+ *
142
+ * Execution durability is the substrate's concern: `box.streamPrompt`
143
+ * auto-reconnects in-call; cross-process reconnect via `X-Execution-ID`
144
+ * is the product's job. The producer this engine wraps already speaks
145
+ * that protocol — the engine just frames the events.
146
+ *
147
+ * Hooks (`ChatTurnHooks`):
148
+ * - `produce` — build the backend event stream
149
+ * - `persistAssistantMessage` — write the assistant turn to the product DB
150
+ * - `onTurnComplete?` — post-process (proposals, citations, …)
151
+ * - `onEvent?` — per-event side channel (e.g. DO broadcast)
152
+ * - `transformFinalText?` — pre-persist transform (e.g. PII redact)
153
+ * - `traceFlush?` — handed to waitUntil so OTLP export lands
154
+ *
155
+ * Framework neutrality: takes already-resolved values (`identity` tuple,
156
+ * a `waitUntil`), never a `Request` or a `Context`. The product's thin
157
+ * route adapter does auth + parse + access-control, then calls
158
+ * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.
159
+ */
160
+ /** The NDJSON line protocol every product chat client already speaks. */
161
+ interface ChatStreamEvent {
162
+ type: string;
163
+ data?: Record<string, unknown>;
164
+ }
165
+ /** Identity of a chat turn. `tenantId` is the workspace id for workspace-
166
+ * scoped products and the user id for session-scoped products. */
167
+ interface ChatTurnIdentity {
168
+ tenantId: string;
169
+ /** Thread / session id. */
170
+ sessionId: string;
171
+ userId: string;
172
+ /** Monotonic 0-based turn index within the session. */
173
+ turnIndex: number;
174
+ }
175
+ /** The live side of a turn — what the product's `produce` hook returns. */
176
+ interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {
177
+ /** The turn's event stream. Forwarded verbatim to the caller. */
178
+ stream: AsyncGenerator<TEvent, void, unknown>;
179
+ /** The turn's final assistant text. Read once, after `stream` drains. */
180
+ finalText(): string;
181
+ }
182
+ interface ChatTurnHooks {
183
+ /** Build the backend stream. The engine forwards events verbatim and
184
+ * reads `finalText()` once the stream drains. */
185
+ produce(): ChatTurnProducer;
186
+ /** Persist the assistant message to the product's own store. Called
187
+ * once, after drain, with the assembled (transform-applied) text. */
188
+ persistAssistantMessage(input: {
189
+ identity: ChatTurnIdentity;
190
+ finalText: string;
191
+ }): Promise<void>;
192
+ /** Optional post-processing (proposals, citations, credit metering …).
193
+ * Errors are swallowed + logged — post-process must never fail a turn
194
+ * that already streamed successfully. */
195
+ onTurnComplete?(input: {
196
+ identity: ChatTurnIdentity;
197
+ finalText: string;
198
+ }): Promise<void>;
199
+ /** Optional per-event side channel (e.g. DO broadcast). Runs for every
200
+ * emitted event, lifecycle envelope included. Errors swallowed — a
201
+ * broadcast failure must not break the chat stream. */
202
+ onEvent?(event: ChatStreamEvent): void | Promise<void>;
203
+ /** Optional pre-persist transform of the final text (e.g. PII
204
+ * redaction). Affects only what is persisted; the live stream is
205
+ * never altered. */
206
+ transformFinalText?(text: string): string | Promise<string>;
207
+ /** Optional trace flush — resolves when OTLP export completes. Handed
208
+ * to `waitUntil` so the worker isolate stays alive for the POST. */
209
+ traceFlush?(): Promise<void>;
210
+ }
211
+ interface RunChatTurnInput {
212
+ identity: ChatTurnIdentity;
213
+ hooks: ChatTurnHooks;
214
+ /** Worker liveness hook. When omitted, trace flush is awaited inline
215
+ * before the stream closes. */
216
+ waitUntil?: (p: Promise<unknown>) => void;
217
+ /** Structured logger for swallowed hook errors. Defaults to
218
+ * `console.error` so failures surface without product wiring. */
219
+ log?: (message: string, meta?: Record<string, unknown>) => void;
220
+ }
221
+ interface ChatTurnResult {
222
+ /** NDJSON body — return this as the platform `Response` body. */
223
+ body: ReadableStream<Uint8Array>;
224
+ /** Content type for the response. */
225
+ contentType: 'application/x-ndjson';
226
+ }
227
+ /**
228
+ * Run one chat turn. Returns immediately with a `ReadableStream` body;
229
+ * the turn executes as the body is pulled. Never rejects — backend
230
+ * failures surface as `error` + `session.run.failed` events.
231
+ */
232
+ declare function handleChatTurn(input: RunChatTurnInput): ChatTurnResult;
233
+ //#endregion
234
+ //#region src/durable/execution-handle.d.ts
235
+ /**
236
+ * Derive a stable executionId from the run identity. The same
237
+ * `(projectId, sessionId, turnIndex)` tuple yields the same id — so a
238
+ * client retry of the same turn lands on the same substrate execution
239
+ * and the orchestrator's buffer replays instead of starting a second
240
+ * prompt.
241
+ *
242
+ * Format is readable, not hashed: operators grepping orchestrator logs
243
+ * for `gtm-agent:thread-abc:3` find the run without translating an
244
+ * opaque id. Substrate executionIds are not a secrecy boundary.
245
+ *
246
+ * Wire integration:
247
+ * - Sandbox PromptOptions accepts `executionId` and `lastEventId`.
248
+ * Products pass this id to make cross-process reconnect land on the
249
+ * same substrate execution instead of spawning a duplicate run.
250
+ */
251
+ declare function deriveExecutionId(input: {
252
+ projectId: string;
253
+ sessionId: string;
254
+ turnIndex: number;
255
+ }): string;
256
+ //#endregion
257
+ //#region src/improvement/build-prompts.d.ts
258
+ /** Evidence supplied to a generated tool or MCP build instruction. */
259
+ interface BuildPromptFindingsInput {
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: BuildPromptFindingsInput): string;
267
+ /** Build the starting instruction for a coder agent tasked with implementing a new MCP server. */
268
+ declare function mcpBuildPrompt(args: BuildPromptFindingsInput): string;
269
+ //#endregion
270
+ //#region src/improvement/driver-loop-generator.d.ts
271
+ interface DriverLoopGeneratorOptions {
272
+ /** The driver-LLM seam — ONE inference turn over the conversation + tool specs (the canonical
273
+ * `ToolLoopChat`, same seam as `driverAgent`): `routerBrain(cfg)` in production, a scripted
274
+ * mock in tests. */
275
+ brain: ToolLoopChat;
276
+ /** Local coding harness the driver's worker sessions run in the worktree. Default `claude`. */
277
+ harness?: LocalHarness;
278
+ /** Per-worker-session wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */
279
+ timeoutMs?: number;
280
+ /** Build the driver's task briefing (domain framing + method + findings) — the same senior
281
+ * prompt the worker path uses (`toolBuildPrompt` / `mcpBuildPrompt`). The driver reads it and
282
+ * folds what each worker needs into its instruction. Default `defaultBuildPrompt`. */
283
+ buildPrompt?: (args: {
284
+ report: unknown;
285
+ findings: AnalystFinding[];
286
+ }) => string;
287
+ /** Verify the worktree (the intrinsic check). Exposed to the driver as `run_verifier` AND
288
+ * re-run by code as the final keep/discard gate. Omitted ⇒ the final gate is dirty-tree only
289
+ * (legacy `agenticGenerator` behavior sans verifier). */
290
+ verify?: Verifier;
291
+ /** Max driver inference turns. Default `max(8, 2 + maxShots * 3)` — room for one
292
+ * observe/rate/decide cycle per worker session plus orientation. */
293
+ maxTurns?: number;
294
+ /** The research seam (adopt-not-build): when set, the driver gets a
295
+ * `research{query}` tool + the `researchDriverNote` doctrine, so it can
296
+ * discover an EXISTING external MCP instead of building one. Wire a real
297
+ * web/search backend here — none is provisioned by default (the build
298
+ * harness has no live web access yet; flagged). */
299
+ research?: (query: string) => Promise<string>;
300
+ /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */
301
+ runHarness?: typeof runLocalHarness;
302
+ /** Test seam — inject the worktree diff reader (defaults to `git diff` in the worktree). */
303
+ readDiff?: (worktreePath: string) => string;
304
+ /** Test seam — inject the changed-paths reader (defaults to `git status --porcelain`). */
305
+ changedPaths?: (worktreePath: string) => string[];
306
+ }
307
+ /** 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. */
308
+ declare function driverLoopGenerator(opts: DriverLoopGeneratorOptions): CandidateGenerator;
309
+ //#endregion
310
+ //#region src/improvement/findings.d.ts
311
+ /** Analyst id stamped on findings lifted from untyped seed values. */
312
+ declare const LIFTED_FINDING_ANALYST_ID = "lifted-seed";
313
+ /** Structural guard for the schema-versioned `AnalystFinding` envelope.
314
+ * Strict on the identity fields `makeFinding` always populates — a partial
315
+ * look-alike is lifted (re-enveloped), not trusted. */
316
+ declare function isAnalystFinding(value: unknown): value is AnalystFinding;
317
+ interface ToAnalystFindingsOptions {
318
+ /** `analyst_id` stamped on lifted (non-conforming) values.
319
+ * Default {@link LIFTED_FINDING_ANALYST_ID}. */
320
+ analystId?: string;
321
+ /** `area` stamped on lifted values. Default `'seed'`. */
322
+ area?: string;
323
+ }
324
+ /**
325
+ * Normalize a mixed `unknown[]` findings array to `AnalystFinding[]`:
326
+ * conforming findings pass through by reference; strings and finding-ish
327
+ * objects are lifted into envelopes (claim = most actionable text, original
328
+ * value under `metadata.raw`); values with no extractable text are dropped.
329
+ * Never throws — a malformed seed must not kill a proposal round.
330
+ */
331
+ declare function toAnalystFindings(findings: readonly unknown[], opts?: ToAnalystFindingsOptions): AnalystFinding[];
332
+ //#endregion
333
+ //#region src/improvement/mcp-serve-verifier.d.ts
334
+ interface McpServeSpec {
335
+ /** Command that starts the built MCP server in the worktree (stdio transport). */
336
+ command: string;
337
+ args?: string[];
338
+ /** Extra env for the server process (merged over `process.env`). */
339
+ env?: Record<string, string>;
340
+ /** Handshake timeout (ms). Default 30s. */
341
+ timeoutMs?: number;
342
+ /** Minimum tools the server must expose to pass. Default 1. */
343
+ minTools?: number;
344
+ }
345
+ /** Build a `Verifier` that boots a generated MCP server over stdio and checks it exposes tools. */
346
+ declare function mcpServeVerifier(spec: McpServeSpec): Verifier;
347
+ //#endregion
348
+ //#region src/improvement/official-optimizers.d.ts
349
+ /** Runtime context appended to an official optimizer's own configuration. */
350
+ interface OfficialOptimizerContextOptions {
351
+ /** Context supplied to the optimizer before Runtime appends the profile surface and findings. */
352
+ background?: string;
353
+ /** Include current trace or analyst findings in the optimizer background. Default true. */
354
+ includeFindings?: boolean;
355
+ /** Reject oversized serialized findings before starting Python. Default 50,000 characters. */
356
+ maxFindingsChars?: number;
357
+ /**
358
+ * Redact caller-supplied context and descriptors before they leave Runtime.
359
+ * The built-in redactor is the default. Pass `false` only for public data
360
+ * that has already been reviewed.
361
+ */
362
+ redact?: Redactor | false;
363
+ /** Authorize one exact candidate containing structurally sensitive fields.
364
+ * The callback must return true for every accepted baseline and candidate. */
365
+ authorizeSensitiveCandidate?: (input: OfficialSensitiveCandidateInput) => boolean;
366
+ }
367
+ interface OfficialSensitiveCandidateInput extends ImproveCandidateValidationInput {
368
+ sensitivePaths: readonly string[];
369
+ }
370
+ /** Official GEPA configuration plus bounded Runtime findings context. */
371
+ type OfficialGepaOptions<TScenario extends {
372
+ id: string;
373
+ kind: string;
374
+ }, TArtifact = unknown> = Omit<GepaOptimizationMethodConfig<TScenario, TArtifact>, 'background' | 'evaluationId'> & OfficialOptimizerContextOptions;
375
+ /** Official SkillOpt configuration plus bounded Runtime findings context. */
376
+ type OfficialSkillOptOptions<TScenario extends {
377
+ id: string;
378
+ kind: string;
379
+ }, TArtifact = unknown> = Omit<SkillOptOptimizationMethodConfig<TScenario, TArtifact>, 'background' | 'evaluationId'> & OfficialOptimizerContextOptions;
380
+ /** Missing optional Python dependencies for an official optimizer. */
381
+ declare class OfficialOptimizerUnavailableError extends ConfigError {
382
+ readonly optimizer: 'gepa' | 'skillopt';
383
+ constructor(optimizer: 'gepa' | 'skillopt', cause: unknown);
384
+ }
385
+ /**
386
+ * Build a complete method backed by GEPA's official Optimize Anything API.
387
+ *
388
+ * The recipe is passed through unchanged. Use `engine`, `sequential`,
389
+ * `adaptive-sequential`, `best-of`, `vote`, or `omni` explicitly.
390
+ */
391
+ declare function officialGepa<TScenario extends {
392
+ id: string;
393
+ kind: string;
394
+ }, TArtifact = unknown>(options: OfficialGepaOptions<TScenario, TArtifact>): ImproveMethodFactory<TScenario, TArtifact>;
395
+ /** Build a complete method backed by Microsoft's official SkillOpt trainer. */
396
+ declare function officialSkillOpt<TScenario extends {
397
+ id: string;
398
+ kind: string;
399
+ }, TArtifact = unknown>(options: OfficialSkillOptOptions<TScenario, TArtifact>): ImproveMethodFactory<TScenario, TArtifact>;
400
+ //#endregion
401
+ //#region src/improvement/optimizer-prompt.d.ts
402
+ /**
403
+ * The senior scientific-method optimizer doctrine — the ONE substantial prompt
404
+ * core shared by every builder/author surface (tool build, MCP build, codebase
405
+ * improvement, strategy authoring) and by the driver that steers build workers
406
+ * (`driverLoopGenerator`).
407
+ *
408
+ * Seeded from the proven senior prompts rather than invented: GEPA's
409
+ * `REFLECTION_SYSTEM` (localize → diagnose → minimal generalizable fix →
410
+ * preserve what works), the /evolve loop (one hypothesis with a mechanism and a
411
+ * falsifiable prediction; attack the largest measured gap first), /pursue (one
412
+ * coherent change set, no partial scaffolding), and the self-improving-loop /
413
+ * supervisor doctrine (a keep is decided by a real check, never by the author;
414
+ * observe → rate → decide). Generalized from "mutate a prompt string" to
415
+ * "build a code surface a held-out measurement will grade".
416
+ */
417
+ /**
418
+ * The shared method block every build/author prompt embeds. Domain framing
419
+ * (what a tool/MCP/codebase-edit deliverable looks like) wraps around it; this
420
+ * is the process itself.
421
+ */
422
+ declare const optimizerMethod: string;
423
+ /**
424
+ * The driver's stance for `driverLoopGenerator` — the build-domain instance of
425
+ * the supervisor doctrine (observe → rate → decide; refine / re-scope /
426
+ * decompose; the check decides delivery, never the driver's prose).
427
+ */
428
+ declare const buildDriverSystem: string;
429
+ /**
430
+ * The driver's ADOPT-not-build doctrine, appended to `buildDriverSystem` when
431
+ * a `research` tool is wired into the loop (`DriverLoopGeneratorOptions.
432
+ * research`). Kept separate so a driver WITHOUT the tool is never told to
433
+ * call a tool it does not have.
434
+ */
435
+ declare const researchDriverNote: string;
436
+ /**
437
+ * The senior authoring process for `authorStrategy` — the same method, shaped
438
+ * to the strategy contract (author-blind, conserved budget, one module out).
439
+ */
440
+ declare const strategyAuthorMethod: string;
441
+ //#endregion
442
+ //#region src/improvement/raw-trace-distiller.d.ts
443
+ interface RawTraceDistillerOptions {
444
+ /** Anchor the emitted paths at this run root instead of the generation `runDir`
445
+ * the loop passes in. Normally unset — each call points at that generation's
446
+ * own directory (`input.runDir`). Pass an absolute path when you construct the
447
+ * producer ahead of the loop and want a fixed anchor (e.g. a test fixture). */
448
+ runDir?: string;
449
+ /** Max candidates to surface trace paths for, worst-scoring first. Default 12. */
450
+ maxCandidates?: number;
451
+ /** Max failing cells to enumerate per candidate before collapsing the rest into
452
+ * an "ls the candidate dir" pointer. Default 8. */
453
+ maxCellsPerCandidate?: number;
454
+ /** Max concrete file paths to list per cell (the agent can always `ls` the dir
455
+ * for the rest). Default 24. */
456
+ maxFilesPerCell?: number;
457
+ /** Findings to fall back to when the generation had NO failing cells, so a
458
+ * clean round never wipes the proposer's steering context. Mirrors the default
459
+ * distiller's static-seed fallback. Default: a single instruction finding. */
460
+ fallbackFindings?: unknown[];
461
+ }
462
+ /**
463
+ * Build an `analyzeGeneration` producer that feeds the proposer RAW-TRACE
464
+ * FILESYSTEM CONTEXT — paths into the prior generation's real run traces plus a
465
+ * grep/cat-to-diagnose instruction — instead of a pre-summarized digest.
466
+ *
467
+ * Drop-in for `analyzeGeneration` on `improve({ surface: 'code' })`:
468
+ *
469
+ * await improve({
470
+ * surface: 'code',
471
+ * findings: seedFindings,
472
+ * code: { repoRoot },
473
+ * runDir: '/abs/run', // MUST be a real path — the traces live here
474
+ * analyzeGeneration: rawTraceDistiller(),
475
+ * scenarios, judge, agent,
476
+ * })
477
+ */
478
+ declare function rawTraceDistiller<TScenario extends Scenario$1 = Scenario$1, TArtifact = unknown>(options?: RawTraceDistillerOptions): NonNullable<SelfImproveOptions<TScenario, TArtifact>['analyzeGeneration']>;
479
+ //#endregion
480
+ //#region src/improvement/reflective-generator.d.ts
481
+ interface ReflectiveGeneratorOptions {
482
+ improvementProposalSource: ImprovementProposalSource<SurfaceImprovementEdit>;
483
+ }
484
+ /** Cheap no-sandbox `CandidateGenerator` (the `shots=1` setting): draft surface edits via the improvement adapter and apply them as one coherent candidate. */
485
+ declare function reflectiveGenerator(opts: ReflectiveGeneratorOptions): CandidateGenerator;
486
+ //#endregion
487
+ //#region src/improvement/rollout-policy.d.ts
488
+ /** The profile extensions namespace the policy persists under. */
489
+ declare const ROLLOUT_POLICY_EXTENSION = "structural-rollout";
490
+ /** Parse a serialized policy surface. Returns `undefined` for non-strings,
491
+ * malformed JSON, or values outside the policy invariants. Unknown fields are
492
+ * dropped; supported optional fields are preserved. */
493
+ declare function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined;
494
+ /** Normalize an untyped policy bag (a parsed surface or a profile extension) into
495
+ * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any
496
+ * present dial violates the policy invariants (mirrors `resolvePolicy`: integer
497
+ * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as "not
498
+ * configured", never as a fabricated recipe. */
499
+ declare function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined;
500
+ /** Stable serialization with fixed field order. */
501
+ declare function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string;
502
+ /** Read the persisted policy off the profile. `undefined` when the profile does
503
+ * not opt into structural rollout. */
504
+ declare function structuralRolloutPolicyFromProfile(profile: ReadonlyAgentProfile): StructuralRolloutPolicy | undefined;
505
+ /** Persist a detached policy under the profile extension without mutating the input. */
506
+ declare function applyRolloutPolicyToProfile(profile: ReadonlyAgentProfile, policy: StructuralRolloutPolicy): AgentProfile$1;
507
+ //#endregion
508
+ //#region src/model-resolution.d.ts
509
+ /**
510
+ *
511
+ * Chat-model resolution + catalog validation — the shared primitive every
512
+ * product chat handler needs and was, until now, hand-rolling. Lifts the
513
+ * router `/v1/models` fetch, the fail-closed id validation, and the
514
+ * precedence resolver out of four near-identical per-repo copies.
515
+ *
516
+ * Policy-free by design: callers pass their own precedence order
517
+ * (`resolveChatModel`) and their own known-good `allowlist`
518
+ * (`validateChatModelId`), so each product keeps its resolution policy while
519
+ * sharing the catalog fetch, the malformed-id guard, and the fail-closed
520
+ * admission rule. No React, no `process.env` assumption — `env` is an
521
+ * explicit narrow record so this runs unchanged in Node and in Workers.
522
+ *
523
+ * @stable
524
+ */
525
+ /**
526
+ * A model entry as returned by the Tangle Router `/v1/models` endpoint.
527
+ * Intentionally minimal — only the fields resolution + validation read.
528
+ */
529
+ interface ModelInfo {
530
+ id: string;
531
+ name?: string;
532
+ description?: string;
533
+ /** Provider slug, when the router exposes it (`provider` or `_provider`). */
534
+ provider?: string;
535
+ _provider?: string;
536
+ architecture?: {
537
+ modality?: string;
538
+ input_modalities?: string[];
539
+ output_modalities?: string[];
540
+ };
541
+ }
542
+ /** Env keys the router base URL is resolved from. */
543
+ interface RouterEnv {
544
+ TANGLE_ROUTER_URL?: string;
545
+ TANGLE_ROUTER_BASE_URL?: string;
546
+ }
547
+ /** Default Tangle Router base URL used when no env override is set. */
548
+ declare const DEFAULT_ROUTER_BASE_URL = "https://router.tangle.tools";
549
+ /** Resolve the router base URL from env, normalised — no trailing `/v1` or `/`. */
550
+ declare function resolveRouterBaseUrl(env?: RouterEnv): string;
551
+ /**
552
+ * Fetch the model catalog from the router's `/v1/models`. Throws on a non-2xx
553
+ * response — callers decide whether to fail open (empty catalog) or closed.
554
+ */
555
+ declare function getModels(routerBaseUrl?: string): Promise<ModelInfo[]>;
556
+ /** Trim a candidate model id; `undefined` for non-strings and blanks. */
557
+ declare function cleanModelId(value: unknown): string | undefined;
558
+ interface ChatModelCandidate {
559
+ /** Stable label for telemetry — e.g. `request`, `workspace`, `env`. */
560
+ source: string;
561
+ model: string | undefined;
562
+ }
563
+ interface ResolvedChatModel {
564
+ source: string;
565
+ model: string;
566
+ }
567
+ /**
568
+ * Resolve a chat model by precedence: the first candidate carrying a
569
+ * non-blank model wins, else `fallback`. The caller owns the precedence
570
+ * order, so each product keeps its own policy (request → workspace → env,
571
+ * etc.) while the first-non-blank logic and the telemetry shape stay shared.
572
+ */
573
+ declare function resolveChatModel(candidates: ChatModelCandidate[], fallback: ResolvedChatModel): ResolvedChatModel;
574
+ type ChatModelValidation = {
575
+ succeeded: true;
576
+ value: string;
577
+ } | {
578
+ succeeded: false;
579
+ error: string;
580
+ };
581
+ /**
582
+ * Validate a caller-supplied chat-model id. Rejects non-strings, malformed
583
+ * ids, and ids absent from both the caller's `allowlist` and the live router
584
+ * catalog. Fails closed: when the catalog cannot be fetched, an unverifiable
585
+ * id is rejected rather than admitted — a bad model never reaches the agent.
586
+ */
587
+ declare function validateChatModelId(modelId: unknown, options?: {
588
+ /**
589
+ * Known-good ids that skip the catalog round trip — e.g. the product's
590
+ * default model plus any env-configured ids.
591
+ */
592
+ allowlist?: string[];
593
+ routerBaseUrl?: string;
594
+ /** Injectable catalog loader — overridden in tests. */
595
+ loadModels?: (routerBaseUrl: string) => Promise<ModelInfo[]>;
596
+ }): Promise<ChatModelValidation>;
597
+ //#endregion
598
+ //#region src/readiness.d.ts
599
+ /**
600
+ * Map a `KnowledgeReadinessReport` to a three-state branch (`ready` / `blocked` / `caveat`) the runtime, route handlers, and UI shells all switch on.
601
+ *
602
+ * @stable
603
+ */
604
+ declare function decideKnowledgeReadiness(report: KnowledgeReadinessReport, options?: {
605
+ minimumScore?: number;
606
+ }): KnowledgeReadinessDecision;
607
+ //#endregion
608
+ //#region src/resolve-agent-backend.d.ts
609
+ /** The transport a chat backend runs on. */
610
+ type AgentBackendKind = 'router' | 'tcloud' | 'cli-bridge' | 'sandbox';
611
+ /**
612
+ * OpenAI-compat passthrough forwarded to `createOpenAICompatibleBackend` for
613
+ * the `router` / `tcloud` / `cli-bridge` kinds. Mirrors that factory's optional
614
+ * inputs so a product keeps its tool advertising / capture-fetch without
615
+ * re-implementing the backend branch.
616
+ */
617
+ type OpenAICompatPassthrough = Pick<Parameters<typeof createOpenAICompatibleBackend>[0], 'tools' | 'toolChoice' | 'responseFormat' | 'temperature' | 'maxTokens' | 'fetchImpl' | 'retry'>;
618
+ interface ResolveAgentBackendOptions<TInput extends AgentBackendInput = AgentBackendInput> extends OpenAICompatPassthrough {
619
+ /** The chat transport to resolve. */
620
+ kind: AgentBackendKind;
621
+ /**
622
+ * Bearer credential for the OpenAI-compat kinds. Empty string is valid for a
623
+ * loopback-anonymous cli-bridge; a `router`/`tcloud` route with an empty key
624
+ * is a caller bug the product surfaces before calling in.
625
+ */
626
+ apiKey: string;
627
+ /** Base URL for the OpenAI-compat kinds. cli-bridge's is its `/v1`. */
628
+ baseUrl: string;
629
+ /** Model id sent on every request. cli-bridge rejects a request without it. */
630
+ model: string;
631
+ /** `kind` label stamped on the resolved backend + its traces. Defaults to `kind`. */
632
+ label?: string;
633
+ /**
634
+ * `sandbox` kind: the product's own domain backend. Required for that kind —
635
+ * the substrate owns no product sandbox shape, so a `sandbox` resolution with
636
+ * no seam is a caller bug, not a silent fallback.
637
+ */
638
+ sandboxBackend?: () => AgentExecutionBackend<TInput>;
639
+ }
640
+ /**
641
+ * Resolve the `AgentExecutionBackend` for the chosen `kind`. Reuse this instead
642
+ * of hand-rolling the `createOpenAICompatibleBackend` branch in each product.
643
+ */
644
+ declare function resolveAgentBackend<TInput extends AgentBackendInput = AgentBackendInput>(opts: ResolveAgentBackendOptions<TInput>): AgentExecutionBackend<TInput>;
645
+ //#endregion
646
+ //#region src/run.d.ts
647
+ /** Stamp cross-cutting defaults onto adapter-projected RunRecords without
648
+ * overriding anything the adapter set explicitly:
649
+ * - `scenarioId` — the run's scenario, when the record omits one.
650
+ * - `failureClass` — the control layer's failure classification promoted
651
+ * onto the canonical cross-agent key, but ONLY when it's a real taxonomy
652
+ * class. This is what lets the substrate aggregate failures across every
653
+ * agent in one vocabulary instead of per-agent ad-hoc strings. */
654
+ declare function applyRunRecordDefaults(records: RunRecord[], scenarioId: string, controlFailureClass: string | undefined): RunRecord[];
655
+ /**
656
+ * Single-shot task lifecycle for adapter-driven tasks: readiness-gated, emits the runtime lifecycle event vocabulary, session-store pluggable.
657
+ *
658
+ * @stable
659
+ */
660
+ declare function runAgentTask<TState, TAction, TActionResult, TEval extends ControlEvalResult = ControlEvalResult>(options: RunAgentTaskOptions<TState, TAction, TActionResult, TEval>): Promise<AgentTaskRunResult<TState, TAction, TActionResult, TEval>>;
661
+ /**
662
+ * Streaming task lifecycle: delegates execution to an `AgentExecutionBackend` (model API, sandbox, or custom iterable) and yields lifecycle events as they happen.
663
+ *
664
+ * @stable
665
+ */
666
+ declare function runAgentTaskStream<TInput extends AgentBackendInput = AgentBackendInput>(options: RunAgentTaskStreamOptions<TInput>): AsyncIterable<RuntimeStreamEvent>;
667
+ //#endregion
668
+ //#region src/sessions.d.ts
669
+ /** In-memory `RuntimeSessionStore` for single-process use and tests. @stable */
670
+ declare class InMemoryRuntimeSessionStore implements RuntimeSessionStore {
671
+ private readonly sessions;
672
+ private readonly events;
673
+ get(sessionId: string): RuntimeSession | undefined;
674
+ put(session: RuntimeSession): void;
675
+ appendEvent(sessionId: string, event: RuntimeStreamEvent): void;
676
+ listEvents(sessionId: string): RuntimeStreamEvent[];
677
+ }
678
+ //#endregion
679
+ //#region src/sse.d.ts
680
+ /** @stable */
681
+ interface ServerSentEventOptions {
682
+ event?: string;
683
+ id?: string;
684
+ retry?: number;
685
+ }
686
+ /** Serialize a `KnowledgeReadinessReport` as a Server-Sent Event string. @stable */
687
+ declare function readinessServerSentEvent(report: KnowledgeReadinessReport, options?: RuntimeTelemetryOptions & ServerSentEventOptions): string;
688
+ /** Serialize a `RuntimeStreamEvent` as a Server-Sent Event string. @stable */
689
+ declare function runtimeStreamServerSentEvent(event: RuntimeStreamEvent, options?: RuntimeTelemetryOptions & ServerSentEventOptions): string;
690
+ //#endregion
691
+ //#region src/tool-loop.d.ts
692
+ interface ToolLoopCall {
693
+ toolCallId?: string;
694
+ toolName: string;
695
+ args: Record<string, unknown>;
696
+ }
697
+ /** Outcome of one tool dispatch — structurally compatible with a hub/integration
698
+ * tool-outcome union, so callers can fold either through the loop. */
699
+ type ToolCallOutcome = {
700
+ ok: true;
701
+ result: unknown;
702
+ } | {
703
+ ok: false;
704
+ code: string;
705
+ message: string;
706
+ status?: number;
707
+ };
708
+ /** One OpenAI-shaped tool-call entry carried on an assistant message. */
709
+ interface ToolLoopAssistantToolCall {
710
+ id: string;
711
+ type: 'function';
712
+ function: {
713
+ name: string;
714
+ arguments: string;
715
+ };
716
+ }
717
+ /**
718
+ * A message in the running conversation the loop sends to `streamTurn`.
719
+ *
720
+ * The base `{ role, content }` covers `system` / `user` / plain `assistant`
721
+ * turns. Two optional fields carry the OpenAI function-calling contract so a
722
+ * strict model (Claude, and any OpenAI-compatible provider that validates tool
723
+ * history) reads its own tool use back instead of re-issuing the same call:
724
+ *
725
+ * - an assistant turn that emitted tool calls carries `tool_calls`, and its
726
+ * `content` is `null` when the turn was tool-only;
727
+ * - each tool result is its own `{ role: 'tool', tool_call_id, content }`
728
+ * message keyed to the call that produced it.
729
+ *
730
+ * Widening is additive: a `streamTurn` that reads only `role` + `content` still
731
+ * works; one that forwards the whole message to an OpenAI-compatible endpoint
732
+ * now sends correct tool history.
733
+ */
734
+ type ToolLoopMessage = {
735
+ role: string;
736
+ content: string | null;
737
+ tool_calls?: ToolLoopAssistantToolCall[];
738
+ tool_call_id?: string;
739
+ };
740
+ type ToolLoopEvent = {
741
+ type: 'text';
742
+ text: string;
743
+ } | {
744
+ type: 'tool_call';
745
+ call: ToolLoopCall;
746
+ } | {
747
+ type: 'other';
748
+ event: unknown;
749
+ };
750
+ /** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =
751
+ * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the
752
+ * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs
753
+ * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /
754
+ * resource outcomes — eval scoring must distinguish them from capability failure. */
755
+ type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget';
756
+ interface ToolLoopResult {
757
+ finalText: string;
758
+ toolResults: Array<{
759
+ call: ToolLoopCall;
760
+ label: string;
761
+ outcome: ToolCallOutcome;
762
+ }>;
763
+ turns: number;
764
+ stopReason: ToolLoopStopReason;
765
+ /** @deprecated Use `stopReason !== 'completed'` instead. */
766
+ cappedOut: boolean;
767
+ }
768
+ interface RunToolLoopOptions {
769
+ systemPrompt: string;
770
+ userMessage: string;
771
+ priorMessages?: ToolLoopMessage[];
772
+ streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>;
773
+ executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
774
+ isExecutableTool: (toolName: string) => boolean;
775
+ /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.
776
+ * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */
777
+ maxToolTurns?: number;
778
+ /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the
779
+ * loop stops with stopReason `deadline`. */
780
+ deadlineMs?: number;
781
+ /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
782
+ maxCostUsd?: number;
783
+ /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
784
+ costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
785
+ renderResult?: (label: string, outcome: ToolCallOutcome) => string;
786
+ labelFor?: (call: ToolLoopCall) => string;
787
+ runId?: string;
788
+ scenarioId?: string;
789
+ hooks?: RuntimeHooks;
790
+ }
791
+ /** Run the bounded tool loop and return the final text + every executed tool
792
+ * outcome. Awaitable — callers needing to stream events to a UI use
793
+ * {@link streamToolLoop}. */
794
+ declare function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult>;
795
+ type StreamToolLoopYield<Raw> = {
796
+ kind: 'event';
797
+ event: Raw;
798
+ } | {
799
+ kind: 'tool_result';
800
+ toolName: string;
801
+ toolCallId?: string;
802
+ label: string;
803
+ outcome: ToolCallOutcome;
804
+ } | {
805
+ kind: 'capped';
806
+ pending: number;
807
+ stopReason: Exclude<ToolLoopStopReason, 'completed'>;
808
+ };
809
+ interface StreamToolLoopOptions<Raw> {
810
+ systemPrompt: string;
811
+ userMessage: string;
812
+ priorMessages?: ToolLoopMessage[];
813
+ streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<Raw>;
814
+ extractText: (event: Raw) => string;
815
+ extractToolCall: (event: Raw) => ToolLoopCall | null;
816
+ isExecutableTool: (toolName: string) => boolean;
817
+ executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
818
+ /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */
819
+ maxToolTurns?: number;
820
+ /** Wall-clock deadline in ms since epoch (Date.now()-based). */
821
+ deadlineMs?: number;
822
+ /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
823
+ maxCostUsd?: number;
824
+ /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
825
+ costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
826
+ renderResult?: (label: string, outcome: ToolCallOutcome) => string;
827
+ labelFor?: (call: ToolLoopCall) => string;
828
+ runId?: string;
829
+ scenarioId?: string;
830
+ hooks?: RuntimeHooks;
831
+ }
832
+ /** Streaming bounded tool loop: yields each raw turn event (the caller maps +
833
+ * telemetries + re-emits it) and each executed `tool_result`; emits one
834
+ * `capped` if it stops for any non-completed reason with calls still pending. */
835
+ declare function streamToolLoop<Raw>(opts: StreamToolLoopOptions<Raw>): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown>;
836
+ //#endregion
837
+ export { rawTraceDistiller as $, ResolveAgentBackendOptions as A, handleChatTurn as At, getModels as B, readinessServerSentEvent as C, deriveExecutionId as Ct, runAgentTask as D, ChatTurnProducer as Dt, applyRunRecordDefaults as E, ChatTurnIdentity as Et, DEFAULT_ROUTER_BASE_URL as F, applyRolloutPolicyToProfile as G, resolveRouterBaseUrl as H, ModelInfo as I, serializeRolloutPolicy as J, normalizeRolloutPolicy as K, ResolvedChatModel as L, decideKnowledgeReadiness as M, createIterableBackend as Mt, ChatModelCandidate as N, createOpenAICompatibleBackend as Nt, runAgentTaskStream as O, ChatTurnResult as Ot, ChatModelValidation as P, createSandboxPromptBackend as Pt, RawTraceDistillerOptions as Q, RouterEnv as R, ServerSentEventOptions as S, toolBuildPrompt as St, InMemoryRuntimeSessionStore as T, ChatTurnHooks as Tt, validateChatModelId as U, resolveChatModel as V, ROLLOUT_POLICY_EXTENSION as W, ReflectiveGeneratorOptions as X, structuralRolloutPolicyFromProfile as Y, reflectiveGenerator as Z, ToolLoopMessage as _, DriverLoopGeneratorOptions as _t, ControlStep$1 as a, OfficialOptimizerContextOptions as at, runToolLoop as b, findingLines as bt, KnowledgeRequirement$1 as c, OfficialSkillOptOptions as ct, StreamToolLoopOptions as d, McpServeSpec as dt, buildDriverSystem as et, StreamToolLoopYield as f, mcpServeVerifier as ft, ToolLoopEvent as g, toAnalystFindings as gt, ToolLoopCall as h, isAnalystFinding as ht, ControlRunResult$1 as i, OfficialGepaOptions as it, resolveAgentBackend as j, BackendRetryPolicy as jt, AgentBackendKind as k, RunChatTurnInput as kt, RunRecord$1 as l, officialGepa as lt, ToolLoopAssistantToolCall as m, ToAnalystFindingsOptions as mt, ControlDecision$1 as n, researchDriverNote as nt, DataAcquisitionPlan$1 as o, OfficialOptimizerUnavailableError as ot, ToolCallOutcome as p, LIFTED_FINDING_ANALYST_ID as pt, parseRolloutPolicy as q, ControlEvalResult$1 as r, strategyAuthorMethod as rt, KnowledgeReadinessReport$1 as s, OfficialSensitiveCandidateInput as st, ControlBudget$1 as t, optimizerMethod as tt, RunToolLoopOptions as u, officialSkillOpt as ut, ToolLoopResult as v, driverLoopGenerator as vt, runtimeStreamServerSentEvent as w, ChatStreamEvent as wt, streamToolLoop as x, mcpBuildPrompt as xt, ToolLoopStopReason as y, BuildPromptFindingsInput as yt, cleanModelId as z };
838
+ //# sourceMappingURL=index-BGdxAwfO.d.ts.map