llm-large-files 0.4.1 → 0.7.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 (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/src/errors.ts CHANGED
@@ -30,6 +30,23 @@ export class DocumentStoreError extends Error {
30
30
  }
31
31
  }
32
32
 
33
+ /**
34
+ * The errors a store threw while `ingest` wrote a document. `ingest` passes them on as they are,
35
+ * and the upload handler tells them apart from a file that could not be read: their message is
36
+ * the store's own (a database driver's names its host), not words for a user.
37
+ */
38
+ const storeWriteFailures = new WeakSet<object>();
39
+
40
+ /** Takes note that a store threw this error while it wrote a document. */
41
+ export function noteStoreWriteFailure(error: unknown): void {
42
+ if (typeof error === "object" && error !== null) storeWriteFailures.add(error);
43
+ }
44
+
45
+ /** Whether a store threw this error while it wrote a document (see `noteStoreWriteFailure`). */
46
+ export function isStoreWriteFailure(error: unknown): boolean {
47
+ return typeof error === "object" && error !== null && storeWriteFailures.has(error);
48
+ }
49
+
33
50
  /**
34
51
  * What to tell a model, or a user, about an error: its message, unless it is a system error, whose
35
52
  * message names a path or a host of the server. Of that one only the code is passed on.
package/src/events.ts ADDED
@@ -0,0 +1,442 @@
1
+ // What a question or an ingest does while it runs, as typed data in order. The callbacks of
2
+ // earlier versions (onText, onActivity, onStep) still get the same strings, at the same moments.
3
+ import type { AskResult } from "./ask.js";
4
+ import { DocumentStoreError } from "./errors.js";
5
+ import type { Evidence } from "./evidence.js";
6
+ import { modelFailureReason } from "./map-reduce.js";
7
+ import type { ModelErrorKind, ModelReply, ModelUsage, ToolTurn } from "./model.js";
8
+ import type { DocumentFormat, DocumentMeta, DocumentSummary, ToolResult } from "./types.js";
9
+
10
+ /** What every event carries. */
11
+ export type EventBase = {
12
+ /** 1 for the first event of a run, then one more for each event after it: no gaps, no repeats. */
13
+ seq: number;
14
+ /** The run the event belongs to: the `runId` you gave, or one made for it ("run_…" for a question, "ing_…" for an ingest). */
15
+ runId: string;
16
+ /** When it was emitted, in milliseconds since 1970 (`Date.now()`). */
17
+ time: number;
18
+ };
19
+
20
+ /** A document as an event names it. */
21
+ export type DocumentRef = {
22
+ id: string;
23
+ name: string;
24
+ format: DocumentFormat;
25
+ estimatedTokens: number;
26
+ pages?: number;
27
+ };
28
+
29
+ /** An error as an event carries it: plain data, safe to send to a browser. */
30
+ export type EventError = {
31
+ /**
32
+ * A message your users may see. A model error is told by its kind and status ("The model was
33
+ * busy (HTTP 429)."), never in the provider's own words, which can name projects, hosts or
34
+ * keys: those stay on the error that is thrown, for your logs. A storage error is told by its
35
+ * code only.
36
+ */
37
+ message: string;
38
+ /** For a model error: what kind it is (`errorKindOf`). */
39
+ kind?: ModelErrorKind;
40
+ /** For an HTTP error: its status. 0 when no answer came. */
41
+ status?: number;
42
+ /** The error's class name: "ModelRequestError", "AbortError", "DocumentsNotFoundError"… */
43
+ name?: string;
44
+ };
45
+
46
+ /**
47
+ * Which model a request goes to, and for what:
48
+ * - "tools": the one model of a question without an explorer, in a turn where it may call tools;
49
+ * - "explorer": the explorer model, which only calls tools;
50
+ * - "answer": the model that writes the answer (with or without an explorer);
51
+ * - "reader": a request of a whole-file read (`analyze_whole_document`), made for one tool call.
52
+ */
53
+ export type RequestRole = "tools" | "explorer" | "answer" | "reader";
54
+
55
+ /**
56
+ * Why a request is made:
57
+ * - "turn": a turn of the tool loop;
58
+ * - "nudge": the same turn asked again after an empty or malformed reply;
59
+ * - "closing": the request for the answer after the tools;
60
+ * - "answer_again": the answer asked for again after it came back without text;
61
+ * - "direct": the one request of a question that needs no tools;
62
+ * - "part", "merge", "final": a whole-file read reading one part, combining notes, writing its answer.
63
+ */
64
+ export type RequestPurpose = "turn" | "nudge" | "closing" | "answer_again" | "direct" | "part" | "merge" | "final";
65
+
66
+ /**
67
+ * How a tool call ended:
68
+ * - "ok": it ran and returned a result;
69
+ * - "error": it ran, or was checked, and returned `{ error }` (bad arguments, a document it cannot
70
+ * read, a regex that took too long…), or it was ended because its turn failed (the question was
71
+ * stopped, or a listener threw): then the model was sent nothing;
72
+ * - "refused": it was not run, for a limit of the question (cost, room, reads of a whole file);
73
+ * - "already_shown": it repeated a call whose result is still in the conversation, and was answered
74
+ * with a pointer to it;
75
+ * - "not_run": the turn had more calls than `limits.callsPerTurn`.
76
+ */
77
+ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run";
78
+
79
+ /**
80
+ * Something the run did that is not a request or a tool call:
81
+ * - "searching_instead": documents too large to send whole are searched instead;
82
+ * - "writing_answer": the tools are done and the answer is asked for;
83
+ * - "replanned": the question started again with less in the prompt (a smaller window than thought);
84
+ * - "room_made": the request was too large for the model, was made smaller and sent again;
85
+ * - "nudged": an empty or malformed reply was asked for again;
86
+ * - "results_shortened": older tool results were shortened to make room;
87
+ * - "answer_again": the answer came back without text and was asked for again;
88
+ * - "calls_not_run": a turn had more calls than `limits.callsPerTurn`;
89
+ * - "budget_reached": `limits.inputTokens` or `limits.requests` was reached, so no more tools run;
90
+ * - "no_room": there is no room left in the conversation for another tool result;
91
+ * - "blocked": the provider refused the prompt (`AskResult.blockReason`).
92
+ */
93
+ export type NoticeCode =
94
+ | "searching_instead"
95
+ | "writing_answer"
96
+ | "replanned"
97
+ | "room_made"
98
+ | "nudged"
99
+ | "results_shortened"
100
+ | "answer_again"
101
+ | "calls_not_run"
102
+ | "budget_reached"
103
+ | "no_room"
104
+ | "blocked";
105
+
106
+ /**
107
+ * Where a notice went in the callbacks of earlier versions: "activity" to `onActivity`, "step" to
108
+ * `onStep` (and `AskResult.steps`), "none" to neither (new in 0.7.0).
109
+ */
110
+ export type NoticeDisplay = "activity" | "step" | "none";
111
+
112
+ /**
113
+ * The result of a question as `run.finish` and `run.error` carry it: an `AskResult` without
114
+ * `toolTurns`, which hold the text of the documents the tools returned, and with its plan naming
115
+ * the documents only (`DocumentRef`). With
116
+ * `AskOptions.eventResults: true` they are there too. The result `askWithFiles` returns (and
117
+ * `askStream`'s `result`, and `partialResultOf`) always has them: keep them from there.
118
+ */
119
+ export type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
120
+ toolTurns?: ToolTurn[];
121
+ /**
122
+ * Which documents went in whole and which were searched, named as `DocumentRef`s: their full
123
+ * `DocumentMeta` (owner, outline headings, the commonest lines of a log) is left out unless
124
+ * `eventResults` is true. The returned result has the full plan.
125
+ */
126
+ plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
127
+ };
128
+
129
+ /** The events of a question (`askWithFiles`, `askStream`), in the order they happen. */
130
+ export type AskEvent =
131
+ /** Always first. */
132
+ | (EventBase & {
133
+ type: "run.start";
134
+ /** The adapter ids: the model that answers, and the explorer when there is one. */
135
+ models: { answer: string; explorer?: string };
136
+ documentIds: string[];
137
+ })
138
+ /**
139
+ * Which documents go into the prompt whole and which are searched. After `run.start`, before any
140
+ * request. Again after a "replanned" notice.
141
+ */
142
+ | (EventBase & { type: "plan"; inline: DocumentRef[]; searchable: DocumentRef[] })
143
+ /** A model request starts. Its retries are `retry` events with the same `requestId`. */
144
+ | (EventBase & {
145
+ type: "request.start";
146
+ /** Unique in the run: "req_1", "req_2"… */
147
+ requestId: string;
148
+ role: RequestRole;
149
+ purpose: RequestPurpose;
150
+ /** The adapter id of the model the request goes to. */
151
+ model: string;
152
+ /** For a request of the chat (not "reader"): its number in the question, from 1, as `AskResult.turns` counts. */
153
+ turn?: number;
154
+ /** For a "reader" request: the tool call of the whole-file read it belongs to. */
155
+ callId?: string;
156
+ /** For a "reader" request: which part ("part 3 of 12"), or which round of combining notes. */
157
+ detail?: string;
158
+ /** For a request of the chat: the library's estimate of its input tokens, before it is sent. */
159
+ estimatedInputTokens?: number;
160
+ })
161
+ /** A model request ended, after any retries. */
162
+ | (EventBase & {
163
+ type: "request.end";
164
+ requestId: string;
165
+ /** From `request.start` to now, retries and their waits included. */
166
+ ms: number;
167
+ outcome: "ok" | "error";
168
+ /** What the provider said this request used (all its HTTP sends, for a "reader" request). */
169
+ usage?: Partial<ModelUsage>;
170
+ /** How the reply ended, in the library's words. */
171
+ finish?: ModelReply["finish"];
172
+ /** How the reply ended, in the provider's words. */
173
+ finishReason?: string;
174
+ /** How many tool calls the reply asked for. */
175
+ toolCalls?: number;
176
+ /** With outcome "error": why. A request that failed may still be followed by others (an overflow made smaller, a part read in halves). */
177
+ error?: EventError;
178
+ })
179
+ /**
180
+ * A model request failed and is sent again after `delayMs`. For a request of the chat, earlier
181
+ * versions told `onActivity` the same in `message`; the retries of a "reader" request (a
182
+ * whole-file read) are told only here.
183
+ */
184
+ | (EventBase & {
185
+ type: "retry";
186
+ requestId: string;
187
+ /** 1 for the first retry. */
188
+ attempt: number;
189
+ delayMs: number;
190
+ error: EventError;
191
+ message: string;
192
+ })
193
+ /** Answer text as it arrives: what `onText` gets. Joined, the deltas of a run are `AskResult.text`. */
194
+ | (EventBase & { type: "text"; requestId: string; delta: string })
195
+ /**
196
+ * A tool call starts to run, or is settled without running (refused, already shown, not run).
197
+ * Calls of one turn run a few at a time, so their starts and ends interleave.
198
+ */
199
+ | (EventBase & {
200
+ type: "tool.start";
201
+ /** Unique in the run: "call_1", "call_2"… The provider's own id, when it sent one, is `providerCallId`. */
202
+ callId: string;
203
+ providerCallId?: string;
204
+ /** The tool's name: "search_document", "read_document"… */
205
+ tool: string;
206
+ /** The arguments as the model sent them. */
207
+ args: Record<string, unknown>;
208
+ /** One line of plain text: "Search app.log (exact) for “timeout”". */
209
+ label: string;
210
+ /** The document the call names, when it names one. */
211
+ documentId?: string;
212
+ /** The turn of the tool loop the call came in, from 1. */
213
+ round: number;
214
+ })
215
+ /** Progress of a tool call that takes long: a whole-file read. Between its `tool.start` and `tool.end`. */
216
+ | (EventBase & {
217
+ type: "tool.progress";
218
+ callId: string;
219
+ /** "map": parts read (its requests have purpose "part"); "reduce": notes combined or the answer written ("merge", "final"). */
220
+ stage: "map" | "reduce";
221
+ done: number;
222
+ total: number;
223
+ /** "Reading app.log: part 3 of 12". */
224
+ message: string;
225
+ })
226
+ /** A tool call ended. Ends come in call order within a turn. */
227
+ | (EventBase & {
228
+ type: "tool.end";
229
+ callId: string;
230
+ outcome: ToolOutcome;
231
+ /** From `tool.start` to now. */
232
+ ms: number;
233
+ /**
234
+ * The finished step, as `onStep` gets it. Absent for "not_run" (one "calls_not_run" notice
235
+ * says it for all of them), and for a call ended because its turn failed (see `outcome`).
236
+ */
237
+ step?: string;
238
+ /** What the call showed the model, as in `AskResult.evidence` (with this `callId`). */
239
+ evidence?: Evidence;
240
+ /** The characters of the JSON result the model was sent. */
241
+ resultCharacters?: number;
242
+ /**
243
+ * When the result the model was sent is an error (outcomes "error", "refused", "not_run"):
244
+ * its message. For a call ended because its turn failed: why, as in `EventError.message`.
245
+ */
246
+ error?: string;
247
+ /** The result itself. Only with `AskOptions.eventResults: true`: it holds document text. */
248
+ result?: ToolResult;
249
+ })
250
+ | (EventBase & { type: "notice"; code: NoticeCode; message: string; display: NoticeDisplay })
251
+ /** Always last when the question returns. Nothing comes after it. */
252
+ | (EventBase & { type: "run.finish"; result: EventResult })
253
+ /**
254
+ * Always last when the question throws (an abort included). Nothing comes after it. `partial` is
255
+ * what `partialResultOf(error)` gives: what the question found before it failed.
256
+ */
257
+ | (EventBase & { type: "run.error"; error: EventError; partial?: EventResult });
258
+
259
+ /** The stages of an ingest that report progress. Not every file goes through each. */
260
+ export type IngestStage = "decode" | "extract" | "check" | "pictures" | "prepare" | "index" | "store";
261
+
262
+ /** The events of an ingest (`IngestInput.onEvent`), in the order they happen. */
263
+ export type IngestEvent =
264
+ /** Always first. `format` is what the name and type say; a text file can still become a log. */
265
+ | (EventBase & { type: "ingest.start"; name: string; format: DocumentFormat; bytes: number })
266
+ /**
267
+ * How far a stage is. `total` is absent when it is not known. Sent at most about every 12 ms, and
268
+ * once more when a stage ends; a stage with no progress to report may send none.
269
+ */
270
+ | (EventBase & {
271
+ type: "ingest.progress";
272
+ stage: IngestStage;
273
+ done: number;
274
+ total?: number;
275
+ unit: "pages" | "parts" | "bytes" | "characters";
276
+ })
277
+ /** Always last when the ingest stores the document. */
278
+ | (EventBase & { type: "ingest.finish"; document: DocumentSummary })
279
+ /** Always last when the ingest throws (a refusal or an abort included). */
280
+ | (EventBase & { type: "ingest.error"; error: EventError });
281
+
282
+ /** Any event of this library. */
283
+ export type LibraryEvent = AskEvent | IngestEvent;
284
+
285
+ /** An event without the fields the emitter stamps on it. */
286
+ export type UnstampedEvent<E> = E extends unknown ? Omit<E, keyof EventBase> : never;
287
+
288
+ const TERMINAL = new Set(["run.finish", "run.error", "ingest.finish", "ingest.error"]);
289
+
290
+ /** A run id: the prefix, "_" and 16 hex digits ("run_3f9a…"). */
291
+ export function newRunId(prefix = "run"): string {
292
+ const random = globalThis.crypto?.randomUUID?.().replace(/-/g, "").slice(0, 16)
293
+ ?? Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
294
+ return `${prefix}_${random}`;
295
+ }
296
+
297
+ /** An error as plain event data. */
298
+ export function eventErrorOf(error: unknown, message?: string): EventError {
299
+ // It never throws: an error whose fields throw when read (a getter, a proxy) is told plainly.
300
+ try {
301
+ const record = (typeof error === "object" && error !== null ? error : {}) as { kind?: unknown; status?: unknown; name?: unknown };
302
+ const out: EventError = { message: message ?? userMessageOf(error) };
303
+ if (typeof record.kind === "string") out.kind = record.kind as ModelErrorKind;
304
+ if (typeof record.status === "number") out.status = record.status;
305
+ if (typeof record.name === "string" && record.name) out.name = record.name;
306
+ return out;
307
+ } catch {
308
+ return { message: message ?? SOMETHING_WENT_WRONG };
309
+ }
310
+ }
311
+
312
+ const SOMETHING_WENT_WRONG = "Something went wrong.";
313
+
314
+ /**
315
+ * A message for users: a model error by its kind and status, a storage error by its code, the
316
+ * library's own errors (refusals, a stop) as they are written, and anything that is not an
317
+ * `Error` as "Something went wrong."
318
+ */
319
+ function userMessageOf(error: unknown): string {
320
+ if (error instanceof DocumentStoreError) return error.message;
321
+ if (typeof error !== "object" || error === null) return SOMETHING_WENT_WRONG;
322
+ const record = error as { kind?: unknown; status?: unknown; code?: unknown; syscall?: unknown; message?: unknown };
323
+ // A model error: the provider's words stay on the error.
324
+ if (typeof record.kind === "string" || typeof record.status === "number") return modelFailureReason(error);
325
+ // A system error (ENOENT, EACCES…): its message names paths of the server.
326
+ if (typeof record.code === "string" && typeof record.syscall === "string") return `The file could not be read from storage (${record.code}).`;
327
+ if (!(error instanceof Error) && !(typeof DOMException !== "undefined" && error instanceof DOMException)) return SOMETHING_WENT_WRONG;
328
+ return typeof record.message === "string" && record.message ? record.message : SOMETHING_WENT_WRONG;
329
+ }
330
+
331
+ /**
332
+ * Stamps events with `seq`, `runId` and `time`, and hands them to one listener. After a terminal
333
+ * event (`run.finish`, `run.error`, `ingest.finish`, `ingest.error`) it drops everything: work
334
+ * that goes on after a question stopped (a part read still running) is never reported.
335
+ */
336
+ export class EventEmitter<E extends { type: string }> {
337
+ private seq = 0;
338
+ private closed = false;
339
+
340
+ constructor(
341
+ readonly runId: string,
342
+ private readonly listener: ((event: E) => void) | undefined,
343
+ ) {}
344
+
345
+ /** False when nobody listens or the run has ended: callers may skip building an event. */
346
+ get active(): boolean {
347
+ return this.listener !== undefined && !this.closed;
348
+ }
349
+
350
+ /** True once a terminal event was emitted. */
351
+ get ended(): boolean {
352
+ return this.closed;
353
+ }
354
+
355
+ emit(event: UnstampedEvent<E>): void {
356
+ if (this.closed) return;
357
+ if (TERMINAL.has(event.type)) this.closed = true;
358
+ if (!this.listener) return;
359
+ this.listener({ ...event, seq: ++this.seq, runId: this.runId, time: Date.now() } as unknown as E);
360
+ }
361
+ }
362
+
363
+ /** The events of a run as an async iterable, and how the run ended. */
364
+ export type EventStream<E, T> = AsyncIterable<E> & {
365
+ /** What the run returned. Rejects with its error; awaiting it is optional (it never goes unhandled). */
366
+ result: Promise<T>;
367
+ /** Stops the run: its signal aborts, and the stream ends after the run's last event. */
368
+ abort(reason?: unknown): void;
369
+ };
370
+
371
+ /**
372
+ * Runs `run` at once and gives its events as an async iterable. Events wait in memory until they
373
+ * are read. Leaving the loop early (`break`, `return`, a throw) aborts the run. The iterable ends
374
+ * after the run's last event; it does not throw when the run fails: read the `run.error` event, or
375
+ * await `result`. It can be iterated once.
376
+ */
377
+ export function eventStream<E, T>(
378
+ run: (onEvent: (event: E) => void, signal: AbortSignal) => Promise<T>,
379
+ options: { signal?: AbortSignal | undefined } = {},
380
+ ): EventStream<E, T> {
381
+ const controller = new AbortController();
382
+ const outer = options.signal;
383
+ const onOuterAbort = () => controller.abort(outer?.reason);
384
+ if (outer?.aborted) controller.abort(outer.reason);
385
+ else outer?.addEventListener("abort", onOuterAbort, { once: true });
386
+
387
+ const queue: E[] = [];
388
+ // Calls of next() waiting for an event, oldest first: each gets the next event in turn.
389
+ const waiters: Array<(result: IteratorResult<E>) => void> = [];
390
+ let finished = false;
391
+ // Set by return(): the reader left, so nothing more is queued or handed out.
392
+ let closed = false;
393
+ const settleWaiters = () => {
394
+ for (const resolve of waiters.splice(0)) resolve({ value: undefined, done: true });
395
+ };
396
+ const onEvent = (event: E) => {
397
+ if (closed) return;
398
+ const waiter = waiters.shift();
399
+ if (waiter) waiter({ value: event, done: false });
400
+ else queue.push(event);
401
+ };
402
+
403
+ let started: Promise<T>;
404
+ try {
405
+ started = run(onEvent, controller.signal);
406
+ } catch (error) {
407
+ started = Promise.reject(error);
408
+ }
409
+ const result = started.finally(() => {
410
+ finished = true;
411
+ outer?.removeEventListener("abort", onOuterAbort);
412
+ // Every event came before the run settled: whoever still waits gets the end.
413
+ settleWaiters();
414
+ });
415
+ result.catch(() => undefined);
416
+
417
+ let iterated = false;
418
+ return {
419
+ result,
420
+ abort(reason?: unknown) {
421
+ controller.abort(reason ?? new DOMException("The run was stopped.", "AbortError"));
422
+ },
423
+ [Symbol.asyncIterator](): AsyncIterator<E> {
424
+ if (iterated) throw new TypeError("These events can be read once.");
425
+ iterated = true;
426
+ return {
427
+ next(): Promise<IteratorResult<E>> {
428
+ if (queue.length > 0) return Promise.resolve({ value: queue.shift()!, done: false });
429
+ if (finished || closed) return Promise.resolve({ value: undefined, done: true });
430
+ return new Promise((resolve) => waiters.push(resolve));
431
+ },
432
+ async return(): Promise<IteratorResult<E>> {
433
+ if (!finished && !closed) controller.abort(new DOMException("The events stopped being read.", "AbortError"));
434
+ closed = true;
435
+ queue.length = 0;
436
+ settleWaiters();
437
+ return { value: undefined, done: true };
438
+ },
439
+ };
440
+ },
441
+ };
442
+ }
@@ -0,0 +1,165 @@
1
+ // What the tools showed a model, as data: the trail an application can keep with an answer, and
2
+ // the short stand-in a tool result leaves behind when the request runs out of room.
3
+ import type { ToolCall } from "./model.js";
4
+ import { sliceWhole } from "./text.js";
5
+ import { TOOL_NAMES } from "./tools.js";
6
+ import type { ToolResult } from "./types.js";
7
+
8
+ /** A range of lines or pages, 1-based, both ends included. */
9
+ export type NumberRange = [from: number, to: number];
10
+
11
+ /** What one tool call showed the model of one document. */
12
+ export type Evidence = {
13
+ /** The tool that was called: "search_document", "read_document", and so on. */
14
+ tool: string;
15
+ documentId: string;
16
+ /** The file's name. */
17
+ document?: string;
18
+ /** The lines the model was shown, as ranges in order. */
19
+ lines?: NumberRange[];
20
+ /** The pages it looked at (`view_pages`), or the pages those lines are on, where the tool said. */
21
+ pages?: NumberRange[];
22
+ /** What was searched for, or the task of a whole-file read. */
23
+ query?: string;
24
+ /** "keywords", "exact" or "regex", for a search. */
25
+ mode?: string;
26
+ /** For an exact or regex search: how many lines match in the whole file. More than were shown, often. */
27
+ totalMatchingLines?: number;
28
+ /** True for a whole-file read: other model calls read every line, and the model saw their answer. */
29
+ whole?: boolean;
30
+ /** The tool call it came from, as its events name it ("call_3"). Set by `askWithFiles`. New in 0.7.0. */
31
+ callId?: string;
32
+ };
33
+
34
+ /** "12-14", "12" or 12 as a range. */
35
+ function rangeOf(value: unknown): NumberRange | undefined {
36
+ if (typeof value === "number" && Number.isFinite(value)) return [value, value];
37
+ if (typeof value !== "string") return undefined;
38
+ const match = /^(\d+)(?:-(\d+))?$/.exec(value.trim());
39
+ if (!match) return undefined;
40
+ const from = Number(match[1]);
41
+ const to = match[2] === undefined ? from : Number(match[2]);
42
+ return to >= from ? [from, to] : undefined;
43
+ }
44
+
45
+ /** Ranges in order, with those that overlap or touch made one. */
46
+ export function mergeRanges(ranges: NumberRange[]): NumberRange[] {
47
+ const sorted = [...ranges].sort((left, right) => left[0] - right[0] || left[1] - right[1]);
48
+ const merged: NumberRange[] = [];
49
+ for (const [from, to] of sorted) {
50
+ const last = merged.at(-1);
51
+ if (last && from <= last[1] + 1) last[1] = Math.max(last[1], to);
52
+ else merged.push([from, to]);
53
+ }
54
+ return merged;
55
+ }
56
+
57
+ const defined = <T>(values: Array<T | undefined>): T[] => values.filter((value): value is T => value !== undefined);
58
+
59
+ /**
60
+ * What a tool call showed of a document, read from the call and its result. Undefined for a call
61
+ * that failed, named no document, or was answered with a stand-in for a dropped result.
62
+ */
63
+ export function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undefined {
64
+ const documentId = call.args.document_id;
65
+ if (typeof documentId !== "string" || !documentId || typeof result.error === "string" || result.dropped === true) return undefined;
66
+ const entry: Evidence = { tool: call.name, documentId, ...(typeof result.document === "string" ? { document: result.document } : {}) };
67
+ const withRanges = (lines: NumberRange[], pages: NumberRange[]): Evidence => ({
68
+ ...entry,
69
+ ...(lines.length > 0 ? { lines: mergeRanges(lines) } : {}),
70
+ ...(pages.length > 0 ? { pages: mergeRanges(pages) } : {}),
71
+ });
72
+ switch (call.name) {
73
+ case TOOL_NAMES.read:
74
+ return withRanges(defined([rangeOf(result.lines)]), defined([rangeOf(result.pages)]));
75
+ case TOOL_NAMES.search: {
76
+ const query = typeof call.args.query === "string" ? { query: call.args.query } : {};
77
+ const mode = typeof result.mode === "string" ? { mode: result.mode } : {};
78
+ if (Array.isArray(result.passages)) {
79
+ const passages = result.passages as Array<{ lines?: unknown; pages?: unknown }>;
80
+ return { ...withRanges(defined(passages.map((passage) => rangeOf(passage.lines))), defined(passages.map((passage) => rangeOf(passage.pages)))), ...query, ...mode };
81
+ }
82
+ const matches = (Array.isArray(result.matches) ? result.matches : []) as Array<{ line?: unknown; page?: unknown; before?: unknown; after?: unknown }>;
83
+ const count = (value: unknown) => (Array.isArray(value) ? value.length : 0);
84
+ const lines = defined(matches.map((match): NumberRange | undefined => (typeof match.line === "number" ? [Math.max(1, match.line - count(match.before)), match.line + count(match.after)] : undefined)));
85
+ return {
86
+ ...withRanges(lines, defined(matches.map((match) => rangeOf(match.page)))),
87
+ ...query,
88
+ ...mode,
89
+ ...(typeof result.total_matching_lines === "number" ? { totalMatchingLines: result.total_matching_lines } : {}),
90
+ };
91
+ }
92
+ case TOOL_NAMES.overview: {
93
+ const total = typeof result.lines === "number" ? result.lines : 0;
94
+ if (total < 1) return entry;
95
+ return withRanges(total > 30 ? [[1, 30], [Math.max(1, total - 19), total]] : [[1, total]], []);
96
+ }
97
+ case TOOL_NAMES.analyze:
98
+ return { ...entry, whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
99
+ case TOOL_NAMES.view:
100
+ return withRanges([], defined([rangeOf(result.pages)]));
101
+ default:
102
+ return entry;
103
+ }
104
+ }
105
+
106
+ /** Below this a result is left as it is: a stand-in would save next to nothing. */
107
+ const SMALL_RESULT_CHARACTERS = 700;
108
+ /** What is kept of the answer of a whole-file read, which cannot be asked for again. */
109
+ const KEPT_ANSWER_CHARACTERS = 6_000;
110
+ const MOST_RANGES = 60;
111
+
112
+ const rangeText = ([from, to]: NumberRange) => (to > from ? `${from}-${to}` : String(from));
113
+
114
+ /**
115
+ * A short stand-in for a tool result that is dropped from the request to make room: it keeps
116
+ * which document it was about and which lines or pages it showed, so the model can read them
117
+ * again, and says that it is a stand-in. Undefined when there is nothing to gain: the result is an
118
+ * error, is small already, or is such a stand-in. `hadFiles` is true for a result whose files
119
+ * (pages) are dropped with it, however small its JSON is.
120
+ */
121
+ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false): ToolResult | undefined {
122
+ if (typeof result.error === "string" || result.dropped === true) return undefined;
123
+ if (!hadFiles && JSON.stringify(result).length < SMALL_RESULT_CHARACTERS) return undefined;
124
+ const evidence = evidenceOf(call, result);
125
+ const base: ToolResult = { ...(typeof result.document === "string" ? { document: result.document } : {}), dropped: true };
126
+ const lines = evidence?.lines?.slice(0, MOST_RANGES).map(rangeText);
127
+ switch (call.name) {
128
+ case TOOL_NAMES.read:
129
+ return {
130
+ ...base,
131
+ ...(typeof result.lines === "string" ? { lines: result.lines } : {}),
132
+ ...(typeof result.total_lines === "number" ? { total_lines: result.total_lines } : {}),
133
+ note: "These lines were shown to you earlier and were dropped from the conversation to make room. Read them again with read_document if you need them.",
134
+ };
135
+ case TOOL_NAMES.search:
136
+ return {
137
+ ...base,
138
+ ...(typeof result.mode === "string" ? { mode: result.mode } : {}),
139
+ ...(typeof call.args.query === "string" ? { query: sliceWhole(call.args.query, 200) } : {}),
140
+ ...(typeof result.total_matching_lines === "number" ? { total_matching_lines: result.total_matching_lines } : {}),
141
+ ...(lines && lines.length > 0 ? { lines_shown: lines } : {}),
142
+ note: "The results of this search were shown to you earlier and were dropped from the conversation to make room. Read the lines listed here with read_document, or search again, if you need them.",
143
+ };
144
+ case TOOL_NAMES.analyze: {
145
+ const answer = typeof result.answer === "string" ? result.answer : "";
146
+ return {
147
+ ...base,
148
+ ...(typeof result.parts_read === "number" ? { parts_read: result.parts_read } : {}),
149
+ answer: answer.length > KEPT_ANSWER_CHARACTERS ? `${sliceWhole(answer, KEPT_ANSWER_CHARACTERS)}…` : answer,
150
+ note: "This is the start of the answer of the whole-file read. The rest was dropped from the conversation to make room.",
151
+ };
152
+ }
153
+ case TOOL_NAMES.view:
154
+ return {
155
+ ...base,
156
+ ...(typeof result.pages === "string" ? { pages: result.pages } : {}),
157
+ ...(typeof result.total_pages === "number" ? { total_pages: result.total_pages } : {}),
158
+ note: "These pages were shown to you earlier and are no longer attached. Look at them again with view_pages if you need them.",
159
+ };
160
+ case TOOL_NAMES.overview:
161
+ return { ...base, note: "The overview was shown to you earlier and was dropped from the conversation to make room. Call get_document_overview again if you need it." };
162
+ default:
163
+ return { ...base, note: "This result was shown to you earlier and was dropped from the conversation to make room." };
164
+ }
165
+ }