@causyne/agent 1.20.9 → 1.20.11

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 (47) hide show
  1. package/package.json +2 -1
  2. package/src/agentLoop.js +127 -72
  3. package/src/agentLoop.ts +137 -75
  4. package/src/browser/causyneBrowser.js +36 -0
  5. package/src/browser/causyneBrowser.ts +36 -1
  6. package/src/commands.js +25 -0
  7. package/src/contextManager.js +16 -0
  8. package/src/providers/antigravity.js +63 -11
  9. package/src/providers/antigravity.ts +62 -12
  10. package/src/provisioning/capabilityProvisioner.js +2 -7
  11. package/src/provisioning/npmInstall.js +19 -0
  12. package/src/provisioning/npmInstall.ts +19 -0
  13. package/src/smartToolsUse.js +20 -0
  14. package/src/smartToolsUse.ts +21 -0
  15. package/src/stallGuard.js +347 -0
  16. package/src/stallGuard.ts +423 -0
  17. package/src/tools/browserAutomator.js +3 -3
  18. package/src/tools/browserAutomator.ts +3 -3
  19. package/src/tools/fsRead.js +91 -80
  20. package/src/tools/fsRead.ts +125 -0
  21. package/src/tools/peerAgent.js +1 -1
  22. package/src/tools/peerAgent.ts +1 -1
  23. package/src/tools/screenshot.js +5 -1
  24. package/src/tools/screenshot.ts +5 -1
  25. package/src/tools/toolScanner.js +19 -0
  26. package/src/tools/toolScanner.ts +17 -0
  27. package/src/tools/toolSelfRepair.js +63 -1
  28. package/src/tools/toolSelfRepair.ts +61 -1
  29. package/src/tools/visionInspector.js +80 -142
  30. package/src/tools/visionInspector.ts +110 -0
  31. package/src/tui/chatboxClipboard.js +152 -0
  32. package/src/tui/chatboxClipboard.ts +201 -0
  33. package/src/tui/clipboardSync.js +38 -7
  34. package/src/tui/clipboardSync.ts +39 -7
  35. package/src/tui/codeProgress.js +89 -18
  36. package/src/tui/codeProgress.ts +102 -17
  37. package/src/tui/codeStreamRenderer.js +7 -2
  38. package/src/tui/codeStreamRenderer.ts +7 -2
  39. package/src/tui/composerControls.js +9 -0
  40. package/src/tui/composerControls.ts +9 -0
  41. package/src/tui/dialogs.js +8 -3
  42. package/src/tui/diff.d.ts +1 -0
  43. package/src/tui/lineEditor.js +166 -14
  44. package/src/tui/mouseHover.js +6 -2
  45. package/src/tui/mouseHover.ts +7 -2
  46. package/src/tui/prompt.js +96 -19
  47. package/src/tui/stageSurface.js +3 -1
@@ -0,0 +1,423 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isMutatingToolCall } from './decisionPolicy.js';
3
+
4
+ export interface ToolCallSignature {
5
+ toolName: string;
6
+ argsHash: string;
7
+ }
8
+
9
+ export interface StallGuardDecision {
10
+ action: 'allow' | 'warn' | 'block' | 'halt';
11
+ code: string;
12
+ message: string;
13
+ toolName: string;
14
+ count: number;
15
+ signature?: ToolCallSignature;
16
+ period?: number;
17
+ }
18
+
19
+ export interface IdenticalCallObservation {
20
+ notice: string | null;
21
+ stub: string | null;
22
+ decision?: StallGuardDecision | null;
23
+ }
24
+
25
+ export interface StallGuardConfig {
26
+ warningsEnabled?: boolean;
27
+ hardStopEnabled?: boolean;
28
+ identicalCallWarnAfter?: number;
29
+ identicalCallHaltAfter?: number;
30
+ cycleWarnAfter?: number;
31
+ cycleHaltAfter?: number;
32
+ researchNudgeAfter?: number;
33
+ stubMinChars?: number;
34
+ }
35
+
36
+ export const STALL_GUARD_REPEATABLE_TOOLS = new Set([
37
+ 'process_list',
38
+ 'sys_run_poll',
39
+ 'proc_term'
40
+ ]);
41
+
42
+ export const FAILURE_TOLERANT_TOOL_NAMES = new Set([
43
+ 'sysRun',
44
+ 'sysRunBg',
45
+ 'terminal_persistent_shell',
46
+ 'grep_search',
47
+ 'fs_search',
48
+ 'code_searcher',
49
+ 'codebase_search',
50
+ 'web_search'
51
+ ]);
52
+
53
+ export const IDEMPOTENT_TOOL_NAMES = new Set([
54
+ 'fs_read',
55
+ 'fs_list',
56
+ 'fs_find',
57
+ 'fs_search',
58
+ 'code_search_ast',
59
+ 'code_searcher',
60
+ 'codebase_search',
61
+ 'pdf_read',
62
+ 'clipboard_read',
63
+ 'read_native_skill',
64
+ 'desktop_open',
65
+ 'check_system_specs',
66
+ 'web_search',
67
+ 'web_fetch',
68
+ 'grep_search',
69
+ 'dir_list',
70
+ 'view_image',
71
+ 'vision_inspect_ui',
72
+ 'ax_snapshot',
73
+ 'browser_snapshot',
74
+ 'browser_console',
75
+ 'browser_get_dom',
76
+ 'read_browser_page',
77
+ 'deferred_mcp_search'
78
+ ]);
79
+
80
+ export const MUTATING_TOOL_NAMES = new Set([
81
+ 'fs_write',
82
+ 'fs_edit',
83
+ 'MultiEdit',
84
+ 'fs_delete',
85
+ 'fs_move',
86
+ 'archive_extract',
87
+ 'game_build_html5',
88
+ 'tool_forge',
89
+ 'create_skill',
90
+ 'manage_local_dependencies',
91
+ 'creative_batch',
92
+ 'blender_act',
93
+ 'godot_act'
94
+ ]);
95
+
96
+ export const STALL_GUARD_IDENTICAL_CALL_THRESHOLD = 3;
97
+ export const STALL_GUARD_IDENTICAL_CALL_HALT = 5;
98
+ export const STALL_GUARD_MAX_CYCLE_PERIOD = 4;
99
+ export const STALL_GUARD_CYCLE_HISTORY = 64;
100
+ export const IDENTICAL_RESULT_STUB_MIN_CHARS = 512;
101
+ export const RESEARCH_INSPECTION_NUDGE_AFTER = 25;
102
+
103
+ function stableSortObject(value: unknown): unknown {
104
+ if (value === null || typeof value !== 'object') {
105
+ return value;
106
+ }
107
+ if (Array.isArray(value)) {
108
+ return value.map(stableSortObject);
109
+ }
110
+ const sorted: Record<string, unknown> = {};
111
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
112
+ sorted[key] = stableSortObject((value as Record<string, unknown>)[key]);
113
+ }
114
+ return sorted;
115
+ }
116
+
117
+ export function canonicalToolArgs(args: unknown): string {
118
+ if (!args || typeof args !== 'object') {
119
+ return JSON.stringify(args ?? {});
120
+ }
121
+ return JSON.stringify(stableSortObject(args));
122
+ }
123
+
124
+ export function buildToolCallSignature(toolName: string, args: unknown): ToolCallSignature {
125
+ const canonical = canonicalToolArgs(args);
126
+ const argsHash = createHash('sha256').update(canonical).digest('hex').slice(0, 16);
127
+ return { toolName, argsHash };
128
+ }
129
+
130
+ export function computeResultHash(result: unknown): string {
131
+ if (result === null || result === undefined) return '';
132
+ const str = typeof result === 'string' ? result : JSON.stringify(result);
133
+ return createHash('sha256').update(str).digest('hex').slice(0, 24);
134
+ }
135
+
136
+ function ordinal(n: number): string {
137
+ const v = n % 100;
138
+ if (v >= 11 && v <= 13) return `${n}th`;
139
+ switch (n % 10) {
140
+ case 1: return `${n}st`;
141
+ case 2: return `${n}nd`;
142
+ case 3: return `${n}rd`;
143
+ default: return `${n}th`;
144
+ }
145
+ }
146
+
147
+ export class StallGuardController {
148
+ private config: Required<StallGuardConfig>;
149
+ private _identicalStreakSig: ToolCallSignature | null = null;
150
+ private _identicalStreakResultHash = '';
151
+ private _identicalStreakCount = 0;
152
+ private _identicalStreakFirstCallId = '';
153
+ private _callHistory: Array<{ sig: ToolCallSignature; resultHash: string; repeatable: boolean }> = [];
154
+ private _exactFailureCounts = new Map<string, number>();
155
+ private _distinctInspectionCount = 0;
156
+ private _researchNudgeEmitted = false;
157
+ private _haltDecision: StallGuardDecision | null = null;
158
+
159
+ constructor(config?: StallGuardConfig) {
160
+ this.config = {
161
+ warningsEnabled: config?.warningsEnabled ?? true,
162
+ hardStopEnabled: config?.hardStopEnabled ?? false,
163
+ identicalCallWarnAfter: config?.identicalCallWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
164
+ identicalCallHaltAfter: config?.identicalCallHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
165
+ cycleWarnAfter: config?.cycleWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
166
+ cycleHaltAfter: config?.cycleHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
167
+ researchNudgeAfter: config?.researchNudgeAfter ?? RESEARCH_INSPECTION_NUDGE_AFTER,
168
+ stubMinChars: config?.stubMinChars ?? IDENTICAL_RESULT_STUB_MIN_CHARS
169
+ };
170
+ }
171
+
172
+ get haltDecision(): StallGuardDecision | null {
173
+ return this._haltDecision;
174
+ }
175
+
176
+ get distinctInspectionCount(): number {
177
+ return this._distinctInspectionCount;
178
+ }
179
+
180
+ reset(): void {
181
+ this._identicalStreakSig = null;
182
+ this._identicalStreakResultHash = '';
183
+ this._identicalStreakCount = 0;
184
+ this._identicalStreakFirstCallId = '';
185
+ this._callHistory = [];
186
+ this._exactFailureCounts.clear();
187
+ this._distinctInspectionCount = 0;
188
+ this._researchNudgeEmitted = false;
189
+ this._haltDecision = null;
190
+ }
191
+
192
+ isRepeatable(toolName: string, args: Record<string, unknown> = {}): boolean {
193
+ if (STALL_GUARD_REPEATABLE_TOOLS.has(toolName)) return true;
194
+ if (toolName.endsWith('_poll') || toolName.endsWith('_status') || toolName.endsWith('_get_result')) return true;
195
+ if (toolName === 'sysRun' || toolName === 'sysRunBg') {
196
+ const cmd = String(args.command ?? '').trim();
197
+ if (/^(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)\b/i.test(cmd)) return true;
198
+ }
199
+ return false;
200
+ }
201
+
202
+ isMutating(toolName: string, args: Record<string, unknown> = {}): boolean {
203
+ if (MUTATING_TOOL_NAMES.has(toolName)) return true;
204
+ return isMutatingToolCall(toolName, args);
205
+ }
206
+
207
+ isFailureTolerant(toolName: string): boolean {
208
+ return FAILURE_TOLERANT_TOOL_NAMES.has(toolName);
209
+ }
210
+
211
+ recordMutation(): void {
212
+ this._exactFailureCounts.clear();
213
+ this._distinctInspectionCount = 0;
214
+ this._researchNudgeEmitted = false;
215
+ }
216
+
217
+ beforeCall(
218
+ toolName: string,
219
+ args: Record<string, unknown> = {},
220
+ context?: { isAuthoringTask?: boolean }
221
+ ): StallGuardDecision {
222
+ const signature = buildToolCallSignature(toolName, args);
223
+ const sigKey = `${signature.toolName}:${signature.argsHash}`;
224
+
225
+ if (this._haltDecision) {
226
+ return this._haltDecision;
227
+ }
228
+
229
+ const failureCount = this._exactFailureCounts.get(sigKey) || 0;
230
+ if (this.config.hardStopEnabled && failureCount >= this.config.identicalCallHaltAfter) {
231
+ const decision: StallGuardDecision = {
232
+ action: 'halt',
233
+ code: 'repeated_exact_failure_halt',
234
+ message: `Halted: identical call to '${toolName}' failed ${failureCount} times with unchanged arguments. Change strategy or explain the blocker.`,
235
+ toolName,
236
+ count: failureCount,
237
+ signature
238
+ };
239
+ this._haltDecision = decision;
240
+ return decision;
241
+ }
242
+
243
+ const repeatable = this.isRepeatable(toolName, args);
244
+ if (!repeatable && this._identicalStreakSig !== null) {
245
+ const isStreakMatch = this._identicalStreakSig.toolName === signature.toolName
246
+ && this._identicalStreakSig.argsHash === signature.argsHash;
247
+
248
+ if (isStreakMatch && this.config.hardStopEnabled && this._identicalStreakCount >= this.config.identicalCallHaltAfter) {
249
+ const decision: StallGuardDecision = {
250
+ action: 'halt',
251
+ code: 'identical_call_limit_halt',
252
+ message: `Halted: tool '${toolName}' was invoked identically ${this._identicalStreakCount} times without progress.`,
253
+ toolName,
254
+ count: this._identicalStreakCount,
255
+ signature
256
+ };
257
+ this._haltDecision = decision;
258
+ return decision;
259
+ }
260
+ }
261
+
262
+ // Distinct inspections can be necessary for large codebases and research.
263
+ // Count them for a progress nudge, but only stop on evidence of repetition
264
+ // or an explicit task budget. Task intent alone is not evidence of a stall.
265
+
266
+ return {
267
+ action: 'allow',
268
+ code: 'allow',
269
+ message: '',
270
+ toolName,
271
+ count: 0,
272
+ signature
273
+ };
274
+ }
275
+
276
+ observeCall(
277
+ toolName: string,
278
+ args: Record<string, unknown> = {},
279
+ result: unknown,
280
+ toolCallId = '',
281
+ failed = false
282
+ ): IdenticalCallObservation {
283
+ const signature = buildToolCallSignature(toolName, args);
284
+ const sigKey = `${signature.toolName}:${signature.argsHash}`;
285
+ const resultStr = typeof result === 'string' ? result : JSON.stringify(result ?? {});
286
+ const rHash = computeResultHash(resultStr);
287
+ const repeatable = this.isRepeatable(toolName, args);
288
+ const mutating = this.isMutating(toolName, args);
289
+
290
+ if (mutating && !failed) {
291
+ this.recordMutation();
292
+ } else if (!mutating) {
293
+ this._distinctInspectionCount++;
294
+ }
295
+
296
+ if (failed) {
297
+ const count = (this._exactFailureCounts.get(sigKey) || 0) + 1;
298
+ this._exactFailureCounts.set(sigKey, count);
299
+ this._identicalStreakSig = null;
300
+ this._identicalStreakResultHash = '';
301
+ this._identicalStreakCount = 0;
302
+
303
+ let notice: string | null = null;
304
+ if (this.config.warningsEnabled && count >= this.config.identicalCallWarnAfter) {
305
+ notice = `[STALL GUARD: Tool '${toolName}' with identical arguments failed ${count} times. Stop retrying unchanged; change arguments or adopt an alternative approach.]`;
306
+ }
307
+ return { notice, stub: null };
308
+ }
309
+
310
+ const matchesStreak = this._identicalStreakSig !== null
311
+ && this._identicalStreakSig.toolName === signature.toolName
312
+ && this._identicalStreakSig.argsHash === signature.argsHash
313
+ && this._identicalStreakResultHash === rHash;
314
+
315
+ if (matchesStreak) {
316
+ this._identicalStreakCount++;
317
+ } else {
318
+ this._identicalStreakSig = signature;
319
+ this._identicalStreakResultHash = rHash;
320
+ this._identicalStreakCount = 1;
321
+ this._identicalStreakFirstCallId = toolCallId || '';
322
+ }
323
+
324
+ const count = this._identicalStreakCount;
325
+ let stub: string | null = null;
326
+ let notice: string | null = null;
327
+ let decision: StallGuardDecision | null = null;
328
+
329
+ if (count >= 2 && !failed && resultStr.length >= this.config.stubMinChars) {
330
+ const argsPreview = canonicalToolArgs(args).slice(0, 100);
331
+ const priorId = this._identicalStreakFirstCallId ? `prior call ${this._identicalStreakFirstCallId}` : 'previous call';
332
+ stub = JSON.stringify({
333
+ success: true,
334
+ unchanged: true,
335
+ stub: `[Duplicate result identical to ${priorId}: ${toolName}(${argsPreview})]`
336
+ });
337
+ }
338
+
339
+ if (!repeatable && count >= this.config.identicalCallWarnAfter) {
340
+ notice = `[STALL GUARD: This is the ${ordinal(count)} consecutive identical call to '${toolName}' with identical arguments returning the unchanged result. Do not repeat it — change arguments, use a different tool, or proceed with what you have.]`;
341
+
342
+ if (this.config.hardStopEnabled && count >= this.config.identicalCallHaltAfter && !this._haltDecision) {
343
+ decision = {
344
+ action: 'halt',
345
+ code: 'identical_call_streak_halt',
346
+ message: `Stopped ${toolName}: the same call with identical arguments returned the same result ${count} times in a row. Stop repeating it unchanged; use the result already provided or change strategy.`,
347
+ toolName,
348
+ count,
349
+ signature
350
+ };
351
+ this._haltDecision = decision;
352
+ }
353
+ }
354
+
355
+ this._callHistory.push({ sig: signature, resultHash: rHash, repeatable });
356
+ if (this._callHistory.length > STALL_GUARD_CYCLE_HISTORY) {
357
+ this._callHistory.shift();
358
+ }
359
+
360
+ if (!notice) {
361
+ const cycle = this.detectIdenticalCycle();
362
+ if (cycle) {
363
+ const { period, laps } = cycle;
364
+ notice = `[STALL GUARD: The last ${laps} rounds repeated the same cycle of ${period} tool calls (ending with '${toolName}') with identical arguments and identical results. Do not repeat the batch — change arguments, synthesize findings, or proceed.]`;
365
+
366
+ if (this.config.hardStopEnabled && laps >= this.config.cycleHaltAfter && !this._haltDecision) {
367
+ decision = {
368
+ action: 'halt',
369
+ code: 'identical_cycle_halt',
370
+ message: `Stopped ${toolName}: repeating cycle of ${period} tool calls with identical arguments and results has run ${laps} times. Repeating the batch unchanged is not progress; use the results already provided or change strategy.`,
371
+ toolName,
372
+ count: laps,
373
+ period,
374
+ signature
375
+ };
376
+ this._haltDecision = decision;
377
+ }
378
+ }
379
+ }
380
+
381
+ if (!notice && !this._researchNudgeEmitted && this._distinctInspectionCount >= this.config.researchNudgeAfter) {
382
+ this._researchNudgeEmitted = true;
383
+ notice = `[RESEARCH PROGRESS NOTICE: You have performed ${this._distinctInspectionCount} consecutive inspection steps across the workspace. If sufficient context has been gathered, consider proceeding to implementation or updating the plan.]`;
384
+ }
385
+
386
+ return { notice, stub, decision };
387
+ }
388
+
389
+ detectIdenticalCycle(): { period: number; laps: number } | null {
390
+ const history = this._callHistory;
391
+ for (let period = 2; period <= STALL_GUARD_MAX_CYCLE_PERIOD; period++) {
392
+ if (history.length < period * this.config.cycleWarnAfter) {
393
+ continue;
394
+ }
395
+ let laps = 1;
396
+ while (true) {
397
+ const base = history.length - period * (laps + 1);
398
+ if (base < 0) break;
399
+
400
+ let lapEqual = true;
401
+ for (let i = 0; i < period; i++) {
402
+ const past = history[base + i];
403
+ const curr = history[history.length - period + i];
404
+ if (!past || !curr || past.sig.toolName !== curr.sig.toolName || past.sig.argsHash !== curr.sig.argsHash || past.resultHash !== curr.resultHash) {
405
+ lapEqual = false;
406
+ break;
407
+ }
408
+ }
409
+ if (!lapEqual) break;
410
+ laps++;
411
+ }
412
+
413
+ if (laps >= this.config.cycleWarnAfter) {
414
+ const tail = history.slice(history.length - period);
415
+ if (tail.every(item => item.repeatable)) {
416
+ continue;
417
+ }
418
+ return { period, laps };
419
+ }
420
+ }
421
+ return null;
422
+ }
423
+ }
@@ -5,7 +5,7 @@ const SUPPORTED_ACTION_TYPES = [
5
5
  'listTabs', 'list_tabs',
6
6
  'closeTab', 'close_tab',
7
7
  'search',
8
- 'goto', 'open', 'navigate',
8
+ 'goto', 'open', 'navigate', 'preview',
9
9
  'snapshot', 'scrape',
10
10
  'click', 'clickIndex',
11
11
  'type', 'typeIndex', 'fill',
@@ -45,7 +45,7 @@ function normalizeActions(args) {
45
45
  export const browserAct = {
46
46
  schema: {
47
47
  name: 'browser.act',
48
- description: `Use the dedicated Causyne Browser for resilient search, navigation, search macros (${getSupportedSearchMacros().slice(0, 6).join(', ')}, etc.), accessible snapshots (including child iframes and structured forms/tables), interaction, deterministic schema extraction, and workspace-scoped uploads/downloads. Take a snapshot before interacting by ref.`,
48
+ description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
49
49
  parameters: {
50
50
  type: 'object',
51
51
  properties: {
@@ -94,7 +94,7 @@ export const browserAct = {
94
94
  { type: 'string' },
95
95
  { type: 'array', items: { type: 'string' } }
96
96
  ],
97
- description: 'Workspace-relative file path(s) for upload action.'
97
+ description: 'Workspace-relative HTML path for preview, or file path(s) for upload.'
98
98
  },
99
99
  outputFile: { type: 'string', description: 'Download or screenshot destination inside the selected workspace.' },
100
100
  fullPage: { type: 'boolean', description: 'Capture the complete page for a screenshot instead of the visible viewport.' }
@@ -17,7 +17,7 @@ const SUPPORTED_ACTION_TYPES: BrowserActionType[] = [
17
17
  'listTabs', 'list_tabs',
18
18
  'closeTab', 'close_tab',
19
19
  'search',
20
- 'goto', 'open', 'navigate',
20
+ 'goto', 'open', 'navigate', 'preview',
21
21
  'snapshot', 'scrape',
22
22
  'click', 'clickIndex',
23
23
  'type', 'typeIndex', 'fill',
@@ -58,7 +58,7 @@ function normalizeActions(args: Record<string, unknown> | undefined): BrowserAct
58
58
  export const browserAct = {
59
59
  schema: {
60
60
  name: 'browser.act',
61
- description: `Use the dedicated Causyne Browser for resilient search, navigation, search macros (${getSupportedSearchMacros().slice(0, 6).join(', ')}, etc.), accessible snapshots (including child iframes and structured forms/tables), interaction, deterministic schema extraction, and workspace-scoped uploads/downloads. Take a snapshot before interacting by ref.`,
61
+ description: `Use the dedicated Causyne Browser for search, public navigation, and preview of a workspace HTML file (type preview, filePath), accessible snapshots, interaction, extraction, and workspace-scoped screenshots. Use preview followed by snapshot and screenshot to check a local web page; a saved screenshot alone is not visual inspection by the model.`,
62
62
  parameters: {
63
63
  type: 'object',
64
64
  properties: {
@@ -107,7 +107,7 @@ export const browserAct = {
107
107
  { type: 'string' },
108
108
  { type: 'array', items: { type: 'string' } }
109
109
  ],
110
- description: 'Workspace-relative file path(s) for upload action.'
110
+ description: 'Workspace-relative HTML path for preview, or file path(s) for upload.'
111
111
  },
112
112
  outputFile: { type: 'string', description: 'Download or screenshot destination inside the selected workspace.' },
113
113
  fullPage: { type: 'boolean', description: 'Capture the complete page for a screenshot instead of the visible viewport.' }
@@ -1,87 +1,98 @@
1
- import fs from 'fs';
2
- import readline from 'readline';
3
- import path from 'path';
4
- import os from 'os';
5
-
6
- // Phase 3 AGI Upgrade: Fast Binary Detection
1
+ import fs from 'node:fs';
2
+ import readline from 'node:readline';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ const BINARY_EXTENSIONS = /\.(png|jpe?g|webp|gif|svg|bmp|ico|blend\d?|glb|gltf|wasm|zip|tar|gz|bz2|xz|7z|rar|mp4|mov|avi|mkv|webm|mp3|wav|ogg|flac|aac|m4a|pdf|exe|dll|dylib|so|bin|iso|dmg)$/i;
6
+ /** Fast Binary Detection: inspect the first 1024 bytes for a null byte. */
7
7
  async function isBinary(filePath) {
8
- try {
9
- const fd = await fs.promises.open(filePath, 'r');
10
- const buffer = Buffer.alloc(1024);
11
- const { bytesRead } = await fd.read(buffer, 0, 1024, 0);
12
- await fd.close();
13
-
14
- for (let i = 0; i < bytesRead; i++) {
15
- if (buffer[i] === 0) return true; // Null byte indicates binary
8
+ try {
9
+ const fd = await fs.promises.open(filePath, 'r');
10
+ const buffer = Buffer.alloc(1024);
11
+ const { bytesRead } = await fd.read(buffer, 0, 1024, 0);
12
+ await fd.close();
13
+ for (let i = 0; i < bytesRead; i++) {
14
+ if (buffer[i] === 0)
15
+ return true;
16
+ }
17
+ return false;
18
+ }
19
+ catch {
20
+ return false;
16
21
  }
17
- return false;
18
- } catch (e) {
19
- return false;
20
- }
21
22
  }
22
-
23
23
  export const fsRead = {
24
- schema: {
25
- name: 'fs.read',
26
- description: 'Read file contents intelligently. Automatically pages large files to protect Context Window.',
27
- parameters: {
28
- type: 'object',
29
- properties: {
30
- path: { type: 'string' },
31
- startLine: { type: 'number' },
32
- endLine: { type: 'number' }
33
- },
34
- required: ['path']
35
- }
36
- },
37
- async execute(args) {
38
- try {
39
- const target = args.path.replace(/^~\//, os.homedir() + '/');
40
-
41
- if (!fs.existsSync(target)) {
42
- return { success: false, error: "File does not exist." };
43
- }
44
-
45
- // Phase 3 AGI Upgrade: Binary Rejection
46
- if (await isBinary(target)) {
47
- return { success: false, error: "Cannot read binary file as text. Use viewImage or OCR tools instead." };
48
- }
49
-
50
- const start = args.startLine ? Math.max(1, args.startLine) : 1;
51
- let end = args.endLine ? args.endLine : start + 799;
52
-
53
- // Phase 3 AGI Upgrade: Mandatory Paging Limit (800)
54
- if (end - start + 1 > 800) {
55
- end = start + 799;
56
- }
57
-
58
- let currentLine = 1;
59
- let outputLines = [];
60
- let totalLines = 0;
61
-
62
- // Phase 3 AGI Upgrade: Stream (no full buffering)
63
- const rl = readline.createInterface({
64
- input: fs.createReadStream(target),
65
- crlfDelay: Infinity
66
- });
67
-
68
- for await (const line of rl) {
69
- totalLines++;
70
- if (currentLine >= start && currentLine <= end) {
71
- outputLines.push(line);
24
+ schema: {
25
+ name: 'fs.read',
26
+ description: 'Read file contents intelligently. Automatically pages large files to protect Context Window.',
27
+ parameters: {
28
+ type: 'object',
29
+ properties: {
30
+ path: { type: 'string' },
31
+ startLine: { type: 'number' },
32
+ endLine: { type: 'number' }
33
+ },
34
+ required: ['path']
35
+ }
36
+ },
37
+ async execute(args) {
38
+ try {
39
+ if (!args || typeof args.path !== 'string' || !args.path.trim()) {
40
+ return { success: false, error: 'Missing required parameter: path' };
41
+ }
42
+ const target = args.path.replace(/^~\//, os.homedir() + '/');
43
+ if (!fs.existsSync(target)) {
44
+ return { success: false, error: 'File does not exist.' };
45
+ }
46
+ const ext = path.extname(target).toLowerCase();
47
+ const isKnownBinaryExt = BINARY_EXTENSIONS.test(ext);
48
+ // Fast check for binary media/executables to prevent token context blowup
49
+ if (isKnownBinaryExt || (await isBinary(target))) {
50
+ let stat = null;
51
+ try {
52
+ stat = fs.statSync(target);
53
+ }
54
+ catch {
55
+ // ignore stat error
56
+ }
57
+ const sizeStr = stat ? `${(stat.size / 1024).toFixed(1)} KB` : 'unknown size';
58
+ const isImage = /\.(png|jpe?g|webp|gif|svg|bmp|ico)$/i.test(ext);
59
+ return {
60
+ success: false,
61
+ isBinary: true,
62
+ error: isImage
63
+ ? `Cannot read image file '${path.basename(target)}' as plain text. Use view_image (or vision inspection). File metadata: ${sizeStr}, format: ${ext.replace('.', '').toUpperCase() || 'IMAGE'}.`
64
+ : `Cannot read binary file '${path.basename(target)}' as plain text. File size: ${sizeStr}.`
65
+ };
66
+ }
67
+ const start = typeof args.startLine === 'number' && args.startLine > 0 ? Math.floor(args.startLine) : 1;
68
+ let end = typeof args.endLine === 'number' && args.endLine >= start ? Math.floor(args.endLine) : start + 799;
69
+ // Mandatory Paging Limit: at most 800 lines per read to preserve context
70
+ if (end - start + 1 > 800) {
71
+ end = start + 799;
72
+ }
73
+ let currentLine = 1;
74
+ const outputLines = [];
75
+ let totalLines = 0;
76
+ const rl = readline.createInterface({
77
+ input: fs.createReadStream(target),
78
+ crlfDelay: Infinity
79
+ });
80
+ for await (const line of rl) {
81
+ totalLines++;
82
+ if (currentLine >= start && currentLine <= end) {
83
+ outputLines.push(line);
84
+ }
85
+ currentLine++;
86
+ }
87
+ let finalOutput = outputLines.join('\n');
88
+ if (totalLines > end) {
89
+ finalOutput += `\n\n[WARNING: File truncated at line ${end} out of ${totalLines}. Use { startLine: ${end + 1}, endLine: ${end + 800} } to read more.]`;
90
+ }
91
+ return { success: true, output: finalOutput };
92
+ }
93
+ catch (e) {
94
+ const msg = e instanceof Error ? e.message : String(e);
95
+ return { success: false, error: msg };
72
96
  }
73
- currentLine++;
74
- }
75
-
76
- let finalOutput = outputLines.join('\n');
77
-
78
- if (totalLines > end) {
79
- finalOutput += `\n\n[WARNING: File truncated at line ${end} out of ${totalLines}. Use { startLine: ${end + 1}, endLine: ${end + 800} } to read more.]`;
80
- }
81
-
82
- return { success: true, output: finalOutput };
83
- } catch (e) {
84
- return { success: false, error: e.message };
85
97
  }
86
- }
87
98
  };