@librechat/agents 4.0.5 → 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 (191) 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 +7 -6
  26. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  27. package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
  28. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  29. package/dist/cjs/llm/bedrock/index.cjs +8 -5
  30. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  31. package/dist/cjs/llm/google/index.cjs +1 -1
  32. package/dist/cjs/llm/google/index.cjs.map +1 -1
  33. package/dist/cjs/llm/google/utils/common.cjs +8 -2
  34. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  35. package/dist/cjs/main.cjs +45 -0
  36. package/dist/cjs/rerank/bm25.cjs +110 -0
  37. package/dist/cjs/rerank/bm25.cjs.map +1 -0
  38. package/dist/cjs/rerank/cache.cjs +50 -0
  39. package/dist/cjs/rerank/cache.cjs.map +1 -0
  40. package/dist/cjs/rerank/core.cjs +29 -0
  41. package/dist/cjs/rerank/crossEncoder.cjs +172 -0
  42. package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
  43. package/dist/cjs/rerank/fallback.cjs +280 -0
  44. package/dist/cjs/rerank/fallback.cjs.map +1 -0
  45. package/dist/cjs/rerank/index.cjs +8 -0
  46. package/dist/cjs/rerank/outcome.cjs +382 -0
  47. package/dist/cjs/rerank/outcome.cjs.map +1 -0
  48. package/dist/cjs/rerank/pin.cjs +74 -0
  49. package/dist/cjs/rerank/pin.cjs.map +1 -0
  50. package/dist/cjs/rerank/semaphore.cjs +38 -0
  51. package/dist/cjs/rerank/semaphore.cjs.map +1 -0
  52. package/dist/cjs/rerank/systemone.cjs +476 -50
  53. package/dist/cjs/rerank/systemone.cjs.map +1 -1
  54. package/dist/cjs/session/AgentSession.cjs +1 -1
  55. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  56. package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
  57. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  58. package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
  59. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  60. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
  61. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  62. package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
  63. package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
  64. package/dist/esm/agents/AgentContext.mjs +7 -5
  65. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  66. package/dist/esm/decisions/breaker.mjs +56 -0
  67. package/dist/esm/decisions/breaker.mjs.map +1 -0
  68. package/dist/esm/decisions/core.mjs +11 -0
  69. package/dist/esm/decisions/dialect.mjs +65 -12
  70. package/dist/esm/decisions/dialect.mjs.map +1 -1
  71. package/dist/esm/decisions/hook.mjs +19 -0
  72. package/dist/esm/decisions/hook.mjs.map +1 -0
  73. package/dist/esm/decisions/http.mjs +2 -1
  74. package/dist/esm/decisions/http.mjs.map +1 -1
  75. package/dist/esm/decisions/index.mjs +6 -0
  76. package/dist/esm/decisions/node.mjs +313 -0
  77. package/dist/esm/decisions/node.mjs.map +1 -0
  78. package/dist/esm/decisions/probe.mjs +54 -0
  79. package/dist/esm/decisions/probe.mjs.map +1 -0
  80. package/dist/esm/decisions/redact.mjs +108 -0
  81. package/dist/esm/decisions/redact.mjs.map +1 -0
  82. package/dist/esm/decisions/structuredChat.mjs +2 -3
  83. package/dist/esm/decisions/structuredChat.mjs.map +1 -1
  84. package/dist/esm/decisions/transport.mjs +56 -23
  85. package/dist/esm/decisions/transport.mjs.map +1 -1
  86. package/dist/esm/decisions/types.mjs +2 -0
  87. package/dist/esm/decisions/types.mjs.map +1 -1
  88. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +7 -7
  89. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  90. package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
  91. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  92. package/dist/esm/llm/bedrock/index.mjs +7 -4
  93. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  94. package/dist/esm/llm/google/index.mjs +2 -2
  95. package/dist/esm/llm/google/index.mjs.map +1 -1
  96. package/dist/esm/llm/google/utils/common.mjs +8 -3
  97. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  98. package/dist/esm/main.mjs +15 -3
  99. package/dist/esm/rerank/bm25.mjs +108 -0
  100. package/dist/esm/rerank/bm25.mjs.map +1 -0
  101. package/dist/esm/rerank/cache.mjs +50 -0
  102. package/dist/esm/rerank/cache.mjs.map +1 -0
  103. package/dist/esm/rerank/core.mjs +9 -0
  104. package/dist/esm/rerank/crossEncoder.mjs +172 -0
  105. package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
  106. package/dist/esm/rerank/fallback.mjs +278 -0
  107. package/dist/esm/rerank/fallback.mjs.map +1 -0
  108. package/dist/esm/rerank/index.mjs +8 -0
  109. package/dist/esm/rerank/outcome.mjs +360 -0
  110. package/dist/esm/rerank/outcome.mjs.map +1 -0
  111. package/dist/esm/rerank/pin.mjs +73 -0
  112. package/dist/esm/rerank/pin.mjs.map +1 -0
  113. package/dist/esm/rerank/semaphore.mjs +38 -0
  114. package/dist/esm/rerank/semaphore.mjs.map +1 -0
  115. package/dist/esm/rerank/systemone.mjs +476 -50
  116. package/dist/esm/rerank/systemone.mjs.map +1 -1
  117. package/dist/esm/session/AgentSession.mjs +1 -1
  118. package/dist/esm/session/AgentSession.mjs.map +1 -1
  119. package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
  120. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  121. package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
  122. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  123. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
  124. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  125. package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
  126. package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
  127. package/dist/types/decisions/breaker.d.ts +37 -0
  128. package/dist/types/decisions/core.d.ts +19 -0
  129. package/dist/types/decisions/hook.d.ts +9 -0
  130. package/dist/types/decisions/index.d.ts +3 -8
  131. package/dist/types/decisions/node.d.ts +90 -0
  132. package/dist/types/decisions/probe.d.ts +37 -0
  133. package/dist/types/decisions/redact.d.ts +22 -0
  134. package/dist/types/decisions/structuredChat.d.ts +1 -0
  135. package/dist/types/decisions/transport.d.ts +16 -3
  136. package/dist/types/decisions/types.d.ts +43 -4
  137. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  138. package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
  139. package/dist/types/llm/bedrock/index.d.ts +2 -1
  140. package/dist/types/llm/google/index.d.ts +1 -0
  141. package/dist/types/llm/google/utils/common.d.ts +2 -0
  142. package/dist/types/rerank/bm25.d.ts +46 -0
  143. package/dist/types/rerank/cache.d.ts +40 -0
  144. package/dist/types/rerank/core.d.ts +24 -0
  145. package/dist/types/rerank/crossEncoder.d.ts +48 -0
  146. package/dist/types/rerank/fallback.d.ts +67 -0
  147. package/dist/types/rerank/index.d.ts +1 -3
  148. package/dist/types/rerank/outcome.d.ts +144 -0
  149. package/dist/types/rerank/pin.d.ts +48 -0
  150. package/dist/types/rerank/semaphore.d.ts +9 -0
  151. package/dist/types/rerank/systemone.d.ts +51 -5
  152. package/dist/types/rerank/types.d.ts +116 -1
  153. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
  154. package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
  155. package/dist/types/types/tools.d.ts +16 -0
  156. package/package.json +26 -1
  157. package/src/agents/AgentContext.ts +33 -4
  158. package/src/decisions/breaker.ts +110 -0
  159. package/src/decisions/core.ts +23 -0
  160. package/src/decisions/dialect.ts +134 -20
  161. package/src/decisions/hook.ts +32 -0
  162. package/src/decisions/http.ts +4 -1
  163. package/src/decisions/index.ts +3 -12
  164. package/src/decisions/node.ts +671 -0
  165. package/src/decisions/probe.ts +114 -0
  166. package/src/decisions/redact.ts +222 -0
  167. package/src/decisions/structuredChat.ts +6 -8
  168. package/src/decisions/transport.ts +104 -22
  169. package/src/decisions/types.ts +46 -5
  170. package/src/llm/anthropic/utils/message_inputs.ts +16 -16
  171. package/src/llm/bedrock/cachePoints.ts +47 -0
  172. package/src/llm/bedrock/index.ts +35 -13
  173. package/src/llm/google/index.ts +5 -3
  174. package/src/llm/google/utils/common.ts +19 -5
  175. package/src/rerank/bm25.ts +190 -0
  176. package/src/rerank/cache.ts +103 -0
  177. package/src/rerank/core.ts +47 -0
  178. package/src/rerank/crossEncoder.ts +289 -0
  179. package/src/rerank/fallback.ts +625 -0
  180. package/src/rerank/index.ts +1 -3
  181. package/src/rerank/outcome.ts +767 -0
  182. package/src/rerank/pin.ts +157 -0
  183. package/src/rerank/semaphore.ts +47 -0
  184. package/src/rerank/systemone.ts +914 -88
  185. package/src/rerank/types.ts +143 -1
  186. package/src/session/AgentSession.ts +3 -1
  187. package/src/tools/local/LocalCodingTools.ts +139 -19
  188. package/src/tools/local/LocalExecutionTools.ts +21 -1
  189. package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
  190. package/src/tools/local/toolResultCaps.ts +60 -0
  191. package/src/types/tools.ts +16 -0
@@ -1,4 +1,4 @@
1
- import type { DecisionUsage } from '@/decisions';
1
+ import type { DecisionUsage } from '../decisions/types';
2
2
 
3
3
  export interface RerankRequest {
4
4
  query: string;
@@ -6,6 +6,18 @@ export interface RerankRequest {
6
6
  topK?: number;
7
7
  signal?: AbortSignal;
8
8
  timeoutMs?: number;
9
+ /**
10
+ * Called once per request a reranker sends, retries included, for one that
11
+ * reports them (see `DecisionRequest.onRequest`). Not awaited; a throw is ignored.
12
+ */
13
+ onRequest?: () => void;
14
+ /**
15
+ * Called once per reported request that ended with a reply (its HTTP
16
+ * status, and its `Retry-After` in milliseconds when it was not OK and
17
+ * sent one) or a failure without one (`null`), for one that reports them
18
+ * (see `DecisionRequest.onResponse`). Not awaited; a throw is ignored.
19
+ */
20
+ onResponse?: (status: number | null, retryAfterMs?: number) => void;
9
21
  }
10
22
 
11
23
  export interface RankedDocument {
@@ -24,5 +36,135 @@ export interface RerankResult {
24
36
  /** Rankings retain candidate identity; failures reject rather than fabricate scores. */
25
37
  export interface Reranker {
26
38
  readonly id: string;
39
+ /**
40
+ * True when `rerank` reports every request it sends through `onRequest` and
41
+ * every one that ends through `onResponse` (see
42
+ * `DecisionModel.reportsRequests`), so `toOutcomeReranker` counts only what
43
+ * was really sent.
44
+ */
45
+ readonly reportsRequests?: boolean;
27
46
  rerank(request: RerankRequest): Promise<RerankResult>;
28
47
  }
48
+
49
+ /**
50
+ * Where a ranking came from. `systemone` asks a Jev/Laya decision model,
51
+ * `cross-encoder` a Cohere-shaped `/rerank` endpoint, `bm25` scores in
52
+ * process, and `none` is identity order.
53
+ */
54
+ export type RerankKind = 'systemone' | 'cross-encoder' | 'bm25' | 'none';
55
+
56
+ /** `ok`: the first step answered. `degraded`: a later step did. `skipped`: identity order. */
57
+ export type RerankStatus = 'ok' | 'degraded' | 'skipped';
58
+
59
+ /**
60
+ * Reasons the SDK reports. A `withFallback` gate may report its own string
61
+ * (for example `backoff` or `budget`), so outcome reasons are typed `string`.
62
+ */
63
+ export type RerankReason =
64
+ | 'empty'
65
+ | 'invalid_request'
66
+ | 'too_many_documents'
67
+ | 'disabled'
68
+ | 'no_endpoint'
69
+ | 'no_api_key'
70
+ | 'timeout'
71
+ | 'aborted'
72
+ | 'partial'
73
+ | 'unauthorized'
74
+ | 'quota'
75
+ | 'rate_limited'
76
+ | 'circuit_open'
77
+ | 'unsupported'
78
+ | 'pin_mismatch'
79
+ | 'bad_response'
80
+ | 'invalid_results'
81
+ | 'error';
82
+
83
+ /**
84
+ * What a ranking was charged. Reported counts are summed as the host sent
85
+ * them; `estimated*` counts charge requests a host received but a deadline
86
+ * abandoned (see `estimatedUsage`): for a reranker whose requests are
87
+ * reported, only those still in flight when it fired, never one the host had
88
+ * already answered. Never a price.
89
+ */
90
+ export interface RerankUsage {
91
+ /**
92
+ * Requests sent, including re-issues and retries. A decision model that
93
+ * reports its requests (`reportsRequests`, as the SDK's HTTP decision model
94
+ * does) is counted from those reports, so a `decide()` that failed before
95
+ * sending (a credential minter that failed or hung, a state that cannot be
96
+ * serialized) counts nothing; any other model counts one per `decide()`.
97
+ */
98
+ calls: number;
99
+ inputTokens: number;
100
+ outputTokens: number;
101
+ searchUnits: number;
102
+ /** Scores served from a score cache instead of a request. */
103
+ cached: number;
104
+ estimatedTokens: number;
105
+ estimatedSearchUnits: number;
106
+ }
107
+
108
+ /** One step that ran (`ok` or `failed`) or was skipped without a request. */
109
+ export interface RerankAttempt {
110
+ provider: RerankKind;
111
+ model: string;
112
+ status: 'ok' | 'failed' | 'skipped';
113
+ reason: string | null;
114
+ durationMs: number;
115
+ usage: RerankUsage;
116
+ }
117
+
118
+ export interface RerankEntry {
119
+ /** Index into the submitted documents. */
120
+ index: number;
121
+ /** Provider-specific score; `null` when the document was not scored. */
122
+ score: number | null;
123
+ /** Set only by a step with a threshold calibrated for its pinned model. */
124
+ kept?: boolean;
125
+ }
126
+
127
+ /**
128
+ * A ranking that never rejects. `results` is always a full permutation of the
129
+ * input: score descending, ties in input order, `null` scores last. A
130
+ * `skipped` outcome is identity order with every score `null`, so a caller
131
+ * can always serve the order it already had.
132
+ */
133
+ export interface RerankOutcome {
134
+ results: RerankEntry[];
135
+ provider: RerankKind;
136
+ /** The model the host echoed, else the configured one. */
137
+ model: string;
138
+ status: RerankStatus;
139
+ /** `null` when `ok`; for `degraded` and `skipped`, the first failed step's reason. */
140
+ reason: string | null;
141
+ attempts: RerankAttempt[];
142
+ durationMs: number;
143
+ /** Summed over every attempt: spend counts what was sent, not what answered. */
144
+ usage: RerankUsage;
145
+ /** Present when the answering step has a pin: whether every response echoed it. */
146
+ pinVerified?: boolean;
147
+ /** The calibrated threshold behind `kept`, when the answering step has one. */
148
+ threshold?: number;
149
+ }
150
+
151
+ /** No `topK`: an outcome ranks every document, and the caller slices. */
152
+ export interface RankRequest {
153
+ query: string;
154
+ documents: readonly string[];
155
+ signal?: AbortSignal;
156
+ /**
157
+ * This call's deadline. It caps the reranker's own timeout rather than
158
+ * replacing it: a reranker configured with a shorter timeout still gives up
159
+ * at that timeout, so a chain's later steps keep their time.
160
+ */
161
+ deadlineMs?: number;
162
+ }
163
+
164
+ /** Ranks without throwing or rejecting; every failure is an outcome's `reason`. */
165
+ export interface OutcomeReranker {
166
+ readonly id: string;
167
+ readonly kind: RerankKind;
168
+ readonly model: string;
169
+ rank(request: RankRequest): Promise<RerankOutcome>;
170
+ }
@@ -1720,7 +1720,9 @@ export class AgentSession {
1720
1720
  options.retainRecentTurns,
1721
1721
  options.instructions
1722
1722
  ),
1723
- this.runConfig.tokenCounter
1723
+ this.runConfig.tokenCounter,
1724
+ undefined,
1725
+ this.runConfig.toolExecution
1724
1726
  );
1725
1727
  const graph = createManualCompactGraph({
1726
1728
  runId: compactRunId,
@@ -30,9 +30,10 @@ import { createLocalFileCheckpointer } from './FileCheckpointer';
30
30
  import { isWorkspaceClientTimeoutError } from './workspaceFS';
31
31
  import { applyEdit, locateEdit } from './editStrategies';
32
32
  import { decodeFile, encodeFile } from './textEncoding';
33
- import { runPostEditSyntaxCheck } from './syntaxCheck';
34
33
  import { withIntent } from '@/tools/intentArg';
35
- import { Constants } from '@/common';
34
+ import { runPostEditSyntaxCheck } from './syntaxCheck';
35
+ import { capHeadTail, capLines } from './toolResultCaps';
36
+ import { Constants, LOCAL_CODING_BUNDLE_NAMES } from '@/common';
36
37
 
37
38
  const MAX_READ_CHARS = 256000;
38
39
  const DEFAULT_MAX_RESULTS = 200;
@@ -235,6 +236,49 @@ function lineWindow(
235
236
  };
236
237
  }
237
238
 
239
+ /** Reads whole lines from `offset` until `maxChars` or `limit` lines, then says how to continue. */
240
+ function cappedLineWindow(
241
+ content: string,
242
+ offset: number | undefined,
243
+ limit: number | undefined,
244
+ maxChars: number
245
+ ): string {
246
+ const start = Math.max(offset ?? 1, 1);
247
+ // Walk newline indices instead of splitting the file, so a page costs
248
+ // O(offset + page) rather than O(file).
249
+ let cursor = 0;
250
+ for (let line = 1; line < start; line++) {
251
+ const next = content.indexOf('\n', cursor);
252
+ if (next === -1) return '';
253
+ cursor = next + 1;
254
+ }
255
+ const maxLines = limit != null && limit > 0 ? limit : Infinity;
256
+ const kept: string[] = [];
257
+ let used = 0;
258
+ while (cursor <= content.length && kept.length < maxLines) {
259
+ const newline = content.indexOf('\n', cursor);
260
+ const lineEnd = newline === -1 ? content.length : newline;
261
+ const text = content.slice(cursor, Math.min(lineEnd, cursor + maxChars));
262
+ const full = `${String(start + kept.length).padStart(6, ' ')}\t${text}`;
263
+ const numbered =
264
+ lineEnd - cursor > maxChars || full.length > maxChars
265
+ ? `${full.slice(0, maxChars)} [line truncated]`
266
+ : full;
267
+ if (used + numbered.length + 1 > maxChars && kept.length > 0) break;
268
+ kept.push(numbered);
269
+ used += numbered.length + 1;
270
+ if (newline === -1) {
271
+ cursor = content.length + 1;
272
+ break;
273
+ }
274
+ cursor = newline + 1;
275
+ }
276
+ const end = start + kept.length - 1;
277
+ return cursor <= content.length
278
+ ? `${kept.join('\n')}\n[showing lines ${start}-${end}; continue with offset=${end + 1}]`
279
+ : kept.join('\n');
280
+ }
281
+
238
282
  const MAX_DIFF_CHARS = 4000;
239
283
 
240
284
  type SyntaxRun =
@@ -500,6 +544,17 @@ export function createLocalReadFileTool(
500
544
  }
501
545
 
502
546
  const content = await fs.readFile(path, 'utf8');
547
+ if (config.toolResultMaxChars != null && config.toolResultMaxChars > 0) {
548
+ return [
549
+ cappedLineWindow(
550
+ content,
551
+ input.offset,
552
+ input.limit,
553
+ config.toolResultMaxChars
554
+ ),
555
+ { path, bytes: fileStat.size },
556
+ ];
557
+ }
503
558
  const result = lineWindow(content, input.offset, input.limit);
504
559
  return [
505
560
  result.truncated ? `${result.text}\n[truncated]` : result.text,
@@ -1000,6 +1055,34 @@ function formatFallbackGrepDisplay(result: FallbackGrepResult): string {
1000
1055
  return 'No matches found.';
1001
1056
  }
1002
1057
 
1058
+ /**
1059
+ * Fallback grep display under `toolResultMaxChars`: skip notices get at most
1060
+ * a fifth of the budget (with a count of the ones left out), matches get the
1061
+ * rest, so neither can push the result past the cap or hide the other.
1062
+ */
1063
+ function capFallbackGrepDisplay(
1064
+ matches: string[],
1065
+ skipped: string[],
1066
+ maxChars: number
1067
+ ): string {
1068
+ const skipText =
1069
+ skipped.length === 0
1070
+ ? ''
1071
+ : capLines(
1072
+ skipped,
1073
+ Math.max(1, Math.floor(maxChars / 5)),
1074
+ (omitted) => `${omitted} more files skipped`
1075
+ );
1076
+ if (matches.length === 0) {
1077
+ return skipText === '' ? 'No matches found.' : skipText;
1078
+ }
1079
+ const matchText = capLines(
1080
+ matches,
1081
+ Math.max(1, maxChars - skipText.length)
1082
+ );
1083
+ return skipText === '' ? matchText : `${matchText}\n${skipText}`;
1084
+ }
1085
+
1003
1086
  async function fallbackGrep(
1004
1087
  root: string,
1005
1088
  pattern: string,
@@ -1167,8 +1250,12 @@ export function createLocalGrepSearchTool(
1167
1250
  (result.exitCode != null && result.exitCode > 1)
1168
1251
  ) {
1169
1252
  const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;
1253
+ const shown =
1254
+ config.toolResultMaxChars != null && config.toolResultMaxChars > 0
1255
+ ? capHeadTail(detail, config.toolResultMaxChars)
1256
+ : detail;
1170
1257
  return [
1171
- `grep_search failed: ${detail}`,
1258
+ `grep_search failed: ${shown}`,
1172
1259
  {
1173
1260
  matches: 0,
1174
1261
  engine: 'ripgrep',
@@ -1181,10 +1268,17 @@ export function createLocalGrepSearchTool(
1181
1268
  .split('\n')
1182
1269
  .filter(Boolean)
1183
1270
  .slice(0, maxResults);
1184
- const output =
1271
+ const joined =
1185
1272
  lines.length > 0
1186
1273
  ? lines.join('\n')
1187
1274
  : result.stderr.trim() || 'No matches found.';
1275
+ let output = joined;
1276
+ if (config.toolResultMaxChars != null && config.toolResultMaxChars > 0) {
1277
+ output =
1278
+ lines.length > 0
1279
+ ? capLines(lines, config.toolResultMaxChars)
1280
+ : capHeadTail(joined, config.toolResultMaxChars);
1281
+ }
1188
1282
  return [output, { matches: lines.length, engine: 'ripgrep' }];
1189
1283
  }
1190
1284
 
@@ -1198,7 +1292,10 @@ export function createLocalGrepSearchTool(
1198
1292
  );
1199
1293
  // Artifact count: ONLY real matches (Codex P2 [43] —
1200
1294
  // skip sentinels used to inflate the count and the budget).
1201
- const display = formatFallbackGrepDisplay({ matches, skipped });
1295
+ const display =
1296
+ config.toolResultMaxChars != null && config.toolResultMaxChars > 0
1297
+ ? capFallbackGrepDisplay(matches, skipped, config.toolResultMaxChars)
1298
+ : formatFallbackGrepDisplay({ matches, skipped });
1202
1299
  return [
1203
1300
  display,
1204
1301
  {
@@ -1209,8 +1306,12 @@ export function createLocalGrepSearchTool(
1209
1306
  ];
1210
1307
  } catch (e) {
1211
1308
  if (e instanceof FallbackGrepError) {
1309
+ const reason =
1310
+ config.toolResultMaxChars != null && config.toolResultMaxChars > 0
1311
+ ? capHeadTail(e.message, config.toolResultMaxChars)
1312
+ : e.message;
1212
1313
  return [
1213
- `grep_search refused the pattern: ${e.message}`,
1314
+ `grep_search refused the pattern: ${reason}`,
1214
1315
  {
1215
1316
  matches: 0,
1216
1317
  engine: 'node-fallback',
@@ -1360,19 +1461,38 @@ export function createLocalCodingTools(
1360
1461
  (config.fileCheckpointing === true
1361
1462
  ? createLocalFileCheckpointer({ fs: config.exec?.fs })
1362
1463
  : undefined);
1363
- return [
1364
- createLocalReadFileTool(config),
1365
- createLocalWriteFileTool(config, checkpointer),
1366
- createLocalEditFileTool(config, checkpointer),
1367
- createLocalGrepSearchTool(config),
1368
- createLocalGlobSearchTool(config),
1369
- createLocalListDirectoryTool(config),
1370
- createCompileCheckTool(config),
1371
- createLocalBashExecutionTool({ config }),
1372
- createLocalCodeExecutionTool(config),
1373
- createLocalProgrammaticToolCallingTool(config),
1374
- createLocalBashProgrammaticToolCallingTool(config),
1375
- ];
1464
+ const create = (name: string): DynamicStructuredTool => {
1465
+ switch (name) {
1466
+ case Constants.READ_FILE:
1467
+ return createLocalReadFileTool(config);
1468
+ case Constants.WRITE_FILE:
1469
+ return createLocalWriteFileTool(config, checkpointer);
1470
+ case Constants.EDIT_FILE:
1471
+ return createLocalEditFileTool(config, checkpointer);
1472
+ case Constants.GREP_SEARCH:
1473
+ return createLocalGrepSearchTool(config);
1474
+ case Constants.GLOB_SEARCH:
1475
+ return createLocalGlobSearchTool(config);
1476
+ case Constants.LIST_DIRECTORY:
1477
+ return createLocalListDirectoryTool(config);
1478
+ case Constants.COMPILE_CHECK:
1479
+ return createCompileCheckTool(config);
1480
+ case Constants.BASH_TOOL:
1481
+ return createLocalBashExecutionTool({ config });
1482
+ case Constants.EXECUTE_CODE:
1483
+ return createLocalCodeExecutionTool(config);
1484
+ case Constants.PROGRAMMATIC_TOOL_CALLING:
1485
+ return createLocalProgrammaticToolCallingTool(config);
1486
+ default:
1487
+ return createLocalBashProgrammaticToolCallingTool(config);
1488
+ }
1489
+ };
1490
+ // Select by name before constructing, so omitted tools are never built.
1491
+ const names =
1492
+ config.codingToolNames == null ? undefined : new Set(config.codingToolNames);
1493
+ return LOCAL_CODING_BUNDLE_NAMES.filter(
1494
+ (name) => names == null || names.has(name)
1495
+ ).map(create);
1376
1496
  }
1377
1497
 
1378
1498
  /**
@@ -13,6 +13,7 @@ import {
13
13
  BashExecutionToolSchema,
14
14
  BashToolOutputReferencesGuide,
15
15
  } from '@/tools/BashExecutor';
16
+ import { capHeadTail } from './toolResultCaps';
16
17
  import {
17
18
  CodeExecutionToolName,
18
19
  CodeExecutionToolSchema,
@@ -127,6 +128,25 @@ export function createLocalCodeExecutionTool(
127
128
  );
128
129
  }
129
130
 
131
+ /**
132
+ * Applies `toolResultMaxChars` to stdout and stderr before formatting, so
133
+ * the status lines (`exit_code`, `timed_out`, `killed`) are always kept.
134
+ * stderr gets at most half of the budget.
135
+ */
136
+ function capStreams<T extends { stdout: string; stderr: string }>(
137
+ result: T,
138
+ config: t.LocalExecutionConfig
139
+ ): T {
140
+ const maxChars = config.toolResultMaxChars;
141
+ if (maxChars == null || maxChars <= 0) return result;
142
+ const stderrBudget = Math.min(result.stderr.length, Math.floor(maxChars / 2));
143
+ return {
144
+ ...result,
145
+ stdout: capHeadTail(result.stdout, maxChars - stderrBudget),
146
+ stderr: capHeadTail(result.stderr, Math.max(stderrBudget, 1)),
147
+ };
148
+ }
149
+
130
150
  export function createLocalBashExecutionTool(options?: {
131
151
  config?: t.LocalExecutionConfig;
132
152
  enableToolOutputReferences?: boolean;
@@ -147,7 +167,7 @@ export function createLocalBashExecutionTool(options?: {
147
167
  ? await executeLocalBashWithArgs(input.command, input.args, config)
148
168
  : await executeLocalBash(input.command, config);
149
169
  return [
150
- formatLocalOutput(result, cwd),
170
+ formatLocalOutput(capStreams(result, config), cwd),
151
171
  {
152
172
  session_id: getLocalSessionId(config),
153
173
  files: [],
@@ -81,7 +81,10 @@ export function isProgrammaticRunnerAutoBound(
81
81
  getCloudflareConfig(config)
82
82
  ).has(name);
83
83
  }
84
- return shouldUseLocalExecution(config);
84
+ return (
85
+ shouldUseLocalExecution(config) &&
86
+ (getSelectedLocalCodingToolNames(config?.local ?? {})?.has(name) ?? true)
87
+ );
85
88
  }
86
89
 
87
90
  /** Mirrors whether resolver policy creates or replaces this runner locally. */
@@ -129,6 +132,19 @@ function getSelectedCloudflareCodingToolNames(
129
132
  );
130
133
  }
131
134
 
135
+ /** The local coding tools selected by `local.codingToolNames`, or `undefined` for the whole suite. */
136
+ function getSelectedLocalCodingToolNames(
137
+ config: t.LocalExecutionConfig
138
+ ): Set<string> | undefined {
139
+ if (config.codingToolNames == null) {
140
+ return undefined;
141
+ }
142
+ const requestedNames = new Set(config.codingToolNames);
143
+ return new Set(
144
+ LOCAL_CODING_BUNDLE_NAMES.filter((name) => requestedNames.has(name))
145
+ );
146
+ }
147
+
132
148
  function filterCloudflareCodingToolAllowlist(
133
149
  tools: t.GraphTools | undefined,
134
150
  selectedNames: Set<string>
@@ -137,15 +153,59 @@ function filterCloudflareCodingToolAllowlist(
137
153
  if (existingTools.length === 0) {
138
154
  return tools;
139
155
  }
140
- return existingTools.filter((existingTool) => {
141
- if (!('name' in existingTool) || typeof existingTool.name !== 'string') {
142
- return true;
156
+ const keeps = (name: string | undefined): boolean =>
157
+ name == null ||
158
+ !LOCAL_CODING_BUNDLE_NAMES.includes(name) ||
159
+ selectedNames.has(name);
160
+ const filtered: unknown[] = [];
161
+ for (const existingTool of existingTools as unknown[]) {
162
+ const declarations = functionDeclarationsOf(existingTool);
163
+ if (declarations == null) {
164
+ if (keeps(bindableToolName(existingTool))) filtered.push(existingTool);
165
+ continue;
143
166
  }
144
- return (
145
- !LOCAL_CODING_BUNDLE_NAMES.includes(existingTool.name) ||
146
- selectedNames.has(existingTool.name)
167
+ // Google tool objects group several functions; keep the allowed ones.
168
+ const kept = declarations.filter((declaration) =>
169
+ keeps(bindableToolName(declaration))
147
170
  );
148
- });
171
+ if (kept.length === declarations.length) {
172
+ filtered.push(existingTool);
173
+ } else if (kept.length > 0) {
174
+ filtered.push({
175
+ ...(existingTool as object),
176
+ functionDeclarations: kept,
177
+ });
178
+ }
179
+ }
180
+ return filtered as t.GraphTools;
181
+ }
182
+
183
+ /**
184
+ * Name of a bindable tool in any supported shape: `{ name }`, OpenAI's
185
+ * `{ function: { name } }` or Bedrock's `{ toolSpec: { name } }`.
186
+ */
187
+ function bindableToolName(tool: unknown): string | undefined {
188
+ if (tool == null || typeof tool !== 'object') return undefined;
189
+ const {
190
+ name,
191
+ function: fn,
192
+ toolSpec,
193
+ } = tool as {
194
+ name?: unknown;
195
+ function?: { name?: unknown };
196
+ toolSpec?: { name?: unknown };
197
+ };
198
+ if (typeof name === 'string') return name;
199
+ if (typeof fn?.name === 'string') return fn.name;
200
+ return typeof toolSpec?.name === 'string' ? toolSpec.name : undefined;
201
+ }
202
+
203
+ /** The `functionDeclarations` of a Google tool object, if it is one. */
204
+ function functionDeclarationsOf(tool: unknown): unknown[] | undefined {
205
+ if (tool == null || typeof tool !== 'object') return undefined;
206
+ const declarations = (tool as { functionDeclarations?: unknown })
207
+ .functionDeclarations;
208
+ return Array.isArray(declarations) ? declarations : undefined;
149
209
  }
150
210
 
151
211
  function pruneCloudflareCodingToolAllowlist(
@@ -291,8 +351,14 @@ export function resolveLocalToolsForBinding(args: {
291
351
 
292
352
  const localConfig = args.toolExecution?.local ?? {};
293
353
  if (shouldIncludeCodingTools(args.toolExecution)) {
354
+ const selectedNames = getSelectedLocalCodingToolNames(localConfig);
294
355
  return filterToolsForDirectCaller(
295
- mergeToolsByName(args.tools, createLocalCodingTools(localConfig)),
356
+ mergeToolsByName(
357
+ selectedNames == null
358
+ ? args.tools
359
+ : filterCloudflareCodingToolAllowlist(args.tools, selectedNames),
360
+ createLocalCodingTools(localConfig)
361
+ ),
296
362
  args.toolRegistry,
297
363
  args.discoveredToolNames
298
364
  );
@@ -334,6 +400,10 @@ export function resolveLocalToolRegistry(args: {
334
400
  getCloudflareConfig(args.toolExecution)
335
401
  )
336
402
  : undefined;
403
+ const localSelected =
404
+ selectedNames == null
405
+ ? getSelectedLocalCodingToolNames(args.toolExecution?.local ?? {})
406
+ : undefined;
337
407
 
338
408
  if (selectedNames != null) {
339
409
  const callableInsideCloudflare = new Set(selectedNames);
@@ -355,8 +425,15 @@ export function resolveLocalToolRegistry(args: {
355
425
  }
356
426
  }
357
427
 
428
+ if (localSelected != null) {
429
+ for (const name of LOCAL_CODING_BUNDLE_NAMES) {
430
+ if (!localSelected.has(name)) registry.delete(name);
431
+ }
432
+ }
433
+
358
434
  for (const definition of createLocalCodingToolDefinitions()) {
359
- if (selectedNames != null && !selectedNames.has(definition.name)) {
435
+ const keep = selectedNames ?? localSelected;
436
+ if (keep != null && !keep.has(definition.name)) {
360
437
  registry.delete(definition.name);
361
438
  continue;
362
439
  }
@@ -371,6 +448,29 @@ export function resolveLocalToolRegistry(args: {
371
448
  return registry;
372
449
  }
373
450
 
451
+ /**
452
+ * Drops host-bound coding tools outside `local.codingToolNames`, so prompt
453
+ * projections (instruction tokens, runner guidance) see the same tools that
454
+ * are finally bound. Returns `tools` unchanged when no local allowlist applies.
455
+ */
456
+ export function filterToolsByLocalAllowlist(
457
+ tools: t.GraphTools | undefined,
458
+ toolExecution?: t.ToolExecutionConfig
459
+ ): t.GraphTools | undefined {
460
+ if (
461
+ !shouldUseLocalExecution(toolExecution) ||
462
+ !shouldIncludeCodingTools(toolExecution)
463
+ ) {
464
+ return tools;
465
+ }
466
+ const selectedNames = getSelectedLocalCodingToolNames(
467
+ toolExecution?.local ?? {}
468
+ );
469
+ return selectedNames == null
470
+ ? tools
471
+ : filterCloudflareCodingToolAllowlist(tools, selectedNames);
472
+ }
473
+
374
474
  /** Names that this execution config creates or replaces in the local tool map. */
375
475
  export function resolveLocalImplementationNames(
376
476
  toolNames: Iterable<string>,
@@ -385,7 +485,8 @@ export function resolveLocalImplementationNames(
385
485
  if (shouldIncludeCodingTools(toolExecution)) {
386
486
  return shouldUseCloudflareSandboxExecution(toolExecution)
387
487
  ? getSelectedCloudflareCodingToolNames(getCloudflareConfig(toolExecution))
388
- : new Set(LOCAL_CODING_BUNDLE_NAMES);
488
+ : (getSelectedLocalCodingToolNames(toolExecution?.local ?? {}) ??
489
+ new Set(LOCAL_CODING_BUNDLE_NAMES));
389
490
  }
390
491
  const existingNames = new Set(toolNames);
391
492
  return new Set(
@@ -493,6 +594,10 @@ export function resolveLocalExecutionTools(args: {
493
594
  const localConfig = args.toolExecution?.local ?? {};
494
595
 
495
596
  if (shouldIncludeCodingTools(args.toolExecution)) {
597
+ const selectedNames = getSelectedLocalCodingToolNames(localConfig);
598
+ if (selectedNames != null) {
599
+ pruneCloudflareCodingToolAllowlist(toolMap, selectedNames);
600
+ }
496
601
  // Use the bundle factory when fileCheckpointing is on so we can
497
602
  // surface the checkpointer back to the caller — without this, the
498
603
  // execution-path tools each captured into a checkpointer that was
@@ -0,0 +1,60 @@
1
+ /** Keeps the last `maxChars` characters, starting at a line boundary when one is near. */
2
+ export function tailTruncate(text: string, maxChars: number): string {
3
+ if (text.length <= maxChars) {
4
+ return text;
5
+ }
6
+ const tail = text.slice(text.length - maxChars);
7
+ const newline = tail.indexOf('\n');
8
+ return newline >= 0 && newline < 200 && newline < tail.length - 1
9
+ ? tail.slice(newline + 1)
10
+ : tail;
11
+ }
12
+
13
+ /** Longest grep match line kept when results are capped. */
14
+ export const CAPPED_GREP_LINE_CHARS = 300;
15
+
16
+ /**
17
+ * Caps line-oriented results (search matches): each line is cut to
18
+ * `CAPPED_GREP_LINE_CHARS`, and lines stop at `maxChars` with a note naming
19
+ * how many were left out.
20
+ */
21
+ export function capLines(
22
+ text: string | readonly string[],
23
+ maxChars: number,
24
+ note: (omitted: number) => string = (omitted) =>
25
+ `${omitted} more matching lines not shown; narrow the pattern or path`
26
+ ): string {
27
+ // An array is capped line by line without joining it first.
28
+ const lines = typeof text === 'string' ? text.split('\n') : text;
29
+ const lineChars = Math.max(1, Math.min(CAPPED_GREP_LINE_CHARS, maxChars));
30
+ const kept: string[] = [];
31
+ let used = 0;
32
+ for (const raw of lines) {
33
+ const line =
34
+ raw.length > lineChars
35
+ ? `${raw.slice(0, lineChars)} [line truncated]`
36
+ : raw;
37
+ if (used + line.length + 1 > maxChars && kept.length > 0) break;
38
+ kept.push(line);
39
+ used += line.length + 1;
40
+ }
41
+ const omitted = lines.length - kept.length;
42
+ return omitted > 0
43
+ ? `${kept.join('\n')}\n[${note(omitted)}]`
44
+ : kept.join('\n');
45
+ }
46
+
47
+ /**
48
+ * Caps free-form output (shell results): keeps the first 20% and the last 80%
49
+ * of `maxChars`, where errors and test summaries are, and says how much was
50
+ * left out so the model can rerun a narrower command.
51
+ */
52
+ export function capHeadTail(text: string, maxChars: number): string {
53
+ if (text.length <= maxChars) {
54
+ return text;
55
+ }
56
+ const head = text.slice(0, Math.floor(maxChars * 0.2));
57
+ const tail = tailTruncate(text, Math.floor(maxChars * 0.8));
58
+ const omitted = text.length - head.length - tail.length;
59
+ return `${head}\n[... ${omitted} characters omitted; rerun with narrower output to see them ...]\n${tail}`;
60
+ }