@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,625 @@
1
+ import type {
2
+ RerankKind,
3
+ RerankEntry,
4
+ RerankUsage,
5
+ RankRequest,
6
+ RerankAttempt,
7
+ RerankOutcome,
8
+ OutcomeReranker,
9
+ } from './types';
10
+ import {
11
+ elapsedMs,
12
+ isAborted,
13
+ stepOutcome,
14
+ isRerankKind,
15
+ documentCount,
16
+ validDeadline,
17
+ addRerankUsage,
18
+ estimatedUsage,
19
+ identityOutcome,
20
+ isRankedOrder,
21
+ emptyRerankUsage,
22
+ everySlot,
23
+ isRerankUsage,
24
+ rankRequestProblem,
25
+ isRerankPermutation,
26
+ } from './outcome';
27
+ import { DecisionError, isDecisionObject } from '../decisions/types';
28
+ import { callHook } from '../decisions/hook';
29
+
30
+ /**
31
+ * Identity order, never a request: the last step of a chain, or the whole
32
+ * chain when nothing is configured. Its one attempt is `skipped` with
33
+ * `reason` and no usage, so a chain's history shows it ran. A malformed
34
+ * request is `invalid_request` and an empty one `empty`, as for every other
35
+ * reranker, so a bad call is never mistaken for a disabled one.
36
+ */
37
+ export function noneReranker(
38
+ options: { reason?: string } = {}
39
+ ): OutcomeReranker {
40
+ const reason =
41
+ typeof options.reason === 'string' && options.reason !== ''
42
+ ? options.reason
43
+ : 'disabled';
44
+ return {
45
+ id: 'none',
46
+ kind: 'none',
47
+ model: '',
48
+ async rank(request: RankRequest): Promise<RerankOutcome> {
49
+ return stepOutcome({
50
+ kind: 'none',
51
+ documents: documentCount(request),
52
+ startedAt: performance.now(),
53
+ model: '',
54
+ reason: rankRequestProblem(request) ?? reason,
55
+ called: false,
56
+ });
57
+ },
58
+ };
59
+ }
60
+
61
+ export interface FallbackStep {
62
+ reranker: OutcomeReranker;
63
+ /** This step's own deadline, so a hung step cannot starve the next one. */
64
+ deadlineMs?: number;
65
+ }
66
+
67
+ export interface FallbackOptions {
68
+ /**
69
+ * Returns a reason to skip a step without a request (a backoff, a budget,
70
+ * an unverified pin), or nothing to run it. Not consulted for `none` steps.
71
+ * A gate that throws skips its step with `error`. The wait for it is
72
+ * bounded like a step: a gate still pending when the request's deadline
73
+ * passes or its signal aborts is abandoned and the chain stops with
74
+ * `timeout` or `aborted`.
75
+ */
76
+ gate?: (
77
+ reranker: OutcomeReranker
78
+ ) => string | null | undefined | Promise<string | null | undefined>;
79
+ /**
80
+ * Sees every step that ran, for backoff bookkeeping, as a copy: changing
81
+ * it changes nothing the chain returns. Not awaited; a throw or a rejected
82
+ * promise is ignored.
83
+ */
84
+ onAttempt?: (reranker: OutcomeReranker, outcome: RerankOutcome) => void;
85
+ }
86
+
87
+ export interface FallbackReranker extends OutcomeReranker {
88
+ readonly steps: readonly FallbackStep[];
89
+ }
90
+
91
+ const STATUSES: ReadonlySet<string> = new Set(['ok', 'degraded', 'skipped']);
92
+ const ATTEMPT_STATUSES: ReadonlySet<string> = new Set([
93
+ 'ok',
94
+ 'failed',
95
+ 'skipped',
96
+ ]);
97
+
98
+ /**
99
+ * Grace after a step's deadline or the caller's abort for a reranker that
100
+ * honors its abort to report its own timeout and spend. A full answer that
101
+ * arrives within it is accepted: waiting for it costs nothing the timeout
102
+ * would not.
103
+ */
104
+ export const STEP_GRACE_MS = 50;
105
+
106
+ function usageOf(value: unknown): RerankUsage {
107
+ return addRerankUsage(emptyRerankUsage(), value);
108
+ }
109
+
110
+ /** A step that broke its contract or outlived its deadline, charged what it reported or an estimate. */
111
+ function failedStep(
112
+ reranker: OutcomeReranker,
113
+ documents: number,
114
+ reason: string,
115
+ durationMs: number,
116
+ usage: RerankUsage = emptyRerankUsage()
117
+ ): RerankOutcome {
118
+ const attempt: RerankAttempt = {
119
+ provider: reranker.kind,
120
+ model: reranker.model,
121
+ status: 'failed',
122
+ reason,
123
+ durationMs,
124
+ usage: { ...usage },
125
+ };
126
+ return {
127
+ ...identityOutcome(documents, {
128
+ reason,
129
+ provider: reranker.kind,
130
+ model: reranker.model,
131
+ durationMs,
132
+ }),
133
+ attempts: [attempt],
134
+ usage,
135
+ };
136
+ }
137
+
138
+ /** What a step that never returned is charged: every document it was sent, at the estimate. */
139
+ function abandonedUsage(kind: RerankKind, documents: number): RerankUsage {
140
+ if (kind === 'bm25' || kind === 'none' || documents === 0) {
141
+ return emptyRerankUsage();
142
+ }
143
+ const estimate = estimatedUsage(kind, documents);
144
+ return {
145
+ ...emptyRerankUsage(),
146
+ calls: kind === 'systemone' ? documents : 1,
147
+ ...estimate,
148
+ };
149
+ }
150
+
151
+ /** `null` exactly when `status` is `ok`; otherwise the non-empty reason it failed or degraded. */
152
+ const reasonFits = (status: string, reason: unknown): boolean =>
153
+ status === 'ok'
154
+ ? reason === null
155
+ : typeof reason === 'string' && reason !== '';
156
+
157
+ const isFiniteNumber = (value: unknown): value is number =>
158
+ typeof value === 'number' && Number.isFinite(value);
159
+
160
+ function isAttempt(value: unknown): value is RerankAttempt {
161
+ return (
162
+ isDecisionObject(value) &&
163
+ isRerankKind(value.provider) &&
164
+ typeof value.model === 'string' &&
165
+ typeof value.status === 'string' &&
166
+ ATTEMPT_STATUSES.has(value.status) &&
167
+ reasonFits(value.status, value.reason) &&
168
+ isFiniteNumber(value.durationMs) &&
169
+ value.durationMs >= 0 &&
170
+ isRerankUsage(value.usage)
171
+ );
172
+ }
173
+
174
+ /** Every entry's `kept` is what `threshold` says of its score, as `rankedEntries` sets it. */
175
+ const keptByThreshold = (
176
+ results: readonly RerankEntry[],
177
+ threshold: number
178
+ ): boolean =>
179
+ results.every(
180
+ (entry) => entry.kept === (entry.score !== null && entry.score >= threshold)
181
+ );
182
+
183
+ /** A step that did not answer has no `ok` attempt, and an answer that reports attempts has one. */
184
+ const attemptsFit = (
185
+ status: string,
186
+ attempts: readonly RerankAttempt[]
187
+ ): boolean =>
188
+ status === 'skipped'
189
+ ? attempts.every((attempt) => attempt.status !== 'ok')
190
+ : attempts.length === 0 ||
191
+ attempts.some((attempt) => attempt.status === 'ok');
192
+
193
+ /**
194
+ * The whole `RerankOutcome` contract, since a step's results and attempts are
195
+ * passed through as they are: `reason` is `null` exactly when the status
196
+ * (the outcome's and each attempt's) is `ok`, an answer (`ok` or
197
+ * `degraded`) scores every document while a `skipped` outcome scores none
198
+ * (so it is identity order), the attempts agree with the status, and `kept`
199
+ * comes only with the `threshold` behind it, on every entry and matching it.
200
+ */
201
+ function isOutcome(value: unknown, documents: number): value is RerankOutcome {
202
+ return (
203
+ isDecisionObject(value) &&
204
+ typeof value.status === 'string' &&
205
+ STATUSES.has(value.status) &&
206
+ isRerankKind(value.provider) &&
207
+ typeof value.model === 'string' &&
208
+ reasonFits(value.status, value.reason) &&
209
+ isRerankPermutation(value.results, documents) &&
210
+ isRankedOrder(value.results) &&
211
+ // A skipped step scored nothing, so ranked order is then identity order.
212
+ value.results.every(
213
+ (entry) => (value.status === 'skipped') === (entry.score === null)
214
+ ) &&
215
+ (value.threshold === undefined
216
+ ? value.results.every((entry) => entry.kept === undefined)
217
+ : isFiniteNumber(value.threshold) &&
218
+ keptByThreshold(value.results, value.threshold)) &&
219
+ Array.isArray(value.attempts) &&
220
+ everySlot(value.attempts as unknown[], isAttempt) &&
221
+ attemptsFit(value.status, value.attempts as RerankAttempt[]) &&
222
+ (value.pinVerified === undefined || typeof value.pinVerified === 'boolean')
223
+ );
224
+ }
225
+
226
+ /** A copy of a validated outcome for a hook, so nothing it does reaches the chain's results or history. */
227
+ function hookCopy(outcome: RerankOutcome): RerankOutcome {
228
+ return {
229
+ ...outcome,
230
+ results: outcome.results.map((entry) => ({ ...entry })),
231
+ attempts: outcome.attempts.map((attempt) => ({
232
+ ...attempt,
233
+ usage: { ...attempt.usage },
234
+ })),
235
+ usage: usageOf(outcome.usage),
236
+ };
237
+ }
238
+
239
+ /** The attempt a step that ran but reported none stands for, so the chain's history keeps every step. */
240
+ function ownAttempt(outcome: RerankOutcome): RerankAttempt {
241
+ const usage = usageOf(outcome.usage);
242
+ let status: RerankAttempt['status'] = 'ok';
243
+ if (outcome.status === 'skipped') {
244
+ status = usage.calls > 0 ? 'failed' : 'skipped';
245
+ }
246
+ return {
247
+ provider: outcome.provider,
248
+ model: outcome.model,
249
+ status,
250
+ // A `degraded` step answered, so its own attempt is `ok` and carries no reason.
251
+ reason: status === 'ok' ? null : outcome.reason,
252
+ durationMs: isFiniteNumber(outcome.durationMs)
253
+ ? Math.max(0, outcome.durationMs)
254
+ : 0,
255
+ usage,
256
+ };
257
+ }
258
+
259
+ type GateVerdict = { why: string | null } | { stop: 'aborted' | 'timeout' };
260
+
261
+ /**
262
+ * The gate's verdict, or why the chain stopped first: a gate that is slow or
263
+ * never settles is abandoned at the chain's deadline or the caller's abort.
264
+ */
265
+ async function consult(
266
+ gate: NonNullable<FallbackOptions['gate']>,
267
+ reranker: OutcomeReranker,
268
+ signal: AbortSignal | undefined,
269
+ expiresAt: number
270
+ ): Promise<GateVerdict> {
271
+ const cleanup: Array<() => void> = [];
272
+ const contenders: Array<Promise<GateVerdict>> = [
273
+ Promise.resolve()
274
+ .then(() => gate(reranker))
275
+ .then(
276
+ (why): GateVerdict => ({
277
+ why: typeof why === 'string' && why !== '' ? why : null,
278
+ }),
279
+ (): GateVerdict => ({ why: 'error' })
280
+ ),
281
+ ];
282
+ if (expiresAt !== Infinity) {
283
+ contenders.push(
284
+ new Promise<GateVerdict>((resolve) => {
285
+ const timer = setTimeout(
286
+ () => resolve({ stop: 'timeout' }),
287
+ Math.max(0, expiresAt - performance.now())
288
+ );
289
+ cleanup.push(() => clearTimeout(timer));
290
+ })
291
+ );
292
+ }
293
+ if (signal !== undefined) {
294
+ contenders.push(
295
+ new Promise<GateVerdict>((resolve) => {
296
+ const onAbort = (): void => resolve({ stop: 'aborted' });
297
+ signal.addEventListener('abort', onAbort, { once: true });
298
+ cleanup.push(() => signal.removeEventListener('abort', onAbort));
299
+ })
300
+ );
301
+ }
302
+ try {
303
+ return await Promise.race(contenders);
304
+ } finally {
305
+ for (const release of cleanup) {
306
+ release();
307
+ }
308
+ }
309
+ }
310
+
311
+ /** The step's deadline reached it as an abort; to the chain's caller it is the step's timeout. */
312
+ function asTimeout(outcome: RerankOutcome): RerankOutcome {
313
+ const timeout = (reason: string | null): string | null =>
314
+ reason === 'aborted' ? 'timeout' : reason;
315
+ return {
316
+ ...outcome,
317
+ reason: timeout(outcome.reason),
318
+ attempts: outcome.attempts.map((attempt) => ({
319
+ ...attempt,
320
+ reason: timeout(attempt.reason),
321
+ })),
322
+ };
323
+ }
324
+
325
+ /**
326
+ * One step under its own deadline: an abort signal the reranker should honor,
327
+ * and timers that end the wait `STEP_GRACE_MS` after its deadline or the
328
+ * caller's abort regardless, so a step that ignores its abort cannot hold the
329
+ * chain or its caller.
330
+ */
331
+ async function runStep(
332
+ reranker: OutcomeReranker,
333
+ query: string,
334
+ documents: readonly string[],
335
+ deadlineMs: number | undefined,
336
+ outer: AbortSignal | undefined
337
+ ): Promise<RerankOutcome> {
338
+ const startedAt = performance.now();
339
+ const n = documents.length;
340
+ const deadline = new AbortController();
341
+ let signal = outer;
342
+ if (deadlineMs !== undefined) {
343
+ signal = outer
344
+ ? AbortSignal.any([outer, deadline.signal])
345
+ : deadline.signal;
346
+ }
347
+ const timers: Array<ReturnType<typeof setTimeout>> = [];
348
+ /** A step that gave up without an answer after its signal fired was stopped, not broken: `asTimeout` then names a deadline. */
349
+ const failure = (): 'aborted' | 'error' =>
350
+ isAborted(signal) ? 'aborted' : 'error';
351
+ const work = Promise.resolve()
352
+ .then(() =>
353
+ reranker.rank({
354
+ query,
355
+ documents,
356
+ ...(signal !== undefined ? { signal } : {}),
357
+ ...(deadlineMs !== undefined ? { deadlineMs } : {}),
358
+ })
359
+ )
360
+ .then(
361
+ (outcome: unknown): RerankOutcome => {
362
+ if (isOutcome(outcome, n)) {
363
+ return outcome;
364
+ }
365
+ const reason = outcome == null ? failure() : 'invalid_results';
366
+ const reported = isDecisionObject(outcome) ? outcome.usage : null;
367
+ return failedStep(
368
+ reranker,
369
+ n,
370
+ reason,
371
+ elapsedMs(startedAt),
372
+ usageOf(reported)
373
+ );
374
+ },
375
+ () => failedStep(reranker, n, failure(), elapsedMs(startedAt))
376
+ );
377
+ if (deadlineMs === undefined && outer === undefined) {
378
+ return work;
379
+ }
380
+ /** A step still pending this long is abandoned, charged as if every document was sent. */
381
+ const abandon = (
382
+ reason: 'timeout' | 'aborted',
383
+ afterMs: number
384
+ ): Promise<RerankOutcome> =>
385
+ new Promise<RerankOutcome>((resolve) => {
386
+ timers.push(
387
+ setTimeout(
388
+ () =>
389
+ resolve(
390
+ failedStep(
391
+ reranker,
392
+ n,
393
+ reason,
394
+ elapsedMs(startedAt),
395
+ abandonedUsage(reranker.kind, n)
396
+ )
397
+ ),
398
+ afterMs
399
+ )
400
+ );
401
+ });
402
+ const contenders = [work];
403
+ if (deadlineMs !== undefined) {
404
+ timers.push(setTimeout(() => deadline.abort(), deadlineMs));
405
+ contenders.push(abandon('timeout', deadlineMs + STEP_GRACE_MS));
406
+ }
407
+ let release = (): void => {};
408
+ if (outer !== undefined) {
409
+ contenders.push(
410
+ new Promise<RerankOutcome>((resolve) => {
411
+ const onAbort = (): void => {
412
+ resolve(abandon('aborted', STEP_GRACE_MS));
413
+ };
414
+ if (outer.aborted) {
415
+ onAbort();
416
+ return;
417
+ }
418
+ outer.addEventListener('abort', onAbort, { once: true });
419
+ release = (): void => outer.removeEventListener('abort', onAbort);
420
+ })
421
+ );
422
+ }
423
+ try {
424
+ const outcome = await Promise.race(contenders);
425
+ return deadline.signal.aborted && !isAborted(outer)
426
+ ? asTimeout(outcome)
427
+ : outcome;
428
+ } finally {
429
+ release();
430
+ for (const timer of timers) {
431
+ clearTimeout(timer);
432
+ }
433
+ }
434
+ }
435
+
436
+ /**
437
+ * A step's own deadline bounded by what is left of the chain's; a step
438
+ * without one gets the rest of the chain's. `undefined` only when neither
439
+ * the step nor the request has a deadline.
440
+ */
441
+ function stepDeadline(
442
+ own: number | undefined,
443
+ expiresAt: number
444
+ ): number | undefined {
445
+ if (expiresAt === Infinity) {
446
+ return own;
447
+ }
448
+ const remaining = Math.max(1, Math.ceil(expiresAt - performance.now()));
449
+ return own === undefined ? remaining : Math.min(own, remaining);
450
+ }
451
+
452
+ /**
453
+ * A chain of steps tried in order; the first that answers wins. Step 0
454
+ * answering is `ok`; a later step is `degraded` with the first failed step's
455
+ * reason; none answering is `skipped` in identity order with that reason. A
456
+ * `none` step never answers. `kept`, `threshold`, and `pinVerified` come from
457
+ * the answering step only, so falling back to a cross-encoder never carries a
458
+ * System One threshold. A step that throws, rejects, returns something that
459
+ * breaks the `RerankOutcome` contract (a full permutation in score order,
460
+ * every document scored when it answers, `kept` only with a `threshold` and
461
+ * then on every entry, `true` exactly where the score reaches it, well-formed
462
+ * attempts whose usage counters and durations are finite counts of at least
463
+ * zero, and well-formed fields), or outlives its deadline or the
464
+ * caller's abort by `STEP_GRACE_MS` is a failed step; a step that ran but
465
+ * reported no attempt is recorded as one. A request's `deadlineMs` bounds the whole
466
+ * chain, gates included: each step gets the lesser of its own deadline and
467
+ * what is left, a step without one gets what is left, and once nothing is
468
+ * left the chain stops with `timeout`. A step's deadline reaches it as
469
+ * `RankRequest.deadlineMs`, which caps the reranker's own timeout and never
470
+ * extends it. Usage sums every attempt, from the
471
+ * attempts themselves rather than a step's own total: spend counts what was
472
+ * sent, not what answered. An invalid request is identity order over every
473
+ * document. Never throws.
474
+ */
475
+ export function withFallback(
476
+ steps: readonly FallbackStep[],
477
+ options: FallbackOptions = {}
478
+ ): FallbackReranker {
479
+ if (
480
+ !Array.isArray(steps) ||
481
+ steps.length === 0 ||
482
+ !everySlot(
483
+ steps,
484
+ (step) =>
485
+ step !== null &&
486
+ typeof step === 'object' &&
487
+ typeof step.reranker?.rank === 'function' &&
488
+ isRerankKind(step.reranker.kind) &&
489
+ typeof step.reranker.model === 'string' &&
490
+ (step.deadlineMs === undefined ||
491
+ (Number.isSafeInteger(step.deadlineMs) &&
492
+ validDeadline(step.deadlineMs) !== undefined))
493
+ )
494
+ ) {
495
+ throw new DecisionError('bad_request', 'invalid reranker chain', {
496
+ provider: 'fallback',
497
+ });
498
+ }
499
+ const chain = steps.map((step) => ({ ...step }));
500
+ const head =
501
+ chain.find(({ reranker }) => reranker.kind !== 'none')?.reranker ??
502
+ chain[0].reranker;
503
+ const { gate, onAttempt } = options;
504
+
505
+ return {
506
+ id: `fallback(${chain.map((step) => step.reranker.id).join(',')})`,
507
+ kind: head.kind,
508
+ model: head.model,
509
+ steps: chain,
510
+ async rank(request: RankRequest): Promise<RerankOutcome> {
511
+ const startedAt = performance.now();
512
+ const documents = documentCount(request);
513
+ if (rankRequestProblem(request) === 'invalid_request') {
514
+ return identityOutcome(documents, {
515
+ reason: 'invalid_request',
516
+ durationMs: elapsedMs(startedAt),
517
+ });
518
+ }
519
+ if (documents === 0) {
520
+ return identityOutcome(0, {
521
+ reason: 'empty',
522
+ durationMs: elapsedMs(startedAt),
523
+ });
524
+ }
525
+ const attempts: RerankAttempt[] = [];
526
+ const usage = emptyRerankUsage();
527
+ const budget = validDeadline(request.deadlineMs);
528
+ const expiresAt = budget === undefined ? Infinity : startedAt + budget;
529
+ /** Read before every step and after every gate: either may have run out the clock. */
530
+ const stopped = (): 'aborted' | 'timeout' | null => {
531
+ if (isAborted(request.signal)) {
532
+ return 'aborted';
533
+ }
534
+ return performance.now() >= expiresAt ? 'timeout' : null;
535
+ };
536
+ let first: string | null = null;
537
+ try {
538
+ for (let index = 0; index < chain.length; index++) {
539
+ const { reranker } = chain[index];
540
+ let stop = stopped();
541
+ if (stop === null && gate && reranker.kind !== 'none') {
542
+ const verdict = await consult(
543
+ gate,
544
+ reranker,
545
+ request.signal,
546
+ expiresAt
547
+ );
548
+ if ('stop' in verdict) {
549
+ stop = verdict.stop;
550
+ } else if (verdict.why !== null) {
551
+ attempts.push({
552
+ provider: reranker.kind,
553
+ model: reranker.model,
554
+ status: 'skipped',
555
+ reason: verdict.why,
556
+ durationMs: 0,
557
+ usage: emptyRerankUsage(),
558
+ });
559
+ first ??= verdict.why;
560
+ continue;
561
+ } else {
562
+ stop = stopped();
563
+ }
564
+ }
565
+ if (stop !== null) {
566
+ first ??= stop;
567
+ break;
568
+ }
569
+ const outcome = await runStep(
570
+ reranker,
571
+ request.query,
572
+ request.documents,
573
+ stepDeadline(chain[index].deadlineMs, expiresAt),
574
+ request.signal
575
+ );
576
+ // Bookkeeping, sync or async, must not break a ranking.
577
+ if (onAttempt !== undefined) {
578
+ const seen = hookCopy(outcome);
579
+ callHook(() => onAttempt(reranker, seen));
580
+ }
581
+ const ran =
582
+ outcome.attempts.length > 0
583
+ ? outcome.attempts
584
+ : [ownAttempt(outcome)];
585
+ attempts.push(...ran);
586
+ // From the validated attempts, never the step's own total, so `usage` always sums `attempts`.
587
+ for (const attempt of ran) {
588
+ addRerankUsage(usage, attempt.usage);
589
+ }
590
+ if (outcome.provider !== 'none' && outcome.status !== 'skipped') {
591
+ const ok = index === 0 && outcome.status === 'ok';
592
+ return {
593
+ results: outcome.results,
594
+ provider: outcome.provider,
595
+ model: outcome.model,
596
+ status: ok ? 'ok' : 'degraded',
597
+ reason: ok ? null : (first ?? outcome.reason ?? 'error'),
598
+ attempts,
599
+ durationMs: elapsedMs(startedAt),
600
+ usage,
601
+ ...(outcome.pinVerified !== undefined
602
+ ? { pinVerified: outcome.pinVerified }
603
+ : {}),
604
+ ...(outcome.threshold !== undefined
605
+ ? { threshold: outcome.threshold }
606
+ : {}),
607
+ };
608
+ }
609
+ first ??= outcome.reason ?? 'error';
610
+ }
611
+ } catch {
612
+ // Every helper above is meant never to throw; this keeps `rank` from rejecting if one does.
613
+ first ??= 'error';
614
+ }
615
+ return {
616
+ ...identityOutcome(documents, {
617
+ reason: first ?? 'error',
618
+ durationMs: elapsedMs(startedAt),
619
+ }),
620
+ attempts,
621
+ usage,
622
+ };
623
+ },
624
+ };
625
+ }
@@ -1,4 +1,2 @@
1
- export type * from './types';
2
- export { createSystemOneReranker } from './systemone';
3
- export type { SystemOneRerankerOptions } from './systemone';
1
+ export * from './core';
4
2
  export { createWebSearchReranker } from './search';