llm-large-files 0.5.0 → 0.8.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -1,17 +1,20 @@
1
1
  // Claude (the Messages API) as a model of `askWithFiles`. No SDK, like the other adapters: the
2
2
  // caller gives a key or a token, and may give the URL of a gateway that speaks the same API.
3
- import { base64, resolveHeaderSource, resolveSecret, unreachableReason, type HeaderSource, type SecretSource } from "../http.js";
4
- import { ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, type HeaderSource, type IdleWatch, type SecretSource } from "../http.js";
5
+ import { laterResult, ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
5
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
6
- import { retryAfterMs } from "../retry.js";
7
- import { parseSseJson } from "../sse.js";
7
+ import { noteNoRetry, retryAfterMs } from "../retry.js";
8
+ import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
9
+ import { estimateTokens, sliceWhole } from "../text.js";
8
10
  import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
9
11
 
10
12
  /** The API answered with an HTTP error, or could not be reached (`status` 0). `type` is the API's own word: "rate_limit_error". */
11
13
  export class AnthropicRequestError extends ModelRequestError {
12
14
  readonly type?: string;
13
- constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown; type?: string } = {}) {
14
- super(message, status, options);
15
+ constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] & { type?: string } = {}) {
16
+ // The API's own word tells the kind: "request_too_large" is a request larger than Claude takes.
17
+ super(message, status, { ...options, ...(options.type ? { code: options.type } : {}) });
15
18
  this.name = "AnthropicRequestError";
16
19
  if (options.type) this.type = options.type;
17
20
  }
@@ -93,6 +96,19 @@ export type AnthropicOptions = {
93
96
  tokenScale?: number | undefined;
94
97
  /** Milliseconds a part read may take. Defaults to 180,000. */
95
98
  timeoutMs?: number | undefined;
99
+ /**
100
+ * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
101
+ * a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
102
+ * whole at the end. A request that gets nothing for that long is aborted and sent again, once.
103
+ * Defaults to 600,000. 0 waits without end.
104
+ */
105
+ firstByteTimeoutMs?: number | undefined;
106
+ /**
107
+ * The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
108
+ * arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
109
+ * again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
110
+ */
111
+ idleTimeoutMs?: number | undefined;
96
112
  /** Names the model in usage totals. Defaults to `model`. */
97
113
  id?: string | undefined;
98
114
  fetch?: typeof fetch | undefined;
@@ -101,16 +117,32 @@ export type AnthropicOptions = {
101
117
  type Json = Record<string, any>;
102
118
  type Block = Record<string, any>;
103
119
 
104
- const STATUS_OF_TYPE: Record<string, number> = { overloaded_error: 529, rate_limit_error: 429, api_error: 500, timeout_error: 408 };
120
+ /**
121
+ * The status of an error event in a stream that began with 200, from its type. A type it does not
122
+ * know is the server's failure, 500, as an OpenAI-compatible stream's is.
123
+ */
124
+ const STATUS_OF_TYPE: Record<string, number> = {
125
+ overloaded_error: 529, rate_limit_error: 429, api_error: 500, timeout_error: 408,
126
+ invalid_request_error: 400, authentication_error: 401, billing_error: 402, permission_error: 403, not_found_error: 404, request_too_large: 413,
127
+ };
105
128
 
106
129
  /** Blocks of a model that declined part-way must not go back: only what came after the last switch to another model does. */
107
130
  const INTERNAL_BEFORE_FALLBACK = new Set(["thinking", "redacted_thinking", "tool_use", "server_tool_use"]);
108
131
 
132
+ const isThinking = (block: Block | undefined) => block?.type === "thinking" || block?.type === "redacted_thinking";
133
+
109
134
  /** The content of a reply as it goes back in the next request. */
110
135
  function echoable(content: Block[]): Block[] {
111
136
  const boundary = content.map((block) => block?.type).lastIndexOf("fallback");
112
- if (boundary < 0) return content;
113
- return content.filter((block, index) => index >= boundary || !INTERNAL_BEFORE_FALLBACK.has(block?.type));
137
+ const kept = boundary < 0 ? content : content.filter((block, index) => index >= boundary || !INTERNAL_BEFORE_FALLBACK.has(block?.type));
138
+ // A text block that a stream opened and closed with nothing in it is refused when it is sent back
139
+ // ("text content blocks must be non-empty"). One before a thinking block is left: the thinking
140
+ // is checked against what comes before it in its turn.
141
+ let lastThinking = -1;
142
+ kept.forEach((block, index) => {
143
+ if (isThinking(block)) lastThinking = index;
144
+ });
145
+ return kept.filter((block, index) => !(index > lastThinking && block?.type === "text" && !block.text && !(Array.isArray(block.citations) && block.citations.length > 0)));
114
146
  }
115
147
 
116
148
  function usageOf(usage: Json | undefined): GenerateUsage {
@@ -132,10 +164,16 @@ async function failure(response: Response): Promise<AnthropicRequestError> {
132
164
  const data = await response.json().catch(() => null) as Json | null;
133
165
  const wait = retryAfterMs(response.headers, data);
134
166
  const type = typeof data?.error?.type === "string" ? data.error.type as string : undefined;
135
- return new AnthropicRequestError(typeof data?.error?.message === "string" && data.error.message ? data.error.message : `Claude returned HTTP ${response.status}.`, response.status, {
167
+ // The spending cap of the organization comes as a rate limit (HTTP 429): no wait mends it.
168
+ const spent = data?.error?.details?.error_code === "enforced_spend_limit_reached";
169
+ const error = new AnthropicRequestError(typeof data?.error?.message === "string" && data.error.message ? data.error.message : `Claude returned HTTP ${response.status}.`, response.status, {
136
170
  ...(wait === undefined ? {} : { retryAfterMs: wait }),
137
171
  ...(type ? { type } : {}),
172
+ ...(spent ? { kind: "quota" as const } : {}),
138
173
  });
174
+ // The API says when another try cannot help, as its own SDKs read it.
175
+ if (response.headers.get("x-should-retry") === "false") noteNoRetry(error);
176
+ return error;
139
177
  }
140
178
 
141
179
  const toolResultOf = (id: string, result: ToolResult, documents: Block[]): Block => ({
@@ -146,9 +184,33 @@ const toolResultOf = (id: string, result: ToolResult, documents: Block[]): Block
146
184
  ...(typeof result.error === "string" ? { is_error: true } : {}),
147
185
  });
148
186
 
149
- /** The two messages of one tool round. `number` makes the IDs of calls that came without one. */
150
- function roundMessages(round: ModelToolRound, number: number, files: "inside" | "beside" | "none"): AnthropicMessage[] {
151
- const idOf = (call: ToolCall, index: number) => call.id ?? `toolu_${number}_${index + 1}`;
187
+ /**
188
+ * The IDs of the calls of a round, as the API takes them: of the characters `[A-Za-z0-9_-]` only,
189
+ * and each once in a request. A call that came without one, or from another provider (Kimi's
190
+ * "functions.search:0"), or that has the ID of a call of an earlier round (two questions whose
191
+ * stored rounds were numbered alike), is given one that fits. `used` holds the IDs taken so far
192
+ * in the request. The IDs of Claude's own turns are its own, and are kept as they are.
193
+ */
194
+ function callIds(round: ModelToolRound, number: number, used: Set<string>): string[] {
195
+ if (round.raw !== undefined) {
196
+ for (const block of Array.isArray(round.raw) ? round.raw as Block[] : []) {
197
+ if (block?.type === "tool_use" && typeof block.id === "string") used.add(block.id);
198
+ }
199
+ return round.calls.map((call, index) => call.id ?? `toolu_${number}_${index + 1}`);
200
+ }
201
+ return round.calls.map((call, index) => {
202
+ const base = (call.id ?? "").replace(/[^A-Za-z0-9_-]/g, "_") || `toolu_${number}_${index + 1}`;
203
+ let id = base;
204
+ for (let again = 2; used.has(id); again++) id = `${base}_${again}`;
205
+ used.add(id);
206
+ return id;
207
+ });
208
+ }
209
+
210
+ /** The two messages of one tool round, with the IDs `callIds` gave its calls. */
211
+ function roundMessages(round: ModelToolRound, ids: string[], files: "inside" | "beside" | "none"): AnthropicMessage[] {
212
+ const byCall = new Map(round.calls.map((call, index) => [call, ids[index]!]));
213
+ const idOf = (call: ToolCall, index: number) => byCall.get(call) ?? ids[index] ?? call.id ?? `toolu_${index + 1}`;
152
214
  // Its own turn goes back exactly as it came: Claude checks its thinking blocks against the conversation they were written in.
153
215
  const asked: AnthropicMessage = {
154
216
  role: "assistant",
@@ -225,12 +287,25 @@ export function fromAnthropicMessages(history: AnthropicMessage[]): ChatMessage[
225
287
  * an application that keeps its history in that form: put them between the question and its answer.
226
288
  */
227
289
  export function anthropicToolTurns(turns: ToolTurn[]): AnthropicMessage[] {
290
+ const used = new Set<string>();
228
291
  return turns.flatMap((turn, index) => {
229
- const answers = turn.calls.map(({ result, ...call }) => ({ call, result }));
230
- return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, "none");
292
+ // A call that came without an ID is given one that no round of another question has: these
293
+ // messages are kept, and sent again next to those of later questions.
294
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `toolu_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
295
+ const round: ModelToolRound = { role: "tools", calls: answers.map((answer) => answer.call), answers };
296
+ return roundMessages(round, callIds(round, index + 1, used), "none");
231
297
  });
232
298
  }
233
299
 
300
+ /**
301
+ * True when `body` asks Claude to clear old tool results on its side (context editing with
302
+ * `clear_tool_uses`), or to compact the conversation: a result shown earlier may then be gone.
303
+ */
304
+ function clearsToolResults(body: Record<string, unknown> | undefined): boolean {
305
+ const edits = (body?.context_management as { edits?: unknown } | null | undefined)?.edits;
306
+ return Array.isArray(edits) && edits.some((edit) => /^(?:clear_tool_uses|compact)/.test(String((edit as { type?: unknown } | null)?.type ?? "")));
307
+ }
308
+
234
309
  /** A Claude model for `askWithFiles`. */
235
310
  export function anthropic(options: AnthropicOptions): ModelAdapter {
236
311
  const fetchImpl = options.fetch ?? fetch;
@@ -247,6 +322,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
247
322
  const streaming = options.stream !== false;
248
323
  const eager = options.eagerInputStreaming ?? firstParty;
249
324
  const cache = options.cache === false ? undefined : { type: "ephemeral", ...(options.cache === "1h" ? { ttl: "1h" } : {}) };
325
+ const scale = options.tokenScale ?? 1.35;
250
326
  const betas = [...new Set([...(options.betas ?? []), ...(options.fallbacks ? [FALLBACK_BETA] : [])])];
251
327
 
252
328
  const headersNow = async (): Promise<Record<string, string>> => {
@@ -261,18 +337,20 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
261
337
  };
262
338
  };
263
339
 
264
- const built = new WeakMap<ModelToolRound, { number: number; messages: AnthropicMessage[] }>();
340
+ const built = new WeakMap<ModelToolRound, { key: string; messages: AnthropicMessage[] }>();
265
341
  const toMessages = (messages: ModelMessage[]): AnthropicMessage[] => {
266
342
  let rounds = 0;
343
+ const used = new Set<string>();
267
344
  return joined(messages.flatMap((message): AnthropicMessage[] => {
268
345
  if (message.role !== "tools") {
269
346
  // The API refuses an empty text block.
270
347
  return [{ role: message.role, content: message.parts.flatMap((part): Block[] => (part.native !== undefined ? [part.native as Block] : part.text ? [{ type: "text", text: part.text }] : [])) }];
271
348
  }
272
- const number = ++rounds;
349
+ const ids = callIds(message, ++rounds, used);
350
+ const key = ids.join(" ");
273
351
  let known = built.get(message);
274
- if (!known || known.number !== number) {
275
- known = { number, messages: roundMessages(message, number, files) };
352
+ if (!known || known.key !== key) {
353
+ known = { key, messages: roundMessages(message, ids, files) };
276
354
  built.set(message, known);
277
355
  }
278
356
  return known.messages;
@@ -298,13 +376,13 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
298
376
  ...options.body,
299
377
  });
300
378
 
301
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
379
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => AnthropicRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
302
380
  let response: Response;
303
381
  try {
304
- response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
382
+ response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
305
383
  } catch (error) {
306
384
  if (stopped()) throw error;
307
- throw new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
385
+ throw lost(error);
308
386
  }
309
387
  if (!response.ok) throw await failure(response);
310
388
  return response;
@@ -327,11 +405,13 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
327
405
  }];
328
406
  });
329
407
  const category = typeof stopDetails?.category === "string" ? `: ${stopDetails.category as string}` : "";
408
+ const finish = finishOfClaude(stopReason);
330
409
  return {
331
410
  text,
332
411
  calls,
333
412
  raw: echoable(content),
334
413
  ...(typeof stopReason === "string" ? { finishReason: stopReason } : {}),
414
+ ...(finish ? { finish } : {}),
335
415
  ...(refused ? { blockReason: `refusal${category}` } : {}),
336
416
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
337
417
  };
@@ -347,14 +427,21 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
347
427
  messages: [{ role: "user", content: prompt }],
348
428
  ...options.analysisBody?.(limit),
349
429
  }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
350
- const data = await response.json() as Json;
351
- onUsage?.(usageOf(data.usage as Json | undefined));
430
+ const data = await readJson<Json>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error));
431
+ const used = usageOf(data.usage as Json | undefined);
432
+ onUsage?.(used);
352
433
  const content: Block[] = Array.isArray(data.content) ? data.content : [];
434
+ const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
353
435
  return {
354
- text: content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join(""),
436
+ text,
355
437
  cutOff: data.stop_reason === "max_tokens",
438
+ // Claude stopped before the end, for its safety rules or because its window was full: what
439
+ // it wrote is not all there is. (Not `cutOff`: a larger output limit would not help.)
440
+ stopped: data.stop_reason === "refusal" || data.stop_reason === "model_context_window_exceeded",
356
441
  ...(typeof data.stop_reason === "string" ? { reason: data.stop_reason } : {}),
357
- thoughts: 0,
442
+ // Claude does not count its thoughts apart: they are what it wrote besides its text, when it
443
+ // thought. A reply that thought most of its limit away is then asked for with a larger one.
444
+ thoughts: content.some(isThinking) ? Math.max(0, (used.outputTokens ?? 0) - Math.ceil(estimateTokens(text) * scale)) : 0,
358
445
  };
359
446
  };
360
447
  return completeWithinLimit(`${url}|${options.model}`, maxOutputTokens, send, { signal, onTruncated });
@@ -367,21 +454,50 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
367
454
  maxRequestBytes: options.maxRequestBytes ?? 32_000_000,
368
455
  toolFiles: files,
369
456
  pageTokens: options.pageTokens ?? 3_500,
370
- tokenScale: options.tokenScale ?? 1.35,
457
+ tokenScale: scale,
371
458
  outputTokens: maxTokens,
372
459
  // Claude checks its thinking blocks against the conversation they were written in: an
373
460
  // earlier turn that is rewritten makes the later ones invalid.
374
461
  appendOnly: true,
462
+ // With context editing, Claude may no longer have a result shown earlier: none is pointed to.
463
+ ...(clearsToolResults(options.body) ? { clearsToolResults: true } : {}),
375
464
  },
376
465
  requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, streaming))),
377
466
  generateText,
378
467
 
379
468
  async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
380
- const response = await post(bodyOf(request, streaming), hooks.signal, () => Boolean(hooks.signal?.aborted));
469
+ // A key or token is fetched before the watch starts: the time that takes is not the model's.
470
+ const headers = await headersNow();
471
+ const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
472
+ // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
473
+ const lost = (error: unknown) => (watch.expired ? new AnthropicRequestError(`Claude sent nothing for ${Math.round(watch.waitedMs / 1_000)} s.`, 0, { kind: "timeout" }) : unreachable(error));
474
+ try {
475
+ // The headers are no piece of the reply: a server may send them at once and then think.
476
+ const response = await post(bodyOf(request, streaming), watch.signal, () => Boolean(hooks.signal?.aborted), lost, headers);
477
+ return await readReply(response, hooks, watch, lost);
478
+ } finally {
479
+ watch.stop();
480
+ }
481
+ },
482
+ };
483
+
484
+ /** The reply of a request that was answered: streamed, or in one piece. */
485
+ async function readReply(answer: Response, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => AnthropicRequestError): Promise<ModelReply> {
486
+ {
381
487
  const problems = new Map<number, string>();
382
- if (!(streaming && response.body && (response.headers.get("content-type") ?? "").includes("text/event-stream"))) {
488
+ let response = answer;
489
+ let events = false;
490
+ if (streaming && answer.body) {
491
+ try {
492
+ ({ events, response } = await streamedReply(answer, watch));
493
+ } catch (error) {
494
+ if (hooks.signal?.aborted) throw error;
495
+ throw noteCutReply(lost(error));
496
+ }
497
+ }
498
+ if (!(events && response.body)) {
383
499
  // In one piece: streaming is off, or the gateway answered without it.
384
- const data = await response.json() as Json;
500
+ const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, (error) => notJson(answer, error));
385
501
  const content: Block[] = Array.isArray(data.content) ? data.content : [];
386
502
  const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
387
503
  if (text) hooks.onText?.(text);
@@ -389,17 +505,23 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
389
505
  }
390
506
  const content: Block[] = [];
391
507
  const inputs = new Map<number, string>();
508
+ /** Blocks whose stop event came: a call whose block was never closed did not arrive whole. */
509
+ const closed = new Set<number>();
392
510
  let text = "";
393
511
  let stopReason: unknown;
394
512
  let stopDetails: Json | undefined;
395
513
  let usage: Json | undefined;
514
+ // `message_stop` ends the reply: a gateway that leaves the connection open after it is not waited for.
515
+ const end = replyEnd(watch);
396
516
  try {
397
- for await (const event of parseSseJson<Json>(response.body)) {
517
+ for await (const event of parseSseJson<Json>(response.body, { onData: watch.pulse, signal: end.signal })) {
398
518
  if (event.type === "error") {
399
519
  const type = typeof event.error?.type === "string" ? event.error.type as string : undefined;
400
- throw new AnthropicRequestError(String(event.error?.message ?? "Claude reported an error."), (type && STATUS_OF_TYPE[type]) || response.status, type ? { type } : {});
520
+ throw new AnthropicRequestError(String(event.error?.message ?? "Claude reported an error."), (type && STATUS_OF_TYPE[type]) || 500, type ? { type } : {});
401
521
  }
402
- if (event.type === "message_start") {
522
+ if (event.type === "message_stop") {
523
+ end.reached();
524
+ } else if (event.type === "message_start") {
403
525
  usage = { ...event.message?.usage };
404
526
  } else if (event.type === "content_block_start" && typeof event.index === "number") {
405
527
  content[event.index] = { ...event.content_block };
@@ -420,6 +542,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
420
542
  (block.citations ??= []).push(delta.citation);
421
543
  }
422
544
  } else if (event.type === "content_block_stop" && typeof event.index === "number") {
545
+ closed.add(event.index);
423
546
  const written = inputs.get(event.index);
424
547
  const block = content[event.index];
425
548
  if (block?.type === "tool_use" && written !== undefined && written.trim()) {
@@ -430,25 +553,62 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
430
553
  block.input = input;
431
554
  } catch {
432
555
  block.input = {};
433
- problems.set(event.index, `The arguments of this call were not valid JSON, and it was not run: ${written.slice(0, 300)}. Send the call again.`);
556
+ problems.set(event.index, `The arguments of this call were not valid JSON, and it was not run: ${sliceWhole(written, 300)}. Send the call again.`);
434
557
  }
435
558
  }
436
559
  } else if (event.type === "message_delta") {
437
560
  stopReason = event.delta?.stop_reason ?? stopReason;
438
561
  stopDetails = (event.delta?.stop_details as Json | undefined) ?? stopDetails;
439
- usage = { ...usage, ...event.usage };
562
+ // Only the numbers it has: the input fields of message_delta may be null, and the real
563
+ // ones are message_start's (the official SDK keeps them the same way).
564
+ // (As own properties, whatever their names: no key of the provider's sets a prototype.)
565
+ usage = { ...usage, ...Object.fromEntries(Object.entries((event.usage ?? {}) as Json).filter(([, value]) => value !== null && value !== undefined)) };
440
566
  }
441
567
  }
442
568
  } catch (error) {
443
- if (hooks.signal?.aborted || error instanceof AnthropicRequestError) throw error;
444
- // The connection went while the answer was on its way.
445
- throw new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
569
+ // The reply ended with `message_stop`, and the connection then stayed open, or broke rather
570
+ // than end: what came before it is whole.
571
+ const whole = end.left(error) || (end.whole && !hooks.signal?.aborted && !(error instanceof AnthropicRequestError));
572
+ if (!whole) {
573
+ if (hooks.signal?.aborted || error instanceof AnthropicRequestError) throw error;
574
+ // An event too long to read would come again: it is not sent again, like a page in the reply's place.
575
+ if (error instanceof SseEventTooLongError) throw new AnthropicRequestError(eventTooLongMessage("Claude's", error), answer.status, { kind: "invalid", cause: error });
576
+ // The connection went while the answer was on its way, or nothing came for the whole wait.
577
+ throw noteCutReply(lost(error));
578
+ }
579
+ } finally {
580
+ end.dispose();
446
581
  }
582
+ // Every reply ends with the reason it stopped. A stream that closed without one was cut short
583
+ // (a gateway that ended it as if it were whole): its text is not the answer, and it is sent
584
+ // again like a connection that failed, when none of it was shown.
585
+ if (stopReason === undefined) throw noteCutReply(new AnthropicRequestError("Claude's reply ended before it was complete.", 0));
586
+ content.forEach((block, index) => {
587
+ if ((block?.type === "tool_use" || block?.type === "server_tool_use") && !closed.has(index)) problems.set(index, "This call did not arrive whole, and was not run. Send it again.");
588
+ });
447
589
  const blocks = content.filter(Boolean);
448
590
  // The problems were noted by the place of the block in the stream: the same place, with no gaps, in what is kept.
449
591
  const placed = new Map<number, string>();
450
592
  for (const [index, problem] of problems) placed.set(blocks.indexOf(content[index]!), problem);
451
593
  return replyOf(blocks, stopReason, stopDetails, usage, placed, text);
452
- },
453
- };
594
+ }
595
+ }
596
+ }
597
+
598
+ /** A body that came with a status of success but is no JSON (a gateway's page): it is not sent again. */
599
+ function notJson(response: Response, error: unknown): AnthropicRequestError {
600
+ return new AnthropicRequestError(notJsonMessage("Claude's", response), response.status, { kind: "invalid", cause: error });
601
+ }
602
+
603
+ /** A request that got no answer: the reason, without the stack of the HTTP client. */
604
+ function unreachable(error: unknown): AnthropicRequestError {
605
+ return new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });
606
+ }
607
+
608
+ /** `stop_reason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
609
+ function finishOfClaude(reason: unknown): ModelReply["finish"] {
610
+ if (reason === "end_turn" || reason === "tool_use" || reason === "stop_sequence") return "complete";
611
+ if (reason === "max_tokens" || reason === "model_context_window_exceeded") return "cut";
612
+ if (reason === "refusal") return "filtered";
613
+ return undefined;
454
614
  }