@hraness/wordcell 0.21.2 → 0.22.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 (87) hide show
  1. package/README.md +196 -66
  2. package/dist/{authority-4sp9d552.js → authority-1pgftmwq.js} +55 -10
  3. package/dist/benchmark.js +3 -3
  4. package/dist/capture.js +6 -5
  5. package/dist/cli.js +61 -3800
  6. package/dist/clip/acquire.js +3 -2
  7. package/dist/clip/cli.js +6 -5
  8. package/dist/clip/doctor.js +4 -3
  9. package/dist/clip/jobs.js +3 -3
  10. package/dist/clip/refresh.js +1 -1
  11. package/dist/evaluation-builder.js +18 -17
  12. package/dist/evaluation-kb.js +14 -13
  13. package/dist/graph-authority.js +3 -3
  14. package/dist/graph-percolation.js +5 -5
  15. package/dist/index-0dqfnrz9.js +1985 -0
  16. package/dist/{index-0k2x4nn9.js → index-1tm7bgx7.js} +16 -4
  17. package/dist/{index-vdw5yjfa.js → index-2hf27mws.js} +108 -18
  18. package/dist/index-3agn8scn.js +306 -0
  19. package/dist/index-4ag64rc1.js +4299 -0
  20. package/dist/index-4knsp9qj.js +34 -0
  21. package/dist/index-66pshdtx.js +341 -0
  22. package/dist/index-9rf81m0p.js +368 -0
  23. package/dist/{index-59ssmqqm.js → index-a6kbv718.js} +1 -1
  24. package/dist/{index-51bap0mq.js → index-avbce90h.js} +9 -9
  25. package/dist/{index-180zbkkt.js → index-de2w8crk.js} +14 -13
  26. package/dist/{index-pbr6rv47.js → index-e6p9e926.js} +6 -6
  27. package/dist/{index-bcfn9xah.js → index-famy7fhs.js} +5 -5
  28. package/dist/{index-by0pbant.js → index-fc4dr114.js} +5 -2
  29. package/dist/{index-x6m57nfc.js → index-g5vsqmdy.js} +28 -57
  30. package/dist/{index-115b07ap.js → index-hcw140eb.js} +5 -5
  31. package/dist/index-j70m75wd.js +217 -0
  32. package/dist/{index-3ehtt59c.js → index-qwgsmtsz.js} +1 -1
  33. package/dist/{index-bgfzwt4h.js → index-t2bs9xdr.js} +4 -4
  34. package/dist/index.js +285 -93
  35. package/dist/portfolio.js +14 -13
  36. package/dist/publish-model.js +36 -0
  37. package/dist/publish-reader/reader.css +1042 -0
  38. package/dist/publish-reader/reader.js +1534 -0
  39. package/dist/publish-reader/theme.js +92 -0
  40. package/dist/publish-search.js +52 -0
  41. package/dist/publish.js +36 -0
  42. package/dist/rerank-typesafe.js +13 -0
  43. package/dist/rerank.js +14 -0
  44. package/dist/sdk.js +14 -11
  45. package/dist/search.js +2 -2
  46. package/dist/semantic.js +4 -4
  47. package/dist/support-mywv1em0.js +140 -0
  48. package/dist/workflows/decision-context.js +13 -12
  49. package/dist/workflows/index.js +13 -12
  50. package/package.json +68 -7
  51. package/skills/wordcell/AGENTS.md +1 -0
  52. package/skills/wordcell/SKILL.md +21 -1
  53. package/skills/wordcell/agents/openai.yaml +1 -1
  54. package/skills/wordcell/references/publish.md +93 -0
  55. package/skills/wordcell/references/query.md +22 -0
  56. package/src/cli-program.ts +353 -9
  57. package/src/cli.ts +12 -1
  58. package/src/clip/acquire.ts +2 -0
  59. package/src/clip/doctor.ts +2 -0
  60. package/src/clip/media.ts +2 -0
  61. package/src/index.ts +4 -0
  62. package/src/oh/authority.ts +14 -5
  63. package/src/oh/canonical-rust.ts +127 -0
  64. package/src/oh/projection-rust.ts +63 -0
  65. package/src/oh-adoption.ts +7 -1
  66. package/src/publish-graph.ts +0 -0
  67. package/src/publish-index.ts +195 -0
  68. package/src/publish-markdown.ts +617 -0
  69. package/src/publish-model.ts +599 -0
  70. package/src/publish-nav.ts +204 -0
  71. package/src/publish-pages.ts +382 -0
  72. package/src/publish-reader/reader.css +1042 -0
  73. package/src/publish-reader/reader.ts +1017 -0
  74. package/src/publish-reader/theme.ts +97 -0
  75. package/src/publish-search.ts +418 -0
  76. package/src/publish-select.ts +419 -0
  77. package/src/publish-theme.ts +106 -0
  78. package/src/publish.ts +904 -0
  79. package/src/rerank-credentials.ts +56 -0
  80. package/src/rerank-typesafe.ts +472 -0
  81. package/src/rerank.ts +389 -0
  82. package/src/sdk.ts +157 -6
  83. package/src/serve.ts +180 -0
  84. package/src/support-profile.ts +7 -0
  85. package/src/support.ts +73 -0
  86. package/src/vault.ts +23 -9
  87. package/dist/{index-why54q5p.js → index-gm9t95d9.js} +3 -3
@@ -0,0 +1,56 @@
1
+ import { constants } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join } from "node:path";
5
+ import type { SearchReranker } from "./rerank.js";
6
+ import { createTypeSafeReranker } from "./rerank-typesafe.js";
7
+
8
+ function unavailable(message: string): SearchReranker {
9
+ return { id: "typesafe", rerank: async () => ({ status: "unavailable", message }) };
10
+ }
11
+
12
+ /** CLI-only credential discovery, called only after explicit --rerank typesafe. */
13
+ export async function createCliTypeSafeReranker(
14
+ environment: Readonly<Record<string, string | undefined>> = process.env,
15
+ homeDirectory: string = homedir(),
16
+ ): Promise<SearchReranker> {
17
+ // An explicit value, including an invalid one, must never select another key.
18
+ if (Object.hasOwn(environment, "TYPESAFE_API_KEY")) {
19
+ return createTypeSafeReranker({ environment: { TYPESAFE_API_KEY: environment["TYPESAFE_API_KEY"] } });
20
+ }
21
+ const explicitFile = environment["TYPESAFE_API_KEY_FILE"];
22
+ const configDirectory = environment["XDG_CONFIG_HOME"];
23
+ if (
24
+ (explicitFile !== undefined && !isAbsolute(explicitFile))
25
+ || (configDirectory !== undefined && configDirectory !== "" && !isAbsolute(configDirectory))
26
+ ) {
27
+ return unavailable("TypeSafe credential file configuration requires absolute paths.");
28
+ }
29
+ const path = explicitFile ?? join(
30
+ configDirectory || join(homeDirectory, ".config"), "wordcell", "typesafe-api-key",
31
+ );
32
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
33
+ try {
34
+ // Nonblocking open rejects FIFOs without hanging; no-follow rejects a final symlink.
35
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
36
+ const metadata = await handle.stat();
37
+ const uid = process.getuid?.();
38
+ if (
39
+ !metadata.isFile() || metadata.nlink !== 1 || metadata.size < 1 || metadata.size > 514
40
+ || (process.platform !== "win32" && ((metadata.mode & 0o077) !== 0 || metadata.uid !== uid))
41
+ ) {
42
+ return unavailable("TypeSafe credential file must be an owner-only regular file containing one API key.");
43
+ }
44
+ const bytes = Buffer.alloc(515);
45
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
46
+ const key = bytes.subarray(0, bytesRead).toString("utf8").replace(/\r?\n$/u, "");
47
+ if (!/^[\x21-\x7e]{1,512}$/u.test(key)) {
48
+ return unavailable("TypeSafe credential file must contain one valid API key.");
49
+ }
50
+ return createTypeSafeReranker({ environment: { TYPESAFE_API_KEY: key } });
51
+ } catch {
52
+ return unavailable("TypeSafe credentials are unavailable; set TYPESAFE_API_KEY or an owner-only TYPESAFE_API_KEY_FILE.");
53
+ } finally {
54
+ await handle?.close();
55
+ }
56
+ }
@@ -0,0 +1,472 @@
1
+ import {
2
+ MAX_RERANK_CANDIDATES,
3
+ MAX_RERANK_SNIPPET_BYTES,
4
+ MAX_RERANK_STATE_BYTES,
5
+ type SearchRerankRequest,
6
+ type SearchRerankResult,
7
+ type SearchRerankDetails,
8
+ type SearchReranker,
9
+ } from "./rerank.js";
10
+
11
+ export const DEFAULT_SYSTEMONE_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
12
+ export const DEFAULT_SYSTEMONE_MODEL = "jev-1.13.0";
13
+ const DEFAULT_RERANK_TIMEOUT_MS = 8_000;
14
+ const DEFAULT_RERANK_MAX_RESPONSE_BYTES = 64 * 1_024;
15
+ const DEFAULT_RERANK_CONCURRENCY = 4;
16
+ const MAX_RERANK_TIMEOUT_MS = DEFAULT_RERANK_TIMEOUT_MS;
17
+ const MAX_RERANK_RESPONSE_BYTES = DEFAULT_RERANK_MAX_RESPONSE_BYTES;
18
+ const MAX_RERANK_CONCURRENCY = 8;
19
+
20
+ const RELEVANCE_QUESTION = "relevant";
21
+ const RELEVANCE_INSTRUCTIONS =
22
+ "Could this note help answer the search query in a personal Markdown knowledge "
23
+ + "vault of notes, plans, concepts, and captured sources?";
24
+ const RELEVANCE_CRITERIA = {
25
+ true: "The note's title, path, or snippet directly addresses the query's subject or task.",
26
+ false: "The note is unrelated to the query or only touches a neighboring topic.",
27
+ } as const;
28
+
29
+ export type SystemOneTransport = (request: {
30
+ readonly url: string;
31
+ readonly body: Uint8Array;
32
+ readonly headers: Readonly<Record<string, string>>;
33
+ readonly timeoutMs: number;
34
+ readonly maxResponseBytes: number;
35
+ readonly signal?: AbortSignal;
36
+ }) => Promise<{ readonly status: number; readonly body: Uint8Array }>;
37
+
38
+ export type TypeSafeRerankerOptions = {
39
+ readonly transport?: SystemOneTransport;
40
+ /** Whole hosted-window deadline, including every request wave; at most 8 seconds. */
41
+ readonly timeoutMs?: number;
42
+ /** May lower, but never raise, the fixed response byte bound. */
43
+ readonly maxResponseBytes?: number;
44
+ /** May lower, but never raise, the fixed request concurrency bound. */
45
+ readonly concurrency?: number;
46
+ /** Test seam for environment lookups; production callers leave this unset. */
47
+ readonly environment?: Readonly<Record<string, string | undefined>>;
48
+ };
49
+
50
+ type ParsedSystemOneAnswer = {
51
+ readonly noul: number;
52
+ readonly model: string;
53
+ readonly inputTokens: number;
54
+ readonly outputTokens: number;
55
+ };
56
+
57
+ async function readBoundedResponse(
58
+ response: Response,
59
+ maxBytes: number,
60
+ signal: AbortSignal,
61
+ ): Promise<Uint8Array> {
62
+ const body = response.body;
63
+ if (body === null) return new Uint8Array();
64
+ const reader = body.getReader();
65
+ const abort = (): void => { void reader.cancel().catch(() => undefined); };
66
+ signal.addEventListener("abort", abort, { once: true });
67
+ const chunks: Uint8Array[] = [];
68
+ let total = 0;
69
+ try {
70
+ for (;;) {
71
+ if (signal.aborted) throw new Error("request aborted");
72
+ const { done, value } = await reader.read();
73
+ if (signal.aborted) throw new Error("request aborted");
74
+ if (done) break;
75
+ if (value === undefined || value.byteLength === 0) continue;
76
+ total += value.byteLength;
77
+ if (total > maxBytes) {
78
+ void reader.cancel().catch(() => undefined);
79
+ throw new Error(`response exceeds the ${maxBytes}-byte limit`);
80
+ }
81
+ chunks.push(value);
82
+ }
83
+ } finally {
84
+ signal.removeEventListener("abort", abort);
85
+ if (signal.aborted) abort();
86
+ reader.releaseLock();
87
+ }
88
+ const bytes = new Uint8Array(total);
89
+ let offset = 0;
90
+ for (const chunk of chunks) {
91
+ bytes.set(chunk, offset);
92
+ offset += chunk.byteLength;
93
+ }
94
+ return bytes;
95
+ }
96
+
97
+ async function fetchSystemOneTransport(request: {
98
+ readonly url: string;
99
+ readonly body: Uint8Array;
100
+ readonly headers: Readonly<Record<string, string>>;
101
+ readonly timeoutMs: number;
102
+ readonly maxResponseBytes: number;
103
+ readonly signal?: AbortSignal;
104
+ }): Promise<{ readonly status: number; readonly body: Uint8Array }> {
105
+ const signals = [AbortSignal.timeout(request.timeoutMs)];
106
+ if (request.signal !== undefined) signals.push(request.signal);
107
+ const signal = AbortSignal.any(signals);
108
+ const body = new Uint8Array(request.body.byteLength);
109
+ body.set(request.body);
110
+ const response = await fetch(request.url, {
111
+ method: "POST",
112
+ headers: request.headers,
113
+ body: body.buffer,
114
+ redirect: "error",
115
+ signal,
116
+ });
117
+ // A nonstandard fetch may fulfill after abort. Release its body without
118
+ // waiting for an uncooperative cancel implementation.
119
+ if (signal.aborted) {
120
+ void response.body?.cancel().catch(() => undefined);
121
+ throw new Error("request aborted");
122
+ }
123
+ return {
124
+ status: response.status,
125
+ body: await readBoundedResponse(response, request.maxResponseBytes, signal),
126
+ };
127
+ }
128
+
129
+ function finiteNumber(value: unknown): number | null {
130
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
131
+ }
132
+
133
+ function recordValue(value: unknown): Record<string, unknown> | null {
134
+ return typeof value === "object" && value !== null && !Array.isArray(value)
135
+ ? value as Record<string, unknown>
136
+ : null;
137
+ }
138
+
139
+ function hasExactKeys(
140
+ value: Record<string, unknown>,
141
+ expected: readonly string[],
142
+ ): boolean {
143
+ const actual = Object.keys(value);
144
+ return actual.length === expected.length
145
+ && expected.every((key) => Object.hasOwn(value, key));
146
+ }
147
+
148
+ function tokenCount(value: unknown): number | null {
149
+ return typeof value === "number"
150
+ && Number.isSafeInteger(value)
151
+ && value >= 0
152
+ && value <= 1_000_000_000
153
+ ? value
154
+ : null;
155
+ }
156
+
157
+ function acceptedResponseModel(value: unknown): value is string {
158
+ return value === DEFAULT_SYSTEMONE_MODEL;
159
+ }
160
+
161
+ function parseSystemOneResponse(value: unknown): ParsedSystemOneAnswer | null {
162
+ const root = recordValue(value);
163
+ if (root === null || !hasExactKeys(root, ["model", "answers", "usage"])) return null;
164
+ const answers = recordValue(root["answers"]);
165
+ if (answers === null || !hasExactKeys(answers, [RELEVANCE_QUESTION])) return null;
166
+ const answer = recordValue(answers[RELEVANCE_QUESTION]);
167
+ if (
168
+ answer === null
169
+ || !hasExactKeys(answer, ["type", "noul"])
170
+ || answer["type"] !== "noul"
171
+ ) return null;
172
+ const noul = finiteNumber(answer["noul"]);
173
+ if (noul === null || noul < 0 || noul > 1) return null;
174
+ const usage = recordValue(root["usage"]);
175
+ if (usage === null || !hasExactKeys(usage, ["input_tokens", "output_tokens"])) return null;
176
+ const inputTokens = tokenCount(usage["input_tokens"]);
177
+ const outputTokens = tokenCount(usage["output_tokens"]);
178
+ if (
179
+ !acceptedResponseModel(root["model"])
180
+ || inputTokens === null
181
+ || outputTokens === null
182
+ ) return null;
183
+ return { noul, model: root["model"], inputTokens, outputTokens };
184
+ }
185
+
186
+ async function mapWithConcurrency<T, R>(
187
+ items: readonly T[],
188
+ concurrency: number,
189
+ operation: (item: T, index: number) => Promise<R>,
190
+ ): Promise<R[]> {
191
+ const results = new Array<R>(items.length);
192
+ let cursor = 0;
193
+ const workers = Array.from(
194
+ { length: Math.max(1, Math.min(concurrency, items.length)) },
195
+ async () => {
196
+ while (cursor < items.length) {
197
+ const index = cursor;
198
+ cursor += 1;
199
+ results[index] = await operation(items[index] as T, index);
200
+ }
201
+ },
202
+ );
203
+ await Promise.all(workers);
204
+ return results;
205
+ }
206
+
207
+ function validApiKey(value: string | undefined): value is string {
208
+ return value !== undefined && /^[\x21-\x7e]{1,512}$/u.test(value);
209
+ }
210
+
211
+ function boundedPositiveInteger(
212
+ value: number | undefined,
213
+ fallback: number,
214
+ maximum: number,
215
+ ): number | null {
216
+ const resolved = value ?? fallback;
217
+ return Number.isSafeInteger(resolved) && resolved >= 1 && resolved <= maximum
218
+ ? resolved
219
+ : null;
220
+ }
221
+
222
+ function validRerankRequest(value: unknown): value is SearchRerankRequest {
223
+ const request = recordValue(value);
224
+ if (
225
+ request === null
226
+ || typeof request["query"] !== "string"
227
+ || request["query"].trim() === ""
228
+ || Buffer.byteLength(request["query"], "utf8") > MAX_RERANK_STATE_BYTES
229
+ || (request["signal"] !== undefined && !(request["signal"] instanceof AbortSignal))
230
+ || !Array.isArray(request["candidates"])
231
+ || request["candidates"].length > MAX_RERANK_CANDIDATES
232
+ ) return false;
233
+ const ids = new Set<string>();
234
+ for (const [index, value] of request["candidates"].entries()) {
235
+ const candidate = recordValue(value);
236
+ if (
237
+ candidate === null
238
+ || typeof candidate["id"] !== "string"
239
+ || candidate["id"] === ""
240
+ || ids.has(candidate["id"])
241
+ || candidate["baselineRank"] !== index + 1
242
+ || typeof candidate["score"] !== "number"
243
+ || !Number.isFinite(candidate["score"])
244
+ || typeof candidate["title"] !== "string"
245
+ || typeof candidate["path"] !== "string"
246
+ || typeof candidate["snippet"] !== "string"
247
+ || Buffer.byteLength(candidate["id"], "utf8") > MAX_RERANK_STATE_BYTES
248
+ || Buffer.byteLength(candidate["title"], "utf8") > MAX_RERANK_STATE_BYTES
249
+ || Buffer.byteLength(candidate["path"], "utf8") > MAX_RERANK_STATE_BYTES
250
+ || Buffer.byteLength(candidate["snippet"], "utf8") > MAX_RERANK_SNIPPET_BYTES
251
+ ) return false;
252
+ ids.add(candidate["id"]);
253
+ }
254
+ return true;
255
+ }
256
+
257
+ type ScoredCandidate =
258
+ | {
259
+ readonly ok: true;
260
+ readonly noul: number;
261
+ readonly model: string;
262
+ readonly inputTokens: number;
263
+ readonly outputTokens: number;
264
+ }
265
+ | { readonly ok: false; readonly message: string };
266
+
267
+ /**
268
+ * Pointwise-noul reranker for the TypeSafe System One API. Each candidate is
269
+ * scored by one independent noul question so the window keeps an inspectable
270
+ * model-assigned relevance probability per note. The API key is read only from
271
+ * the TYPESAFE_API_KEY environment variable. A missing key degrades to
272
+ * `unavailable` without any network call; transport, HTTP, timeout, and
273
+ * malformed-response failures degrade to `failed` without provider bodies.
274
+ */
275
+ export function createTypeSafeReranker(
276
+ options: TypeSafeRerankerOptions = {},
277
+ ): SearchReranker {
278
+ const transport = options.transport ?? fetchSystemOneTransport;
279
+ const timeoutMs = boundedPositiveInteger(
280
+ options.timeoutMs,
281
+ DEFAULT_RERANK_TIMEOUT_MS,
282
+ MAX_RERANK_TIMEOUT_MS,
283
+ );
284
+ const maxResponseBytes = boundedPositiveInteger(
285
+ options.maxResponseBytes,
286
+ DEFAULT_RERANK_MAX_RESPONSE_BYTES,
287
+ MAX_RERANK_RESPONSE_BYTES,
288
+ );
289
+ const concurrency = boundedPositiveInteger(
290
+ options.concurrency,
291
+ DEFAULT_RERANK_CONCURRENCY,
292
+ MAX_RERANK_CONCURRENCY,
293
+ );
294
+ const environment = options.environment ?? process.env;
295
+ const apiKey = Object.hasOwn(environment, "TYPESAFE_API_KEY")
296
+ ? environment["TYPESAFE_API_KEY"]
297
+ : undefined;
298
+
299
+ return {
300
+ id: "typesafe",
301
+ rerank: async (request: SearchRerankRequest): Promise<SearchRerankResult> => {
302
+ const started = performance.now();
303
+ const controller = new AbortController();
304
+ let attempted = 0;
305
+ let completed = 0;
306
+ let usageReceipts = 0;
307
+ let inputTokens = 0;
308
+ let outputTokens = 0;
309
+ let candidateCount = 0;
310
+ let observedModel: string | undefined;
311
+ let closed = false;
312
+ let firstFailure: string | undefined;
313
+ let timer: ReturnType<typeof setTimeout> | undefined;
314
+ let callerAbort: (() => void) | undefined;
315
+ let callerSignal: AbortSignal | undefined;
316
+ let resolveStopped: (() => void) | undefined;
317
+ const stopped = new Promise<void>((resolve) => { resolveStopped = resolve; });
318
+ const stop = (message: string): void => {
319
+ firstFailure ??= message;
320
+ controller.abort();
321
+ resolveStopped?.();
322
+ };
323
+ const details = (): SearchRerankDetails => attempted === 0 ? {} : {
324
+ ...(observedModel === undefined ? {} : { model: observedModel }),
325
+ usage: Object.freeze({ inputTokens, outputTokens }),
326
+ accounting: Object.freeze({
327
+ candidates: candidateCount, attempted, completed,
328
+ elapsedMs: performance.now() - started,
329
+ usageComplete: usageReceipts === attempted && completed === attempted,
330
+ }),
331
+ };
332
+ const failed = (message: string): SearchRerankResult => ({
333
+ status: "failed", message, ...details(),
334
+ });
335
+ try {
336
+ if (timeoutMs === null || maxResponseBytes === null || concurrency === null) {
337
+ return failed("TypeSafe rerank configuration was invalid.");
338
+ }
339
+ if (!validRerankRequest(request)) {
340
+ return failed("TypeSafe rerank request was malformed or exceeded its limits.");
341
+ }
342
+ candidateCount = request.candidates.length;
343
+ callerSignal = request.signal;
344
+ if (callerSignal?.aborted === true) {
345
+ return failed("TypeSafe rerank request was aborted.");
346
+ }
347
+ if (!validApiKey(apiKey)) {
348
+ return { status: "unavailable", message: "TYPESAFE_API_KEY is missing or invalid; the TypeSafe rerank lane is unavailable." };
349
+ }
350
+ if (candidateCount === 0) return { status: "ready", ordering: [], probabilities: {} };
351
+ const encoder = new TextEncoder();
352
+ const decoder = new TextDecoder("utf-8", { fatal: true });
353
+ // Admit the entire bounded window before any paid request.
354
+ const bodies: Uint8Array[] = [];
355
+ for (const candidate of request.candidates) {
356
+ const state = { query: request.query, candidate: {
357
+ key: candidate.id, title: candidate.title, path: candidate.path, snippet: candidate.snippet,
358
+ } };
359
+ if (encoder.encode(JSON.stringify(state)).byteLength > MAX_RERANK_STATE_BYTES) {
360
+ return failed(`TypeSafe rerank state exceeds the ${MAX_RERANK_STATE_BYTES}-byte limit.`);
361
+ }
362
+ bodies.push(encoder.encode(JSON.stringify({
363
+ model: DEFAULT_SYSTEMONE_MODEL, state,
364
+ questions: { [RELEVANCE_QUESTION]: {
365
+ type: "noul", instructions: RELEVANCE_INSTRUCTIONS, criteria: RELEVANCE_CRITERIA,
366
+ } },
367
+ })));
368
+ }
369
+ const deadline = started + timeoutMs;
370
+ const timeoutMessage = "TypeSafe rerank window exceeded its deadline.";
371
+ callerAbort = () => stop("TypeSafe rerank request was aborted.");
372
+ callerSignal?.addEventListener("abort", callerAbort, { once: true });
373
+ if (callerSignal?.aborted) callerAbort();
374
+ timer = setTimeout(() => stop(timeoutMessage), Math.max(0, deadline - performance.now()));
375
+ const scored = await Promise.race([
376
+ mapWithConcurrency(bodies, concurrency, async (body): Promise<ScoredCandidate> => {
377
+ if (closed || firstFailure !== undefined) return { ok: false, message: firstFailure ?? timeoutMessage };
378
+ if (performance.now() >= deadline) {
379
+ stop(timeoutMessage);
380
+ return { ok: false, message: timeoutMessage };
381
+ }
382
+ attempted += 1;
383
+ let response: { readonly status: number; readonly body: Uint8Array };
384
+ try {
385
+ response = await transport({
386
+ url: DEFAULT_SYSTEMONE_ENDPOINT, body,
387
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
388
+ timeoutMs: Math.max(1, Math.ceil(deadline - performance.now())),
389
+ maxResponseBytes, signal: controller.signal,
390
+ });
391
+ } catch {
392
+ if (!closed) {
393
+ completed += 1;
394
+ stop("TypeSafe rerank request failed.");
395
+ }
396
+ return { ok: false, message: firstFailure ?? "TypeSafe rerank request failed." };
397
+ }
398
+ // Late fulfillment cannot change a returned receipt or dispatch queued work.
399
+ if (closed) return { ok: false, message: firstFailure ?? timeoutMessage };
400
+ completed += 1;
401
+ if (performance.now() >= deadline) stop(timeoutMessage);
402
+ try {
403
+ if (!Number.isSafeInteger(response.status) || !(response.body instanceof Uint8Array)
404
+ || response.body.byteLength > maxResponseBytes) {
405
+ stop("TypeSafe rerank transport returned a malformed or oversized response.");
406
+ return { ok: false, message: firstFailure! };
407
+ }
408
+ let parsed: unknown;
409
+ try { parsed = JSON.parse(decoder.decode(response.body)) as unknown; }
410
+ catch {
411
+ stop(response.status === 200 ? "TypeSafe rerank response was not valid UTF-8 JSON." : `TypeSafe rerank request returned HTTP ${response.status}.`);
412
+ return { ok: false, message: firstFailure! };
413
+ }
414
+ // Billing evidence is independent of whether the relevance answer is usable.
415
+ const root = recordValue(parsed);
416
+ const usage = recordValue(root?.["usage"]);
417
+ const input = tokenCount(usage?.["input_tokens"]);
418
+ const output = tokenCount(usage?.["output_tokens"]);
419
+ if (usage !== null && hasExactKeys(usage, ["input_tokens", "output_tokens"])
420
+ && input !== null && output !== null) {
421
+ if (inputTokens + input > 1_000_000_000 || outputTokens + output > 1_000_000_000) {
422
+ stop("TypeSafe rerank aggregate usage exceeded its limits.");
423
+ return { ok: false, message: firstFailure! };
424
+ }
425
+ inputTokens += input;
426
+ outputTokens += output;
427
+ usageReceipts += 1;
428
+ }
429
+ if (acceptedResponseModel(root?.["model"])) observedModel = DEFAULT_SYSTEMONE_MODEL;
430
+ if (response.status !== 200) {
431
+ stop(`TypeSafe rerank request returned HTTP ${response.status}.`);
432
+ return { ok: false, message: firstFailure! };
433
+ }
434
+ const answer = parseSystemOneResponse(parsed);
435
+ if (answer === null) {
436
+ stop("TypeSafe rerank response was malformed.");
437
+ return { ok: false, message: firstFailure! };
438
+ }
439
+ return { ok: true, ...answer };
440
+ } catch {
441
+ stop("TypeSafe rerank transport returned a malformed response.");
442
+ return { ok: false, message: firstFailure! };
443
+ }
444
+ }),
445
+ stopped.then(() => undefined),
446
+ ]);
447
+ closed = true;
448
+ if (firstFailure !== undefined) return failed(firstFailure);
449
+ if (scored === undefined || scored.some((entry) => !entry.ok)) {
450
+ return failed("TypeSafe rerank result was incomplete.");
451
+ }
452
+ const probabilities: Record<string, number> = Object.create(null) as Record<string, number>;
453
+ for (const [index, entry] of scored.entries()) {
454
+ const candidate = request.candidates[index];
455
+ if (candidate === undefined || !entry.ok) return failed("TypeSafe rerank result was incomplete.");
456
+ probabilities[candidate.id] = entry.noul;
457
+ }
458
+ const ordering = request.candidates.toSorted((left, right) =>
459
+ (probabilities[right.id] ?? -1) - (probabilities[left.id] ?? -1)
460
+ || left.baselineRank - right.baselineRank || left.id.localeCompare(right.id)).map(({ id }) => id);
461
+ return { status: "ready", ordering: Object.freeze(ordering), probabilities, ...details() };
462
+ } catch {
463
+ return failed("TypeSafe rerank request was malformed or failed.");
464
+ } finally {
465
+ closed = true;
466
+ if (timer !== undefined) clearTimeout(timer);
467
+ if (callerAbort !== undefined) callerSignal?.removeEventListener("abort", callerAbort);
468
+ controller.abort();
469
+ }
470
+ },
471
+ };
472
+ }