@causyne/agent 1.20.121 → 1.20.122

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 (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -19,31 +19,91 @@ export interface FsEditResult {
19
19
  error?: string;
20
20
  }
21
21
 
22
+ export interface FsEditContext {
23
+ workspaceRoot?: string;
24
+ workspacePaths?: string[];
25
+ grantAllAccess?: boolean;
26
+ parentLoop?: { workspaceRoot?: string };
27
+ }
28
+
29
+ function expandHome(value: string): string {
30
+ const trimmed = value.trim();
31
+ if (trimmed === '~') return os.homedir();
32
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
33
+ return path.join(os.homedir(), trimmed.slice(2));
34
+ }
35
+ return trimmed;
36
+ }
37
+
38
+ function insideRoot(root: string, target: string): boolean {
39
+ const rel = path.relative(root, target);
40
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
41
+ }
42
+
43
+ async function assertWithinEditScope(target: string, context?: FsEditContext): Promise<void> {
44
+ if (!context || context.grantAllAccess === true) return;
45
+ const configured = Array.isArray(context.workspacePaths)
46
+ ? context.workspacePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
47
+ : [];
48
+ const roots = configured.length > 0
49
+ ? configured
50
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
51
+ .filter((p): p is string => typeof p === 'string' && p.trim().length > 0)
52
+ .map(p => p.trim());
53
+ if (roots.length === 0) return;
54
+ const realTarget = await fs.realpath(target);
55
+ for (const root of roots) {
56
+ try {
57
+ const realRoot = await fs.realpath(path.resolve(expandHome(root)));
58
+ if (insideRoot(realRoot, realTarget)) return;
59
+ } catch {
60
+ continue;
61
+ }
62
+ }
63
+ throw new Error(`Target resolves outside the selected workspace: ${target}`);
64
+ }
65
+
66
+ const MAX_FUZZY_CHARS = 8_192;
67
+
22
68
  function getLevenshteinDistance(a: string, b: string): number {
23
- const matrix: number[][] = Array(a.length + 1)
24
- .fill(null)
25
- .map(() => Array(b.length + 1).fill(0));
26
-
27
- for (let i = 0; i <= a.length; i++) matrix[i]![0] = i;
28
- for (let j = 0; j <= b.length; j++) matrix[0]![j] = j;
29
-
30
- for (let i = 1; i <= a.length; i++) {
31
- for (let j = 1; j <= b.length; j++) {
32
- const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
33
- matrix[i]![j] = Math.min(
34
- matrix[i - 1]![j]! + 1, // deletion
35
- matrix[i]![j - 1]! + 1, // insertion
36
- matrix[i - 1]![j - 1]! + indicator // substitution
37
- );
69
+ let s1 = a;
70
+ let s2 = b;
71
+ if (s1.length > s2.length) {
72
+ const tmp = s1;
73
+ s1 = s2;
74
+ s2 = tmp;
75
+ }
76
+ const m = s1.length;
77
+ const n = s2.length;
78
+ if (m === 0) return n;
79
+ let prev = new Int32Array(m + 1);
80
+ let curr = new Int32Array(m + 1);
81
+ for (let j = 0; j <= m; j++) prev[j] = j;
82
+
83
+ for (let i = 1; i <= n; i++) {
84
+ curr[0] = i;
85
+ const ch2 = s2.charCodeAt(i - 1);
86
+ for (let j = 1; j <= m; j++) {
87
+ const cost = s1.charCodeAt(j - 1) === ch2 ? 0 : 1;
88
+ const del = prev[j]! + 1;
89
+ const ins = curr[j - 1]! + 1;
90
+ const sub = prev[j - 1]! + cost;
91
+ curr[j] = del < ins ? (del < sub ? del : sub) : (ins < sub ? ins : sub);
38
92
  }
93
+ const swap = prev;
94
+ prev = curr;
95
+ curr = swap;
39
96
  }
40
- return matrix[a.length]![b.length]!;
97
+ return prev[m]!;
41
98
  }
42
99
 
43
100
  function calculateConfidence(original: string, match: string): number {
44
- const dist = getLevenshteinDistance(original, match);
45
101
  const maxLen = Math.max(original.length, match.length);
46
102
  if (maxLen === 0) return 100;
103
+ if (maxLen > MAX_FUZZY_CHARS) return 0;
104
+ // Impossible to reach 90% confidence when length difference alone exceeds 10%
105
+ if (Math.abs(original.length - match.length) / maxLen > 0.1) return 0;
106
+ const dist = getLevenshteinDistance(original, match);
47
107
  return ((maxLen - dist) / maxLen) * 100;
48
108
  }
49
109
 
@@ -71,7 +131,7 @@ export const fsEdit = {
71
131
  }
72
132
  },
73
133
 
74
- async execute(args: FsEditArgs): Promise<FsEditResult> {
134
+ async execute(args: FsEditArgs, context?: FsEditContext): Promise<FsEditResult> {
75
135
  try {
76
136
  if (!args || typeof args !== 'object') {
77
137
  return { success: false, error: 'fs_edit requires an object with path and edits array.' };
@@ -83,27 +143,39 @@ export const fsEdit = {
83
143
  return { success: false, error: 'fs_edit requires a non-empty edits array.' };
84
144
  }
85
145
 
86
- const targetPath = args.path.trim();
87
- const target = targetPath.startsWith('~/') || targetPath.startsWith('~\\')
88
- ? path.join(os.homedir(), targetPath.slice(2))
89
- : path.resolve(targetPath);
90
-
146
+ const expandedPath = expandHome(args.path);
147
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
148
+ || context?.workspaceRoot?.trim()
149
+ || context?.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)?.trim();
150
+ const target = path.isAbsolute(expandedPath)
151
+ ? path.resolve(expandedPath)
152
+ : path.resolve(baseRoot ? path.resolve(expandHome(baseRoot)) : process.cwd(), expandedPath);
153
+
154
+ const stat = await fs.lstat(target);
155
+ if (stat.isSymbolicLink()) {
156
+ return { success: false, error: `Refusing to edit symbolic link ${target}; edit a regular file in the selected workspace.` };
157
+ }
158
+ if (!stat.isFile()) {
159
+ return { success: false, error: `Target is not a regular file: ${target}` };
160
+ }
161
+ await assertWithinEditScope(target, context);
162
+ const originalMode = stat.mode & 0o777;
91
163
  const originalContent = await fs.readFile(target, 'utf8');
92
164
  let workingContent = originalContent;
93
165
  let replacements = 0;
94
166
 
95
167
  for (let i = 0; i < args.edits.length; i++) {
96
168
  const edit = args.edits[i];
97
- if (!edit || typeof edit.searchContent !== 'string' || typeof edit.replaceContent !== 'string') {
169
+ if (!edit || typeof edit.searchContent !== 'string' || edit.searchContent.length === 0 || typeof edit.replaceContent !== 'string') {
98
170
  return {
99
171
  success: false,
100
- error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid searchContent or replaceContent strings. Rollback complete.`
172
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid non-empty searchContent or replaceContent strings. Rollback complete.`
101
173
  };
102
174
  }
103
175
 
104
176
  // Try exact match first
105
177
  if (workingContent.includes(edit.searchContent)) {
106
- workingContent = workingContent.replace(edit.searchContent, edit.replaceContent);
178
+ workingContent = workingContent.replace(edit.searchContent, () => edit.replaceContent);
107
179
  replacements++;
108
180
  continue;
109
181
  }
@@ -111,7 +183,7 @@ export const fsEdit = {
111
183
  // Fuzzy Match Fallback
112
184
  const lines = workingContent.split('\n');
113
185
  const oldLines = edit.searchContent.split('\n');
114
- let bestMatch: string | null = null;
186
+ let bestIndex = -1;
115
187
  let highestConfidence = 0;
116
188
 
117
189
  for (let j = 0; j <= lines.length - oldLines.length; j++) {
@@ -119,12 +191,13 @@ export const fsEdit = {
119
191
  const conf = calculateConfidence(edit.searchContent, chunk);
120
192
  if (conf > highestConfidence) {
121
193
  highestConfidence = conf;
122
- bestMatch = chunk;
194
+ bestIndex = j;
123
195
  }
124
196
  }
125
197
 
126
- if (highestConfidence >= 90 && bestMatch) {
127
- workingContent = workingContent.replace(bestMatch, edit.replaceContent);
198
+ if (highestConfidence >= 90 && bestIndex !== -1) {
199
+ lines.splice(bestIndex, oldLines.length, edit.replaceContent);
200
+ workingContent = lines.join('\n');
128
201
  replacements++;
129
202
  } else {
130
203
  return {
@@ -134,8 +207,8 @@ export const fsEdit = {
134
207
  }
135
208
  }
136
209
 
137
- // Commit the transaction atomically
138
- atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
210
+ // Commit the transaction atomically, preserving original file permissions
211
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8', mode: originalMode });
139
212
  return { success: true, output: `Transaction Success: ${replacements} replacement(s) safely applied to ${args.path}` };
140
213
  } catch (e: unknown) {
141
214
  return { success: false, error: e instanceof Error ? e.message : String(e) };
@@ -51,11 +51,14 @@ function isMatch(filename, keywords, extensions, fuzzyMatch) {
51
51
  lowerKw.length <= MAX_FUZZY_LENGTH &&
52
52
  lowerFilename.length <= MAX_FUZZY_LENGTH) {
53
53
  const maxDistance = Math.floor(lowerKw.length / 4);
54
- const winLen = lowerKw.length + 1;
55
- for (let i = 0; i <= lowerFilename.length - lowerKw.length + 1; i++) {
56
- const chunk = lowerFilename.slice(i, i + winLen);
57
- if (levenshteinDistance(chunk, lowerKw) <= maxDistance)
58
- return true;
54
+ const winLengths = [lowerKw.length, lowerKw.length + 1, Math.max(1, lowerKw.length - 1)];
55
+ for (const winLen of winLengths) {
56
+ const maxStart = Math.max(0, lowerFilename.length - winLen);
57
+ for (let i = 0; i <= maxStart; i++) {
58
+ const chunk = lowerFilename.slice(i, i + winLen);
59
+ if (levenshteinDistance(chunk, lowerKw) <= maxDistance)
60
+ return true;
61
+ }
59
62
  }
60
63
  }
61
64
  }
@@ -82,10 +82,13 @@ function isMatch(
82
82
  lowerFilename.length <= MAX_FUZZY_LENGTH
83
83
  ) {
84
84
  const maxDistance = Math.floor(lowerKw.length / 4);
85
- const winLen = lowerKw.length + 1;
86
- for (let i = 0; i <= lowerFilename.length - lowerKw.length + 1; i++) {
87
- const chunk = lowerFilename.slice(i, i + winLen);
88
- if (levenshteinDistance(chunk, lowerKw) <= maxDistance) return true;
85
+ const winLengths = [lowerKw.length, lowerKw.length + 1, Math.max(1, lowerKw.length - 1)];
86
+ for (const winLen of winLengths) {
87
+ const maxStart = Math.max(0, lowerFilename.length - winLen);
88
+ for (let i = 0; i <= maxStart; i++) {
89
+ const chunk = lowerFilename.slice(i, i + winLen);
90
+ if (levenshteinDistance(chunk, lowerKw) <= maxDistance) return true;
91
+ }
89
92
  }
90
93
  }
91
94
  }
@@ -2,14 +2,71 @@ import fs from 'node:fs';
2
2
  import readline from 'node:readline';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
+ import { isOutputRecoveryRead } from '../outputRecovery.js';
6
+ function expandHomePath(raw) {
7
+ const trimmed = raw.trim();
8
+ if (trimmed === '~')
9
+ return os.homedir();
10
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
11
+ return path.join(os.homedir(), trimmed.slice(2));
12
+ }
13
+ return trimmed;
14
+ }
15
+ function isWithinRoot(root, candidate) {
16
+ const rel = path.relative(root, candidate);
17
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
18
+ }
19
+ function checkReadScope(target, context) {
20
+ if (!context || context.grantAllAccess === true)
21
+ return null;
22
+ const configured = Array.isArray(context.workspacePaths)
23
+ ? context.workspacePaths.filter((p) => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
24
+ : [];
25
+ const roots = configured.length > 0
26
+ ? configured
27
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
28
+ .filter((p) => typeof p === 'string' && p.trim().length > 0)
29
+ .map(p => p.trim());
30
+ if (roots.length === 0)
31
+ return null;
32
+ if (Array.isArray(context.parentLoop?.messages)) {
33
+ const knownSpills = new Set();
34
+ for (const msg of context.parentLoop.messages) {
35
+ if (typeof msg?.spillPath === 'string' && msg.spillPath.trim()) {
36
+ knownSpills.add(path.resolve(msg.spillPath));
37
+ }
38
+ }
39
+ if (knownSpills.size > 0 && isOutputRecoveryRead('fs_read', target, knownSpills)) {
40
+ return null;
41
+ }
42
+ }
43
+ let realTarget;
44
+ try {
45
+ realTarget = fs.realpathSync(target);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ for (const root of roots) {
51
+ try {
52
+ const realRoot = fs.realpathSync(path.resolve(expandHomePath(root)));
53
+ if (isWithinRoot(realRoot, realTarget))
54
+ return null;
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ }
60
+ return `Target resolves outside the selected workspace: ${target}`;
61
+ }
5
62
  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
63
  /** Fast Binary Detection: inspect the first 1024 bytes for a null byte. */
7
64
  async function isBinary(filePath) {
65
+ let fd = null;
8
66
  try {
9
- const fd = await fs.promises.open(filePath, 'r');
67
+ fd = await fs.promises.open(filePath, 'r');
10
68
  const buffer = Buffer.alloc(1024);
11
69
  const { bytesRead } = await fd.read(buffer, 0, 1024, 0);
12
- await fd.close();
13
70
  for (let i = 0; i < bytesRead; i++) {
14
71
  if (buffer[i] === 0)
15
72
  return true;
@@ -19,6 +76,11 @@ async function isBinary(filePath) {
19
76
  catch {
20
77
  return false;
21
78
  }
79
+ finally {
80
+ if (fd) {
81
+ await fd.close().catch(() => { });
82
+ }
83
+ }
22
84
  }
23
85
  export const fsRead = {
24
86
  schema: {
@@ -34,15 +96,32 @@ export const fsRead = {
34
96
  required: ['path']
35
97
  }
36
98
  },
37
- async execute(args) {
99
+ async execute(args, context) {
38
100
  try {
39
101
  if (!args || typeof args.path !== 'string' || !args.path.trim()) {
40
102
  return { success: false, error: 'Missing required parameter: path' };
41
103
  }
42
- const target = args.path.replace(/^~\//, os.homedir() + '/');
104
+ const expanded = expandHomePath(args.path);
105
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
106
+ || context?.workspaceRoot?.trim()
107
+ || context?.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)?.trim();
108
+ const target = path.isAbsolute(expanded)
109
+ ? path.resolve(expanded)
110
+ : path.resolve(baseRoot ? path.resolve(expandHomePath(baseRoot)) : process.cwd(), expanded);
43
111
  if (!fs.existsSync(target)) {
44
112
  return { success: false, error: 'File does not exist.' };
45
113
  }
114
+ const scopeErr = checkReadScope(target, context);
115
+ if (scopeErr) {
116
+ return { success: false, error: scopeErr };
117
+ }
118
+ const targetStat = fs.statSync(target);
119
+ if (targetStat.isDirectory()) {
120
+ return { success: false, error: `Path is a directory, not a file: ${target}. Use fs_list to inspect directories.` };
121
+ }
122
+ if (!targetStat.isFile()) {
123
+ return { success: false, error: `Path is not a regular readable file: ${target}` };
124
+ }
46
125
  const ext = path.extname(target).toLowerCase();
47
126
  const isKnownBinaryExt = BINARY_EXTENSIONS.test(ext);
48
127
  // Fast check for binary media/executables to prevent token context blowup
@@ -64,28 +143,55 @@ export const fsRead = {
64
143
  : `Cannot read binary file '${path.basename(target)}' as plain text. File size: ${sizeStr}.`
65
144
  };
66
145
  }
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;
146
+ const start = typeof args.startLine === 'number' && Number.isFinite(args.startLine) && args.startLine > 0 ? Math.floor(args.startLine) : 1;
147
+ let end = typeof args.endLine === 'number' && Number.isFinite(args.endLine) && args.endLine >= start ? Math.floor(args.endLine) : start + 799;
69
148
  // Mandatory Paging Limit: at most 800 lines per read to preserve context
70
149
  if (end - start + 1 > 800) {
71
150
  end = start + 799;
72
151
  }
152
+ const MAX_READ_OUTPUT_CHARS = 512 * 1024;
73
153
  let currentLine = 1;
74
154
  const outputLines = [];
155
+ let collectedChars = 0;
156
+ let charTruncated = false;
75
157
  let totalLines = 0;
158
+ const stream = fs.createReadStream(target);
76
159
  const rl = readline.createInterface({
77
- input: fs.createReadStream(target),
160
+ input: stream,
78
161
  crlfDelay: Infinity
79
162
  });
80
- for await (const line of rl) {
81
- totalLines++;
82
- if (currentLine >= start && currentLine <= end) {
83
- outputLines.push(line);
163
+ try {
164
+ for await (const line of rl) {
165
+ if (context?.signal?.aborted) {
166
+ return { success: false, error: 'File read aborted.' };
167
+ }
168
+ totalLines++;
169
+ if (currentLine >= start && currentLine <= end && !charTruncated) {
170
+ const remaining = MAX_READ_OUTPUT_CHARS - collectedChars;
171
+ if (line.length <= remaining) {
172
+ outputLines.push(line);
173
+ collectedChars += line.length + 1;
174
+ }
175
+ else {
176
+ if (remaining > 0) {
177
+ outputLines.push(line.slice(0, remaining));
178
+ }
179
+ collectedChars = MAX_READ_OUTPUT_CHARS;
180
+ charTruncated = true;
181
+ }
182
+ }
183
+ currentLine++;
84
184
  }
85
- currentLine++;
185
+ }
186
+ finally {
187
+ rl.close();
188
+ stream.destroy();
86
189
  }
87
190
  let finalOutput = outputLines.join('\n');
88
- if (totalLines > end) {
191
+ if (charTruncated) {
192
+ finalOutput += `\n\n[WARNING: Output truncated at ${MAX_READ_OUTPUT_CHARS} characters. Narrow the line range or inspect specific sections.]`;
193
+ }
194
+ else if (totalLines > end) {
89
195
  finalOutput += `\n\n[WARNING: File truncated at line ${end} out of ${totalLines}. Use { startLine: ${end + 1}, endLine: ${end + 800} } to read more.]`;
90
196
  }
91
197
  return { success: true, output: finalOutput };
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import readline from 'node:readline';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
+ import { isOutputRecoveryRead } from '../outputRecovery.js';
5
6
 
6
7
  export interface FsReadArgs {
7
8
  path: string;
@@ -9,6 +10,70 @@ export interface FsReadArgs {
9
10
  endLine?: number;
10
11
  }
11
12
 
13
+ export interface FsReadContext {
14
+ workspaceRoot?: string;
15
+ workspacePaths?: string[];
16
+ grantAllAccess?: boolean;
17
+ signal?: AbortSignal;
18
+ parentLoop?: {
19
+ workspaceRoot?: string;
20
+ messages?: ReadonlyArray<{ spillPath?: unknown }>;
21
+ };
22
+ }
23
+
24
+ function expandHomePath(raw: string): string {
25
+ const trimmed = raw.trim();
26
+ if (trimmed === '~') return os.homedir();
27
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
28
+ return path.join(os.homedir(), trimmed.slice(2));
29
+ }
30
+ return trimmed;
31
+ }
32
+
33
+ function isWithinRoot(root: string, candidate: string): boolean {
34
+ const rel = path.relative(root, candidate);
35
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
36
+ }
37
+
38
+ function checkReadScope(target: string, context?: FsReadContext): string | null {
39
+ if (!context || context.grantAllAccess === true) return null;
40
+ const configured = Array.isArray(context.workspacePaths)
41
+ ? context.workspacePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
42
+ : [];
43
+ const roots = configured.length > 0
44
+ ? configured
45
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
46
+ .filter((p): p is string => typeof p === 'string' && p.trim().length > 0)
47
+ .map(p => p.trim());
48
+ if (roots.length === 0) return null;
49
+ if (Array.isArray(context.parentLoop?.messages)) {
50
+ const knownSpills = new Set<string>();
51
+ for (const msg of context.parentLoop.messages) {
52
+ if (typeof msg?.spillPath === 'string' && msg.spillPath.trim()) {
53
+ knownSpills.add(path.resolve(msg.spillPath));
54
+ }
55
+ }
56
+ if (knownSpills.size > 0 && isOutputRecoveryRead('fs_read', target, knownSpills)) {
57
+ return null;
58
+ }
59
+ }
60
+ let realTarget: string;
61
+ try {
62
+ realTarget = fs.realpathSync(target);
63
+ } catch {
64
+ return null;
65
+ }
66
+ for (const root of roots) {
67
+ try {
68
+ const realRoot = fs.realpathSync(path.resolve(expandHomePath(root)));
69
+ if (isWithinRoot(realRoot, realTarget)) return null;
70
+ } catch {
71
+ continue;
72
+ }
73
+ }
74
+ return `Target resolves outside the selected workspace: ${target}`;
75
+ }
76
+
12
77
  export interface FsReadResult {
13
78
  success: boolean;
14
79
  output?: string;
@@ -20,11 +85,11 @@ const BINARY_EXTENSIONS = /\.(png|jpe?g|webp|gif|svg|bmp|ico|blend\d?|glb|gltf|w
20
85
 
21
86
  /** Fast Binary Detection: inspect the first 1024 bytes for a null byte. */
22
87
  async function isBinary(filePath: string): Promise<boolean> {
88
+ let fd: fs.promises.FileHandle | null = null;
23
89
  try {
24
- const fd = await fs.promises.open(filePath, 'r');
90
+ fd = await fs.promises.open(filePath, 'r');
25
91
  const buffer = Buffer.alloc(1024);
26
92
  const { bytesRead } = await fd.read(buffer, 0, 1024, 0);
27
- await fd.close();
28
93
 
29
94
  for (let i = 0; i < bytesRead; i++) {
30
95
  if (buffer[i] === 0) return true;
@@ -32,6 +97,10 @@ async function isBinary(filePath: string): Promise<boolean> {
32
97
  return false;
33
98
  } catch {
34
99
  return false;
100
+ } finally {
101
+ if (fd) {
102
+ await fd.close().catch(() => {});
103
+ }
35
104
  }
36
105
  }
37
106
 
@@ -50,17 +119,35 @@ export const fsRead = {
50
119
  }
51
120
  },
52
121
 
53
- async execute(args: FsReadArgs): Promise<FsReadResult> {
122
+ async execute(args: FsReadArgs, context?: FsReadContext): Promise<FsReadResult> {
54
123
  try {
55
124
  if (!args || typeof args.path !== 'string' || !args.path.trim()) {
56
125
  return { success: false, error: 'Missing required parameter: path' };
57
126
  }
58
127
 
59
- const target = args.path.replace(/^~\//, os.homedir() + '/');
128
+ const expanded = expandHomePath(args.path);
129
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
130
+ || context?.workspaceRoot?.trim()
131
+ || context?.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)?.trim();
132
+ const target = path.isAbsolute(expanded)
133
+ ? path.resolve(expanded)
134
+ : path.resolve(baseRoot ? path.resolve(expandHomePath(baseRoot)) : process.cwd(), expanded);
60
135
 
61
136
  if (!fs.existsSync(target)) {
62
137
  return { success: false, error: 'File does not exist.' };
63
138
  }
139
+ const scopeErr = checkReadScope(target, context);
140
+ if (scopeErr) {
141
+ return { success: false, error: scopeErr };
142
+ }
143
+
144
+ const targetStat = fs.statSync(target);
145
+ if (targetStat.isDirectory()) {
146
+ return { success: false, error: `Path is a directory, not a file: ${target}. Use fs_list to inspect directories.` };
147
+ }
148
+ if (!targetStat.isFile()) {
149
+ return { success: false, error: `Path is not a regular readable file: ${target}` };
150
+ }
64
151
 
65
152
  const ext = path.extname(target).toLowerCase();
66
153
  const isKnownBinaryExt = BINARY_EXTENSIONS.test(ext);
@@ -85,34 +172,58 @@ export const fsRead = {
85
172
  };
86
173
  }
87
174
 
88
- const start = typeof args.startLine === 'number' && args.startLine > 0 ? Math.floor(args.startLine) : 1;
89
- let end = typeof args.endLine === 'number' && args.endLine >= start ? Math.floor(args.endLine) : start + 799;
175
+ const start = typeof args.startLine === 'number' && Number.isFinite(args.startLine) && args.startLine > 0 ? Math.floor(args.startLine) : 1;
176
+ let end = typeof args.endLine === 'number' && Number.isFinite(args.endLine) && args.endLine >= start ? Math.floor(args.endLine) : start + 799;
90
177
 
91
178
  // Mandatory Paging Limit: at most 800 lines per read to preserve context
92
179
  if (end - start + 1 > 800) {
93
180
  end = start + 799;
94
181
  }
95
182
 
183
+ const MAX_READ_OUTPUT_CHARS = 512 * 1024;
96
184
  let currentLine = 1;
97
185
  const outputLines: string[] = [];
186
+ let collectedChars = 0;
187
+ let charTruncated = false;
98
188
  let totalLines = 0;
99
189
 
190
+ const stream = fs.createReadStream(target);
100
191
  const rl = readline.createInterface({
101
- input: fs.createReadStream(target),
192
+ input: stream,
102
193
  crlfDelay: Infinity
103
194
  });
104
195
 
105
- for await (const line of rl) {
106
- totalLines++;
107
- if (currentLine >= start && currentLine <= end) {
108
- outputLines.push(line);
196
+ try {
197
+ for await (const line of rl) {
198
+ if (context?.signal?.aborted) {
199
+ return { success: false, error: 'File read aborted.' };
200
+ }
201
+ totalLines++;
202
+ if (currentLine >= start && currentLine <= end && !charTruncated) {
203
+ const remaining = MAX_READ_OUTPUT_CHARS - collectedChars;
204
+ if (line.length <= remaining) {
205
+ outputLines.push(line);
206
+ collectedChars += line.length + 1;
207
+ } else {
208
+ if (remaining > 0) {
209
+ outputLines.push(line.slice(0, remaining));
210
+ }
211
+ collectedChars = MAX_READ_OUTPUT_CHARS;
212
+ charTruncated = true;
213
+ }
214
+ }
215
+ currentLine++;
109
216
  }
110
- currentLine++;
217
+ } finally {
218
+ rl.close();
219
+ stream.destroy();
111
220
  }
112
221
 
113
222
  let finalOutput = outputLines.join('\n');
114
223
 
115
- if (totalLines > end) {
224
+ if (charTruncated) {
225
+ finalOutput += `\n\n[WARNING: Output truncated at ${MAX_READ_OUTPUT_CHARS} characters. Narrow the line range or inspect specific sections.]`;
226
+ } else if (totalLines > end) {
116
227
  finalOutput += `\n\n[WARNING: File truncated at line ${end} out of ${totalLines}. Use { startLine: ${end + 1}, endLine: ${end + 800} } to read more.]`;
117
228
  }
118
229
 
@@ -37,9 +37,14 @@ async function physicalTarget(target) {
37
37
  async function checkScope(target, context) {
38
38
  if (!context || context.grantAllAccess === true)
39
39
  return;
40
- const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
41
- ? context.workspacePaths
42
- : [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter((value) => typeof value === 'string' && value.length > 0);
40
+ const configuredPaths = Array.isArray(context.workspacePaths)
41
+ ? context.workspacePaths.filter((value) => typeof value === 'string' && value.trim().length > 0).map(value => value.trim())
42
+ : [];
43
+ const roots = configuredPaths.length > 0
44
+ ? configuredPaths
45
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
46
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
47
+ .map(value => value.trim());
43
48
  if (roots.length === 0)
44
49
  return;
45
50
  const physical = await physicalTarget(target);
@@ -81,10 +86,17 @@ export const fsWrite = {
81
86
  if (typeof args.content !== 'string') {
82
87
  return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
83
88
  }
84
- if (args.path.endsWith('/') || args.path.endsWith('\\')) {
89
+ const trimmedPath = args.path.trim();
90
+ if (trimmedPath.endsWith('/') || trimmedPath.endsWith('\\')) {
85
91
  return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
86
92
  }
87
- const target = path.resolve(expandHome(args.path.trim()));
93
+ const expandedPath = expandHome(trimmedPath);
94
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
95
+ || context?.workspaceRoot?.trim()
96
+ || context?.workspacePaths?.find((value) => typeof value === 'string' && value.trim().length > 0)?.trim();
97
+ const target = path.isAbsolute(expandedPath)
98
+ ? path.resolve(expandedPath)
99
+ : path.resolve(baseRoot ? path.resolve(expandHome(baseRoot)) : process.cwd(), expandedPath);
88
100
  let temporary = '';
89
101
  try {
90
102
  await checkScope(target, context);