llm-large-files 0.9.0 → 0.10.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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
package/src/access.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Who is asking, and what they may use: the owner and the scope of a call, the context the store is
2
2
  // given for it, and the rule that decides which documents serve it. New in 0.9.0.
3
3
  import { DocumentScopeError, DocumentStoreError, type DocumentStoreOperation } from "./errors.js";
4
+ import { until } from "./http.js";
4
5
  import { checkScope, sameScope, scopeKey } from "./scope.js";
5
6
  import { DOCUMENT_META_VERSION } from "./stores.js";
6
7
  import type { DocumentContext, DocumentMeta, DocumentScope } from "./types.js";
@@ -31,6 +32,11 @@ export type Caller = {
31
32
  readonly context: DocumentContext;
32
33
  /** The key of the scope (`scopeKey`): what this caller's copies of documents are kept under in memory. */
33
34
  readonly key: string;
35
+ /**
36
+ * Ends this caller's waits for the store (`AccessOptions.signal`), with its reason: never a store
37
+ * call that other callers wait on too. New in 0.10.0.
38
+ */
39
+ readonly signal?: AbortSignal;
34
40
  };
35
41
 
36
42
  /** The context of a store call: a frozen object, without the fields that are absent. */
@@ -42,9 +48,10 @@ export function storeContext(scope: DocumentScope | undefined, owner: string | u
42
48
  * The caller of a call made with `access`. Null is no owner and no scope, as a database gives a
43
49
  * field that was left out. The scope is checked (`checkScope`: a `DocumentScopeError` when it is
44
50
  * not valid). Under `requireOwner`, a call without an owner, or with one that `checkOwner` refuses,
45
- * is a TypeError; under `requireScope`, a call without a scope.
51
+ * is a TypeError; under `requireScope`, a call without a scope. A `signal` that is not an
52
+ * `AbortSignal` is a TypeError (0.10.0).
46
53
  */
47
- export function callerOf(access: { readonly owner?: unknown; readonly scope?: unknown } | undefined, rules: AccessRules): Caller {
54
+ export function callerOf(access: { readonly owner?: unknown; readonly scope?: unknown; readonly signal?: unknown } | undefined, rules: AccessRules): Caller {
48
55
  const owner = (access?.owner ?? undefined) as string | undefined;
49
56
  if (rules.requireOwner) {
50
57
  if (owner === undefined) throw new TypeError(OWNER_REQUIRED);
@@ -52,11 +59,14 @@ export function callerOf(access: { readonly owner?: unknown; readonly scope?: un
52
59
  }
53
60
  const scope = checkScope(access?.scope ?? undefined);
54
61
  if (rules.requireScope && scope === undefined) throw new TypeError(SCOPE_REQUIRED);
62
+ const signal: unknown = access?.signal ?? undefined;
63
+ if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal.");
55
64
  return {
56
65
  ...(owner !== undefined ? { owner } : {}),
57
66
  ...(scope !== undefined ? { scope } : {}),
58
67
  context: storeContext(scope, owner),
59
68
  key: scopeKey(scope),
69
+ ...(signal !== undefined ? { signal } : {}),
60
70
  };
61
71
  }
62
72
 
@@ -114,17 +124,130 @@ export function metaOf(found: DocumentMeta | undefined, id: string): DocumentMet
114
124
  return { ...rest, ...(owner !== null && owner !== undefined ? { owner: owner as string } : {}), ...(scope !== null && scope !== undefined ? { scope: scope as string[] } : {}) };
115
125
  }
116
126
 
127
+ /** The longest a Node.js timer waits: a longer time limit is no limit. */
128
+ const LONGEST_TIMER_MS = 2 ** 31 - 1;
129
+
130
+ /** Whether `ms` is a time limit a timer can keep: 0, and a time past what a timer can wait, are none. */
131
+ export const isTimeLimit = (ms: number): boolean => ms > 0 && ms <= LONGEST_TIMER_MS;
132
+
133
+ /** A time limit in the words of a message: "500 ms", "30 s", "2 min". */
134
+ export function formatDuration(ms: number): string {
135
+ if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
136
+ if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
137
+ return `${Number((ms / 60_000).toFixed(1))} min`;
138
+ }
139
+
140
+ /**
141
+ * The calls of this process that ran past their time limit and have not settled. One count for
142
+ * every library, and for every copy of the package (two versions side by side, or one bundled):
143
+ * the calls of a process share one pool of threads (libuv's, `UV_THREADPOOL_SIZE`), and a call
144
+ * that does not answer holds one of them. New in 0.10.0.
145
+ */
146
+ const STUCK = Symbol.for("llm-large-files.stuckCalls");
147
+ const stuck = (() => {
148
+ const shared = globalThis as typeof globalThis & { [STUCK]?: { count: number } };
149
+ const found = shared[STUCK];
150
+ if (typeof found === "object" && found !== null && typeof found.count === "number") return found;
151
+ return (shared[STUCK] = { count: 0 });
152
+ })();
153
+
154
+ /** Store calls of this process past their time limit that have not settled, and calls to the disk of the upload handlers. New in 0.10.0. */
155
+ export function stuckCalls(): number {
156
+ return stuck.count;
157
+ }
158
+
159
+ /**
160
+ * Counts `call` as stuck once it has run `ms` without settling, until it settles: whether or not
161
+ * anyone still waits for it. A call that settles within `ms` never counts, and nothing counts
162
+ * without a time limit (`isTimeLimit`). `late` is called when it passes `ms`. Returns `call`.
163
+ * New in 0.10.0.
164
+ */
165
+ export function watchStuck<T>(call: Promise<T>, ms: number, late?: () => void): Promise<T> {
166
+ if (!isTimeLimit(ms)) return call;
167
+ let counted = false;
168
+ // The timer keeps the process alive: a call that never ends may hold nothing that does, and a
169
+ // caller that waits on it would be lost.
170
+ const timer = setTimeout(() => {
171
+ counted = true;
172
+ stuck.count++;
173
+ late?.();
174
+ }, ms);
175
+ const settle = () => {
176
+ clearTimeout(timer);
177
+ if (counted) stuck.count--;
178
+ };
179
+ call.then(settle, settle);
180
+ return call;
181
+ }
182
+
183
+ /** The time limit of a store call, and the limit on calls left stuck, of one library (`storeTimeoutMs`, `maxStuckStoreCalls`). New in 0.10.0. */
184
+ export type StoreCallOptions = {
185
+ /** The most time the call may take, in milliseconds. 0, or a time past what a timer can wait, sets none. */
186
+ timeoutMs?: number;
187
+ /**
188
+ * While this many calls of the process are stuck (`stuckCalls`), the call is refused at once, with
189
+ * a `DocumentStoreError` of code "STORE_STUCK", and the store is not called. Defaults to no limit.
190
+ */
191
+ maxStuck?: number;
192
+ /** Whether the call counts as stuck once past `timeoutMs`. Defaults to true; false for a sweep. */
193
+ counts?: boolean;
194
+ /** Ends the caller's wait with its reason. The call itself goes on: a store call cannot be stopped. */
195
+ signal?: AbortSignal;
196
+ };
197
+
198
+ /** Refuses a call of `operation` while `maxStuck` calls of the process are stuck: the store is not answering. New in 0.10.0. */
199
+ export function checkStuck(operation: DocumentStoreOperation, maxStuck: number): void {
200
+ if (stuck.count < maxStuck) return;
201
+ const found = Object.assign(new Error(`${stuck.count} store calls of this process ran past their time limit and have not ended (the limit is ${maxStuck}): the store is not answering.`), { code: "STORE_STUCK" });
202
+ throw new DocumentStoreError(found, { operation, code: "STORE_STUCK" });
203
+ }
204
+
205
+ /** A store call that did not end within `ms`. */
206
+ export const storeTimeout = (operation: DocumentStoreOperation, ms: number) => new DocumentStoreError(
207
+ Object.assign(new Error(`The store did not answer within ${formatDuration(ms)}.`), { code: "ETIMEDOUT" }),
208
+ { operation, code: "ETIMEDOUT" },
209
+ );
210
+
117
211
  /**
118
212
  * A call of the store. What it throws is passed on as a `DocumentStoreError` of `operation`, with
119
213
  * the store's error as `cause`: the store's own error may name a path, a host or a bucket, and a
120
214
  * store that failed is not a document that is gone. A `DocumentStoreError` is passed on as it is,
121
215
  * and so is a `DocumentScopeError`: a scope the store cannot use is a mistake of the call, and the
122
216
  * same call would fail again.
217
+ *
218
+ * New in 0.10.0, `options`: a call that does not end within `timeoutMs` is a `DocumentStoreError`
219
+ * of code "ETIMEDOUT", and counts as stuck until it ends; while `maxStuck` calls are stuck, it is
220
+ * refused at once ("STORE_STUCK"); `signal` ends the caller's wait with its reason, as it is.
123
221
  */
124
- export async function storeCall<T>(operation: DocumentStoreOperation, call: () => Promise<T>): Promise<T> {
222
+ export async function storeCall<T>(operation: DocumentStoreOperation, call: () => Promise<T>, options: StoreCallOptions = {}): Promise<T> {
223
+ const { timeoutMs = 0, maxStuck = Number.POSITIVE_INFINITY, counts = true, signal } = options;
224
+ checkStuck(operation, maxStuck);
225
+ // A caller that has left starts no call. (Its signal may be an object made like an AbortSignal,
226
+ // which `ToolOptions.signal` takes as before 0.10.0.)
227
+ if (signal?.aborted) throw signal.reason;
228
+ let running: Promise<T>;
229
+ try {
230
+ running = Promise.resolve(call());
231
+ } catch (error) {
232
+ running = Promise.reject(error);
233
+ }
234
+ let waited: Promise<T> = running;
235
+ if (isTimeLimit(timeoutMs)) {
236
+ waited = new Promise<T>((resolve, reject) => {
237
+ const late = () => reject(storeTimeout(operation, timeoutMs));
238
+ if (counts) watchStuck(running, timeoutMs, late);
239
+ else {
240
+ const timer = setTimeout(late, timeoutMs);
241
+ const settle = () => clearTimeout(timer);
242
+ running.then(settle, settle);
243
+ }
244
+ running.then(resolve, reject);
245
+ });
246
+ }
125
247
  try {
126
- return await call();
248
+ return await until(waited, signal);
127
249
  } catch (error) {
250
+ if (signal?.aborted && error === signal.reason) throw error;
128
251
  throw DocumentStoreError.is(error) || DocumentScopeError.is(error) ? error : new DocumentStoreError(error, { operation });
129
252
  }
130
253
  }
package/src/aggregate.ts CHANGED
@@ -94,6 +94,8 @@ export type AggregateResult = {
94
94
  distinctCapped: boolean;
95
95
  /** For each numeric metric, how many matched rows had a value in its column that is not a number (left out). */
96
96
  notNumbers: Record<string, number>;
97
+ /** The filters whose value named a column: each row's cell of `column` was compared with its cell of `with` (since 0.10.0). */
98
+ compared?: Array<{ column: string; op: FilterOp; with: string }>;
97
99
  };
98
100
 
99
101
  /**
@@ -224,11 +226,30 @@ function splitCsvLine(line: string, separator: string, carry?: { fields: string[
224
226
  return { fields, open: false, field: "" };
225
227
  }
226
228
 
227
- /** A column a request names, resolved against the header: its index, and the part of a date to group by. */
228
- type ColumnRef = { index: number; name: string; datePart?: DatePart };
229
+ /**
230
+ * A column a request names, resolved against the header: its index, the part of a date to group
231
+ * by, and whether it was named by its letter ("C").
232
+ */
233
+ type ColumnRef = { index: number; name: string; datePart?: DatePart; byLetter?: boolean };
234
+
235
+ /**
236
+ * The number of a column named by its letters ("C" is 3, "AA" is 27), or undefined when `name` is
237
+ * not one to three letters A to Z.
238
+ */
239
+ function letterNumber(name: string): number | undefined {
240
+ if (!/^[A-Z]{1,3}$/i.test(name)) return undefined;
241
+ let number = 0;
242
+ for (const letter of name.toUpperCase()) number = number * 26 + letter.charCodeAt(0) - 64;
243
+ return number;
244
+ }
229
245
 
230
- /** Finds a column by its header name (ignoring case and spaces), its letter ("C"), or its number ("3"). */
231
- function columnOf(header: string[], given: string, letters: boolean): ColumnRef {
246
+ /**
247
+ * Finds a column by its header name (ignoring case and spaces), the lower name of a joined header
248
+ * when only one column has it, its letter ("C"), or its number ("3"). A letter or a number names a
249
+ * column only when no column has that name. Until 0.10.0 a letter named a column only in a sheet
250
+ * with no header, though the tool's description says it works in every table.
251
+ */
252
+ function columnOf(header: string[], given: string): ColumnRef {
232
253
  let name = given.trim();
233
254
  let datePart: DatePart | undefined;
234
255
  const part = /:(year|month|day)$/i.exec(name);
@@ -246,21 +267,67 @@ function columnOf(header: string[], given: string, letters: boolean): ColumnRef
246
267
  throw new Error(`${JSON.stringify(sliceWhole(name, 80))} names ${lower.length} columns of this table: ${lower.map((at) => JSON.stringify(header[at])).join(", ")}. Name one of them in full.`);
247
268
  }
248
269
  }
249
- if (index === -1 && letters && /^[A-Z]{1,3}$/i.test(name)) {
250
- let number = 0;
251
- for (const letter of name.toUpperCase()) number = number * 26 + letter.charCodeAt(0) - 64;
252
- if (number <= header.length) index = number - 1;
270
+ let byLetter = false;
271
+ if (index === -1) {
272
+ const number = letterNumber(name);
273
+ if (number !== undefined && number <= header.length) {
274
+ index = number - 1;
275
+ byLetter = true;
276
+ }
253
277
  }
254
278
  if (index === -1 && /^\d+$/.test(name) && Number(name) >= 1 && Number(name) <= header.length) index = Number(name) - 1;
255
279
  if (index === -1) {
256
280
  const listed = header.slice(0, 40).map((column) => JSON.stringify(column)).join(", ");
257
281
  throw new Error(`No column ${JSON.stringify(sliceWhole(name, 80))} in this table. Its columns are: ${listed}${header.length > 40 ? ", …" : ""}.`);
258
282
  }
259
- return { index, name: header[index]!, ...(datePart ? { datePart } : {}) };
283
+ return { index, name: header[index]!, ...(datePart ? { datePart } : {}), ...(byLetter ? { byLetter } : {}) };
284
+ }
285
+
286
+ /** The filters that order a column against a value: when the value names a column, against that column. */
287
+ const ORDER_OPS: ReadonlySet<FilterOp> = new Set(["<", "<=", ">", ">="]);
288
+
289
+ /**
290
+ * The columns the value of a filter names, when the filter orders its column against it (`>`,
291
+ * `>=`, `<`, `<=`) and the value is not a number: the column of that full name, else the columns
292
+ * whose lower name (of a joined header) it is, else the column of that letter when the filter's own
293
+ * column was named by its letter ("C" > "B"). Such a value compared as text matched no row, with no
294
+ * word of why: "Q1 / Actual" > "Q1 / Budget" is meant cell against cell. Empty for any other
295
+ * filter: `=`, `!=` and the text filters may well look for a value that is also a column's name
296
+ * ("Department" != "Total").
297
+ */
298
+ function columnsNamedBy(header: string[], filter: { op: FilterOp; value: string; number: number | undefined }, column: ColumnRef): number[] {
299
+ if (!ORDER_OPS.has(filter.op) || filter.number !== undefined) return [];
300
+ const wanted = valueKey(filter.value);
301
+ if (!wanted) return [];
302
+ const full = header.flatMap((name, at) => (valueKey(name) === wanted ? [at] : []));
303
+ if (full.length) return full;
304
+ const lower = header.flatMap((name, at) => (valueKey(name.split(" / ").at(-1) ?? "") === wanted ? [at] : []));
305
+ if (lower.length) return lower;
306
+ const number = column.byLetter ? letterNumber(filter.value.trim()) : undefined;
307
+ return number !== undefined && number <= header.length ? [number - 1] : [];
308
+ }
309
+
310
+ /**
311
+ * Whether the cell `left` stands in `op` (`>`, `>=`, `<`, `<=`) to the cell `right` of the same
312
+ * row, for a filter whose value names a column (`columnsNamedBy`): two numbers compare as numbers,
313
+ * two texts (ISO dates among them) as text, ignoring case. A number and a text, or an empty cell,
314
+ * never match: "n/a" is neither more nor less than 900.
315
+ */
316
+ function compareCells(left: string, right: string, op: FilterOp): boolean {
317
+ const leftKey = valueKey(left);
318
+ const rightKey = valueKey(right);
319
+ const leftNumber = parseNumber(left);
320
+ const rightNumber = parseNumber(right);
321
+ if (!leftKey || !rightKey || (leftNumber === undefined) !== (rightNumber === undefined)) return false;
322
+ const order = leftNumber !== undefined && rightNumber !== undefined
323
+ ? Math.sign(leftNumber - rightNumber)
324
+ : leftKey === rightKey ? 0 : leftKey < rightKey ? -1 : 1;
325
+ return op === ">" ? order > 0 : op === ">=" ? order >= 0 : op === "<" ? order < 0 : order <= 0;
260
326
  }
261
327
 
262
328
  type Metric = { name: string; op: AggregateOp; column?: ColumnRef };
263
- type Filter = { column: ColumnRef; op: FilterOp; value: string; number: number | undefined; key: string };
329
+ /** A filter, resolved; `against` is the column its value names, whose cell of each row it is compared with (since 0.10.0). */
330
+ type Filter = { column: ColumnRef; op: FilterOp; value: string; number: number | undefined; key: string; against?: ColumnRef };
264
331
  type GroupState = { key: Record<string, string>; count: number; sums: number[]; numbers: number[]; minimums: Array<number | string | undefined>; maximums: Array<number | string | undefined>; distinct: Array<Set<string> | undefined>; lines: number[] };
265
332
 
266
333
  /** The value of a cell for comparing: a number when it is one, a date as written, or folded text. */
@@ -353,9 +420,17 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
353
420
  if (!FILTER_OPS.includes(filter.op)) throw new Error(`A filter's op must be one of ${FILTER_OPS.map((op) => `"${op}"`).join(", ")}.`);
354
421
  const value = filter.value === undefined || filter.value === null ? "" : String(filter.value);
355
422
  if (value === "" && filter.op !== "empty" && filter.op !== "not_empty" && filter.op !== "=" && filter.op !== "!=") throw new Error(`The filter on ${JSON.stringify(filter.column)} needs a value.`);
356
- return { column: columnOf(columns, String(filter.column ?? ""), letters), op: filter.op, value, number: parseNumber(value), key: valueKey(value) };
423
+ const resolved: Filter = { column: columnOf(columns, String(filter.column ?? "")), op: filter.op, value, number: parseNumber(value), key: valueKey(value) };
424
+ // A value that names a column: each row's cell is compared with that column's (since 0.10.0).
425
+ const named = columnsNamedBy(columns, resolved, resolved.column);
426
+ if (named.length > 1) {
427
+ const names = named.slice(0, 10).map((at) => JSON.stringify(columns[at])).join(", ");
428
+ throw new Error(`${JSON.stringify(sliceWhole(value.trim(), 80))} names ${named.length} columns of this table: ${names}${named.length > 10 ? ", …" : ""}. Name one of them in full, to compare ${JSON.stringify(resolved.column.name)} with it in each row.`);
429
+ }
430
+ if (named.length === 1) resolved.against = { index: named[0]!, name: columns[named[0]!]! };
431
+ return resolved;
357
432
  });
358
- groupColumns = (request.groupBy ?? []).map((name) => columnOf(columns, String(name), letters));
433
+ groupColumns = (request.groupBy ?? []).map((name) => columnOf(columns, String(name)));
359
434
  metrics = metricsGiven.map((given) => {
360
435
  const text = String(given).trim();
361
436
  const [rawOp, ...rest] = text.split(":");
@@ -364,7 +439,7 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
364
439
  const columnName = rest.join(":").trim();
365
440
  if (op === "count") return { name: "count", op };
366
441
  if (!columnName) throw new Error(`The metric "${op}" needs a column: "${op}:<column>".`);
367
- const column = columnOf(columns, columnName, letters);
442
+ const column = columnOf(columns, columnName);
368
443
  return { name: `${op}:${column.name}`, op, column };
369
444
  });
370
445
  notNumbers = metrics.map(() => 0);
@@ -455,7 +530,9 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
455
530
  if (row.slice(header.length).some((cell) => cell !== "") || (kind === "csv" && row.length !== header.length)) irregularRows++;
456
531
  rowsRead++;
457
532
  const cell = (column: ColumnRef) => row[column.index] ?? "";
458
- for (const filter of filters) if (!compare(cell(filter.column), filter)) return;
533
+ for (const filter of filters) {
534
+ if (!(filter.against ? compareCells(cell(filter.column), cell(filter.against), filter.op) : compare(cell(filter.column), filter))) return;
535
+ }
459
536
  rowsMatched++;
460
537
  const values = groupColumns.map((column) => groupValue(cell(column), column));
461
538
  const key = values.map(valueKey).join("\u0000");
@@ -650,6 +727,7 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
650
727
  irregularRows,
651
728
  distinctCapped,
652
729
  notNumbers: Object.fromEntries(metrics.flatMap((metric, index) => (notNumbers[index]! > 0 && (metric.op === "sum" || metric.op === "avg" || metric.op === "min" || metric.op === "max") ? [[metric.name, notNumbers[index]!]] : []))),
730
+ ...(filters.some((filter) => filter.against) ? { compared: filters.flatMap((filter) => (filter.against ? [{ column: filter.column.name, op: filter.op, with: filter.against.name }] : [])) } : {}),
653
731
  };
654
732
  }
655
733
 
package/src/analyze.ts CHANGED
@@ -166,8 +166,8 @@ function outlineEntry(lines: string[], index: number, hashes: HashHeadings = "al
166
166
  return undefined;
167
167
  }
168
168
 
169
- /** The outline kept from all the headings found: at most 400 of them. */
170
- function pickOutline(entries: OutlineEntry[]): OutlineEntry[] {
169
+ /** The outline kept from all the headings found: at most 400 of them. Also picks a PDF's headings from type sizes (pdf-outline.ts). */
170
+ export function pickOutline<T extends { level: number }>(entries: T[]): T[] {
171
171
  if (entries.length <= MAX_OUTLINE_ENTRIES) return entries;
172
172
  // Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
173
173
  // a larger one is sampled evenly, so the outline still spans the document.
@@ -0,0 +1,45 @@
1
+ // How an answer ended, in one value an application can switch on for the message it shows: the
2
+ // answer's own counterpart of `errorInfoOf`. New in 0.10.0.
3
+ import type { AskResult } from "./ask.js";
4
+
5
+ /** How an answer ended (`answerInfoOf`). New in 0.10.0. */
6
+ export type AnswerInfo = {
7
+ /** True when the answer came whole: not stopped by a filter or the output limit, and not refused. */
8
+ complete: boolean;
9
+ /**
10
+ * Why it is not complete: "filtered" by the provider's filters, "cut" at the output limit,
11
+ * "blocked" (the prompt was refused), "language" (Gemini's LANGUAGE: a language the model does
12
+ * not take), "no_answer" (no text came), or "other".
13
+ */
14
+ reason?: "filtered" | "cut" | "blocked" | "language" | "no_answer" | "other";
15
+ /** `AskResult.finish`. */
16
+ finish?: AskResult["finish"];
17
+ /** The provider's own word (`AskResult.finishReason`). */
18
+ finishReason?: string;
19
+ };
20
+
21
+ /**
22
+ * How the answer of `result` ended, for the message to show: complete, or why not. The reasons
23
+ * are tried in this order: a refused prompt ("blocked"), a filter ("filtered"), the output limit
24
+ * ("cut"), Gemini's LANGUAGE ("language": the model does not take the language of the question,
25
+ * which is no filter), another reason that asking again does not mend ("other"), and no text at
26
+ * all ("no_answer"). A result that was built by hand without `finish` is told by `answered`,
27
+ * `blockReason` and `finishReason` alone. New in 0.10.0.
28
+ */
29
+ export function answerInfoOf(result: Pick<AskResult, "answered" | "finish" | "finishReason" | "blockReason">): AnswerInfo {
30
+ const { answered, finish, finishReason, blockReason } = result;
31
+ const told = {
32
+ ...(finish !== undefined ? { finish } : {}),
33
+ ...(typeof finishReason === "string" ? { finishReason } : {}),
34
+ };
35
+ const incomplete = (reason: NonNullable<AnswerInfo["reason"]>): AnswerInfo => ({ complete: false, reason, ...told });
36
+ if (typeof blockReason === "string" && blockReason) return incomplete("blocked");
37
+ if (finish === "filtered") return incomplete("filtered");
38
+ if (finish === "cut") return incomplete("cut");
39
+ // Gemini's word for a language the model does not take. An adapter maps it to "other" (asking
40
+ // again would not mend it); an older one leaves `finish` unset. Either way it is not a filter.
41
+ if (finish !== "complete" && typeof finishReason === "string" && finishReason.toUpperCase() === "LANGUAGE") return incomplete("language");
42
+ if (finish === "other") return incomplete("other");
43
+ if (answered !== true) return incomplete("no_answer");
44
+ return { complete: true, ...told };
45
+ }
@@ -1,7 +1,7 @@
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
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";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, partTimer, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, until, waitText, type HeaderSource, type IdleWatch, type PartTimer, type SecretSource } from "../http.js";
5
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";
6
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
7
7
  import { noteNoRetry, retryAfterMs } from "../retry.js";
@@ -94,7 +94,11 @@ export type AnthropicOptions = {
94
94
  * reports with each reply corrects it during a question.
95
95
  */
96
96
  tokenScale?: number | undefined;
97
- /** Milliseconds a part read may take. Defaults to 180,000. */
97
+ /**
98
+ * Milliseconds a part read may take, its whole reply included. Defaults to 180,000; 0 sets none
99
+ * (since 0.10.0). A part past it is an `AnthropicRequestError` of kind "timeout" and status 0
100
+ * (since 0.10.0; before, the abort of the timer), which a whole-file read sends again once.
101
+ */
98
102
  timeoutMs?: number | undefined;
99
103
  /**
100
104
  * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
@@ -376,10 +380,15 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
376
380
  ...options.body,
377
381
  });
378
382
 
379
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => AnthropicRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
383
+ /**
384
+ * Sends a request. A `bounded` one (a part read, whose time limit is its signal) stops waiting
385
+ * when the signal aborts, even for a fetch that does not stop then itself.
386
+ */
387
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => AnthropicRequestError = unreachable, headers?: Record<string, string>, bounded = false): Promise<Response> => {
380
388
  let response: Response;
381
389
  try {
382
- response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
390
+ const sent = fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
391
+ response = await (bounded ? until(sent, signal) : sent);
383
392
  } catch (error) {
384
393
  if (stopped()) throw error;
385
394
  throw lost(error);
@@ -388,8 +397,8 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
388
397
  return response;
389
398
  };
390
399
 
391
- /** The reply, from the content of a finished message. */
392
- const replyOf = (content: Block[], stopReason: unknown, stopDetails: Json | undefined, usage: Json | undefined, problems: Map<number, string>, text: string): ModelReply => {
400
+ /** The reply, from the content of a finished message. `named` is the message's own fields: its ID and model. */
401
+ const replyOf = (content: Block[], stopReason: unknown, stopDetails: Json | undefined, usage: Json | undefined, problems: Map<number, string>, text: string, named?: Json): ModelReply => {
393
402
  const boundary = content.map((block) => block?.type).lastIndexOf("fallback");
394
403
  const refused = stopReason === "refusal";
395
404
  // Cut off at the output limit with a call half-written: the call is answered, not run.
@@ -413,21 +422,33 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
413
422
  ...(typeof stopReason === "string" ? { finishReason: stopReason } : {}),
414
423
  ...(finish ? { finish } : {}),
415
424
  ...(refused ? { blockReason: `refusal${category}` } : {}),
425
+ ...(typeof named?.id === "string" && named.id ? { responseId: named.id } : {}),
426
+ ...(typeof named?.model === "string" && named.model ? { responseModel: named.model } : {}),
416
427
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
417
428
  };
418
429
  };
419
430
 
420
431
  const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
421
432
  const send = async (limit: number): Promise<LimitedReply> => {
422
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
433
+ const timer = partTimer(signal, options.timeoutMs);
434
+ try {
435
+ return await read(limit, timer);
436
+ } finally {
437
+ timer.stop();
438
+ }
439
+ };
440
+ /** One part read, within its time limit: past it, a timeout. A stop of the caller's is reported as it is. */
441
+ const read = async (limit: number, timer: PartTimer): Promise<LimitedReply> => {
442
+ const stopped = () => Boolean(signal?.aborted);
443
+ const lost = (error: unknown) => (timer.expired && !signal?.aborted ? tooSlow(timer.limitMs) : unreachable(error));
423
444
  const response = await post({
424
445
  model: options.model,
425
446
  max_tokens: limit,
426
447
  system,
427
448
  messages: [{ role: "user", content: prompt }],
428
449
  ...options.analysisBody?.(limit),
429
- }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
430
- const data = await readJson<Json>(response, () => Boolean(signal?.aborted) || timeout.aborted, unreachable, undefined, (error) => notJson(response, error));
450
+ }, timer.signal, stopped, lost, undefined, true);
451
+ const data = await readJson<Json>(response, stopped, lost, timer.signal ? { pulse: () => undefined, signal: timer.signal } : undefined, (error) => notJson(response, error));
431
452
  const used = usageOf(data.usage as Json | undefined);
432
453
  onUsage?.(used);
433
454
  const content: Block[] = Array.isArray(data.content) ? data.content : [];
@@ -501,7 +522,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
501
522
  const content: Block[] = Array.isArray(data.content) ? data.content : [];
502
523
  const text = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : "")).join("");
503
524
  if (text) hooks.onText?.(text);
504
- return replyOf(content, data.stop_reason, data.stop_details as Json | undefined, data.usage as Json | undefined, problems, text);
525
+ return replyOf(content, data.stop_reason, data.stop_details as Json | undefined, data.usage as Json | undefined, problems, text, data);
505
526
  }
506
527
  const content: Block[] = [];
507
528
  const inputs = new Map<number, string>();
@@ -511,6 +532,8 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
511
532
  let stopReason: unknown;
512
533
  let stopDetails: Json | undefined;
513
534
  let usage: Json | undefined;
535
+ /** The message's own fields, from `message_start`: its ID and model. */
536
+ let named: Json | undefined;
514
537
  // `message_stop` ends the reply: a gateway that leaves the connection open after it is not waited for.
515
538
  const end = replyEnd(watch);
516
539
  try {
@@ -523,6 +546,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
523
546
  end.reached();
524
547
  } else if (event.type === "message_start") {
525
548
  usage = { ...event.message?.usage };
549
+ named = event.message as Json | undefined;
526
550
  } else if (event.type === "content_block_start" && typeof event.index === "number") {
527
551
  content[event.index] = { ...event.content_block };
528
552
  } else if (event.type === "content_block_delta" && typeof event.index === "number") {
@@ -590,7 +614,7 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
590
614
  // The problems were noted by the place of the block in the stream: the same place, with no gaps, in what is kept.
591
615
  const placed = new Map<number, string>();
592
616
  for (const [index, problem] of problems) placed.set(blocks.indexOf(content[index]!), problem);
593
- return replyOf(blocks, stopReason, stopDetails, usage, placed, text);
617
+ return replyOf(blocks, stopReason, stopDetails, usage, placed, text, named);
594
618
  }
595
619
  }
596
620
  }
@@ -600,6 +624,11 @@ function notJson(response: Response, error: unknown): AnthropicRequestError {
600
624
  return new AnthropicRequestError(notJsonMessage("Claude's", response), response.status, { kind: "invalid", cause: error });
601
625
  }
602
626
 
627
+ /** A part read whose whole reply did not come within its time limit (`timeoutMs`). */
628
+ function tooSlow(limitMs: number): AnthropicRequestError {
629
+ return new AnthropicRequestError(`Claude took longer than ${waitText(limitMs)} to answer.`, 0, { kind: "timeout" });
630
+ }
631
+
603
632
  /** A request that got no answer: the reason, without the stack of the HTTP client. */
604
633
  function unreachable(error: unknown): AnthropicRequestError {
605
634
  return new AnthropicRequestError(`Claude could not be reached${unreachableReason(error)}.`, 0, { cause: error });