@orion-agents/orion-code 0.4.3 → 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.
- package/CHANGELOG.md +14 -0
- package/README.md +4 -4
- package/README.zh-CN.md +4 -4
- package/dist/acp/session-updates.d.ts +4 -3
- package/dist/acp/session-updates.js +23 -2
- package/dist/acp/sessions.js +19 -6
- package/dist/commands/core-command-handlers.js +10 -22
- package/dist/commands/diagnostic-command-handlers.js +48 -52
- package/dist/commands/registry.js +1 -1
- package/dist/commands/target-command.js +49 -6
- package/dist/commands/workflow-commands.js +2 -2
- package/dist/core/tool-artifacts.js +17 -4
- package/dist/framework/loop-budget-contract.d.ts +1 -12
- package/dist/framework/loop-budget-contract.js +1 -7
- package/dist/framework/loop-progress.d.ts +3 -7
- package/dist/framework/loop-progress.js +7 -23
- package/dist/framework/query.d.ts +12 -24
- package/dist/framework/query.js +294 -301
- package/dist/framework/tool-state.d.ts +4 -0
- package/dist/harness/assembler.js +1 -1
- package/dist/harness/context-harness.d.ts +12 -2
- package/dist/harness/context-harness.js +288 -60
- package/dist/harness/contract.js +3 -1
- package/dist/harness/drift-guard.js +67 -17
- package/dist/harness/goal-verification.d.ts +11 -0
- package/dist/harness/goal-verification.js +62 -0
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/ledger.d.ts +1 -0
- package/dist/harness/ledger.js +28 -4
- package/dist/harness/progress-controller.js +57 -35
- package/dist/harness/state.js +4 -0
- package/dist/harness/stop-controller.d.ts +0 -5
- package/dist/harness/stop-controller.js +11 -31
- package/dist/harness/task-checklist.d.ts +12 -2
- package/dist/harness/task-checklist.js +50 -9
- package/dist/harness/types.d.ts +15 -0
- package/dist/harness/verification.d.ts +11 -1
- package/dist/harness/verification.js +47 -2
- package/dist/print-ui/event-stream.d.ts +5 -0
- package/dist/print-ui/event-stream.js +22 -5
- package/dist/runtime/agent-loop.d.ts +2 -1
- package/dist/runtime/agent-loop.js +23 -17
- package/dist/runtime/agent-runtime-controller.d.ts +1 -1
- package/dist/runtime/agent-runtime-controller.js +21 -11
- package/dist/runtime/batch-read-service.js +21 -4
- package/dist/runtime/goal-lifecycle-v2.d.ts +6 -4
- package/dist/runtime/goal-lifecycle-v2.js +164 -56
- package/dist/runtime/goal-runtime-coordinator.d.ts +6 -3
- package/dist/runtime/goal-runtime-coordinator.js +91 -36
- package/dist/runtime/goals/presentation.js +3 -1
- package/dist/runtime/goals/types.d.ts +1 -3
- package/dist/runtime/goals/types.js +0 -3
- package/dist/runtime/loop-budget.d.ts +0 -7
- package/dist/runtime/loop-budget.js +8 -54
- package/dist/runtime/orion-runtime-v1.js +55 -14
- package/dist/runtime/product-orion-runtime.js +30 -13
- package/dist/runtime/rsi/evaluation.js +1 -7
- package/dist/runtime/step-snapshot.d.ts +3 -1
- package/dist/runtime/step-snapshot.js +11 -1
- package/dist/runtime/subagent-thread-runtime.js +27 -5
- package/dist/runtime/subagents/production.js +0 -4
- package/dist/runtime/task-context-recovery.js +30 -7
- package/dist/runtime/task-context-service.d.ts +7 -1
- package/dist/runtime/task-context-service.js +40 -8
- package/dist/runtime/thread-admission.d.ts +2 -0
- package/dist/runtime/thread-admission.js +9 -1
- package/dist/runtime/thread-runtime.d.ts +3 -0
- package/dist/runtime/thread-runtime.js +42 -3
- package/dist/runtime/thread-ui-adapter.js +1 -11
- package/dist/runtime/tool-gateway.d.ts +2 -0
- package/dist/runtime/tool-gateway.js +4 -0
- package/dist/runtime/tool-receipt-validator.js +4 -0
- package/dist/runtime/ui-events.d.ts +3 -1
- package/dist/runtime/ui-view-model.js +62 -59
- package/dist/runtime/workspace-verification.d.ts +7 -0
- package/dist/runtime/workspace-verification.js +98 -0
- package/dist/services/chat-completion-sse.d.ts +9 -0
- package/dist/services/chat-completion-sse.js +50 -0
- package/dist/services/compact/summary-generator.d.ts +1 -1
- package/dist/services/compact/summary-generator.js +12 -0
- package/dist/services/config.js +3 -7
- package/dist/services/global-config.d.ts +3 -11
- package/dist/services/global-config.js +36 -26
- package/dist/services/llm.d.ts +3 -1
- package/dist/services/llm.js +171 -285
- package/dist/services/provider-diagnostics.d.ts +2 -1
- package/dist/services/provider-diagnostics.js +15 -4
- package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
- package/dist/services/provider-resilience/error-classifier.js +14 -0
- package/dist/tools/core/common.d.ts +0 -11
- package/dist/tools/core/common.js +0 -18
- package/dist/tools/core/edit-file.js +61 -88
- package/dist/tools/core/exec-command.js +61 -80
- package/dist/tools/core/grep.js +84 -24
- package/dist/tools/core/read-file.js +3 -2
- package/dist/tools/core/write-file.js +5 -3
- package/dist/tools/todo.d.ts +2 -2
- package/dist/tools/todo.js +29 -10
- package/dist/tui-ui/chrome-view-model.js +15 -6
- package/dist/utils/utf8.d.ts +6 -0
- package/dist/utils/utf8.js +14 -0
- package/docs/cli-guide.md +58 -40
- package/docs/orion.example.yaml +4 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -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(
|
|
64
|
-
const
|
|
65
|
-
return
|
|
66
|
-
const
|
|
67
|
-
const
|
|
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
|
|
77
|
-
match,
|
|
78
|
-
contextBefore,
|
|
79
|
-
contextAfter,
|
|
80
|
-
isReplaceAll:
|
|
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
|
|
85
|
-
const
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
*
|
|
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 =
|
|
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
|
|
124
|
-
|
|
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 =
|
|
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
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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,18 +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((
|
|
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
|
|
261
|
-
const
|
|
262
|
-
const
|
|
263
|
-
|
|
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);
|
|
234
|
+
if (newContent !== content)
|
|
235
|
+
(0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
|
|
264
236
|
return {
|
|
265
237
|
success: true,
|
|
266
|
-
output: `Fuzzy edited ${normalizedPath} (matched by ${fuzzyResult.strategy}, "${
|
|
238
|
+
output: `Fuzzy edited ${normalizedPath} (matched by ${fuzzyResult.strategy}, "${text.slice(0, 50)}...")`,
|
|
267
239
|
...(newContent !== content ? { metadata: { workspaceWritePath: normalizedPath } } : {}),
|
|
268
240
|
};
|
|
269
241
|
}
|
|
@@ -285,7 +257,8 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
|
|
|
285
257
|
const idx = content.indexOf(old_string);
|
|
286
258
|
newContent = content.slice(0, idx) + new_string + content.slice(idx + old_string.length);
|
|
287
259
|
}
|
|
288
|
-
|
|
260
|
+
if (newContent !== content)
|
|
261
|
+
(0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
|
|
289
262
|
return {
|
|
290
263
|
success: true,
|
|
291
264
|
output: `Replaced ${count} occurrence(s) of old_string with new_string in ${normalizedPath}`,
|
|
@@ -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
|
-
|
|
183
|
-
|
|
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
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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: (
|
|
302
|
-
error
|
|
307
|
+
output: failedOutput(stdout, stderr, maxBytes),
|
|
308
|
+
error,
|
|
309
|
+
metadata: !interrupted && code !== null ? { exitCode: code } : undefined,
|
|
303
310
|
});
|
|
304
311
|
return;
|
|
305
312
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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({
|
package/dist/tools/core/grep.js
CHANGED
|
@@ -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.
|
|
34
|
-
|
|
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
|
-
|
|
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)(
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
-
|
|
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
|
-
|
|
215
|
-
|
|
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 {
|
|
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) };
|
|
@@ -5,6 +5,7 @@ const fs_1 = require("fs");
|
|
|
5
5
|
const tool_1 = require("../../framework/tool");
|
|
6
6
|
const descriptors_1 = require("../../runtime/core-tools/descriptors");
|
|
7
7
|
const errors_1 = require("../../utils/errors");
|
|
8
|
+
const utf8_1 = require("../../utils/utf8");
|
|
8
9
|
const common_1 = require("./common");
|
|
9
10
|
const descriptor = (0, descriptors_1.coreToolDescriptorV1)('read_file');
|
|
10
11
|
exports.coreTool = (0, tool_1.buildTool)({
|
|
@@ -103,7 +104,7 @@ async function readFileSync_(path, maxLines, offset, cwd) {
|
|
|
103
104
|
const byteLen = Buffer.byteLength(selected, 'utf8');
|
|
104
105
|
const notice = `\n\n[... truncated, ${remainingLines} more lines; showing lines ${offset}-${offset + selectedLines.length - 1} of ${lines.length}]`;
|
|
105
106
|
if (byteLen > maxBytes) {
|
|
106
|
-
const cut = (0,
|
|
107
|
+
const cut = (0, utf8_1.truncateToBytes)(selected, maxBytes);
|
|
107
108
|
return {
|
|
108
109
|
success: true,
|
|
109
110
|
output: cut.text + `\n\n[... truncated at ${cut.bytes}B]`,
|
|
@@ -114,7 +115,7 @@ async function readFileSync_(path, maxLines, offset, cwd) {
|
|
|
114
115
|
// Also apply byte limit to the selected page.
|
|
115
116
|
const byteLen = Buffer.byteLength(selected, 'utf8');
|
|
116
117
|
if (byteLen > maxBytes) {
|
|
117
|
-
const cut = (0,
|
|
118
|
+
const cut = (0, utf8_1.truncateToBytes)(selected, maxBytes);
|
|
118
119
|
return {
|
|
119
120
|
success: true,
|
|
120
121
|
output: cut.text + `\n\n[... truncated at ${cut.bytes}B of ${byteLen}B]`,
|