@librechat/agents 4.0.6 → 4.1.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 (175) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +6 -4
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/decisions/breaker.cjs +59 -0
  4. package/dist/cjs/decisions/breaker.cjs.map +1 -0
  5. package/dist/cjs/decisions/core.cjs +44 -0
  6. package/dist/cjs/decisions/dialect.cjs +65 -12
  7. package/dist/cjs/decisions/dialect.cjs.map +1 -1
  8. package/dist/cjs/decisions/hook.cjs +19 -0
  9. package/dist/cjs/decisions/hook.cjs.map +1 -0
  10. package/dist/cjs/decisions/http.cjs +2 -1
  11. package/dist/cjs/decisions/http.cjs.map +1 -1
  12. package/dist/cjs/decisions/index.cjs +6 -0
  13. package/dist/cjs/decisions/node.cjs +315 -0
  14. package/dist/cjs/decisions/node.cjs.map +1 -0
  15. package/dist/cjs/decisions/probe.cjs +56 -0
  16. package/dist/cjs/decisions/probe.cjs.map +1 -0
  17. package/dist/cjs/decisions/redact.cjs +109 -0
  18. package/dist/cjs/decisions/redact.cjs.map +1 -0
  19. package/dist/cjs/decisions/structuredChat.cjs +2 -3
  20. package/dist/cjs/decisions/structuredChat.cjs.map +1 -1
  21. package/dist/cjs/decisions/transport.cjs +56 -23
  22. package/dist/cjs/decisions/transport.cjs.map +1 -1
  23. package/dist/cjs/decisions/types.cjs +2 -0
  24. package/dist/cjs/decisions/types.cjs.map +1 -1
  25. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -0
  26. package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
  27. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  28. package/dist/cjs/llm/bedrock/index.cjs +8 -5
  29. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  30. package/dist/cjs/main.cjs +45 -0
  31. package/dist/cjs/rerank/bm25.cjs +110 -0
  32. package/dist/cjs/rerank/bm25.cjs.map +1 -0
  33. package/dist/cjs/rerank/cache.cjs +50 -0
  34. package/dist/cjs/rerank/cache.cjs.map +1 -0
  35. package/dist/cjs/rerank/core.cjs +29 -0
  36. package/dist/cjs/rerank/crossEncoder.cjs +172 -0
  37. package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
  38. package/dist/cjs/rerank/fallback.cjs +280 -0
  39. package/dist/cjs/rerank/fallback.cjs.map +1 -0
  40. package/dist/cjs/rerank/index.cjs +8 -0
  41. package/dist/cjs/rerank/outcome.cjs +382 -0
  42. package/dist/cjs/rerank/outcome.cjs.map +1 -0
  43. package/dist/cjs/rerank/pin.cjs +74 -0
  44. package/dist/cjs/rerank/pin.cjs.map +1 -0
  45. package/dist/cjs/rerank/semaphore.cjs +38 -0
  46. package/dist/cjs/rerank/semaphore.cjs.map +1 -0
  47. package/dist/cjs/rerank/systemone.cjs +476 -50
  48. package/dist/cjs/rerank/systemone.cjs.map +1 -1
  49. package/dist/cjs/session/AgentSession.cjs +1 -1
  50. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  51. package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
  52. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  53. package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
  54. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  55. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
  56. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  57. package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
  58. package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
  59. package/dist/esm/agents/AgentContext.mjs +7 -5
  60. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  61. package/dist/esm/decisions/breaker.mjs +56 -0
  62. package/dist/esm/decisions/breaker.mjs.map +1 -0
  63. package/dist/esm/decisions/core.mjs +11 -0
  64. package/dist/esm/decisions/dialect.mjs +65 -12
  65. package/dist/esm/decisions/dialect.mjs.map +1 -1
  66. package/dist/esm/decisions/hook.mjs +19 -0
  67. package/dist/esm/decisions/hook.mjs.map +1 -0
  68. package/dist/esm/decisions/http.mjs +2 -1
  69. package/dist/esm/decisions/http.mjs.map +1 -1
  70. package/dist/esm/decisions/index.mjs +6 -0
  71. package/dist/esm/decisions/node.mjs +313 -0
  72. package/dist/esm/decisions/node.mjs.map +1 -0
  73. package/dist/esm/decisions/probe.mjs +54 -0
  74. package/dist/esm/decisions/probe.mjs.map +1 -0
  75. package/dist/esm/decisions/redact.mjs +108 -0
  76. package/dist/esm/decisions/redact.mjs.map +1 -0
  77. package/dist/esm/decisions/structuredChat.mjs +2 -3
  78. package/dist/esm/decisions/structuredChat.mjs.map +1 -1
  79. package/dist/esm/decisions/transport.mjs +56 -23
  80. package/dist/esm/decisions/transport.mjs.map +1 -1
  81. package/dist/esm/decisions/types.mjs +2 -0
  82. package/dist/esm/decisions/types.mjs.map +1 -1
  83. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
  84. package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
  85. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  86. package/dist/esm/llm/bedrock/index.mjs +7 -4
  87. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  88. package/dist/esm/main.mjs +15 -3
  89. package/dist/esm/rerank/bm25.mjs +108 -0
  90. package/dist/esm/rerank/bm25.mjs.map +1 -0
  91. package/dist/esm/rerank/cache.mjs +50 -0
  92. package/dist/esm/rerank/cache.mjs.map +1 -0
  93. package/dist/esm/rerank/core.mjs +9 -0
  94. package/dist/esm/rerank/crossEncoder.mjs +172 -0
  95. package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
  96. package/dist/esm/rerank/fallback.mjs +278 -0
  97. package/dist/esm/rerank/fallback.mjs.map +1 -0
  98. package/dist/esm/rerank/index.mjs +8 -0
  99. package/dist/esm/rerank/outcome.mjs +360 -0
  100. package/dist/esm/rerank/outcome.mjs.map +1 -0
  101. package/dist/esm/rerank/pin.mjs +73 -0
  102. package/dist/esm/rerank/pin.mjs.map +1 -0
  103. package/dist/esm/rerank/semaphore.mjs +38 -0
  104. package/dist/esm/rerank/semaphore.mjs.map +1 -0
  105. package/dist/esm/rerank/systemone.mjs +476 -50
  106. package/dist/esm/rerank/systemone.mjs.map +1 -1
  107. package/dist/esm/session/AgentSession.mjs +1 -1
  108. package/dist/esm/session/AgentSession.mjs.map +1 -1
  109. package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
  110. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  111. package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
  112. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  113. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
  114. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  115. package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
  116. package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
  117. package/dist/types/decisions/breaker.d.ts +37 -0
  118. package/dist/types/decisions/core.d.ts +19 -0
  119. package/dist/types/decisions/hook.d.ts +9 -0
  120. package/dist/types/decisions/index.d.ts +3 -8
  121. package/dist/types/decisions/node.d.ts +90 -0
  122. package/dist/types/decisions/probe.d.ts +37 -0
  123. package/dist/types/decisions/redact.d.ts +22 -0
  124. package/dist/types/decisions/structuredChat.d.ts +1 -0
  125. package/dist/types/decisions/transport.d.ts +16 -3
  126. package/dist/types/decisions/types.d.ts +43 -4
  127. package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
  128. package/dist/types/llm/bedrock/index.d.ts +2 -1
  129. package/dist/types/rerank/bm25.d.ts +46 -0
  130. package/dist/types/rerank/cache.d.ts +40 -0
  131. package/dist/types/rerank/core.d.ts +24 -0
  132. package/dist/types/rerank/crossEncoder.d.ts +48 -0
  133. package/dist/types/rerank/fallback.d.ts +67 -0
  134. package/dist/types/rerank/index.d.ts +1 -3
  135. package/dist/types/rerank/outcome.d.ts +144 -0
  136. package/dist/types/rerank/pin.d.ts +48 -0
  137. package/dist/types/rerank/semaphore.d.ts +9 -0
  138. package/dist/types/rerank/systemone.d.ts +51 -5
  139. package/dist/types/rerank/types.d.ts +116 -1
  140. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
  141. package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
  142. package/dist/types/types/tools.d.ts +16 -0
  143. package/package.json +26 -1
  144. package/src/agents/AgentContext.ts +33 -4
  145. package/src/decisions/breaker.ts +110 -0
  146. package/src/decisions/core.ts +23 -0
  147. package/src/decisions/dialect.ts +134 -20
  148. package/src/decisions/hook.ts +32 -0
  149. package/src/decisions/http.ts +4 -1
  150. package/src/decisions/index.ts +3 -12
  151. package/src/decisions/node.ts +671 -0
  152. package/src/decisions/probe.ts +114 -0
  153. package/src/decisions/redact.ts +222 -0
  154. package/src/decisions/structuredChat.ts +6 -8
  155. package/src/decisions/transport.ts +104 -22
  156. package/src/decisions/types.ts +46 -5
  157. package/src/llm/bedrock/cachePoints.ts +47 -0
  158. package/src/llm/bedrock/index.ts +35 -13
  159. package/src/rerank/bm25.ts +190 -0
  160. package/src/rerank/cache.ts +103 -0
  161. package/src/rerank/core.ts +47 -0
  162. package/src/rerank/crossEncoder.ts +289 -0
  163. package/src/rerank/fallback.ts +625 -0
  164. package/src/rerank/index.ts +1 -3
  165. package/src/rerank/outcome.ts +767 -0
  166. package/src/rerank/pin.ts +157 -0
  167. package/src/rerank/semaphore.ts +47 -0
  168. package/src/rerank/systemone.ts +914 -88
  169. package/src/rerank/types.ts +143 -1
  170. package/src/session/AgentSession.ts +3 -1
  171. package/src/tools/local/LocalCodingTools.ts +139 -19
  172. package/src/tools/local/LocalExecutionTools.ts +21 -1
  173. package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
  174. package/src/tools/local/toolResultCaps.ts +60 -0
  175. package/src/types/tools.ts +16 -0
@@ -0,0 +1,767 @@
1
+ import type {
2
+ Reranker,
3
+ RerankKind,
4
+ RerankResult,
5
+ RerankEntry,
6
+ RerankUsage,
7
+ RankRequest,
8
+ RerankReason,
9
+ RerankAttempt,
10
+ RerankOutcome,
11
+ OutcomeReranker,
12
+ } from './types';
13
+ import type { DecisionFailure } from '../decisions/types';
14
+ import { DecisionError, isDecisionObject } from '../decisions/types';
15
+ import { withDecisionDeadline } from '../decisions/deadline';
16
+ import { failureForStatus } from '../decisions/transport';
17
+
18
+ /** Longest deadline a step may have; matches `withDecisionDeadline`. */
19
+ export const MAX_RERANK_DEADLINE_MS = 3_600_000;
20
+
21
+ /**
22
+ * Input tokens one document costs a request, rounded up from Codegraph's
23
+ * measurements on file summaries (Jev with its rubric and question ~520,
24
+ * qwen3-reranker-8b ~140). Override per reranker for other document shapes.
25
+ */
26
+ export const ESTIMATED_TOKENS_PER_DOCUMENT: Readonly<
27
+ Record<RerankKind, number>
28
+ > = Object.freeze({
29
+ systemone: 600,
30
+ 'cross-encoder': 200,
31
+ bm25: 0,
32
+ none: 0,
33
+ });
34
+
35
+ export function emptyRerankUsage(): RerankUsage {
36
+ return {
37
+ calls: 0,
38
+ inputTokens: 0,
39
+ outputTokens: 0,
40
+ searchUnits: 0,
41
+ cached: 0,
42
+ estimatedTokens: 0,
43
+ estimatedSearchUnits: 0,
44
+ };
45
+ }
46
+
47
+ const USAGE_KEYS = [
48
+ 'calls',
49
+ 'inputTokens',
50
+ 'outputTokens',
51
+ 'searchUnits',
52
+ 'cached',
53
+ 'estimatedTokens',
54
+ 'estimatedSearchUnits',
55
+ ] as const;
56
+
57
+ const count = (value: unknown): number =>
58
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
59
+
60
+ /** Every usage counter present as a finite number of at least zero. */
61
+ export function isRerankUsage(value: unknown): value is RerankUsage {
62
+ if (!isDecisionObject(value)) {
63
+ return false;
64
+ }
65
+ for (const key of USAGE_KEYS) {
66
+ const counter = value[key];
67
+ if (
68
+ typeof counter !== 'number' ||
69
+ !Number.isFinite(counter) ||
70
+ counter < 0
71
+ ) {
72
+ return false;
73
+ }
74
+ }
75
+ return true;
76
+ }
77
+
78
+ /** Adds `usage` into `sum`; anything that is not a positive finite count adds nothing. */
79
+ export function addRerankUsage(sum: RerankUsage, usage: unknown): RerankUsage {
80
+ if (!isDecisionObject(usage)) {
81
+ return sum;
82
+ }
83
+ for (const key of USAGE_KEYS) {
84
+ sum[key] += count(usage[key]);
85
+ }
86
+ return sum;
87
+ }
88
+
89
+ /**
90
+ * The usage `documents` documents sent and never answered are charged as. A
91
+ * deadline aborts the client, not the host: the host received the request and
92
+ * bills it, so counting only answered calls lets every timeout spend without
93
+ * reaching a budget. A cross-encoder request is one search unit per 100
94
+ * documents, as Cohere bills it. `bm25` and `none` cost nothing.
95
+ */
96
+ export function estimatedUsage(
97
+ kind: RerankKind,
98
+ documents: number,
99
+ tokensPerDocument: number = ESTIMATED_TOKENS_PER_DOCUMENT[kind]
100
+ ): Pick<RerankUsage, 'estimatedTokens' | 'estimatedSearchUnits'> {
101
+ const n = Math.max(0, Math.floor(count(documents)));
102
+ if (n === 0 || kind === 'bm25' || kind === 'none') {
103
+ return { estimatedTokens: 0, estimatedSearchUnits: 0 };
104
+ }
105
+ // Search units follow the document count alone, so a zero token estimate never hides them.
106
+ return {
107
+ estimatedTokens: n * count(tokensPerDocument),
108
+ estimatedSearchUnits: kind === 'cross-encoder' ? Math.ceil(n / 100) : 0,
109
+ };
110
+ }
111
+
112
+ /** An `estimatedTokensPerDocument` option: absent, or a finite count of at least zero. */
113
+ export const isTokenEstimate = (value: unknown): boolean =>
114
+ value === undefined ||
115
+ (typeof value === 'number' && Number.isFinite(value) && value >= 0);
116
+
117
+ /**
118
+ * Prices in USD for one model; the SDK ships none. A rate is a finite number
119
+ * of at least zero: `0` prices a dimension as free, while an absent or invalid
120
+ * rate leaves usage of that dimension unpriced.
121
+ */
122
+ export interface RerankPrice {
123
+ inputPerMTok?: number;
124
+ outputPerMTok?: number;
125
+ perSearchUnit?: number;
126
+ }
127
+
128
+ /**
129
+ * A caller-supplied price table: per kind, a model id, a `prefix*` pattern
130
+ * (the longest match wins), or `*` for any model of that kind.
131
+ */
132
+ export type RerankPrices = Readonly<
133
+ Partial<Record<RerankKind, Readonly<Record<string, RerankPrice>>>>
134
+ >;
135
+
136
+ export interface RerankCost {
137
+ /** Every attempt, estimates included. */
138
+ usd: number;
139
+ /**
140
+ * Attempts that used something the table has no rate for (no entry, or an
141
+ * entry without a rate for a dimension they used); their spend is not in `usd`.
142
+ */
143
+ unpriced: Array<{ provider: RerankKind; model: string }>;
144
+ }
145
+
146
+ function priceFor(
147
+ table: Readonly<Record<string, RerankPrice>> | undefined,
148
+ model: string
149
+ ): RerankPrice | undefined {
150
+ if (!table) {
151
+ return undefined;
152
+ }
153
+ if (Object.hasOwn(table, model)) {
154
+ return table[model];
155
+ }
156
+ let best: string | undefined;
157
+ for (const key of Object.keys(table)) {
158
+ if (
159
+ key.endsWith('*') &&
160
+ model.startsWith(key.slice(0, -1)) &&
161
+ (best === undefined || key.length > best.length)
162
+ ) {
163
+ best = key;
164
+ }
165
+ }
166
+ return best === undefined ? undefined : table[best];
167
+ }
168
+
169
+ /** A rate the table sets, or `undefined` when it sets none it can be priced by. */
170
+ const rateOf = (value: unknown): number | undefined =>
171
+ typeof value === 'number' && Number.isFinite(value) && value >= 0
172
+ ? value
173
+ : undefined;
174
+
175
+ /**
176
+ * One attempt's spend under `price`, or `undefined` when part of it has no
177
+ * rate. Each reported dimension needs its own rate. An estimate books tokens
178
+ * and search units together because the SDK cannot tell which one the host
179
+ * bills, so it is priced by the rates the entry has and is unpriced only when
180
+ * the entry has a rate for neither.
181
+ */
182
+ function attemptCost(
183
+ usage: RerankAttempt['usage'],
184
+ price: unknown
185
+ ): number | undefined {
186
+ if (!isDecisionObject(price)) {
187
+ return undefined;
188
+ }
189
+ const input = rateOf(price.inputPerMTok);
190
+ const output = rateOf(price.outputPerMTok);
191
+ const unit = rateOf(price.perSearchUnit);
192
+ const tokens = count(usage.inputTokens);
193
+ const outputTokens = count(usage.outputTokens);
194
+ const units = count(usage.searchUnits);
195
+ const estimatedTokens = count(usage.estimatedTokens);
196
+ const estimatedUnits = count(usage.estimatedSearchUnits);
197
+ if (
198
+ (tokens > 0 && input === undefined) ||
199
+ (outputTokens > 0 && output === undefined) ||
200
+ (units > 0 && unit === undefined)
201
+ ) {
202
+ return undefined;
203
+ }
204
+ if (
205
+ (estimatedTokens > 0 || estimatedUnits > 0) &&
206
+ !(estimatedTokens > 0 && input !== undefined) &&
207
+ !(estimatedUnits > 0 && unit !== undefined)
208
+ ) {
209
+ return undefined;
210
+ }
211
+ return (
212
+ ((tokens + estimatedTokens) * (input ?? 0)) / 1e6 +
213
+ (outputTokens * (output ?? 0)) / 1e6 +
214
+ (units + estimatedUnits) * (unit ?? 0)
215
+ );
216
+ }
217
+
218
+ /**
219
+ * What an outcome's attempts cost under `prices`; reported and estimated
220
+ * usage are priced alike. An attempt with usage the table has no rate for is
221
+ * listed in `unpriced` and adds nothing to `usd`, never counted as free.
222
+ */
223
+ export function rerankCost(
224
+ outcome: Pick<RerankOutcome, 'attempts'>,
225
+ prices: RerankPrices
226
+ ): RerankCost {
227
+ let usd = 0;
228
+ const unpriced: RerankCost['unpriced'] = [];
229
+ for (const attempt of outcome.attempts) {
230
+ const tokens =
231
+ count(attempt.usage.inputTokens) + count(attempt.usage.estimatedTokens);
232
+ const output = count(attempt.usage.outputTokens);
233
+ const units =
234
+ count(attempt.usage.searchUnits) +
235
+ count(attempt.usage.estimatedSearchUnits);
236
+ if (tokens === 0 && output === 0 && units === 0) {
237
+ continue;
238
+ }
239
+ const spent = attemptCost(
240
+ attempt.usage,
241
+ priceFor(prices[attempt.provider], attempt.model)
242
+ );
243
+ if (spent === undefined) {
244
+ if (
245
+ !unpriced.some(
246
+ (seen) =>
247
+ seen.provider === attempt.provider && seen.model === attempt.model
248
+ )
249
+ ) {
250
+ unpriced.push({ provider: attempt.provider, model: attempt.model });
251
+ }
252
+ continue;
253
+ }
254
+ usd += spent;
255
+ }
256
+ return { usd: Math.round(usd * 1e9) / 1e9, unpriced };
257
+ }
258
+
259
+ function byScore(a: RerankEntry, b: RerankEntry): number {
260
+ if (a.score === null) {
261
+ return b.score === null ? a.index - b.index : 1;
262
+ }
263
+ if (b.score === null) {
264
+ return -1;
265
+ }
266
+ return b.score - a.score || a.index - b.index;
267
+ }
268
+
269
+ /** Every input once, score descending, ties in input order, `null` last; a threshold adds `kept`. */
270
+ export function rankedEntries(
271
+ scores: ReadonlyArray<number | null>,
272
+ threshold?: number
273
+ ): RerankEntry[] {
274
+ return scores
275
+ .map(
276
+ (score, index): RerankEntry =>
277
+ threshold === undefined
278
+ ? { index, score }
279
+ : { index, score, kept: score !== null && score >= threshold }
280
+ )
281
+ .sort(byScore);
282
+ }
283
+
284
+ const KINDS: ReadonlySet<string> = new Set<RerankKind>([
285
+ 'systemone',
286
+ 'cross-encoder',
287
+ 'bm25',
288
+ 'none',
289
+ ]);
290
+
291
+ export const isRerankKind = (value: unknown): value is RerankKind =>
292
+ typeof value === 'string' && KINDS.has(value);
293
+
294
+ /**
295
+ * Whether a permutation is in the order `rankedEntries` produces: score
296
+ * descending, ties in input order, `null` last, with `kept` a boolean when set.
297
+ */
298
+ export function isRankedOrder(results: readonly RerankEntry[]): boolean {
299
+ for (let index = 0; index < results.length; index++) {
300
+ const entry = results[index];
301
+ if (entry.kept !== undefined && typeof entry.kept !== 'boolean') {
302
+ return false;
303
+ }
304
+ if (index > 0 && byScore(results[index - 1], entry) >= 0) {
305
+ return false;
306
+ }
307
+ }
308
+ return true;
309
+ }
310
+
311
+ /** Whether `results` is a full permutation of `count` documents with finite or `null` scores. */
312
+ export function isRerankPermutation(
313
+ results: unknown,
314
+ count: number
315
+ ): results is RerankEntry[] {
316
+ if (!Array.isArray(results) || results.length !== count) {
317
+ return false;
318
+ }
319
+ const seen = new Uint8Array(count);
320
+ for (const entry of results as unknown[]) {
321
+ if (!isDecisionObject(entry)) {
322
+ return false;
323
+ }
324
+ const { index, score } = entry;
325
+ if (
326
+ typeof index !== 'number' ||
327
+ !Number.isSafeInteger(index) ||
328
+ index < 0 ||
329
+ index >= count ||
330
+ seen[index] === 1 ||
331
+ (score !== null && (typeof score !== 'number' || !Number.isFinite(score)))
332
+ ) {
333
+ return false;
334
+ }
335
+ seen[index] = 1;
336
+ }
337
+ return true;
338
+ }
339
+
340
+ /** Reads the signal now; a function call keeps TypeScript from narrowing a later read away. */
341
+ export const isAborted = (signal: AbortSignal | undefined): boolean =>
342
+ signal?.aborted === true;
343
+
344
+ /**
345
+ * No signal, or a real `AbortSignal`: `AbortSignal.any` and `fetch` refuse
346
+ * anything else, duck-typed look-alikes included.
347
+ */
348
+ export const isRequestSignal = (value: unknown): boolean =>
349
+ value === undefined ||
350
+ (typeof AbortSignal !== 'undefined' && value instanceof AbortSignal);
351
+
352
+ /** How many documents a request carries, read defensively at the public boundary. */
353
+ export const documentCount = (request: unknown): number =>
354
+ isDecisionObject(request) && Array.isArray(request.documents)
355
+ ? request.documents.length
356
+ : 0;
357
+
358
+ /** Identity order with `null` scores: what a caller serves when nothing answered. */
359
+ export function identityOutcome(
360
+ documents: number,
361
+ options: {
362
+ reason: string;
363
+ provider?: RerankKind;
364
+ model?: string;
365
+ durationMs?: number;
366
+ }
367
+ ): RerankOutcome {
368
+ return {
369
+ results: Array.from({ length: documents }, (_, index) => ({
370
+ index,
371
+ score: null,
372
+ })),
373
+ provider: options.provider ?? 'none',
374
+ model: options.model ?? '',
375
+ status: 'skipped',
376
+ reason: options.reason,
377
+ attempts: [],
378
+ durationMs: options.durationMs ?? 0,
379
+ usage: emptyRerankUsage(),
380
+ };
381
+ }
382
+
383
+ export interface StepOutcome {
384
+ kind: RerankKind;
385
+ documents: number;
386
+ startedAt: number;
387
+ model: string;
388
+ /** One score per document when the step answered. */
389
+ scores?: ReadonlyArray<number | null>;
390
+ /** A failure; identity order is returned. */
391
+ reason?: string;
392
+ usage?: RerankUsage;
393
+ /** False when no request was made, so the attempt is `skipped` rather than `failed`. */
394
+ called?: boolean;
395
+ threshold?: number;
396
+ pinVerified?: boolean;
397
+ }
398
+
399
+ export const elapsedMs = (startedAt: number): number =>
400
+ Math.round(performance.now() - startedAt);
401
+
402
+ function attemptStatus(
403
+ ok: boolean,
404
+ called: boolean | undefined
405
+ ): RerankAttempt['status'] {
406
+ if (ok) {
407
+ return 'ok';
408
+ }
409
+ return called === false ? 'skipped' : 'failed';
410
+ }
411
+
412
+ /** One reranker's own outcome: `ok` with its scores, or `skipped` in identity order with a reason. */
413
+ export function stepOutcome(step: StepOutcome): RerankOutcome {
414
+ const durationMs = elapsedMs(step.startedAt);
415
+ const usage = step.usage ?? emptyRerankUsage();
416
+ const ok = step.reason === undefined && step.scores !== undefined;
417
+ let reason: string | null = null;
418
+ if (!ok) {
419
+ // An empty reason names nothing, so it is reported as the generic one.
420
+ reason =
421
+ step.reason === undefined || step.reason === '' ? 'error' : step.reason;
422
+ }
423
+ const attempt: RerankAttempt = {
424
+ provider: step.kind,
425
+ model: step.model,
426
+ status: attemptStatus(ok, step.called),
427
+ reason,
428
+ durationMs,
429
+ usage: { ...usage },
430
+ };
431
+ const results =
432
+ ok && step.scores
433
+ ? rankedEntries(step.scores, step.threshold)
434
+ : identityOutcome(step.documents, { reason: reason ?? 'error' }).results;
435
+ return {
436
+ results,
437
+ provider: step.kind,
438
+ model: step.model,
439
+ status: ok ? 'ok' : 'skipped',
440
+ reason,
441
+ attempts: [attempt],
442
+ durationMs,
443
+ usage,
444
+ ...(step.pinVerified !== undefined
445
+ ? { pinVerified: step.pinVerified }
446
+ : {}),
447
+ ...(ok && step.threshold !== undefined
448
+ ? { threshold: step.threshold }
449
+ : {}),
450
+ };
451
+ }
452
+
453
+ const REASON_FOR_FAILURE: Readonly<
454
+ Partial<Record<DecisionFailure, RerankReason>>
455
+ > = Object.freeze({
456
+ unauthorized: 'unauthorized',
457
+ quota: 'quota',
458
+ rate_limited: 'rate_limited',
459
+ timeout: 'timeout',
460
+ aborted: 'aborted',
461
+ malformed_response: 'bad_response',
462
+ unsupported_question: 'unsupported',
463
+ unsupported_mode: 'unsupported',
464
+ });
465
+
466
+ /** A failure as an outcome reason; the caller decides whether a fired deadline means `timeout` or `aborted`. */
467
+ export function rerankReasonOf(error: unknown): RerankReason {
468
+ if (!(error instanceof DecisionError)) {
469
+ if (error instanceof Error && error.name === 'TimeoutError') {
470
+ return 'timeout';
471
+ }
472
+ return error instanceof Error && error.name === 'AbortError'
473
+ ? 'aborted'
474
+ : 'error';
475
+ }
476
+ if (error.circuitOpen) {
477
+ return 'circuit_open';
478
+ }
479
+ return REASON_FOR_FAILURE[error.failure] ?? 'error';
480
+ }
481
+
482
+ /**
483
+ * A reply the transport backs off from and retries (HTTP 429 or 5xx), as the
484
+ * error it stands for; `null` for any other reply or none. A deadline that
485
+ * fires after it, with no request in flight and no later request ended,
486
+ * reports this rather than `timeout`: the host answered, and said why.
487
+ */
488
+ export function retriedReply(
489
+ provider: string,
490
+ status: number | null,
491
+ retryAfterMs?: number
492
+ ): DecisionError | null {
493
+ if (status === null || (status !== 429 && status < 500)) {
494
+ return null;
495
+ }
496
+ const error = new DecisionError(
497
+ failureForStatus(status),
498
+ `decision model returned HTTP ${status}`,
499
+ { provider, status }
500
+ );
501
+ error.retryAfterMs = retryAfterMs;
502
+ return error;
503
+ }
504
+
505
+ /**
506
+ * A positive finite deadline rounded up to whole milliseconds, when that is no
507
+ * longer than an hour; otherwise `undefined`. It accepts fractions, so a
508
+ * configured timeout kept as given must also be checked as an integer.
509
+ */
510
+ export function validDeadline(value: unknown): number | undefined {
511
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
512
+ return undefined;
513
+ }
514
+ const ms = Math.ceil(value);
515
+ return ms <= MAX_RERANK_DEADLINE_MS ? ms : undefined;
516
+ }
517
+
518
+ /**
519
+ * `test` holds for every slot of `values`, holes included. `some` and `every`
520
+ * skip the holes of a sparse array, which a spread, an index, or
521
+ * `JSON.stringify` later reads as `undefined` or `null`.
522
+ */
523
+ export function everySlot<T>(
524
+ values: readonly T[],
525
+ test: (value: T | undefined) => boolean
526
+ ): boolean {
527
+ for (let index = 0; index < values.length; index++) {
528
+ if (!test(values[index])) {
529
+ return false;
530
+ }
531
+ }
532
+ return true;
533
+ }
534
+
535
+ /** A non-empty query, string documents, and a real signal if any, or the reason the request cannot be ranked. */
536
+ export function rankRequestProblem(request: unknown): RerankReason | undefined {
537
+ if (
538
+ !isDecisionObject(request) ||
539
+ !Array.isArray(request.documents) ||
540
+ typeof request.query !== 'string' ||
541
+ !request.query.trim() ||
542
+ !everySlot(
543
+ request.documents as unknown[],
544
+ (document) => typeof document === 'string'
545
+ ) ||
546
+ !isRequestSignal(request.signal)
547
+ ) {
548
+ return 'invalid_request';
549
+ }
550
+ if (request.documents.length === 0) {
551
+ return 'empty';
552
+ }
553
+ if (
554
+ request.deadlineMs !== undefined &&
555
+ validDeadline(request.deadlineMs) === undefined
556
+ ) {
557
+ return 'invalid_request';
558
+ }
559
+ return undefined;
560
+ }
561
+
562
+ /**
563
+ * The never-throwing layer over a rejecting `Reranker`: its full ranking
564
+ * becomes an `ok` outcome, a rejection becomes a reason, and a ranking that
565
+ * is not a full permutation in descending score order is `invalid_results`.
566
+ * For a reranker with `reportsRequests`, usage counts each request it
567
+ * reported through `onRequest`, so a call that failed before sending counts
568
+ * none and is `skipped`, and a deadline charges an estimate only while a
569
+ * request was in flight. Any other reranker counts one call, plus every retry
570
+ * it reports through `onRequest`, or none when an open breaker
571
+ * (`circuitOpen`) refused it before dispatch. Tokens are whatever it
572
+ * reported. The request's `deadlineMs` and `signal` bound the wait even for
573
+ * a reranker that ignores them. The deadline reaches the reranker only as
574
+ * its abort signal, never as `timeoutMs`, which would replace its configured
575
+ * timeout: a deadline caps that timeout and never extends it.
576
+ */
577
+ export function toOutcomeReranker(
578
+ reranker: Reranker,
579
+ options: { kind: RerankKind; model?: string }
580
+ ): OutcomeReranker {
581
+ const { kind } = options;
582
+ const model = options.model ?? '';
583
+ return {
584
+ id: reranker.id,
585
+ kind,
586
+ model,
587
+ async rank(request: RankRequest): Promise<RerankOutcome> {
588
+ const startedAt = performance.now();
589
+ const documents = documentCount(request);
590
+ const problem = rankRequestProblem(request);
591
+ if (problem !== undefined) {
592
+ return stepOutcome({
593
+ kind,
594
+ documents,
595
+ startedAt,
596
+ model,
597
+ reason: problem,
598
+ called: false,
599
+ });
600
+ }
601
+ if (isAborted(request.signal)) {
602
+ return stepOutcome({
603
+ kind,
604
+ documents,
605
+ startedAt,
606
+ model,
607
+ reason: 'aborted',
608
+ called: false,
609
+ });
610
+ }
611
+ const usage = emptyRerankUsage();
612
+ const reports = reranker.reportsRequests === true;
613
+ const tally: {
614
+ /** Requests the reranker reported sending. */
615
+ requests: number;
616
+ /** Reported requests that ended, with a reply or without one. */
617
+ ended: number;
618
+ /** The latest ended request's reply, when it is a 429 or 5xx the reranker backs off from. */
619
+ backoff: DecisionError | null;
620
+ /** Set when `rerank` is called; a deadline or abort before it sent nothing. */
621
+ dispatched: boolean;
622
+ } = { requests: 0, ended: 0, backoff: null, dispatched: false };
623
+ let settled = false;
624
+ try {
625
+ const deadlineMs = validDeadline(request.deadlineMs);
626
+ const onResponse = (
627
+ status: number | null,
628
+ retryAfterMs?: number
629
+ ): void => {
630
+ if (!settled) {
631
+ tally.ended += 1;
632
+ // The latest reply only: an earlier one's backoff is over once another request ended.
633
+ tally.backoff = retriedReply(reranker.id, status, retryAfterMs);
634
+ }
635
+ };
636
+ const call = (
637
+ signal: AbortSignal | undefined
638
+ ): Promise<RerankResult> => {
639
+ tally.dispatched = true;
640
+ if (!reports) {
641
+ usage.calls = 1;
642
+ }
643
+ return reranker.rerank({
644
+ query: request.query,
645
+ documents: request.documents,
646
+ ...(signal !== undefined ? { signal } : {}),
647
+ onRequest: () => {
648
+ if (settled) {
649
+ return;
650
+ }
651
+ tally.requests += 1;
652
+ // Without reports, the first request is the call counted at dispatch.
653
+ if (reports || tally.requests > 1) {
654
+ usage.calls += 1;
655
+ }
656
+ },
657
+ ...(reports ? { onResponse } : {}),
658
+ });
659
+ };
660
+ // Bounded here too, so a reranker that ignores its deadline and signal cannot hold the call.
661
+ let response: RerankResult;
662
+ if (deadlineMs === undefined && request.signal === undefined) {
663
+ response = await call(undefined);
664
+ } else {
665
+ response = await withDecisionDeadline(
666
+ reranker.id,
667
+ deadlineMs ?? MAX_RERANK_DEADLINE_MS,
668
+ request.signal,
669
+ (signal, waitFor) =>
670
+ waitFor(
671
+ Promise.resolve().then(() => {
672
+ // An abort that landed after the call was scheduled: nothing is sent, counted, or charged.
673
+ if (signal.aborted) {
674
+ throw new DecisionError(
675
+ 'aborted',
676
+ 'caller aborted the request',
677
+ { provider: reranker.id }
678
+ );
679
+ }
680
+ return call(signal);
681
+ })
682
+ )
683
+ );
684
+ }
685
+ settled = true;
686
+ usage.inputTokens = count(response.usage?.inputTokens);
687
+ usage.outputTokens = count(response.usage?.outputTokens);
688
+ const echoed =
689
+ typeof response.model === 'string' && response.model !== ''
690
+ ? response.model
691
+ : model;
692
+ const results: unknown = response.results;
693
+ if (!isRerankPermutation(results, documents)) {
694
+ return stepOutcome({
695
+ kind,
696
+ documents,
697
+ startedAt,
698
+ model: echoed,
699
+ reason: 'invalid_results',
700
+ usage,
701
+ });
702
+ }
703
+ const scores: Array<number | null> = new Array(documents).fill(null);
704
+ let previous = Infinity;
705
+ for (const entry of results) {
706
+ if (entry.score === null || entry.score > previous) {
707
+ return stepOutcome({
708
+ kind,
709
+ documents,
710
+ startedAt,
711
+ model: echoed,
712
+ reason: 'invalid_results',
713
+ usage,
714
+ });
715
+ }
716
+ previous = entry.score;
717
+ scores[entry.index] = entry.score;
718
+ }
719
+ return stepOutcome({
720
+ kind,
721
+ documents,
722
+ startedAt,
723
+ model: echoed,
724
+ scores,
725
+ usage,
726
+ });
727
+ } catch (error) {
728
+ settled = true;
729
+ // An open breaker refuses before dispatch: nothing was sent, so nothing is charged.
730
+ const sent = reports
731
+ ? usage.calls > 0
732
+ : tally.dispatched &&
733
+ !(error instanceof DecisionError && error.circuitOpen);
734
+ if (!sent) {
735
+ usage.calls = 0;
736
+ }
737
+ /** Requests the host may still be working on: only those are estimated. */
738
+ let outstanding = 0;
739
+ if (sent) {
740
+ outstanding = reports ? usage.calls - tally.ended : 1;
741
+ }
742
+ let reason: string = isAborted(request.signal)
743
+ ? 'aborted'
744
+ : rerankReasonOf(error);
745
+ if (
746
+ reason === 'timeout' &&
747
+ outstanding === 0 &&
748
+ tally.backoff !== null
749
+ ) {
750
+ reason = rerankReasonOf(tally.backoff);
751
+ }
752
+ return stepOutcome({
753
+ kind,
754
+ documents,
755
+ startedAt,
756
+ model,
757
+ reason,
758
+ called: sent,
759
+ usage:
760
+ outstanding > 0 && (reason === 'timeout' || reason === 'aborted')
761
+ ? { ...usage, ...estimatedUsage(kind, documents) }
762
+ : usage,
763
+ });
764
+ }
765
+ },
766
+ };
767
+ }