@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,144 @@
1
+ import type { Reranker, RerankKind, RerankEntry, RerankUsage, RerankReason, RerankOutcome, OutcomeReranker } from './types';
2
+ import { DecisionError } from '../decisions/types';
3
+ /** Longest deadline a step may have; matches `withDecisionDeadline`. */
4
+ export declare const MAX_RERANK_DEADLINE_MS = 3600000;
5
+ /**
6
+ * Input tokens one document costs a request, rounded up from Codegraph's
7
+ * measurements on file summaries (Jev with its rubric and question ~520,
8
+ * qwen3-reranker-8b ~140). Override per reranker for other document shapes.
9
+ */
10
+ export declare const ESTIMATED_TOKENS_PER_DOCUMENT: Readonly<Record<RerankKind, number>>;
11
+ export declare function emptyRerankUsage(): RerankUsage;
12
+ /** Every usage counter present as a finite number of at least zero. */
13
+ export declare function isRerankUsage(value: unknown): value is RerankUsage;
14
+ /** Adds `usage` into `sum`; anything that is not a positive finite count adds nothing. */
15
+ export declare function addRerankUsage(sum: RerankUsage, usage: unknown): RerankUsage;
16
+ /**
17
+ * The usage `documents` documents sent and never answered are charged as. A
18
+ * deadline aborts the client, not the host: the host received the request and
19
+ * bills it, so counting only answered calls lets every timeout spend without
20
+ * reaching a budget. A cross-encoder request is one search unit per 100
21
+ * documents, as Cohere bills it. `bm25` and `none` cost nothing.
22
+ */
23
+ export declare function estimatedUsage(kind: RerankKind, documents: number, tokensPerDocument?: number): Pick<RerankUsage, 'estimatedTokens' | 'estimatedSearchUnits'>;
24
+ /** An `estimatedTokensPerDocument` option: absent, or a finite count of at least zero. */
25
+ export declare const isTokenEstimate: (value: unknown) => boolean;
26
+ /**
27
+ * Prices in USD for one model; the SDK ships none. A rate is a finite number
28
+ * of at least zero: `0` prices a dimension as free, while an absent or invalid
29
+ * rate leaves usage of that dimension unpriced.
30
+ */
31
+ export interface RerankPrice {
32
+ inputPerMTok?: number;
33
+ outputPerMTok?: number;
34
+ perSearchUnit?: number;
35
+ }
36
+ /**
37
+ * A caller-supplied price table: per kind, a model id, a `prefix*` pattern
38
+ * (the longest match wins), or `*` for any model of that kind.
39
+ */
40
+ export type RerankPrices = Readonly<Partial<Record<RerankKind, Readonly<Record<string, RerankPrice>>>>>;
41
+ export interface RerankCost {
42
+ /** Every attempt, estimates included. */
43
+ usd: number;
44
+ /**
45
+ * Attempts that used something the table has no rate for (no entry, or an
46
+ * entry without a rate for a dimension they used); their spend is not in `usd`.
47
+ */
48
+ unpriced: Array<{
49
+ provider: RerankKind;
50
+ model: string;
51
+ }>;
52
+ }
53
+ /**
54
+ * What an outcome's attempts cost under `prices`; reported and estimated
55
+ * usage are priced alike. An attempt with usage the table has no rate for is
56
+ * listed in `unpriced` and adds nothing to `usd`, never counted as free.
57
+ */
58
+ export declare function rerankCost(outcome: Pick<RerankOutcome, 'attempts'>, prices: RerankPrices): RerankCost;
59
+ /** Every input once, score descending, ties in input order, `null` last; a threshold adds `kept`. */
60
+ export declare function rankedEntries(scores: ReadonlyArray<number | null>, threshold?: number): RerankEntry[];
61
+ export declare const isRerankKind: (value: unknown) => value is RerankKind;
62
+ /**
63
+ * Whether a permutation is in the order `rankedEntries` produces: score
64
+ * descending, ties in input order, `null` last, with `kept` a boolean when set.
65
+ */
66
+ export declare function isRankedOrder(results: readonly RerankEntry[]): boolean;
67
+ /** Whether `results` is a full permutation of `count` documents with finite or `null` scores. */
68
+ export declare function isRerankPermutation(results: unknown, count: number): results is RerankEntry[];
69
+ /** Reads the signal now; a function call keeps TypeScript from narrowing a later read away. */
70
+ export declare const isAborted: (signal: AbortSignal | undefined) => boolean;
71
+ /**
72
+ * No signal, or a real `AbortSignal`: `AbortSignal.any` and `fetch` refuse
73
+ * anything else, duck-typed look-alikes included.
74
+ */
75
+ export declare const isRequestSignal: (value: unknown) => boolean;
76
+ /** How many documents a request carries, read defensively at the public boundary. */
77
+ export declare const documentCount: (request: unknown) => number;
78
+ /** Identity order with `null` scores: what a caller serves when nothing answered. */
79
+ export declare function identityOutcome(documents: number, options: {
80
+ reason: string;
81
+ provider?: RerankKind;
82
+ model?: string;
83
+ durationMs?: number;
84
+ }): RerankOutcome;
85
+ export interface StepOutcome {
86
+ kind: RerankKind;
87
+ documents: number;
88
+ startedAt: number;
89
+ model: string;
90
+ /** One score per document when the step answered. */
91
+ scores?: ReadonlyArray<number | null>;
92
+ /** A failure; identity order is returned. */
93
+ reason?: string;
94
+ usage?: RerankUsage;
95
+ /** False when no request was made, so the attempt is `skipped` rather than `failed`. */
96
+ called?: boolean;
97
+ threshold?: number;
98
+ pinVerified?: boolean;
99
+ }
100
+ export declare const elapsedMs: (startedAt: number) => number;
101
+ /** One reranker's own outcome: `ok` with its scores, or `skipped` in identity order with a reason. */
102
+ export declare function stepOutcome(step: StepOutcome): RerankOutcome;
103
+ /** A failure as an outcome reason; the caller decides whether a fired deadline means `timeout` or `aborted`. */
104
+ export declare function rerankReasonOf(error: unknown): RerankReason;
105
+ /**
106
+ * A reply the transport backs off from and retries (HTTP 429 or 5xx), as the
107
+ * error it stands for; `null` for any other reply or none. A deadline that
108
+ * fires after it, with no request in flight and no later request ended,
109
+ * reports this rather than `timeout`: the host answered, and said why.
110
+ */
111
+ export declare function retriedReply(provider: string, status: number | null, retryAfterMs?: number): DecisionError | null;
112
+ /**
113
+ * A positive finite deadline rounded up to whole milliseconds, when that is no
114
+ * longer than an hour; otherwise `undefined`. It accepts fractions, so a
115
+ * configured timeout kept as given must also be checked as an integer.
116
+ */
117
+ export declare function validDeadline(value: unknown): number | undefined;
118
+ /**
119
+ * `test` holds for every slot of `values`, holes included. `some` and `every`
120
+ * skip the holes of a sparse array, which a spread, an index, or
121
+ * `JSON.stringify` later reads as `undefined` or `null`.
122
+ */
123
+ export declare function everySlot<T>(values: readonly T[], test: (value: T | undefined) => boolean): boolean;
124
+ /** A non-empty query, string documents, and a real signal if any, or the reason the request cannot be ranked. */
125
+ export declare function rankRequestProblem(request: unknown): RerankReason | undefined;
126
+ /**
127
+ * The never-throwing layer over a rejecting `Reranker`: its full ranking
128
+ * becomes an `ok` outcome, a rejection becomes a reason, and a ranking that
129
+ * is not a full permutation in descending score order is `invalid_results`.
130
+ * For a reranker with `reportsRequests`, usage counts each request it
131
+ * reported through `onRequest`, so a call that failed before sending counts
132
+ * none and is `skipped`, and a deadline charges an estimate only while a
133
+ * request was in flight. Any other reranker counts one call, plus every retry
134
+ * it reports through `onRequest`, or none when an open breaker
135
+ * (`circuitOpen`) refused it before dispatch. Tokens are whatever it
136
+ * reported. The request's `deadlineMs` and `signal` bound the wait even for
137
+ * a reranker that ignores them. The deadline reaches the reranker only as
138
+ * its abort signal, never as `timeoutMs`, which would replace its configured
139
+ * timeout: a deadline caps that timeout and never extends it.
140
+ */
141
+ export declare function toOutcomeReranker(reranker: Reranker, options: {
142
+ kind: RerankKind;
143
+ model?: string;
144
+ }): OutcomeReranker;
@@ -0,0 +1,48 @@
1
+ import type { DecisionModel } from '../decisions/types';
2
+ import type { RerankReason } from './types';
3
+ /** A model id no host serves: a host that answers it echoes whatever it is asked, so its echo proves nothing. */
4
+ export declare const PIN_SENTINEL_MODEL = "jev-0.0.0-pin-sentinel";
5
+ export interface PinProbeOptions {
6
+ /** The same host and credential, configured for `model`. */
7
+ modelFor: (model: string) => DecisionModel;
8
+ /** The checkpoint to verify, such as `jev-1.13.0`. */
9
+ pin: string;
10
+ /** Defaults to `PIN_SENTINEL_MODEL`; a blank sentinel, or one that is the pin, is `invalid_request`. */
11
+ sentinel?: string;
12
+ /**
13
+ * Per request, enforced around the model call even when the model ignores
14
+ * it; defaults to 15 seconds to allow a slow first token mint. Anything but
15
+ * an integer from 1 to 3,600,000 is `invalid_request`, with no request sent.
16
+ */
17
+ timeoutMs?: number;
18
+ signal?: AbortSignal;
19
+ }
20
+ export type PinProbe = {
21
+ verified: true;
22
+ echoed: string;
23
+ sentinelStatus: 404;
24
+ } | {
25
+ verified: false;
26
+ /**
27
+ * `sentinel_accepted`: the host answered a model it cannot serve.
28
+ * `echo_mismatch`: the pin was answered as another model. Otherwise the
29
+ * request's own failure, which says nothing about the pin.
30
+ */
31
+ reason: 'sentinel_accepted' | 'echo_mismatch' | RerankReason;
32
+ echoed?: string;
33
+ /**
34
+ * The HTTP status the sentinel request got, when it got a reply: for an
35
+ * accepted sentinel, the success status the model reported through
36
+ * `onResponse` (the SDK's HTTP model does), else none.
37
+ */
38
+ sentinelStatus?: number;
39
+ };
40
+ /**
41
+ * Does this host really serve the pinned model? Two answers are needed: a
42
+ * sentinel model no host serves must be refused with HTTP 404 (a host that
43
+ * answers it, as Laya does, echoes whatever it is asked, so its echo proves
44
+ * nothing), and a probe with the pin must echo exactly the pin. Each request
45
+ * is bounded by `timeoutMs` and the caller's signal even when the model ignores
46
+ * them. Never throws.
47
+ */
48
+ export declare function probePin(options: PinProbeOptions): Promise<PinProbe>;
@@ -0,0 +1,9 @@
1
+ /** At most `size` tasks run at once; the rest wait their turn in arrival order. */
2
+ export interface RerankSemaphore {
3
+ readonly size: number;
4
+ readonly active: number;
5
+ readonly waiting: number;
6
+ run<T>(task: () => Promise<T>): Promise<T>;
7
+ }
8
+ /** Share one semaphore between rerankers that call the same host. */
9
+ export declare function createSemaphore(size: number): RerankSemaphore;
@@ -1,13 +1,59 @@
1
- import type { Reranker } from './types';
2
- import type { DecisionModel } from '@/decisions';
1
+ import type { Reranker, OutcomeReranker } from './types';
2
+ import type { DecisionText, DecisionState, DecisionModel } from '../decisions/types';
3
+ import type { RerankScoreCache } from './cache';
4
+ import type { RerankSemaphore } from './semaphore';
5
+ /**
6
+ * `document` (the default) asks one score question per candidate, one request
7
+ * each. `batch` asks every candidate in one request; its scores follow input
8
+ * order (see the README), so use it only where that bias was evaluated.
9
+ */
10
+ export type SystemOneMode = 'document' | 'batch';
11
+ /** A checkpoint every response must echo, never a moving alias such as `jev-latest`. */
12
+ export interface SystemOnePin {
13
+ model: string;
14
+ /** A `kept` threshold calibrated for this checkpoint, rubric, and instructions. */
15
+ threshold?: number;
16
+ }
3
17
  export interface SystemOneRerankerOptions {
4
18
  /** Inject a configured Jev/Laya HTTP decision model; chat cannot produce expected scores. */
5
19
  model: DecisionModel;
6
20
  /** Relevance levels from least to most relevant; evaluate this rubric for the checkpoint. */
7
21
  rubric: readonly string[];
8
- /** Reject oversized batches instead of silently dropping candidates. Defaults to 128. */
22
+ /** Reject oversized candidate sets instead of silently dropping candidates. Defaults to 128. */
9
23
  maxDocuments?: number;
24
+ /**
25
+ * One deadline for the whole ranking, counted from the call: building
26
+ * states, cache lookups, and re-issues included, and no request is sent
27
+ * after it. A ranking the cache answers in full is served even when the
28
+ * lookups outran it. Whole milliseconds from 1 to an hour; anything else
29
+ * throws at construction. Defaults to 10 seconds.
30
+ */
10
31
  timeoutMs?: number;
32
+ mode?: SystemOneMode;
33
+ /** Document mode: the question asked about each candidate. */
34
+ instructions?: DecisionText;
35
+ /** Document mode: the state one candidate is judged in. Defaults to `{ query, document }`. */
36
+ state?: (query: string, document: string) => DecisionState;
37
+ /** Document mode: requests in flight at once, a positive integer, when no `semaphore` is shared. Defaults to 64. */
38
+ concurrency?: number;
39
+ /** Document mode: a semaphore shared with other rerankers calling the same host. */
40
+ semaphore?: RerankSemaphore;
41
+ /** Document mode: scores reused across queries; only an echo of the configured model is stored. */
42
+ cache?: RerankScoreCache;
43
+ /** Document mode: every response must echo this model, and `kept` needs its threshold. */
44
+ pin?: SystemOnePin;
45
+ /**
46
+ * Document mode: the estimate charged for a request a deadline abandoned.
47
+ * Defaults to 600; anything but a finite number of at least 0 throws.
48
+ */
49
+ estimatedTokensPerDocument?: number;
50
+ }
51
+ /** A `Reranker` that rejects on failure, and an `OutcomeReranker` that never does. */
52
+ export interface SystemOneReranker extends Reranker, OutcomeReranker {
53
+ readonly mode: SystemOneMode;
11
54
  }
12
- /** One shared query/candidate state and one score question per candidate, in one request. */
13
- export declare function createSystemOneReranker(options: SystemOneRerankerOptions): Reranker;
55
+ /**
56
+ * System One scores: one question per candidate in its own request by
57
+ * default, or every candidate in one request with `mode: 'batch'`.
58
+ */
59
+ export declare function createSystemOneReranker(options: SystemOneRerankerOptions): SystemOneReranker;
@@ -1,10 +1,22 @@
1
- import type { DecisionUsage } from '@/decisions';
1
+ import type { DecisionUsage } from '../decisions/types';
2
2
  export interface RerankRequest {
3
3
  query: string;
4
4
  documents: readonly string[];
5
5
  topK?: number;
6
6
  signal?: AbortSignal;
7
7
  timeoutMs?: number;
8
+ /**
9
+ * Called once per request a reranker sends, retries included, for one that
10
+ * reports them (see `DecisionRequest.onRequest`). Not awaited; a throw is ignored.
11
+ */
12
+ onRequest?: () => void;
13
+ /**
14
+ * Called once per reported request that ended with a reply (its HTTP
15
+ * status, and its `Retry-After` in milliseconds when it was not OK and
16
+ * sent one) or a failure without one (`null`), for one that reports them
17
+ * (see `DecisionRequest.onResponse`). Not awaited; a throw is ignored.
18
+ */
19
+ onResponse?: (status: number | null, retryAfterMs?: number) => void;
8
20
  }
9
21
  export interface RankedDocument {
10
22
  /** Index into the submitted documents, not an identity derived from text. */
@@ -20,5 +32,108 @@ export interface RerankResult {
20
32
  /** Rankings retain candidate identity; failures reject rather than fabricate scores. */
21
33
  export interface Reranker {
22
34
  readonly id: string;
35
+ /**
36
+ * True when `rerank` reports every request it sends through `onRequest` and
37
+ * every one that ends through `onResponse` (see
38
+ * `DecisionModel.reportsRequests`), so `toOutcomeReranker` counts only what
39
+ * was really sent.
40
+ */
41
+ readonly reportsRequests?: boolean;
23
42
  rerank(request: RerankRequest): Promise<RerankResult>;
24
43
  }
44
+ /**
45
+ * Where a ranking came from. `systemone` asks a Jev/Laya decision model,
46
+ * `cross-encoder` a Cohere-shaped `/rerank` endpoint, `bm25` scores in
47
+ * process, and `none` is identity order.
48
+ */
49
+ export type RerankKind = 'systemone' | 'cross-encoder' | 'bm25' | 'none';
50
+ /** `ok`: the first step answered. `degraded`: a later step did. `skipped`: identity order. */
51
+ export type RerankStatus = 'ok' | 'degraded' | 'skipped';
52
+ /**
53
+ * Reasons the SDK reports. A `withFallback` gate may report its own string
54
+ * (for example `backoff` or `budget`), so outcome reasons are typed `string`.
55
+ */
56
+ export type RerankReason = 'empty' | 'invalid_request' | 'too_many_documents' | 'disabled' | 'no_endpoint' | 'no_api_key' | 'timeout' | 'aborted' | 'partial' | 'unauthorized' | 'quota' | 'rate_limited' | 'circuit_open' | 'unsupported' | 'pin_mismatch' | 'bad_response' | 'invalid_results' | 'error';
57
+ /**
58
+ * What a ranking was charged. Reported counts are summed as the host sent
59
+ * them; `estimated*` counts charge requests a host received but a deadline
60
+ * abandoned (see `estimatedUsage`): for a reranker whose requests are
61
+ * reported, only those still in flight when it fired, never one the host had
62
+ * already answered. Never a price.
63
+ */
64
+ export interface RerankUsage {
65
+ /**
66
+ * Requests sent, including re-issues and retries. A decision model that
67
+ * reports its requests (`reportsRequests`, as the SDK's HTTP decision model
68
+ * does) is counted from those reports, so a `decide()` that failed before
69
+ * sending (a credential minter that failed or hung, a state that cannot be
70
+ * serialized) counts nothing; any other model counts one per `decide()`.
71
+ */
72
+ calls: number;
73
+ inputTokens: number;
74
+ outputTokens: number;
75
+ searchUnits: number;
76
+ /** Scores served from a score cache instead of a request. */
77
+ cached: number;
78
+ estimatedTokens: number;
79
+ estimatedSearchUnits: number;
80
+ }
81
+ /** One step that ran (`ok` or `failed`) or was skipped without a request. */
82
+ export interface RerankAttempt {
83
+ provider: RerankKind;
84
+ model: string;
85
+ status: 'ok' | 'failed' | 'skipped';
86
+ reason: string | null;
87
+ durationMs: number;
88
+ usage: RerankUsage;
89
+ }
90
+ export interface RerankEntry {
91
+ /** Index into the submitted documents. */
92
+ index: number;
93
+ /** Provider-specific score; `null` when the document was not scored. */
94
+ score: number | null;
95
+ /** Set only by a step with a threshold calibrated for its pinned model. */
96
+ kept?: boolean;
97
+ }
98
+ /**
99
+ * A ranking that never rejects. `results` is always a full permutation of the
100
+ * input: score descending, ties in input order, `null` scores last. A
101
+ * `skipped` outcome is identity order with every score `null`, so a caller
102
+ * can always serve the order it already had.
103
+ */
104
+ export interface RerankOutcome {
105
+ results: RerankEntry[];
106
+ provider: RerankKind;
107
+ /** The model the host echoed, else the configured one. */
108
+ model: string;
109
+ status: RerankStatus;
110
+ /** `null` when `ok`; for `degraded` and `skipped`, the first failed step's reason. */
111
+ reason: string | null;
112
+ attempts: RerankAttempt[];
113
+ durationMs: number;
114
+ /** Summed over every attempt: spend counts what was sent, not what answered. */
115
+ usage: RerankUsage;
116
+ /** Present when the answering step has a pin: whether every response echoed it. */
117
+ pinVerified?: boolean;
118
+ /** The calibrated threshold behind `kept`, when the answering step has one. */
119
+ threshold?: number;
120
+ }
121
+ /** No `topK`: an outcome ranks every document, and the caller slices. */
122
+ export interface RankRequest {
123
+ query: string;
124
+ documents: readonly string[];
125
+ signal?: AbortSignal;
126
+ /**
127
+ * This call's deadline. It caps the reranker's own timeout rather than
128
+ * replacing it: a reranker configured with a shorter timeout still gives up
129
+ * at that timeout, so a chain's later steps keep their time.
130
+ */
131
+ deadlineMs?: number;
132
+ }
133
+ /** Ranks without throwing or rejecting; every failure is an outcome's `reason`. */
134
+ export interface OutcomeReranker {
135
+ readonly id: string;
136
+ readonly kind: RerankKind;
137
+ readonly model: string;
138
+ rank(request: RankRequest): Promise<RerankOutcome>;
139
+ }
@@ -29,6 +29,12 @@ export declare function resolveLocalToolRegistry(args: {
29
29
  toolRegistry?: t.LCToolRegistry;
30
30
  toolExecution?: t.ToolExecutionConfig;
31
31
  }): t.LCToolRegistry | undefined;
32
+ /**
33
+ * Drops host-bound coding tools outside `local.codingToolNames`, so prompt
34
+ * projections (instruction tokens, runner guidance) see the same tools that
35
+ * are finally bound. Returns `tools` unchanged when no local allowlist applies.
36
+ */
37
+ export declare function filterToolsByLocalAllowlist(tools: t.GraphTools | undefined, toolExecution?: t.ToolExecutionConfig): t.GraphTools | undefined;
32
38
  /** Names that this execution config creates or replaces in the local tool map. */
33
39
  export declare function resolveLocalImplementationNames(toolNames: Iterable<string>, toolExecution?: t.ToolExecutionConfig): Set<string>;
34
40
  export declare function resolveLocalExecutionTools(args: {
@@ -0,0 +1,16 @@
1
+ /** Keeps the last `maxChars` characters, starting at a line boundary when one is near. */
2
+ export declare function tailTruncate(text: string, maxChars: number): string;
3
+ /** Longest grep match line kept when results are capped. */
4
+ export declare const CAPPED_GREP_LINE_CHARS = 300;
5
+ /**
6
+ * Caps line-oriented results (search matches): each line is cut to
7
+ * `CAPPED_GREP_LINE_CHARS`, and lines stop at `maxChars` with a note naming
8
+ * how many were left out.
9
+ */
10
+ export declare function capLines(text: string | readonly string[], maxChars: number, note?: (omitted: number) => string): string;
11
+ /**
12
+ * Caps free-form output (shell results): keeps the first 20% and the last 80%
13
+ * of `maxChars`, where errors and test summaries are, and says how much was
14
+ * left out so the model can rerun a narrower command.
15
+ */
16
+ export declare function capHeadTail(text: string, maxChars: number): string;
@@ -901,6 +901,22 @@ export type LocalExecutionConfig = {
901
901
  * code/bash execution tools) when `engine` is `local`. Defaults to true.
902
902
  */
903
903
  includeCodingTools?: boolean;
904
+ /**
905
+ * Allowlist of auto-bound local coding tool names (for example
906
+ * `['read_file', 'edit_file', 'grep_search', 'bash_tool']`). Omit to bind
907
+ * the whole suite. Fewer tool schemas means a smaller prompt on every
908
+ * request.
909
+ */
910
+ codingToolNames?: readonly string[];
911
+ /**
912
+ * Opt-in cap, in characters, on the results the model reads most:
913
+ * `read_file` keeps whole lines up to the cap (and its `limit`, when
914
+ * given) with an `offset` hint to continue, `grep_search` cuts long match lines and stops
915
+ * at the cap with a count of omitted lines, and `bash_tool` keeps the head
916
+ * and tail of long stdout and stderr with the status lines intact. Unset
917
+ * keeps the existing limits.
918
+ */
919
+ toolResultMaxChars?: number;
904
920
  /**
905
921
  * Override the process launcher. When set, replaces
906
922
  * `child_process.spawn` for every local tool invocation, allowing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "4.0.6",
3
+ "version": "4.1.0",
4
4
  "reova": {
5
5
  "enabled": true,
6
6
  "endpoint": "https://telemetry.reo.dev/data"
@@ -19,6 +19,21 @@
19
19
  "import": "./dist/esm/provider-registration.mjs",
20
20
  "require": "./dist/cjs/provider-registration.cjs"
21
21
  },
22
+ "./decisions": {
23
+ "types": "./dist/types/decisions/core.d.ts",
24
+ "import": "./dist/esm/decisions/core.mjs",
25
+ "require": "./dist/cjs/decisions/core.cjs"
26
+ },
27
+ "./decisions/node": {
28
+ "types": "./dist/types/decisions/node.d.ts",
29
+ "import": "./dist/esm/decisions/node.mjs",
30
+ "require": "./dist/cjs/decisions/node.cjs"
31
+ },
32
+ "./rerank": {
33
+ "types": "./dist/types/rerank/core.d.ts",
34
+ "import": "./dist/esm/rerank/core.mjs",
35
+ "require": "./dist/cjs/rerank/core.cjs"
36
+ },
22
37
  "./openai": {
23
38
  "types": "./dist/types/openai/index.d.ts",
24
39
  "import": "./dist/esm/openai/index.mjs",
@@ -120,6 +135,15 @@
120
135
  "provider-registration": [
121
136
  "dist/types/provider-registration.d.ts"
122
137
  ],
138
+ "decisions": [
139
+ "dist/types/decisions/core.d.ts"
140
+ ],
141
+ "decisions/node": [
142
+ "dist/types/decisions/node.d.ts"
143
+ ],
144
+ "rerank": [
145
+ "dist/types/rerank/core.d.ts"
146
+ ],
123
147
  "langchain": [
124
148
  "dist/types/langchain/index.d.ts"
125
149
  ],
@@ -193,6 +217,7 @@
193
217
  "build:dev": "tsdown",
194
218
  "check:circular-deps": "node config/circular-deps.mjs",
195
219
  "test:circular-deps": "node --test config/circular-deps.test.mjs",
220
+ "test:light-entries": "node --test config/light-entries.test.mjs",
196
221
  "sort-imports": "node scripts/sort-imports.ts",
197
222
  "sort-imports:check": "node scripts/sort-imports.ts --check",
198
223
  "start": "node dist/esm/main.js",
@@ -38,6 +38,7 @@ import {
38
38
  import {
39
39
  isProgrammaticRunnerAutoBound,
40
40
  isProgrammaticRunnerResolvedDirectly,
41
+ filterToolsByLocalAllowlist,
41
42
  resolveLocalImplementationNames,
42
43
  resolveLocalToolRegistry,
43
44
  } from '@/tools/local/resolveLocalExecutionTools';
@@ -183,7 +184,11 @@ export class AgentContext {
183
184
  * subagent) into this same array and must not mutate the host's input.
184
185
  */
185
186
  if (graphTools && graphTools.length > 0) {
186
- agentContext.graphTools = [...graphTools];
187
+ agentContext.graphTools = [
188
+ ...((filterToolsByLocalAllowlist(graphTools, toolExecution) as
189
+ | t.GenericTool[]
190
+ | undefined) ?? []),
191
+ ] as t.GraphTools;
187
192
  }
188
193
 
189
194
  if (initialSummary?.text != null && initialSummary.text !== '') {
@@ -200,7 +205,28 @@ export class AgentContext {
200
205
  agentContext.baseIndexTokenCountMap = { ...tokenMap };
201
206
  agentContext.indexTokenCountMap = tokenMap;
202
207
 
203
- if (toolSchemaTokens != null && toolSchemaTokens > 0) {
208
+ /** A cached total counts the host's unfiltered tools. Once the local
209
+ * allowlist removed some, recount, but only when the recount can
210
+ * measure every retained tool (it reads `.schema`); otherwise the
211
+ * larger cached total is the safer budget. */
212
+ const allowlistRemovedTools =
213
+ (tools?.length ?? 0) !== (agentContext.tools?.length ?? 0) ||
214
+ (toolDefinitions?.length ?? 0) !==
215
+ (agentContext.toolDefinitions?.length ?? 0) ||
216
+ (graphTools?.length ?? 0) !== (agentContext.graphTools?.length ?? 0);
217
+ const recountMeasuresAll = [
218
+ ...((agentContext.tools as unknown[] | undefined) ?? []),
219
+ ...((agentContext.graphTools as unknown[] | undefined) ?? []),
220
+ ].every(
221
+ (tool) =>
222
+ tool != null &&
223
+ typeof (tool as { schema?: unknown }).schema === 'object'
224
+ );
225
+ if (
226
+ toolSchemaTokens != null &&
227
+ toolSchemaTokens > 0 &&
228
+ !(allowlistRemovedTools && recountMeasuresAll)
229
+ ) {
204
230
  /** Use pre-computed (cached) tool schema tokens — skip calculateInstructionTokens */
205
231
  agentContext.toolSchemaTokens = toolSchemaTokens;
206
232
  agentContext.tokenCalculationPromise = Promise.resolve();
@@ -537,14 +563,17 @@ export class AgentContext {
537
563
  tokenCounter != null && isTokenCounterCacheCompatible(tokenCounter)
538
564
  ? createExactTokenCountCache(tokenCounter)
539
565
  : undefined;
540
- this.tools = tools;
566
+ this.tools = filterToolsByLocalAllowlist(tools, toolExecution);
541
567
  this.toolMap = toolMap;
542
568
  this.toolRegistry = resolveLocalToolRegistry({
543
569
  toolRegistry,
544
570
  toolExecution,
545
571
  });
546
572
  this.toolExecution = toolExecution;
547
- this.toolDefinitions = toolDefinitions;
573
+ this.toolDefinitions = filterToolsByLocalAllowlist(
574
+ toolDefinitions as t.GraphTools | undefined,
575
+ toolExecution
576
+ ) as t.LCTool[] | undefined;
548
577
  this.instructions = instructions;
549
578
  this.additionalInstructions = additionalInstructions;
550
579
  if (reasoningKey) {