@hop-top/kit 0.5.0-alpha.3 → 0.5.0-alpha.4

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 (187) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-JTMPNXVQ.js +1491 -0
  26. package/dist/chunk-KVG7YCTS.js +115 -0
  27. package/dist/chunk-L23O2FFE.js +51 -0
  28. package/dist/chunk-MQXYDYRD.js +968 -0
  29. package/dist/chunk-MUIQVU6E.js +251 -0
  30. package/dist/chunk-POR5L2DG.js +247 -0
  31. package/dist/chunk-PSFYJGDG.js +1445 -0
  32. package/dist/chunk-QJVSKKRQ.js +369 -0
  33. package/dist/chunk-QPUCXQXT.js +67 -0
  34. package/dist/chunk-R5U7XKVJ.js +16 -0
  35. package/dist/chunk-S45UHXQF.js +182 -0
  36. package/dist/chunk-T46YPHKN.js +669 -0
  37. package/dist/chunk-UIOOOK6M.js +334 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WTYDHXPW.js +574 -0
  41. package/dist/chunk-WUOAQVOA.js +86 -0
  42. package/dist/chunk-WWUKGJB5.js +90 -0
  43. package/dist/chunk-YGYQUFGY.js +219 -0
  44. package/dist/chunk-YOBAUCVN.js +583 -0
  45. package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +50 -1057
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -15
  59. package/dist/index.js +39 -6722
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.test.ts +56 -1
  100. package/src/cli.ts +24 -4
  101. package/src/completion-values.test.ts +10 -10
  102. package/src/compliance.test.ts +196 -2
  103. package/src/compliance.ts +440 -20
  104. package/src/config.test.ts +187 -1
  105. package/src/config.ts +173 -7
  106. package/src/gen/crud_pb.ts +7 -7
  107. package/src/id/README.md +38 -0
  108. package/src/id/contract.test.ts +1 -1
  109. package/src/id/index.test.ts +1 -1
  110. package/src/id/index.ts +3 -2
  111. package/src/index.test.ts +12 -0
  112. package/src/index.ts +2 -0
  113. package/src/llm-anthropic.conformance.test.ts +1135 -0
  114. package/src/llm-anthropic.test.ts +152 -0
  115. package/src/llm-anthropic.ts +940 -0
  116. package/src/llm-choice-hermetic.test.ts +335 -0
  117. package/src/llm-config.test.ts +232 -0
  118. package/src/llm-config.ts +106 -0
  119. package/src/llm-endpoint.ts +254 -0
  120. package/src/llm-error.ts +17 -0
  121. package/src/llm-errors.ts +152 -0
  122. package/src/llm-file.ts +126 -0
  123. package/src/llm-http.ts +317 -0
  124. package/src/llm-keys.ts +167 -0
  125. package/src/llm-media.conformance.test.ts +87 -0
  126. package/src/llm-media.test.ts +279 -0
  127. package/src/llm-media.ts +322 -0
  128. package/src/llm-openai.conformance.test.ts +407 -0
  129. package/src/llm-openai.test.ts +510 -0
  130. package/src/llm-openai.ts +708 -0
  131. package/src/llm-payload.ts +155 -0
  132. package/src/llm-quote.ts +46 -0
  133. package/src/llm-routellm.conformance.test.ts +44 -0
  134. package/src/llm-toolnames.conformance.test.ts +112 -0
  135. package/src/llm-toolnames.test.ts +132 -0
  136. package/src/llm-toolnames.ts +298 -0
  137. package/src/llm-uri.ts +99 -0
  138. package/src/llm.test.ts +43 -15
  139. package/src/llm.toolcall.test.ts +175 -0
  140. package/src/llm.ts +602 -190
  141. package/src/mcp/README.md +57 -0
  142. package/src/mcp/conformance.test.ts +24 -3
  143. package/src/mcp/dispatch.ts +4 -4
  144. package/src/mcp/identity.test.ts +166 -0
  145. package/src/mcp/identity.ts +72 -0
  146. package/src/mcp/index.ts +6 -0
  147. package/src/mcp/legacy.ts +21 -8
  148. package/src/mcp/mcp.test.ts +14 -4
  149. package/src/mcp/modern-confirm.ts +1 -1
  150. package/src/mcp/modern.ts +12 -11
  151. package/src/mcp/tasks.ts +1 -1
  152. package/src/mcp/types.ts +80 -8
  153. package/src/netpolicy.test.ts +78 -0
  154. package/src/netpolicy.ts +28 -3
  155. package/src/output/README.md +46 -0
  156. package/src/output/builtins.ts +5 -5
  157. package/src/output/error.ts +144 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +24 -1
  160. package/src/published-types.test.ts +115 -0
  161. package/src/routellm.test.ts +209 -28
  162. package/src/routellm.toolcall.test.ts +521 -0
  163. package/src/routellm.ts +213 -177
  164. package/src/router/README.md +44 -0
  165. package/src/router/server.test.ts +41 -0
  166. package/src/router/server.ts +11 -0
  167. package/src/safety.test.ts +19 -9
  168. package/src/scope-defaults.json +29 -29
  169. package/src/serve.ts +1 -1
  170. package/src/telemetry/README.md +48 -0
  171. package/src/telemetry/client.ts +5 -5
  172. package/src/toolspec.test.ts +2 -2
  173. package/src/triton/README.md +34 -0
  174. package/src/tui/README.md +42 -0
  175. package/src/wizard.test.ts +7 -7
  176. package/test/llm/conformance-helpers.ts +100 -0
  177. package/test/output/dispatch.test.ts +1 -2
  178. package/test/output/error.test.ts +33 -2
  179. package/test/output/smoke-capture.ts +2 -2
  180. package/test/output/smoke.test.ts +2 -2
  181. package/test/output/taxonomy-contract.test.ts +148 -0
  182. package/test/setup-env.ts +16 -0
  183. package/tsconfig.json +3 -1
  184. package/tsconfig.test.json +10 -0
  185. package/vitest.config.ts +9 -0
  186. package/dist/llm-B5XUWH8T.d.ts +0 -231
  187. package/dist/routellm-PGSt2D1y.d.ts +0 -75
package/src/llm.ts CHANGED
@@ -4,8 +4,10 @@
4
4
  * LLM client facade — mirrors Go `llm` package interfaces as TS types.
5
5
  *
6
6
  * Provides URI parsing, config loading, provider registry, Client facade
7
- * with fallback, and typed errors. Adapter implementations (OpenAI,
8
- * Anthropic, Ollama) are deferred; register them via {@link register}.
7
+ * with fallback, and typed errors. Adapters register their URI schemes
8
+ * on import: `@hop-top/kit/anthropic` (`anthropic://`),
9
+ * `@hop-top/kit/openai` (`openai://` and OpenAI-compatible schemes)
10
+ * and `@hop-top/kit/routellm`. Register your own via {@link register}.
9
11
  *
10
12
  * @example
11
13
  * ```ts
@@ -17,11 +19,161 @@
17
19
  * ```
18
20
  */
19
21
 
22
+ import { readFile } from "node:fs/promises";
23
+ import { extname } from "node:path";
24
+ import { LLMError } from "./llm-error";
25
+ import {
26
+ APIError,
27
+ HTTPStatusError,
28
+ KeyEndpointError,
29
+ MissingKeyError,
30
+ ResponseTooLargeError,
31
+ StreamTruncatedError,
32
+ } from "./llm-errors";
33
+ import { ToolNameError } from "./llm-toolnames";
34
+ import {
35
+ DEFAULT_MAX_MEDIA_BYTES,
36
+ MediaTooLargeError,
37
+ MediaURLRefusedError,
38
+ fetchMedia,
39
+ isPublicAddress,
40
+ } from "./llm-media";
41
+
42
+ export * from "./llm-toolnames";
43
+ export { DEFAULT_MAX_MEDIA_BYTES, MediaTooLargeError, MediaURLRefusedError, isPublicAddress };
44
+ export {
45
+ APIError,
46
+ HTTPStatusError,
47
+ KeyEndpointError,
48
+ MissingKeyError,
49
+ ResponseTooLargeError,
50
+ StreamTruncatedError,
51
+ };
52
+ import {
53
+ clearDeclarations,
54
+ declarationOf,
55
+ setDeclaration,
56
+ type Declaration,
57
+ } from "./llm-endpoint";
58
+ import { loadConfig, type LoadOptions } from "./llm-config";
59
+ import { parseURI } from "./llm-uri";
60
+ export {
61
+ checkKeyEndpoint,
62
+ credentialsTrusted,
63
+ redactURI,
64
+ type ProviderKey,
65
+ } from "./llm-endpoint";
66
+ export { loadConfig, parseURI, type LoadOptions };
67
+ export { applyAPIKey } from "./llm-keys";
68
+ export {
69
+ requestStartedPayload,
70
+ responseReceivedPayload,
71
+ type CallOp,
72
+ type RequestStartedPayload,
73
+ type ResponseReceivedPayload,
74
+ } from "./llm-payload";
75
+
20
76
  // ─── Data types ──────────────────────────────────────────────────────────────
21
77
 
78
+ /** Classifies a content part in a multimodal message. */
79
+ export type PartType = "text" | "image" | "audio" | "video";
80
+
81
+ /**
82
+ * Binary media input for a {@link ContentPart}.
83
+ *
84
+ * Built by {@link inlineSource}, {@link urlSource} or {@link fileSource}.
85
+ */
86
+ export interface MediaSource {
87
+ /** Non-empty when the source is URL-backed. */
88
+ url(): string;
89
+ /** Inferred MIME type, or `""`. */
90
+ mimeType(): string;
91
+ /** Reads the media bytes. */
92
+ read(): Promise<Uint8Array>;
93
+ }
94
+
95
+ /**
96
+ * A single typed element within a multimodal message.
97
+ *
98
+ * Rule: if a {@link Message} has non-empty `parts`, they are used
99
+ * instead of its `content`.
100
+ */
101
+ export interface ContentPart {
102
+ type: PartType;
103
+ text?: string;
104
+ source?: MediaSource;
105
+ mimeType?: string;
106
+ metadata?: Record<string, unknown>;
107
+ }
108
+
109
+ /**
110
+ * A single role+content pair in a conversation.
111
+ *
112
+ * Multimodal rule: non-empty `parts` take precedence over `content`.
113
+ *
114
+ * Tool-call linkage: an agentic loop replays a tool round as two kinds
115
+ * of message.
116
+ *
117
+ * - Role `"assistant"` with `toolCalls`: the calls the model made,
118
+ * copied from {@link ToolResponse.toolCalls}. `content` carries any
119
+ * text the model produced alongside them and may be `""`.
120
+ * - Role `"tool"` with `toolCallId`: one tool's result, in `content`.
121
+ * `toolCallId` equals the {@link ToolCall.id} it answers. Send one
122
+ * message per call.
123
+ *
124
+ * `toolCalls` is valid only on role `"assistant"` and `toolCallId` only
125
+ * on role `"tool"`; adapters reject either field on any other role, a
126
+ * tool result carrying `parts`, and linkage the provider cannot express,
127
+ * rather than degrading it to plain text ({@link checkToolLinkage}).
128
+ * Messages that set neither field map exactly as before.
129
+ */
22
130
  export interface Message {
23
131
  role: string;
24
132
  content: string;
133
+ parts?: ContentPart[];
134
+ /** Tool invocations of an assistant turn. */
135
+ toolCalls?: ToolCall[];
136
+ /** Links a role `"tool"` result to the {@link ToolCall} it answers. */
137
+ toolCallId?: string;
138
+ /**
139
+ * Replays an assistant turn's thinking blocks, exactly as the provider
140
+ * returned them ({@link Response.thinking}, {@link ToolResponse.thinking}
141
+ * or {@link StreamOutcome.thinking}). Required with tool use when
142
+ * thinking is enabled. Assistant only.
143
+ */
144
+ thinking?: ThinkingBlock[];
145
+ /**
146
+ * Marks a prompt-cache breakpoint after this message: on a system
147
+ * message its text, otherwise its last content block.
148
+ */
149
+ cacheControl?: CacheControl;
150
+ }
151
+
152
+ /**
153
+ * One block of a model's extended thinking. `signature` verifies
154
+ * `thinking`; a redacted block carries only `redacted`, the provider's
155
+ * opaque data. Pass blocks back exactly as received.
156
+ */
157
+ export interface ThinkingBlock {
158
+ thinking: string;
159
+ signature: string;
160
+ redacted: string;
161
+ }
162
+
163
+ /**
164
+ * A prompt-cache breakpoint. `ttl` is `""` or absent (the provider
165
+ * default, five minutes on Anthropic), `"5m"` or `"1h"`.
166
+ */
167
+ export interface CacheControl {
168
+ ttl?: string;
169
+ }
170
+
171
+ /**
172
+ * Enables extended thinking with a token budget, which must be below
173
+ * the request's max tokens.
174
+ */
175
+ export interface ThinkingConfig {
176
+ budgetTokens: number;
25
177
  }
26
178
 
27
179
  export interface Request {
@@ -31,6 +183,75 @@ export interface Request {
31
183
  maxTokens?: number;
32
184
  stopSequences?: string[];
33
185
  extensions?: Record<string, unknown>;
186
+ /** Enables extended thinking; thinking deltas then stream as {@link Token.thinking}. */
187
+ thinking?: ThinkingConfig;
188
+ /**
189
+ * Makes a stream also yield incremental tool-call events
190
+ * ({@link Token.toolCall}) and usage snapshots ({@link Token.usage}).
191
+ * Unset, a stream yields exactly the tokens it always has. Ignored by
192
+ * `complete` and `callWithTools`.
193
+ */
194
+ streamEvents?: boolean;
195
+ /**
196
+ * Constrains tool use on a tool-calling request (`callWithTools`,
197
+ * `streamWithTools`); unset leaves the provider default. See
198
+ * {@link ToolChoice}.
199
+ */
200
+ toolChoice?: ToolChoice;
201
+ }
202
+
203
+ /** Whether the model must call a tool. */
204
+ export type ToolChoiceMode = "auto" | "any" | "none" | "tool";
205
+
206
+ /**
207
+ * Constrains tool use: `auto` lets the model decide (the providers'
208
+ * default), `any` makes it call at least one tool of its pick, `none`
209
+ * forbids tool calls although tools are defined, `tool` makes it call
210
+ * the tool `name`: its {@link ToolDef.name} as defined, before any
211
+ * provider name mapping. Set `name` with mode `tool` only.
212
+ *
213
+ * Adapters reject an invalid choice ({@link checkToolChoice}) before
214
+ * sending, and so does a call without tools (`complete`, `stream`).
215
+ */
216
+ export interface ToolChoice {
217
+ mode: ToolChoiceMode;
218
+ name?: string;
219
+ }
220
+
221
+ const TOOL_CHOICE_MODES: readonly string[] = ["auto", "any", "none", "tool"];
222
+
223
+ /**
224
+ * Throws an {@link LLMError} saying why `c` cannot go with `tools`: a
225
+ * mode that is not a {@link ToolChoiceMode}, no tools, a name missing
226
+ * with mode `tool` or set with another mode, or naming no tool in
227
+ * `tools`. Undefined `c` is valid. Adapters prefix the message with
228
+ * their scheme.
229
+ */
230
+ export function checkToolChoice(
231
+ c: ToolChoice | undefined,
232
+ tools: ReadonlyArray<{ name: string }>
233
+ ): void {
234
+ if (!c) return;
235
+ const q = (v: string) => JSON.stringify(v);
236
+ if (!TOOL_CHOICE_MODES.includes(c.mode)) {
237
+ throw new LLMError(`unknown tool_choice mode ${q(String(c.mode))}`);
238
+ }
239
+ if (tools.length === 0) {
240
+ throw new LLMError(`tool_choice ${q(c.mode)} needs tools`);
241
+ }
242
+ const name = c.name ?? "";
243
+ if (c.mode !== "tool") {
244
+ if (name !== "") {
245
+ throw new LLMError(`tool_choice ${q(c.mode)} takes no tool name`);
246
+ }
247
+ return;
248
+ }
249
+ if (name === "") {
250
+ throw new LLMError(`tool_choice ${q(c.mode)} needs a tool name`);
251
+ }
252
+ if (!tools.some((t) => t.name === name)) {
253
+ throw new LLMError(`tool_choice names unknown tool ${q(name)}`);
254
+ }
34
255
  }
35
256
 
36
257
  export interface Response {
@@ -38,25 +259,124 @@ export interface Response {
38
259
  role: string;
39
260
  usage?: Usage;
40
261
  finishReason?: string;
262
+ /** The turn's thinking blocks, to replay unchanged. */
263
+ thinking?: ThinkingBlock[];
41
264
  }
42
265
 
43
266
  export interface Usage {
44
267
  promptTokens: number;
45
268
  completionTokens: number;
269
+ /**
270
+ * Input tokens read from or written to the prompt cache, apart from
271
+ * `promptTokens`.
272
+ */
273
+ cacheReadTokens?: number;
274
+ cacheCreationTokens?: number;
275
+ /** Every input and output token, cache ones included. */
46
276
  totalTokens: number;
47
277
  }
48
278
 
279
+ /** A model's rate per million tokens, by kind. */
280
+ export interface Price {
281
+ input: number;
282
+ output: number;
283
+ cacheRead: number;
284
+ cacheWrite: number;
285
+ }
286
+
287
+ /** Cost of `u` at `p`, cache reads and writes at their own rates. */
288
+ export function usageCost(u: Usage, p: Price): number {
289
+ return (
290
+ (u.promptTokens * p.input +
291
+ u.completionTokens * p.output +
292
+ (u.cacheReadTokens ?? 0) * p.cacheRead +
293
+ (u.cacheCreationTokens ?? 0) * p.cacheWrite) /
294
+ 1e6
295
+ );
296
+ }
297
+
298
+ /**
299
+ * A single streaming chunk. The final token has `done: true`; nothing
300
+ * follows it. A token carries one thing: a text delta (`content`), a
301
+ * thinking delta (`thinking`), a tool-call event (`toolCall`), a usage
302
+ * snapshot (`usage`), or the end (`done`); `content` is `""` on all but
303
+ * a text delta.
304
+ */
49
305
  export interface Token {
50
306
  content: string;
307
+ /**
308
+ * A thinking delta, sent only when the request enabled
309
+ * {@link Request.thinking}; `content` is then empty.
310
+ */
311
+ thinking?: string;
312
+ /**
313
+ * An incremental tool-call event, sent only when the request set
314
+ * {@link Request.streamEvents}. See {@link ToolCallEvent}.
315
+ */
316
+ toolCall?: ToolCallEvent;
317
+ /**
318
+ * The turn's usage so far, sent only when the request set
319
+ * {@link Request.streamEvents}, each time the provider reports it. A
320
+ * cumulative snapshot, never a delta: counts never go down, and the
321
+ * last one equals the finished turn's usage ({@link StreamOutcome.usage}).
322
+ */
323
+ usage?: Usage;
51
324
  done: boolean;
52
325
  }
53
326
 
327
+ /**
328
+ * The step of a streamed tool call: `start` opens it (`index`, `id`,
329
+ * `name`), `delta` carries a fragment of its JSON arguments, `end`
330
+ * closes it (`call` holds it complete).
331
+ */
332
+ export type ToolCallEventKind = "start" | "delta" | "end";
333
+
334
+ /**
335
+ * One step of a tool call as it streams.
336
+ *
337
+ * For each call: one start, then any deltas, then one end, in that
338
+ * order; events of parallel calls may interleave and are told apart by
339
+ * `index`, the call's position in {@link StreamOutcome.toolCalls}. A
340
+ * call that started but never ended (the stream failed, was cancelled
341
+ * or closed) did not complete: no end event is made up for it.
342
+ */
343
+ export interface ToolCallEvent {
344
+ kind: ToolCallEventKind;
345
+ index: number;
346
+ /**
347
+ * Set on start and end. `name` is the tool's name as the caller
348
+ * defined it, whatever name went over the wire.
349
+ */
350
+ id?: string;
351
+ name?: string;
352
+ /**
353
+ * A raw fragment of the arguments' JSON, on delta only; fragments
354
+ * concatenate to the complete arguments and are not valid JSON alone.
355
+ */
356
+ argumentsDelta?: string;
357
+ /**
358
+ * The complete call, on end only: exactly the entry at `index` in
359
+ * {@link StreamOutcome.toolCalls}.
360
+ */
361
+ call?: ToolCall;
362
+ }
363
+
54
364
  export interface ToolDef {
55
365
  name: string;
56
366
  description: string;
57
367
  parameters: unknown;
368
+ /** Marks a prompt-cache breakpoint after this tool. */
369
+ cacheControl?: CacheControl;
58
370
  }
59
371
 
372
+ /**
373
+ * A single tool invocation returned by the model.
374
+ *
375
+ * `id` is the handle a tool result quotes back in
376
+ * {@link Message.toolCallId}. `arguments` is the parsed JSON value, or a
377
+ * JSON-encoded string (Go's `json.RawMessage`); adapters send a string
378
+ * as is and encode anything else.
379
+ */
60
380
  export interface ToolCall {
61
381
  id: string;
62
382
  name: string;
@@ -66,6 +386,29 @@ export interface ToolCall {
66
386
  export interface ToolResponse {
67
387
  content: string;
68
388
  toolCalls: ToolCall[];
389
+ /** The turn's thinking blocks, to replay unchanged. */
390
+ thinking?: ThinkingBlock[];
391
+ finishReason?: string;
392
+ usage?: Usage;
393
+ }
394
+
395
+ /** What a finished stream folded into. */
396
+ export interface StreamOutcome {
397
+ content: string;
398
+ /** The turn's thinking blocks in order; replay them unchanged. */
399
+ thinking: ThinkingBlock[];
400
+ toolCalls: ToolCall[];
401
+ finishReason: string;
402
+ usage: Usage;
403
+ }
404
+
405
+ /**
406
+ * A token stream whose finished turn can be read back: `outcome()` is
407
+ * defined only once the final token (`done`) was yielded; after an
408
+ * error it stays undefined.
409
+ */
410
+ export interface ToolStream extends AsyncIterable<Token> {
411
+ outcome(): StreamOutcome | undefined;
69
412
  }
70
413
 
71
414
  // ─── Core interfaces ─────────────────────────────────────────────────────────
@@ -82,8 +425,17 @@ export interface ToolCaller {
82
425
  callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
83
426
  }
84
427
 
428
+ /**
429
+ * Streams a tool-calling completion: text deltas as tokens, then the
430
+ * whole turn (tool calls, stop reason, usage) from
431
+ * {@link ToolStream.outcome}.
432
+ */
433
+ export interface ToolStreamer {
434
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
435
+ }
436
+
85
437
  export interface Provider
86
- extends Partial<Completer & Streamer & ToolCaller> {
438
+ extends Partial<Completer & Streamer & ToolCaller & ToolStreamer> {
87
439
  close(): void;
88
440
  }
89
441
 
@@ -108,20 +460,19 @@ export interface ResolvedConfig {
108
460
  uri: URI;
109
461
  provider: ProviderConfig;
110
462
  fallbacks: string[];
463
+ /**
464
+ * Set by the `hermetic` option ({@link LoadOptions}): the adapter
465
+ * reads nothing ambient while it builds and runs, no environment
466
+ * variable (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`,
467
+ * `ANTHROPIC_WORKSPACE_ID`, `<SCHEME>_API_KEY`, `ROUTELLM_*`,
468
+ * `LLM_BASE_URL`) and no llm.yaml. Only this config counts.
469
+ */
470
+ hermetic?: boolean;
111
471
  }
112
472
 
113
473
  // ─── Errors ──────────────────────────────────────────────────────────────────
114
474
 
115
- export class LLMError extends Error {
116
- statusCode?: number;
117
- code?: string;
118
-
119
- constructor(message: string) {
120
- super(message);
121
- this.name = "LLMError";
122
- Object.setPrototypeOf(this, new.target.prototype);
123
- }
124
- }
475
+ export { LLMError };
125
476
 
126
477
  export class ProviderNotFoundError extends LLMError {
127
478
  scheme: string;
@@ -147,13 +498,42 @@ export class CapabilityNotSupportedError extends LLMError {
147
498
  }
148
499
  }
149
500
 
501
+ /**
502
+ * The provider refused the credential (HTTP 401). A 403 is the narrower
503
+ * {@link PermissionDeniedError}, still an `AuthError`.
504
+ */
150
505
  export class AuthError extends LLMError {
151
506
  provider: string;
152
507
 
153
- constructor(provider: string) {
154
- super(`authentication failed for provider: ${provider}`);
508
+ /** `cause` is the provider's error response, when there is one. */
509
+ constructor(provider: string, cause?: Error) {
510
+ super(
511
+ `authentication failed for provider: ${provider}` +
512
+ (cause ? `: ${cause.message}` : "")
513
+ );
155
514
  this.name = "AuthError";
156
515
  this.provider = provider;
516
+ if (cause) this.cause = cause;
517
+ }
518
+ }
519
+
520
+ /**
521
+ * The credential was accepted but may not do what was asked (HTTP 403,
522
+ * an Anthropic `permission_error`): a key without access to the model,
523
+ * workspace or feature. Retrying with the same key will not help.
524
+ *
525
+ * It is an auth error too: `err instanceof AuthError` holds, with the
526
+ * same `provider` and `cause`, so code written before the split keeps
527
+ * treating a 403 as an auth failure. Test `PermissionDeniedError` first
528
+ * to tell the two apart.
529
+ */
530
+ export class PermissionDeniedError extends AuthError {
531
+ constructor(provider: string, cause?: Error) {
532
+ super(provider, cause);
533
+ this.message =
534
+ `permission denied for provider: ${provider}` +
535
+ (cause ? `: ${cause.message}` : "");
536
+ this.name = "PermissionDeniedError";
157
537
  }
158
538
  }
159
539
 
@@ -198,11 +578,18 @@ export class FallbackExhaustedError extends LLMError {
198
578
  * Returns true when `err` should trigger a fallback attempt.
199
579
  *
200
580
  * Fallbackable conditions:
201
- * - LLMError with statusCode >= 500
581
+ * - LLMError with statusCode >= 500 (an {@link HTTPStatusError} from a
582
+ * 5xx response or an overloaded stream)
202
583
  * - RateLimitError (429)
203
584
  * - Connection/timeout errors (ECONNREFUSED, ETIMEDOUT, ECONNRESET)
585
+ *
586
+ * Never fallbackable: a {@link ToolNameError} (the caller's tool set
587
+ * needs fixing), a {@link StreamTruncatedError} (tokens may already be
588
+ * consumed), a {@link ResponseTooLargeError}, a {@link KeyEndpointError}
589
+ * and an {@link APIError} below 500.
204
590
  */
205
591
  export function isFallbackable(err: Error): boolean {
592
+ if (err instanceof ToolNameError) return false;
206
593
  if (err instanceof RateLimitError) return true;
207
594
  if (err instanceof LLMError) {
208
595
  if (err.code && isConnectionError(err.code)) return true;
@@ -227,151 +614,142 @@ function isConnectionError(code: string): boolean {
227
614
  return CONNECTION_CODES.has(code);
228
615
  }
229
616
 
230
- // ─── URI parsing ─────────────────────────────────────────────────────────────
617
+ // ─── Message rules ───────────────────────────────────────────────────────────
231
618
 
232
619
  /**
233
- * Parses an LLM URI string into its components.
234
- *
235
- * Format: `scheme://[host[:port]/]model[?params]`
620
+ * Enforces the provider-independent tool-call linkage rules on one
621
+ * message: `toolCalls` only on role `"assistant"`, `toolCallId` only on
622
+ * role `"tool"`, and a tool result carries only `content` (no
623
+ * `toolCalls`, no `parts`). Throws {@link LLMError} otherwise, checking
624
+ * in the Go adapters' order. An empty `toolCalls` array counts as unset.
236
625
  *
237
- * When the path portion contains a host:port prefix (detected by the
238
- * presence of a numeric port), the first segment is treated as host.
239
- * Otherwise the entire path is the model name.
626
+ * Adapters call it before mapping a message, then add the rules their
627
+ * provider needs (for example a required `toolCallId`).
240
628
  */
241
- export function parseURI(raw: string): URI {
242
- const sep = "://";
243
- const idx = raw.indexOf(sep);
244
- if (idx < 0) {
245
- throw new LLMError(`invalid LLM URI (missing "://"): ${raw}`);
246
- }
247
-
248
- const scheme = raw.slice(0, idx);
249
- if (!scheme) {
250
- throw new LLMError(`invalid LLM URI (empty scheme): ${raw}`);
251
- }
252
-
253
- let rest = raw.slice(idx + sep.length);
254
- if (!rest) {
255
- throw new LLMError(`invalid LLM URI (empty model): ${raw}`);
256
- }
257
-
258
- // Extract query params
259
- let params: Record<string, string> | undefined;
260
- const qIdx = rest.indexOf("?");
261
- if (qIdx >= 0) {
262
- const qs = rest.slice(qIdx + 1);
263
- rest = rest.slice(0, qIdx);
264
- params = {};
265
- for (const pair of qs.split("&")) {
266
- const eqIdx = pair.indexOf("=");
267
- if (eqIdx > 0) {
268
- params[pair.slice(0, eqIdx)] = decodeURIComponent(
269
- pair.slice(eqIdx + 1)
270
- );
271
- }
629
+ export function checkToolLinkage(m: Message): void {
630
+ const hasCalls = (m.toolCalls?.length ?? 0) > 0;
631
+ if (m.role === "tool") {
632
+ if (hasCalls || (m.parts?.length ?? 0) > 0) {
633
+ throw new LLMError(
634
+ `tool result "${m.toolCallId ?? ""}" carries only content`
635
+ );
272
636
  }
637
+ return;
273
638
  }
274
-
275
- if (!rest) {
276
- throw new LLMError(`invalid LLM URI (empty model): ${raw}`);
639
+ if (m.toolCallId) {
640
+ throw new LLMError(
641
+ `toolCallId is valid only on role tool, got "${m.role}"`
642
+ );
277
643
  }
278
-
279
- // Detect host:port pattern.
280
- // If first segment matches `word:digits`, treat it as host.
281
- let host: string | undefined;
282
- let model: string;
283
-
284
- const hostPortMatch = rest.match(/^([^/]+:\d+)\/(.+)$/);
285
- if (hostPortMatch) {
286
- host = hostPortMatch[1];
287
- model = hostPortMatch[2];
288
- } else {
289
- model = rest;
644
+ if (hasCalls && m.role !== "assistant") {
645
+ throw new LLMError(
646
+ `toolCalls are valid only on role assistant, got "${m.role}"`
647
+ );
290
648
  }
649
+ }
291
650
 
292
- const uri: URI = { scheme, model };
293
- if (host) uri.host = host;
294
- if (params && Object.keys(params).length > 0) uri.params = params;
295
- return uri;
651
+ // ─── Media sources ───────────────────────────────────────────────────────────
652
+
653
+ /** In-memory media bytes with a caller-supplied MIME type. */
654
+ export function inlineSource(data: Uint8Array, mimeType: string): MediaSource {
655
+ return {
656
+ url: () => "",
657
+ mimeType: () => mimeType,
658
+ read: async () => data,
659
+ };
296
660
  }
297
661
 
298
- // ─── Config loading ──────────────────────────────────────────────────────────
662
+ /** Options for {@link urlSource}. */
663
+ export interface URLSourceOptions {
664
+ /** Body cap in bytes (default {@link DEFAULT_MAX_MEDIA_BYTES}). */
665
+ maxBytes?: number;
666
+ }
299
667
 
300
668
  /**
301
- * Builds a {@link ResolvedConfig} from a URI string + env vars.
302
- *
303
- * When `uriStr` is empty/undefined, falls back to `LLM_PROVIDER`
304
- * env var as a full default URI. If neither is provided, throws.
305
- *
306
- * URI query params `api_key` and `base_url` populate provider
307
- * config. If `uri.host` is set, it derives a baseURL. Env vars
308
- * `LLM_API_KEY` and `LLM_BASE_URL` override last.
669
+ * URL-backed media; `read()` downloads lazily.
309
670
  *
310
- * Env vars:
311
- * - `LLM_PROVIDER` — full default URI when no arg provided
312
- * - `LLM_API_KEY` — overrides provider API key
313
- * - `LLM_BASE_URL` — overrides provider base URL
314
- * - `LLM_FALLBACK` — comma-separated fallback URIs
671
+ * The download is guarded against server-side request forgery: http or
672
+ * https only, public addresses only (checked on what is dialed, so DNS
673
+ * rebinding cannot redirect it), no redirects, no proxy, at most
674
+ * `maxBytes` (32 MiB by default; {@link MediaTooLargeError} past it),
675
+ * 30s, and `--offline`. Refusals are {@link MediaURLRefusedError}.
676
+ * Adapters whose provider accepts a URL (Anthropic images and PDFs,
677
+ * OpenAI images) send the URL and never read it. Local or private
678
+ * media: read it yourself and pass {@link inlineSource} or
679
+ * {@link fileSource}.
315
680
  */
316
- export function loadConfig(uriStr?: string): ResolvedConfig {
317
- const effective = uriStr || process.env["LLM_PROVIDER"];
318
- if (!effective) {
319
- throw new LLMError(
320
- "no LLM URI provided and LLM_PROVIDER env var is not set"
321
- );
322
- }
323
-
324
- const uri = parseURI(effective);
325
-
326
- const fallbackEnv = process.env["LLM_FALLBACK"];
327
- const fallbacks = fallbackEnv
328
- ? fallbackEnv.split(",").map((s) => s.trim()).filter(Boolean)
329
- : [];
330
-
331
- const provider: ProviderConfig = {
332
- model: uri.model,
681
+ export function urlSource(url: string, opts: URLSourceOptions = {}): MediaSource {
682
+ const maxBytes = opts.maxBytes && opts.maxBytes > 0 ? opts.maxBytes : DEFAULT_MAX_MEDIA_BYTES;
683
+ return {
684
+ url: () => url,
685
+ mimeType: () => "",
686
+ read: () => fetchMedia(url, maxBytes),
333
687
  };
334
- if (uri.params) provider.params = { ...uri.params };
335
-
336
- // Extract api_key and base_url from URI query params
337
- if (uri.params?.api_key) {
338
- provider.apiKey = uri.params.api_key;
339
- }
340
- if (uri.params?.base_url) {
341
- provider.baseURL = uri.params.base_url;
342
- }
343
-
344
- // Derive baseURL from host if present
345
- if (uri.host) {
346
- provider.baseURL = `http://${uri.host}`;
347
- }
688
+ }
348
689
 
349
- // Env var overrides apply LAST
350
- const envApiKey = process.env["LLM_API_KEY"] || undefined;
351
- const envBaseURL = process.env["LLM_BASE_URL"] || undefined;
352
- if (envApiKey) provider.apiKey = envApiKey;
353
- if (envBaseURL) provider.baseURL = envBaseURL;
690
+ const MIME_BY_EXT: Record<string, string> = {
691
+ ".png": "image/png",
692
+ ".jpg": "image/jpeg",
693
+ ".jpeg": "image/jpeg",
694
+ ".gif": "image/gif",
695
+ ".webp": "image/webp",
696
+ ".pdf": "application/pdf",
697
+ ".mp3": "audio/mpeg",
698
+ ".wav": "audio/wav",
699
+ ".ogg": "audio/ogg",
700
+ ".mp4": "video/mp4",
701
+ ".webm": "video/webm",
702
+ ".mov": "video/quicktime",
703
+ };
354
704
 
355
- return { uri, provider, fallbacks };
705
+ /**
706
+ * File on disk, read on `read()`. The MIME type comes from the
707
+ * extension (common image, PDF, audio and video types); unknown
708
+ * extensions give `""`, so set {@link ContentPart.mimeType} instead.
709
+ */
710
+ export function fileSource(path: string): MediaSource {
711
+ return {
712
+ url: () => "",
713
+ mimeType: () => MIME_BY_EXT[extname(path).toLowerCase()] ?? "",
714
+ read: async () => new Uint8Array(await readFile(path)),
715
+ };
356
716
  }
357
717
 
358
718
  // ─── Registry ────────────────────────────────────────────────────────────────
359
719
 
360
720
  export type Factory = (cfg: ResolvedConfig) => Provider;
361
721
 
722
+ /**
723
+ * What an adapter states about its scheme: the endpoints its
724
+ * credentials may go to besides loopback, `LLM_BASE_URL` and the
725
+ * adapter's own base URL variable (see {@link credentialsTrusted}).
726
+ */
727
+ export type { Declaration };
728
+
362
729
  const registry = new Map<string, Factory>();
363
730
 
364
731
  /** Register a provider factory for the given URI scheme. */
365
- export function register(scheme: string, factory: Factory): void {
732
+ export function register(
733
+ scheme: string,
734
+ factory: Factory,
735
+ decl?: Declaration
736
+ ): void {
366
737
  if (registry.has(scheme)) {
367
738
  throw new LLMError(`provider already registered for scheme: ${scheme}`);
368
739
  }
369
740
  registry.set(scheme, factory);
741
+ setDeclaration(scheme, decl);
370
742
  }
371
743
 
372
- /** Resolve a URI to a Provider instance via the registry. */
373
- export function resolve(uriStr: string): Provider {
374
- const cfg = loadConfig(uriStr);
744
+ export { declarationOf };
745
+
746
+ /**
747
+ * Resolve a URI to a Provider instance via the registry. With
748
+ * `opts.hermetic` neither the config nor the adapter reads anything
749
+ * ambient (see {@link LoadOptions}).
750
+ */
751
+ export function resolve(uriStr: string, opts: LoadOptions = {}): Provider {
752
+ const cfg = loadConfig(uriStr, opts);
375
753
  const factory = registry.get(cfg.uri.scheme);
376
754
  if (!factory) {
377
755
  throw new ProviderNotFoundError(cfg.uri.scheme);
@@ -382,11 +760,12 @@ export function resolve(uriStr: string): Provider {
382
760
  /** Clear the registry (for tests). */
383
761
  export function clearRegistry(): void {
384
762
  registry.clear();
763
+ clearDeclarations();
385
764
  }
386
765
 
387
766
  // ─── Client ──────────────────────────────────────────────────────────────────
388
767
 
389
- export interface ClientOptions {
768
+ export interface ClientOptions extends LoadOptions {
390
769
  fallback?: string[];
391
770
  onRequest?: (req: Request) => void;
392
771
  onResponse?: (resp: Response, durationMs: number) => void;
@@ -398,6 +777,11 @@ export interface Client {
398
777
  complete(req: Request): Promise<Response>;
399
778
  stream(req: Request): AsyncIterable<Token>;
400
779
  callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
780
+ /**
781
+ * Streams a tool-calling completion; falls back like {@link stream},
782
+ * before the first token only.
783
+ */
784
+ streamWithTools(req: Request, tools: ToolDef[]): ToolStream;
401
785
  capabilities(): string[];
402
786
  provider(): Provider;
403
787
  close(): void;
@@ -410,13 +794,14 @@ export interface Client {
410
794
  * On fallbackable errors, it tries each fallback URI in order.
411
795
  */
412
796
  export function createLLM(uri: string, opts?: ClientOptions): Client {
413
- const cfg = loadConfig(uri);
797
+ const load: LoadOptions = { hermetic: opts?.hermetic };
798
+ const cfg = loadConfig(uri, load);
414
799
 
415
800
  // Merge fallbacks: opts > env > none
416
801
  const fallbackURIs = opts?.fallback ?? cfg.fallbacks;
417
802
 
418
803
  // Resolve primary; cache fallback providers for close()
419
- const primary = resolve(uri);
804
+ const primary = resolve(uri, load);
420
805
  const allURIs = [uri, ...fallbackURIs];
421
806
  const resolvedProviders = new Map<number, Provider>();
422
807
  resolvedProviders.set(0, primary);
@@ -424,7 +809,7 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
424
809
  function resolveAt(index: number): Provider {
425
810
  let p = resolvedProviders.get(index);
426
811
  if (!p) {
427
- p = resolve(allURIs[index]);
812
+ p = resolve(allURIs[index], load);
428
813
  resolvedProviders.set(index, p);
429
814
  }
430
815
  return p;
@@ -469,6 +854,76 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
469
854
  throw new FallbackExhaustedError(errors);
470
855
  }
471
856
 
857
+ // Routes a stream through fallback: on creation or first-token
858
+ // failure with a fallbackable/capability error, the next provider is
859
+ // tried. Once a token arrived, errors pass through.
860
+ function fallbackStream(
861
+ request: Request,
862
+ op: "stream" | "streamWithTools",
863
+ open: (p: Provider) => AsyncIterable<Token>
864
+ ): ToolStream {
865
+ let inner: AsyncIterator<Token> | null = null;
866
+ let source: AsyncIterable<Token> | null = null;
867
+ let initialized = false;
868
+
869
+ async function first(): Promise<IteratorResult<Token>> {
870
+ opts?.onRequest?.(request);
871
+ const errors: Error[] = [];
872
+ for (let i = 0; i < allURIs.length; i++) {
873
+ try {
874
+ const p = resolveAt(i);
875
+ if (typeof p[op] !== "function") {
876
+ throw new CapabilityNotSupportedError(
877
+ op,
878
+ parseURI(allURIs[i]).scheme
879
+ );
880
+ }
881
+ const iterable = open(p);
882
+ const iter = iterable[Symbol.asyncIterator]();
883
+ // Attempt first read to detect immediate failures
884
+ const head = await iter.next();
885
+ inner = iter;
886
+ source = iterable;
887
+ return head;
888
+ } catch (err) {
889
+ const e = err instanceof Error ? err : new Error(String(err));
890
+ errors.push(e);
891
+ opts?.onError?.(e);
892
+ const canContinue =
893
+ isFallbackable(e) || e instanceof CapabilityNotSupportedError;
894
+ if (!canContinue || i === allURIs.length - 1) {
895
+ if (errors.length > 1) throw new FallbackExhaustedError(errors);
896
+ throw e;
897
+ }
898
+ opts?.onFallback?.(i, i + 1, e);
899
+ }
900
+ }
901
+ throw new FallbackExhaustedError(errors);
902
+ }
903
+
904
+ return {
905
+ [Symbol.asyncIterator]() {
906
+ return {
907
+ async next(): Promise<IteratorResult<Token>> {
908
+ if (!initialized) {
909
+ initialized = true;
910
+ return first();
911
+ }
912
+ return inner!.next();
913
+ },
914
+ async return(): Promise<IteratorResult<Token>> {
915
+ await inner?.return?.();
916
+ return { value: undefined, done: true };
917
+ },
918
+ };
919
+ },
920
+ outcome(): StreamOutcome | undefined {
921
+ const s = source as Partial<ToolStream> | null;
922
+ return typeof s?.outcome === "function" ? s.outcome() : undefined;
923
+ },
924
+ };
925
+ }
926
+
472
927
  return {
473
928
  async complete(request: Request): Promise<Response> {
474
929
  opts?.onRequest?.(request);
@@ -481,63 +936,13 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
481
936
  },
482
937
 
483
938
  stream(request: Request): AsyncIterable<Token> {
484
- // Route stream through fallback. On creation or first-token
485
- // failure with a fallbackable/capability error, try next provider.
486
- return {
487
- [Symbol.asyncIterator]() {
488
- let inner: AsyncIterator<Token> | null = null;
489
- let initialized = false;
490
-
491
- return {
492
- async next(): Promise<IteratorResult<Token>> {
493
- if (!initialized) {
494
- initialized = true;
495
- opts?.onRequest?.(request);
496
-
497
- const errors: Error[] = [];
498
- for (let i = 0; i < allURIs.length; i++) {
499
- try {
500
- const p = resolveAt(i);
501
- if (
502
- !("stream" in p) ||
503
- typeof p.stream !== "function"
504
- ) {
505
- throw new CapabilityNotSupportedError(
506
- "stream",
507
- parseURI(allURIs[i]).scheme
508
- );
509
- }
510
- const iterable = p.stream(request);
511
- const iter = iterable[Symbol.asyncIterator]();
512
- // Attempt first read to detect immediate failures
513
- const first = await iter.next();
514
- inner = iter;
515
- return first;
516
- } catch (err) {
517
- const e =
518
- err instanceof Error
519
- ? err
520
- : new Error(String(err));
521
- errors.push(e);
522
- opts?.onError?.(e);
523
- const canContinue =
524
- isFallbackable(e) ||
525
- e instanceof CapabilityNotSupportedError;
526
- if (!canContinue || i === allURIs.length - 1) {
527
- if (errors.length > 1)
528
- throw new FallbackExhaustedError(errors);
529
- throw e;
530
- }
531
- opts?.onFallback?.(i, i + 1, e);
532
- }
533
- }
534
- throw new FallbackExhaustedError(errors);
535
- }
536
- return inner!.next();
537
- },
538
- };
539
- },
540
- };
939
+ return fallbackStream(request, "stream", (p) => p.stream!(request));
940
+ },
941
+
942
+ streamWithTools(request: Request, tools: ToolDef[]): ToolStream {
943
+ return fallbackStream(request, "streamWithTools", (p) =>
944
+ p.streamWithTools!(request, tools)
945
+ );
541
946
  },
542
947
 
543
948
  async callWithTools(
@@ -550,7 +955,13 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
550
955
  p.callWithTools!(request, tools)
551
956
  );
552
957
  opts?.onResponse?.(
553
- { content: resp.content, role: "assistant" },
958
+ {
959
+ content: resp.content,
960
+ role: "assistant",
961
+ usage: resp.usage,
962
+ finishReason: resp.finishReason,
963
+ thinking: resp.thinking,
964
+ },
554
965
  Date.now() - start
555
966
  );
556
967
  return resp;
@@ -561,6 +972,7 @@ export function createLLM(uri: string, opts?: ClientOptions): Client {
561
972
  if (primary.complete) caps.push("complete");
562
973
  if (primary.stream) caps.push("stream");
563
974
  if (primary.callWithTools) caps.push("callWithTools");
975
+ if (primary.streamWithTools) caps.push("streamWithTools");
564
976
  return caps;
565
977
  },
566
978