@orion-agents/orion-code 0.4.4 → 0.4.5

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 (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/dist/core/tool-artifacts.js +17 -4
  5. package/dist/framework/query.js +150 -16
  6. package/dist/framework/tool-state.d.ts +4 -0
  7. package/dist/harness/context-harness.d.ts +6 -2
  8. package/dist/harness/context-harness.js +221 -47
  9. package/dist/harness/contract.js +3 -1
  10. package/dist/harness/drift-guard.js +67 -17
  11. package/dist/harness/goal-verification.d.ts +11 -0
  12. package/dist/harness/goal-verification.js +62 -0
  13. package/dist/harness/ledger.js +16 -3
  14. package/dist/harness/state.js +3 -0
  15. package/dist/harness/task-checklist.d.ts +11 -1
  16. package/dist/harness/task-checklist.js +48 -4
  17. package/dist/harness/types.d.ts +10 -0
  18. package/dist/harness/verification.d.ts +11 -1
  19. package/dist/harness/verification.js +47 -2
  20. package/dist/runtime/agent-loop.js +4 -1
  21. package/dist/runtime/batch-read-service.js +21 -4
  22. package/dist/runtime/goal-runtime-coordinator.js +1 -0
  23. package/dist/runtime/product-orion-runtime.js +24 -2
  24. package/dist/runtime/task-context-recovery.js +21 -5
  25. package/dist/runtime/task-context-service.d.ts +3 -1
  26. package/dist/runtime/task-context-service.js +3 -0
  27. package/dist/runtime/workspace-verification.d.ts +2 -2
  28. package/dist/runtime/workspace-verification.js +24 -9
  29. package/dist/services/chat-completion-sse.d.ts +9 -0
  30. package/dist/services/chat-completion-sse.js +50 -0
  31. package/dist/services/compact/summary-generator.d.ts +1 -1
  32. package/dist/services/compact/summary-generator.js +12 -0
  33. package/dist/services/llm.d.ts +1 -1
  34. package/dist/services/llm.js +165 -292
  35. package/dist/services/provider-diagnostics.d.ts +1 -1
  36. package/dist/services/provider-diagnostics.js +7 -2
  37. package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
  38. package/dist/services/provider-resilience/error-classifier.js +14 -0
  39. package/dist/tools/core/common.d.ts +0 -11
  40. package/dist/tools/core/common.js +0 -18
  41. package/dist/tools/core/edit-file.js +57 -86
  42. package/dist/tools/core/exec-command.js +61 -80
  43. package/dist/tools/core/grep.js +84 -24
  44. package/dist/tools/core/read-file.js +3 -2
  45. package/dist/tools/todo.d.ts +2 -2
  46. package/dist/tools/todo.js +13 -10
  47. package/dist/utils/utf8.d.ts +6 -0
  48. package/dist/utils/utf8.js +14 -0
  49. package/docs/cli-guide.md +7 -2
  50. package/npm-shrinkwrap.json +2 -2
  51. package/package.json +1 -1
@@ -11,6 +11,9 @@ export interface ClassificationResult {
11
11
  retryAfterMs?: number;
12
12
  status?: number;
13
13
  }
14
+ export declare class ProviderStreamIncompleteError extends Error {
15
+ constructor();
16
+ }
14
17
  export declare function classifyProviderError(error: unknown, semanticDeltaSeen: boolean): ClassificationResult;
15
18
  export declare function extractRetryAfterMs(error: unknown): number | undefined;
16
19
  //# sourceMappingURL=error-classifier.d.ts.map
@@ -6,8 +6,16 @@
6
6
  * and RetryDisposition. Typed signals take priority over string matching.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ProviderStreamIncompleteError = void 0;
9
10
  exports.classifyProviderError = classifyProviderError;
10
11
  exports.extractRetryAfterMs = extractRetryAfterMs;
12
+ class ProviderStreamIncompleteError extends Error {
13
+ constructor() {
14
+ super('The provider stream ended with an incomplete response.');
15
+ this.name = 'ProviderStreamIncompleteError';
16
+ }
17
+ }
18
+ exports.ProviderStreamIncompleteError = ProviderStreamIncompleteError;
11
19
  function classifyProviderError(error, semanticDeltaSeen) {
12
20
  // Local budget/policy preflight failures happen before any provider request.
13
21
  // Keep them fail-fast so the caller can preserve the typed control signal.
@@ -18,6 +26,12 @@ function classifyProviderError(error, semanticDeltaSeen) {
18
26
  if (isAbortError(error)) {
19
27
  return { kind: 'aborted', disposition: 'fail_fast' };
20
28
  }
29
+ if (error instanceof ProviderStreamIncompleteError) {
30
+ return {
31
+ kind: 'stream_interrupted',
32
+ disposition: semanticDeltaSeen ? 'recover_stream' : 'retry_precommit',
33
+ };
34
+ }
21
35
  // Extract status and headers
22
36
  const status = extractStatus(error);
23
37
  const retryAfterMs = extractRetryAfterMs(error);
@@ -20,15 +20,4 @@ export declare function safePath(input: string, cwd?: string): string;
20
20
  */
21
21
  export declare function isWithinWorkspace(resolved: string, cwd: string): boolean;
22
22
  export declare function isExecCwdWithinWorkspace(workdir: string, projectRoot: string): boolean;
23
- /**
24
- * Truncate text to at most maxBytes UTF-8 bytes, cutting on a character
25
- * boundary (never inside a multi-byte sequence or surrogate pair). Returns the
26
- * truncated text and the byte length it was cut at. String.slice counts UTF-16
27
- * code units, not bytes, so it is wrong for enforcing a byte budget on CJK or
28
- * emoji content and can split a surrogate pair.
29
- */
30
- export declare function truncateToBytes(text: string, maxBytes: number): {
31
- text: string;
32
- bytes: number;
33
- };
34
23
  //# sourceMappingURL=common.d.ts.map
@@ -9,7 +9,6 @@ exports.safeReadFileSync = safeReadFileSync;
9
9
  exports.safePath = safePath;
10
10
  exports.isWithinWorkspace = isWithinWorkspace;
11
11
  exports.isExecCwdWithinWorkspace = isExecCwdWithinWorkspace;
12
- exports.truncateToBytes = truncateToBytes;
13
12
  const fs_1 = require("fs");
14
13
  const path_1 = require("path");
15
14
  const workspace_containment_1 = require("../../services/workspace-containment");
@@ -144,21 +143,4 @@ function isExecCwdWithinWorkspace(workdir, projectRoot) {
144
143
  // take the shared symlink-aware boundary check.
145
144
  return (0, fs_1.existsSync)(root) ? (0, workspace_containment_1.isWorkspacePath)(root, workdir) : true;
146
145
  }
147
- /**
148
- * Truncate text to at most maxBytes UTF-8 bytes, cutting on a character
149
- * boundary (never inside a multi-byte sequence or surrogate pair). Returns the
150
- * truncated text and the byte length it was cut at. String.slice counts UTF-16
151
- * code units, not bytes, so it is wrong for enforcing a byte budget on CJK or
152
- * emoji content and can split a surrogate pair.
153
- */
154
- function truncateToBytes(text, maxBytes) {
155
- const buf = Buffer.from(text, 'utf-8');
156
- if (buf.length <= maxBytes)
157
- return { text, bytes: buf.length };
158
- let cut = maxBytes;
159
- // Walk back past UTF-8 continuation bytes (0x80-0xBF) to a lead-byte boundary.
160
- while (cut > 0 && (buf[cut] & 0xc0) === 0x80)
161
- cut--;
162
- return { text: buf.subarray(0, cut).toString('utf-8'), bytes: cut };
163
- }
164
146
  //# sourceMappingURL=common.js.map
@@ -60,58 +60,50 @@ function findAllMatchIndexes(content, needle, limit = 20) {
60
60
  function previewLine(text) {
61
61
  return text.replace(/\s+/g, ' ').trim().slice(0, 120);
62
62
  }
63
- function buildEditCandidates(params) {
64
- const cursorByMatch = new Map();
65
- return params.matches.slice(0, 20).map((match, index) => {
66
- const cursor = cursorByMatch.get(match) ?? 0;
67
- const matchIndex = params.content.indexOf(match, cursor);
68
- cursorByMatch.set(match, matchIndex >= 0 ? matchIndex + Math.max(match.length, 1) : cursor);
69
- const lineNum = matchIndex >= 0 ? lineNumberForIndex(params.content, matchIndex) : 0;
70
- // Get context lines (3 before, 3 after)
71
- const allLines = params.content.split('\n');
72
- const contextBefore = allLines.slice(Math.max(0, lineNum - 4), lineNum).join('\n');
73
- const contextAfter = allLines.slice(lineNum + 1, lineNum + 4).join('\n');
63
+ function buildEditCandidates(content, matches, count) {
64
+ const allLines = content.split(/\r?\n/u);
65
+ return matches.slice(0, 20).map((match, index) => {
66
+ const line = lineNumberForIndex(content, match.index);
67
+ const endLine = lineNumberForIndex(content, match.index + match.text.length - 1);
74
68
  return {
75
69
  index,
76
- line: lineNum,
77
- match,
78
- contextBefore,
79
- contextAfter,
80
- isReplaceAll: (params.count ?? 1) > 1,
70
+ line,
71
+ match: match.text,
72
+ contextBefore: allLines.slice(Math.max(0, line - 4), line - 1).join('\n'),
73
+ contextAfter: allLines.slice(endLine, endLine + 3).join('\n'),
74
+ isReplaceAll: count > 1,
81
75
  };
82
76
  });
83
77
  }
84
- function formatEditPreview(params) {
85
- const cursorByMatch = new Map();
86
- const lines = [
87
- `Preview: ${params.kind === 'fuzzy' ? `Fuzzy ${params.strategy ?? 'match'}` : 'Exact match'} candidates (${params.matches.length})`,
88
- ];
89
- params.matches.slice(0, 20).forEach((match, index) => {
90
- const cursor = cursorByMatch.get(match) ?? 0;
91
- const matchIndex = params.content.indexOf(match, cursor);
92
- cursorByMatch.set(match, matchIndex >= 0 ? matchIndex + Math.max(match.length, 1) : cursor);
93
- const lineNum = matchIndex >= 0 ? lineNumberForIndex(params.content, matchIndex) : '?';
94
- lines.push(`${index + 1}. line ${lineNum}: "${previewLine(match)}"`);
95
- });
96
- if (params.matches.length > 20) {
97
- lines.push(`... ${params.matches.length - 20} more candidates omitted`);
78
+ function editPreview(params) {
79
+ const candidates = buildEditCandidates(params.content, params.matches, params.count);
80
+ const kind = params.strategy ? 'Fuzzy ' + params.strategy : 'Exact match';
81
+ const lines = [`Preview: ${kind} candidates (${params.count})`];
82
+ for (const candidate of candidates) {
83
+ lines.push(`${candidate.index + 1}. line ${candidate.line}: "${previewLine(candidate.match)}"`);
84
+ }
85
+ if (params.count > candidates.length) {
86
+ lines.push(`... ${params.count - candidates.length} more candidates omitted`);
98
87
  }
99
88
  lines.push(`Would replace with: "${previewLine(params.newString)}"`);
100
- return lines.join('\n');
89
+ return { success: true, output: lines.join('\n'), metadata: { candidates } };
101
90
  }
102
91
  /**
103
92
  * Attempt to find old_string in content using fuzzy matching strategies.
104
- * Returns null if no match found, or the matched strings.
93
+ * Keep the selected offsets so identical text elsewhere cannot change the target.
105
94
  */
106
95
  function fuzzyMatch(content, oldString) {
96
+ const trimmed = oldString.trim();
97
+ if (!trimmed)
98
+ return null;
107
99
  // Strategy 1: Line-by-line matching (allow different indentation)
108
- const oldLines = oldString
109
- .split('\n')
110
- .map(l => l.trim())
111
- .filter(Boolean);
100
+ const oldLines = trimmed.split('\n').map(line => line.trim());
112
101
  const contentLines = content.split('\n');
113
102
  const lineMatches = [];
103
+ let offset = 0;
114
104
  for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
105
+ const index = offset;
106
+ offset += contentLines[i].length + 1;
115
107
  let allMatch = true;
116
108
  for (let j = 0; j < oldLines.length; j++) {
117
109
  if (contentLines[i + j].trim() !== oldLines[j]) {
@@ -120,8 +112,11 @@ function fuzzyMatch(content, oldString) {
120
112
  }
121
113
  }
122
114
  if (allMatch) {
123
- const matchedStr = contentLines.slice(i, i + oldLines.length).join('\n');
124
- lineMatches.push(matchedStr);
115
+ const end = i + oldLines.length;
116
+ const raw = contentLines.slice(i, end).join('\n');
117
+ // Leave the delimiter after the selected lines intact on CRLF files.
118
+ const text = end < contentLines.length && raw.endsWith('\r') ? raw.slice(0, -1) : raw;
119
+ lineMatches.push({ index, text });
125
120
  }
126
121
  }
127
122
  if (lineMatches.length > 0) {
@@ -129,16 +124,14 @@ function fuzzyMatch(content, oldString) {
129
124
  }
130
125
  // Strategy 2: Whitespace-tolerant token match. This preserves the actual
131
126
  // matched span without consuming unrelated leading/trailing blank lines.
132
- const tokens = oldString.trim().split(/\s+/).filter(Boolean);
133
- if (tokens.length === 0)
134
- return null;
127
+ const tokens = trimmed.split(/\s+/u);
135
128
  const pattern = tokens.map(escapeRegExp).join('\\s+');
136
129
  const regex = new RegExp(pattern, 'g');
137
130
  const wsMatches = [];
138
131
  let match;
139
132
  while ((match = regex.exec(content)) !== null) {
140
133
  if (match[0]) {
141
- wsMatches.push(match[0]);
134
+ wsMatches.push({ index: match.index, text: match[0] });
142
135
  }
143
136
  if (wsMatches.length > 5)
144
137
  break; // Safety limit
@@ -187,26 +180,11 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
187
180
  // Check if old_string exists exactly
188
181
  const count = (content.match(new RegExp(escapeRegExp(old_string), 'g')) || []).length;
189
182
  if (count > 0 && preview) {
190
- const matchIndexes = findAllMatchIndexes(content, old_string);
191
- const matches = matchIndexes.map(() => old_string);
192
- return {
193
- success: true,
194
- output: formatEditPreview({
195
- kind: 'exact',
196
- content,
197
- matches,
198
- newString: new_string,
199
- }),
200
- metadata: {
201
- candidates: buildEditCandidates({
202
- kind: 'exact',
203
- content,
204
- matches,
205
- newString: new_string,
206
- count,
207
- }),
208
- },
209
- };
183
+ const matches = findAllMatchIndexes(content, old_string).map(index => ({
184
+ index,
185
+ text: old_string,
186
+ }));
187
+ return editPreview({ content, matches, count, newString: new_string });
210
188
  }
211
189
  if (count === 0) {
212
190
  if (!fuzzy_match) {
@@ -226,25 +204,13 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
226
204
  };
227
205
  }
228
206
  if (preview) {
229
- return {
230
- success: true,
231
- output: formatEditPreview({
232
- kind: 'fuzzy',
233
- content,
234
- matches: fuzzyResult.matches,
235
- newString: new_string,
236
- strategy: fuzzyResult.strategy,
237
- }),
238
- metadata: {
239
- candidates: buildEditCandidates({
240
- kind: 'fuzzy',
241
- content,
242
- matches: fuzzyResult.matches,
243
- newString: new_string,
244
- strategy: fuzzyResult.strategy,
245
- }),
246
- },
247
- };
207
+ return editPreview({
208
+ content,
209
+ matches: fuzzyResult.matches,
210
+ count: fuzzyResult.matches.length,
211
+ newString: new_string,
212
+ strategy: fuzzyResult.strategy,
213
+ });
248
214
  }
249
215
  if (fuzzyResult.matches.length > 1) {
250
216
  return {
@@ -252,19 +218,24 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
252
218
  output: '',
253
219
  error: `Fuzzy match found ${fuzzyResult.matches.length} candidates. Provide a more specific string. First 3 candidates:\n${fuzzyResult.matches
254
220
  .slice(0, 3)
255
- .map((m, i) => ` ${i + 1}: "${m.slice(0, 80)}..."`)
221
+ .map((match, i) => ` ${i + 1}: "${match.text.slice(0, 80)}..."`)
256
222
  .join('\n')}`,
257
223
  };
258
224
  }
259
225
  // Use the single fuzzy match only.
260
- const match = fuzzyResult.matches[0];
261
- const idx = content.indexOf(match);
262
- const newContent = content.slice(0, idx) + new_string + content.slice(idx + match.length);
226
+ const { index, text } = fuzzyResult.matches[0];
227
+ const end = index + text.length;
228
+ const usesCrLf = text.includes('\r\n') ||
229
+ (fuzzyResult.strategy === 'line' &&
230
+ (content.startsWith('\r\n', end) ||
231
+ (end === content.length && index >= 2 && content.startsWith('\r\n', index - 2))));
232
+ const replacement = usesCrLf ? new_string.replace(/\r?\n/gu, '\r\n') : new_string;
233
+ const newContent = content.slice(0, index) + replacement + content.slice(end);
263
234
  if (newContent !== content)
264
235
  (0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
265
236
  return {
266
237
  success: true,
267
- output: `Fuzzy edited ${normalizedPath} (matched by ${fuzzyResult.strategy}, "${match.slice(0, 50)}...")`,
238
+ output: `Fuzzy edited ${normalizedPath} (matched by ${fuzzyResult.strategy}, "${text.slice(0, 50)}...")`,
268
239
  ...(newContent !== content ? { metadata: { workspaceWritePath: normalizedPath } } : {}),
269
240
  };
270
241
  }
@@ -6,6 +6,7 @@ const fs_1 = require("fs");
6
6
  const path_1 = require("path");
7
7
  const tool_1 = require("../../framework/tool");
8
8
  const descriptors_1 = require("../../runtime/core-tools/descriptors");
9
+ const utf8_1 = require("../../utils/utf8");
9
10
  const bash_security_1 = require("../bash_security");
10
11
  const sandbox_1 = require("../sandbox");
11
12
  const common_1 = require("./common");
@@ -105,6 +106,47 @@ exports.coreTool = (0, tool_1.buildTool)({
105
106
  return `šŸ”§ exec (${bytes}B output)${commandSummary}`;
106
107
  },
107
108
  });
109
+ function collectOutput(stream, maxBytes) {
110
+ const output = { text: '', bytes: 0, truncated: false };
111
+ // Let the stream resolve UTF-8 characters split across pipe buffers.
112
+ stream.setEncoding('utf8');
113
+ stream.on('data', (chunk) => {
114
+ if (output.truncated)
115
+ return;
116
+ const bounded = (0, utf8_1.truncateToBytes)(chunk, maxBytes - output.bytes);
117
+ output.text += bounded.text;
118
+ output.bytes += bounded.bytes;
119
+ output.truncated = bounded.text.length < chunk.length;
120
+ });
121
+ return output;
122
+ }
123
+ function formatOutput(output, maxBytes, name) {
124
+ const content = output.text.trim();
125
+ if (!output.truncated && Buffer.byteLength(content, 'utf8') <= maxBytes)
126
+ return content;
127
+ const marker = '\n[... ' + name + ' truncated]';
128
+ const markerBytes = Buffer.byteLength(marker, 'utf8');
129
+ if (maxBytes <= markerBytes)
130
+ return (0, utf8_1.truncateToBytes)(marker.trimStart(), maxBytes).text;
131
+ return (0, utf8_1.truncateToBytes)(content, maxBytes - markerBytes).text + marker;
132
+ }
133
+ function failedOutput(stdout, stderr, maxBytes) {
134
+ if (!stderr.truncated && !stderr.text.trim())
135
+ return formatOutput(stdout, maxBytes, 'stdout');
136
+ if (!stdout.truncated && !stdout.text.trim())
137
+ return formatOutput(stderr, maxBytes, 'stderr');
138
+ // Reserve space for both streams. Put stderr first so the diagnostic
139
+ // survives even when the model-visible preview is smaller than this result.
140
+ const stderrHeader = '[stderr]\n';
141
+ const stdoutHeader = '\n[stdout]\n';
142
+ const room = maxBytes - Buffer.byteLength(stderrHeader + stdoutHeader, 'utf8');
143
+ const stdoutLimit = room - Math.min(stderr.bytes, Math.floor(room / 2));
144
+ const stderrLimit = room - Math.min(stdout.bytes, stdoutLimit);
145
+ return (stderrHeader +
146
+ formatOutput(stderr, stderrLimit, 'stderr') +
147
+ stdoutHeader +
148
+ formatOutput(stdout, stdoutLimit, 'stdout'));
149
+ }
108
150
  // Issue #32 #3.2: execCommand_ ę”ÆęŒ abortSignal
109
151
  function resolveExecCommandPaths(cwd, baseCwd) {
110
152
  const projectRoot = (0, path_1.resolve)(baseCwd ?? process.cwd());
@@ -179,13 +221,8 @@ async function execCommand_(command, cwd, timeout, maxOutput, abortSignal, baseC
179
221
  // (cat, sort, grep, `python3 -`, ...) block waiting for EOF until the timeout.
180
222
  // Close it immediately so the child receives EOF and can proceed.
181
223
  child.stdin?.end();
182
- let stdoutData = '';
183
- let stderrData = '';
184
- let stdoutTruncated = false;
185
- let stderrTruncated = false;
186
- // Issue #32 äæ®å¤ļ¼šä½æē”Øē‹¬ē«‹č®”ę•°å™Ø
187
- let stdoutBytes = 0;
188
- let stderrBytes = 0;
224
+ const stdout = collectOutput(child.stdout, maxBytes);
225
+ const stderr = collectOutput(child.stderr, maxBytes);
189
226
  let interrupted = null;
190
227
  // Issue #32 #3.2: AbortSignal 处理
191
228
  // Declared uninitialized on purpose: `finish()` below closes over it before the
@@ -256,84 +293,28 @@ async function execCommand_(command, cwd, timeout, maxOutput, abortSignal, baseC
256
293
  terminateChild();
257
294
  }
258
295
  }, timeoutMs);
259
- // Stream stdout with truncation
260
- child.stdout.on('data', (data) => {
261
- if (!stdoutTruncated) {
262
- const chunk = data.toString();
263
- // Issue #30: count UTF-8 bytes, not UTF-16 code units, so CJK/emoji
264
- // output is bounded by `maxBytes` (a UTF-16 count could exceed it ~2x).
265
- const chunkBytes = Buffer.byteLength(chunk, 'utf8');
266
- if (stdoutBytes + chunkBytes > maxBytes) {
267
- stdoutTruncated = true;
268
- const room = Math.max(0, maxBytes - stdoutBytes);
269
- // Byte-accurate truncation that respects multi-byte character boundaries.
270
- stdoutData += (0, common_1.truncateToBytes)(chunk, room).text;
271
- stdoutBytes = maxBytes;
272
- }
273
- else {
274
- stdoutData += chunk;
275
- stdoutBytes += chunkBytes;
276
- }
277
- }
278
- });
279
- // Stream stderr with truncation (Issue #32 äæ®å¤ļ¼šä½æē”Øē‹¬ē«‹č®”ę•°å™Ø)
280
- child.stderr.on('data', (data) => {
281
- if (!stderrTruncated) {
282
- const chunk = data.toString();
283
- // Issue #30: count UTF-8 bytes, not UTF-16 code units.
284
- const chunkBytes = Buffer.byteLength(chunk, 'utf8');
285
- if (stderrBytes + chunkBytes > maxBytes) {
286
- stderrTruncated = true;
287
- const room = Math.max(0, maxBytes - stderrBytes);
288
- stderrData += (0, common_1.truncateToBytes)(chunk, room).text;
289
- stderrBytes = maxBytes;
290
- }
291
- else {
292
- stderrData += chunk;
293
- stderrBytes += chunkBytes;
294
- }
295
- }
296
- });
297
- child.on('close', code => {
298
- if (interrupted === 'aborted') {
296
+ child.on('close', (code, signal) => {
297
+ if (interrupted || code !== 0) {
298
+ const error = interrupted === 'aborted'
299
+ ? 'Command aborted by user'
300
+ : interrupted === 'timeout'
301
+ ? 'Command timed out after ' + timeoutMs + 'ms'
302
+ : signal
303
+ ? 'Command terminated by signal ' + signal
304
+ : 'Command exited with code ' + code;
299
305
  finish({
300
306
  success: false,
301
- output: (0, common_1.truncateToBytes)(stdoutData, maxBytes).text,
302
- error: 'Command aborted by user',
307
+ output: failedOutput(stdout, stderr, maxBytes),
308
+ error,
309
+ metadata: !interrupted && code !== null ? { exitCode: code } : undefined,
303
310
  });
304
311
  return;
305
312
  }
306
- if (interrupted === 'timeout') {
307
- finish({
308
- success: false,
309
- output: (0, common_1.truncateToBytes)(stdoutData, maxBytes).text,
310
- error: `Command timed out after ${timeoutMs}ms`,
311
- });
312
- return;
313
- }
314
- const output = stdoutData.trim();
315
- const errOutput = stderrData.trim();
316
- // Add truncation notice if output was truncated
317
- let finalOutput = output;
318
- if (stdoutTruncated) {
319
- finalOutput += '\n\n[... output truncated, exceeded 50KB limit]';
320
- }
321
- if (code !== 0) {
322
- finish({
323
- success: false,
324
- output: finalOutput || errOutput,
325
- error: `Command exited with code ${code}`,
326
- });
327
- }
328
- else {
329
- finish({
330
- success: true,
331
- output: finalOutput || '(no output)',
332
- error: stderrTruncated
333
- ? errOutput + '\n\n[... stderr truncated]'
334
- : errOutput || undefined,
335
- });
336
- }
313
+ finish({
314
+ success: true,
315
+ output: formatOutput(stdout, maxBytes, 'stdout') || '(no output)',
316
+ error: formatOutput(stderr, maxBytes, 'stderr') || undefined,
317
+ });
337
318
  });
338
319
  child.on('error', err => {
339
320
  finish({
@@ -10,11 +10,14 @@ const descriptors_1 = require("../../runtime/core-tools/descriptors");
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const common_1 = require("./common");
12
12
  const descriptor = (0, descriptors_1.coreToolDescriptorV1)('grep');
13
+ const MAX_MATCHES = 100;
14
+ const MAX_CONTEXT_ROWS = 400;
13
15
  exports.coreTool = (0, tool_1.buildTool)({
14
16
  name: descriptor.name,
15
17
  aliases: [...descriptor.aliases],
16
18
  description: descriptor.description,
17
19
  parameters: structuredClone(descriptor.parameters),
20
+ validateInput: args => (0, common_1.validateOptionalSafeInteger)(args, 'grep', 'context', 0, Number.MAX_SAFE_INTEGER),
18
21
  execute: async (args, context) => {
19
22
  // Ensure pattern is a valid string
20
23
  const pattern = args.pattern;
@@ -30,10 +33,34 @@ exports.coreTool = (0, tool_1.buildTool)({
30
33
  const pattern = args.pattern;
31
34
  if (!result.success)
32
35
  return `šŸ”Ž grep /${pattern}/ → error`;
33
- const count = result.output.split('\n').filter(l => l && !l.startsWith('--')).length;
34
- return `šŸ”Ž grep /${pattern}/ → ${count} matches`;
36
+ const count = result.metadata?.returnedMatches;
37
+ const lowerBound = result.metadata?.matchCountLowerBound;
38
+ const summary = typeof count === 'number'
39
+ ? matchCountSummary(count, typeof lowerBound === 'number' ? lowerBound : undefined)
40
+ : 'results';
41
+ return `šŸ”Ž grep /${pattern}/ → ${summary}`;
35
42
  },
36
43
  });
44
+ function contextWindows(matches, context, lineCount) {
45
+ const windows = [];
46
+ for (const match of matches) {
47
+ const start = Math.max(0, match - context);
48
+ const end = Math.min(lineCount - 1, match + context);
49
+ const last = windows.at(-1);
50
+ if (last && start <= last.end + 1) {
51
+ last.end = end;
52
+ }
53
+ else {
54
+ windows.push({ start, end, firstMatch: match });
55
+ }
56
+ }
57
+ return windows;
58
+ }
59
+ function matchCountSummary(count, lowerBound) {
60
+ return lowerBound === undefined
61
+ ? `${count} matches`
62
+ : `${count} of at least ${lowerBound} matches`;
63
+ }
37
64
  /**
38
65
  * Validate a caller-supplied regular expression pattern before compiling it.
39
66
  *
@@ -99,7 +126,10 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
99
126
  const regex = new RegExp(pattern);
100
127
  const context = contextLines ?? 0;
101
128
  const results = [];
102
- const maxResults = 100;
129
+ let returnedMatches = 0;
130
+ let omittedMatches = false;
131
+ let remainingContext = MAX_CONTEXT_ROWS;
132
+ let omittedContext = false;
103
133
  // Get list of files to search
104
134
  const files = [];
105
135
  const skippedDangling = [];
@@ -128,6 +158,8 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
128
158
  skippedDangling.push(fullPath);
129
159
  continue;
130
160
  }
161
+ if (!(0, common_1.isWithinWorkspace)(fullPath, workspaceRoot))
162
+ continue;
131
163
  }
132
164
  files.push(fullPath);
133
165
  }
@@ -162,8 +194,6 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
162
194
  }
163
195
  // Search each file
164
196
  for (const file of files) {
165
- if (results.length >= maxResults)
166
- break;
167
197
  try {
168
198
  // Skip dangling symlinks and unreadable files before creating the stream.
169
199
  const fileStat = (0, common_1.safeStatSync)(file);
@@ -175,7 +205,7 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
175
205
  crlfDelay: Infinity,
176
206
  });
177
207
  const lines = [];
178
- const relPath = (0, path_1.relative)(base, file);
208
+ const relPath = (0, path_1.relative)(workspaceRoot, file);
179
209
  rl.on('line', line => {
180
210
  lines.push(line);
181
211
  });
@@ -184,25 +214,42 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
184
214
  stream.on('error', reject);
185
215
  rl.on('close', resolve);
186
216
  });
187
- // Search for matches
188
- for (let i = 0; i < lines.length && results.length < maxResults; i++) {
189
- if (regex.test(lines[i])) {
190
- // Format: file:line:content
191
- const start = Math.max(0, i - context);
192
- const end = Math.min(lines.length - 1, i + context);
193
- if (context > 0) {
194
- results.push(`${relPath}:${i + 1}:`);
195
- for (let j = start; j <= end; j++) {
196
- const prefix = j === i ? '>' : ' ';
197
- results.push(` ${prefix}${j + 1}: ${lines[j]}`);
217
+ const matches = [];
218
+ let contextEnd = lines.length;
219
+ for (let index = 0; index < lines.length; index++) {
220
+ if (!regex.test(lines[index]))
221
+ continue;
222
+ if (returnedMatches === MAX_MATCHES) {
223
+ omittedMatches = true;
224
+ contextEnd = index;
225
+ break;
226
+ }
227
+ matches.push(index);
228
+ returnedMatches++;
229
+ }
230
+ if (context === 0) {
231
+ results.push(...matches.map(index => `${relPath}:${index + 1}: ${lines[index]}`));
232
+ }
233
+ else {
234
+ const selected = new Set(matches);
235
+ for (const window of contextWindows(matches, context, contextEnd)) {
236
+ results.push(`${relPath}:${window.firstMatch + 1}:`);
237
+ for (let index = window.start; index <= window.end; index++) {
238
+ if (!selected.has(index)) {
239
+ if (remainingContext === 0) {
240
+ omittedContext = true;
241
+ continue;
242
+ }
243
+ remainingContext--;
198
244
  }
199
- results.push('');
200
- }
201
- else {
202
- results.push(`${relPath}:${i + 1}: ${lines[i]}`);
245
+ const prefix = selected.has(index) ? '>' : ' ';
246
+ results.push(` ${prefix}${index + 1}: ${lines[index]}`);
203
247
  }
248
+ results.push('');
204
249
  }
205
250
  }
251
+ if (omittedMatches)
252
+ break;
206
253
  }
207
254
  catch {
208
255
  // skip unreadable files
@@ -211,10 +258,23 @@ async function grep_(pattern, basePath, globPattern, contextLines, cwd) {
211
258
  const symlinkWarning = skippedDangling.length > 0
212
259
  ? `\nāš ļø Skipped ${skippedDangling.length} dangling symlink(s): ${skippedDangling.slice(0, 3).join(', ')}${skippedDangling.length > 3 ? '...' : ''}\n`
213
260
  : '';
214
- if (results.length === 0) {
215
- return { success: true, output: 'No matches found' + symlinkWarning };
261
+ const matchCountLowerBound = omittedMatches ? returnedMatches + 1 : undefined;
262
+ if (matchCountLowerBound !== undefined) {
263
+ results.push(`[Showing ${returnedMatches} of at least ${matchCountLowerBound} matching lines. Narrow the search for more results.]`);
264
+ }
265
+ if (omittedContext) {
266
+ results.push(`[Context output limited to ${MAX_CONTEXT_ROWS} surrounding lines.]`);
216
267
  }
217
- return { success: true, output: results.slice(0, maxResults).join('\n') + symlinkWarning };
268
+ return {
269
+ success: true,
270
+ output: (results.length > 0 ? results.join('\n') : 'No matches found') + symlinkWarning,
271
+ summary: matchCountSummary(returnedMatches, matchCountLowerBound),
272
+ metadata: {
273
+ returnedMatches,
274
+ ...(matchCountLowerBound !== undefined ? { matchCountLowerBound } : {}),
275
+ ...(omittedContext ? { contextTruncated: true } : {}),
276
+ },
277
+ };
218
278
  }
219
279
  catch (err) {
220
280
  return { success: false, output: '', error: (0, errors_1.errorMessage)(err) };