@causyne/agent 1.20.120 → 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 (276) 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 +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -12,19 +12,46 @@
12
12
  * Authorship: Strict TypeScript (Causyne Agent).
13
13
  */
14
14
 
15
+ import fs from 'node:fs';
15
16
  import os from 'node:os';
16
17
  import path from 'node:path';
17
18
  import { episodicStore } from '../memory/episodicStore.js';
18
19
  import { foldSourceFileOutline } from '../memory/symbolFolder.js';
19
20
  import type { ObservationType } from '../memory/episodicTypes.js';
20
21
 
22
+ const MAX_OUTLINE_FILE_BYTES = 2 * 1024 * 1024;
23
+
21
24
  interface MemoryRecallContext {
22
25
  workspaceRoot?: string | undefined;
26
+ workspacePaths?: string[] | undefined;
27
+ grantAllAccess?: boolean | undefined;
28
+ isPathAllowed?: ((targetPath: string) => boolean) | undefined;
23
29
  parentLoop?: {
24
30
  workspaceRoot?: string | undefined;
31
+ sandbox?: {
32
+ isPathAllowed?: ((targetPath: string) => boolean) | undefined;
33
+ } | undefined;
25
34
  } | undefined;
26
35
  }
27
36
 
37
+ function safeOptionalInt(value: unknown): number | undefined {
38
+ return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined;
39
+ }
40
+
41
+ function expandOutlineHome(raw: string): string {
42
+ const trimmed = raw.trim();
43
+ if (trimmed === '~') return os.homedir();
44
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
45
+ return path.join(os.homedir(), trimmed.slice(2));
46
+ }
47
+ return trimmed;
48
+ }
49
+
50
+ function isWithinOutlineRoot(root: string, candidate: string): boolean {
51
+ const rel = path.relative(root, candidate);
52
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
53
+ }
54
+
28
55
  interface MemoryRecallArgs {
29
56
  action?: 'search' | 'timeline' | 'get' | 'outline' | 'stats' | undefined;
30
57
  query?: string | undefined;
@@ -106,24 +133,27 @@ export const memoryRecall = {
106
133
  const args = (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)
107
134
  ? rawArgs
108
135
  : {}) as MemoryRecallArgs;
109
- const rawFileCandidate = String(
110
- args.filePath ?? args.path ?? args.file_path ?? args.filepath ?? args.target ?? ''
111
- ).trim();
136
+ const rawCandidateValue = args.filePath ?? args.path ?? args.file_path ?? args.filepath ?? args.target;
137
+ const rawFileCandidate = typeof rawCandidateValue === 'string' ? rawCandidateValue.trim() : '';
112
138
  const inferredAction = args.action
113
139
  ?? (rawFileCandidate ? 'outline' : undefined)
114
140
  ?? (args.anchorId !== undefined ? 'timeline' : undefined)
115
141
  ?? (Array.isArray(args.ids) && args.ids.length > 0 ? 'get' : undefined)
116
142
  ?? 'search';
117
143
  const action = inferredAction;
118
- const workspace = context.parentLoop?.workspaceRoot ?? context.workspaceRoot ?? process.cwd();
144
+ const workspace = context?.parentLoop?.workspaceRoot
145
+ ?? context?.workspaceRoot
146
+ ?? context?.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)
147
+ ?? process.cwd();
148
+ const safeQuery = typeof args.query === 'string' ? args.query : undefined;
119
149
 
120
150
  try {
121
151
  if (action === 'search') {
122
152
  const res = episodicStore.searchIndex({
123
- query: args.query,
153
+ query: safeQuery,
124
154
  workspace,
125
155
  type: args.type,
126
- limit: args.limit,
156
+ limit: safeOptionalInt(args.limit),
127
157
  workspaceOnly: args.workspaceOnly
128
158
  });
129
159
  const formatted = res.results.length === 0
@@ -151,8 +181,8 @@ export const memoryRecall = {
151
181
  const windowResult = episodicStore.getTimelineWindow({
152
182
  anchorId: args.anchorId,
153
183
  workspace,
154
- depthBefore: args.depthBefore,
155
- depthAfter: args.depthAfter
184
+ depthBefore: safeOptionalInt(args.depthBefore),
185
+ depthAfter: safeOptionalInt(args.depthAfter)
156
186
  });
157
187
  if (!windowResult.anchor) {
158
188
  return {
@@ -212,13 +242,40 @@ export const memoryRecall = {
212
242
  if (!rawFileCandidate) {
213
243
  return { success: false, error: 'Missing required parameter "filePath" for action="outline".' };
214
244
  }
215
- const expanded = rawFileCandidate.startsWith('~/')
216
- ? path.join(os.homedir(), rawFileCandidate.slice(2))
217
- : rawFileCandidate;
245
+ const expanded = expandOutlineHome(rawFileCandidate);
218
246
  const targetPath = path.isAbsolute(expanded)
219
- ? expanded
247
+ ? path.resolve(expanded)
220
248
  : path.resolve(workspace, expanded);
221
- const outline = foldSourceFileOutline(targetPath, args.query);
249
+ const pathPolicy = context?.parentLoop?.sandbox ?? context;
250
+ if (context?.grantAllAccess !== true) {
251
+ if (typeof pathPolicy?.isPathAllowed === 'function' && !pathPolicy.isPathAllowed(targetPath)) {
252
+ return { success: false, error: `Path outside allowed workspace: ${targetPath}` };
253
+ }
254
+ const configuredRoots = Array.isArray(context?.workspacePaths)
255
+ ? context.workspacePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0)
256
+ : [context?.parentLoop?.workspaceRoot, context?.workspaceRoot].filter((p): p is string => typeof p === 'string' && p.trim().length > 0);
257
+ if (configuredRoots.length > 0) {
258
+ const realTarget = fs.realpathSync(targetPath);
259
+ const allowed = configuredRoots.some((root) => {
260
+ try {
261
+ return isWithinOutlineRoot(fs.realpathSync(path.resolve(expandOutlineHome(root))), realTarget);
262
+ } catch {
263
+ return false;
264
+ }
265
+ });
266
+ if (!allowed) {
267
+ return { success: false, error: `Path outside allowed workspace: ${targetPath}` };
268
+ }
269
+ }
270
+ }
271
+ const stat = fs.statSync(targetPath);
272
+ if (!stat.isFile()) {
273
+ return { success: false, error: `Outline target is not a regular file: ${targetPath}` };
274
+ }
275
+ if (stat.size > MAX_OUTLINE_FILE_BYTES) {
276
+ return { success: false, error: `File exceeds ${MAX_OUTLINE_FILE_BYTES / (1024 * 1024)} MB outline limit: ${targetPath}` };
277
+ }
278
+ const outline = foldSourceFileOutline(targetPath, safeQuery);
222
279
  return {
223
280
  success: true,
224
281
  action: 'outline',
@@ -28,20 +28,33 @@ export const memoryWrite = {
28
28
  }
29
29
  },
30
30
  execute: async (args, dependencies) => {
31
- if (!args || (!args.fact && !args.creativePattern)) {
31
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
32
32
  return { success: false, error: "Missing 'fact' or 'creativePattern' parameter." };
33
33
  }
34
- if (!args.fact && args.creativePattern) {
35
- const cp = args.creativePattern;
36
- const project = cp.project || 'project';
37
- const approach = cp.designApproach ? ` ${cp.designApproach}` : '';
38
- const palette = cp.colorPalette ? ` with ${cp.colorPalette}` : '';
39
- const fonts = cp.fonts ? ` (${cp.fonts})` : '';
40
- args.fact = `Creative pattern for ${project}:${approach}${palette}${fonts}`.trim();
34
+ if (args.fact !== undefined && typeof args.fact !== 'string') {
35
+ return { success: false, error: "'fact' parameter must be a string." };
36
+ }
37
+ if (args.creativePattern !== undefined &&
38
+ (args.creativePattern === null || typeof args.creativePattern !== 'object' || Array.isArray(args.creativePattern))) {
39
+ return { success: false, error: "'creativePattern' parameter must be an object." };
40
+ }
41
+ const rawFact = typeof args.fact === 'string' ? args.fact.trim() : '';
42
+ const cp = args.creativePattern;
43
+ let fact = rawFact;
44
+ if (!fact && cp) {
45
+ const project = typeof cp.project === 'string' && cp.project.trim() ? cp.project.trim() : 'project';
46
+ const approach = typeof cp.designApproach === 'string' && cp.designApproach.trim() ? ` ${cp.designApproach.trim()}` : '';
47
+ const palette = typeof cp.colorPalette === 'string' && cp.colorPalette.trim() ? ` with ${cp.colorPalette.trim()}` : '';
48
+ const fonts = typeof cp.fonts === 'string' && cp.fonts.trim() ? ` (${cp.fonts.trim()})` : '';
49
+ if (approach || palette || fonts || (typeof cp.project === 'string' && cp.project.trim())) {
50
+ fact = `Creative pattern for ${project}:${approach}${palette}${fonts}`.trim();
51
+ }
52
+ }
53
+ if (!fact) {
54
+ return { success: false, error: "Missing non-empty 'fact' or 'creativePattern' parameter." };
41
55
  }
42
56
  try {
43
57
  const memory = getMemory();
44
- const fact = String(args.fact).trim();
45
58
  const workspace = dependencies?.parentLoop?.workspaceRoot || dependencies?.workspaceRoot;
46
59
  const { memory: updated, alreadyKnown } = recordScopedFact(memory, fact, {
47
60
  workspace,
@@ -51,13 +64,13 @@ export const memoryWrite = {
51
64
  saveMemory(updated);
52
65
  }
53
66
  let creativeSaved = false;
54
- if (args.creativePattern && args.creativePattern.designApproach) {
67
+ if (cp && typeof cp.designApproach === 'string' && cp.designApproach.trim()) {
55
68
  try {
56
69
  await cortexDb.saveCreativePattern({
57
- project: args.creativePattern.project || 'untitled project',
58
- designApproach: args.creativePattern.designApproach,
59
- colorPalette: args.creativePattern.colorPalette || 'unspecified',
60
- fonts: args.creativePattern.fonts || 'unspecified'
70
+ project: typeof cp.project === 'string' && cp.project.trim() ? cp.project.trim() : 'untitled project',
71
+ designApproach: cp.designApproach.trim(),
72
+ colorPalette: typeof cp.colorPalette === 'string' && cp.colorPalette.trim() ? cp.colorPalette.trim() : 'unspecified',
73
+ fonts: typeof cp.fonts === 'string' && cp.fonts.trim() ? cp.fonts.trim() : 'unspecified'
61
74
  });
62
75
  creativeSaved = true;
63
76
  }
@@ -55,22 +55,38 @@ export const memoryWrite = {
55
55
  args: MemoryWriteArgs | null | undefined,
56
56
  dependencies?: MemoryWriteDependencies
57
57
  ): Promise<{ success: boolean; output?: string; error?: string }> => {
58
- if (!args || (!args.fact && !args.creativePattern)) {
58
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
59
59
  return { success: false, error: "Missing 'fact' or 'creativePattern' parameter." };
60
60
  }
61
+ if (args.fact !== undefined && typeof args.fact !== 'string') {
62
+ return { success: false, error: "'fact' parameter must be a string." };
63
+ }
64
+ if (
65
+ args.creativePattern !== undefined &&
66
+ (args.creativePattern === null || typeof args.creativePattern !== 'object' || Array.isArray(args.creativePattern))
67
+ ) {
68
+ return { success: false, error: "'creativePattern' parameter must be an object." };
69
+ }
70
+
71
+ const rawFact = typeof args.fact === 'string' ? args.fact.trim() : '';
72
+ const cp = args.creativePattern;
73
+ let fact = rawFact;
74
+ if (!fact && cp) {
75
+ const project = typeof cp.project === 'string' && cp.project.trim() ? cp.project.trim() : 'project';
76
+ const approach = typeof cp.designApproach === 'string' && cp.designApproach.trim() ? ` ${cp.designApproach.trim()}` : '';
77
+ const palette = typeof cp.colorPalette === 'string' && cp.colorPalette.trim() ? ` with ${cp.colorPalette.trim()}` : '';
78
+ const fonts = typeof cp.fonts === 'string' && cp.fonts.trim() ? ` (${cp.fonts.trim()})` : '';
79
+ if (approach || palette || fonts || (typeof cp.project === 'string' && cp.project.trim())) {
80
+ fact = `Creative pattern for ${project}:${approach}${palette}${fonts}`.trim();
81
+ }
82
+ }
61
83
 
62
- if (!args.fact && args.creativePattern) {
63
- const cp = args.creativePattern;
64
- const project = cp.project || 'project';
65
- const approach = cp.designApproach ? ` ${cp.designApproach}` : '';
66
- const palette = cp.colorPalette ? ` with ${cp.colorPalette}` : '';
67
- const fonts = cp.fonts ? ` (${cp.fonts})` : '';
68
- args.fact = `Creative pattern for ${project}:${approach}${palette}${fonts}`.trim();
84
+ if (!fact) {
85
+ return { success: false, error: "Missing non-empty 'fact' or 'creativePattern' parameter." };
69
86
  }
70
87
 
71
88
  try {
72
89
  const memory = getMemory();
73
- const fact = String(args.fact).trim();
74
90
  const workspace = dependencies?.parentLoop?.workspaceRoot || dependencies?.workspaceRoot;
75
91
  const { memory: updated, alreadyKnown } = recordScopedFact(memory, fact, {
76
92
  workspace,
@@ -82,13 +98,13 @@ export const memoryWrite = {
82
98
  }
83
99
 
84
100
  let creativeSaved = false;
85
- if (args.creativePattern && args.creativePattern.designApproach) {
101
+ if (cp && typeof cp.designApproach === 'string' && cp.designApproach.trim()) {
86
102
  try {
87
103
  await cortexDb.saveCreativePattern({
88
- project: args.creativePattern.project || 'untitled project',
89
- designApproach: args.creativePattern.designApproach,
90
- colorPalette: args.creativePattern.colorPalette || 'unspecified',
91
- fonts: args.creativePattern.fonts || 'unspecified'
104
+ project: typeof cp.project === 'string' && cp.project.trim() ? cp.project.trim() : 'untitled project',
105
+ designApproach: cp.designApproach.trim(),
106
+ colorPalette: typeof cp.colorPalette === 'string' && cp.colorPalette.trim() ? cp.colorPalette.trim() : 'unspecified',
107
+ fonts: typeof cp.fonts === 'string' && cp.fonts.trim() ? cp.fonts.trim() : 'unspecified'
92
108
  });
93
109
  creativeSaved = true;
94
110
  } catch {
@@ -2,30 +2,87 @@ import fs from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { atomicWriteFileSync } from '../infra/atomicWriter.js';
5
+ function expandHome(value) {
6
+ const trimmed = value.trim();
7
+ if (trimmed === '~')
8
+ return os.homedir();
9
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
10
+ return path.join(os.homedir(), trimmed.slice(2));
11
+ }
12
+ return trimmed;
13
+ }
14
+ function insideRoot(root, target) {
15
+ const rel = path.relative(root, target);
16
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
17
+ }
18
+ async function assertWithinScope(target, context) {
19
+ if (!context || context.grantAllAccess === true)
20
+ return;
21
+ const configured = Array.isArray(context.workspacePaths)
22
+ ? context.workspacePaths.filter((p) => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
23
+ : [];
24
+ const roots = configured.length > 0
25
+ ? configured
26
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
27
+ .filter((p) => typeof p === 'string' && p.trim().length > 0)
28
+ .map(p => p.trim());
29
+ if (roots.length === 0)
30
+ return;
31
+ const realTarget = await fs.realpath(target);
32
+ for (const root of roots) {
33
+ try {
34
+ const realRoot = await fs.realpath(path.resolve(expandHome(root)));
35
+ if (insideRoot(realRoot, realTarget))
36
+ return;
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ }
42
+ throw new Error(`Target resolves outside the selected workspace: ${target}`);
43
+ }
44
+ const MAX_FUZZY_CHARS = 8_192;
5
45
  function getLevenshteinDistance(a, b) {
6
- const matrix = Array(a.length + 1)
7
- .fill(null)
8
- .map(() => Array(b.length + 1).fill(0));
9
- for (let i = 0; i <= a.length; i++)
10
- matrix[i][0] = i;
11
- for (let j = 0; j <= b.length; j++)
12
- matrix[0][j] = j;
13
- for (let i = 1; i <= a.length; i++) {
14
- for (let j = 1; j <= b.length; j++) {
15
- const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
16
- matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
17
- matrix[i][j - 1] + 1, // insertion
18
- matrix[i - 1][j - 1] + indicator // substitution
19
- );
46
+ let s1 = a;
47
+ let s2 = b;
48
+ if (s1.length > s2.length) {
49
+ const tmp = s1;
50
+ s1 = s2;
51
+ s2 = tmp;
52
+ }
53
+ const m = s1.length;
54
+ const n = s2.length;
55
+ if (m === 0)
56
+ return n;
57
+ let prev = new Int32Array(m + 1);
58
+ let curr = new Int32Array(m + 1);
59
+ for (let j = 0; j <= m; j++)
60
+ prev[j] = j;
61
+ for (let i = 1; i <= n; i++) {
62
+ curr[0] = i;
63
+ const ch2 = s2.charCodeAt(i - 1);
64
+ for (let j = 1; j <= m; j++) {
65
+ const cost = s1.charCodeAt(j - 1) === ch2 ? 0 : 1;
66
+ const del = prev[j] + 1;
67
+ const ins = curr[j - 1] + 1;
68
+ const sub = prev[j - 1] + cost;
69
+ curr[j] = del < ins ? (del < sub ? del : sub) : (ins < sub ? ins : sub);
20
70
  }
71
+ const swap = prev;
72
+ prev = curr;
73
+ curr = swap;
21
74
  }
22
- return matrix[a.length][b.length];
75
+ return prev[m];
23
76
  }
24
77
  function calculateConfidence(original, match) {
25
- const dist = getLevenshteinDistance(original, match);
26
78
  const maxLen = Math.max(original.length, match.length);
27
79
  if (maxLen === 0)
28
80
  return 100;
81
+ if (maxLen > MAX_FUZZY_CHARS)
82
+ return 0;
83
+ if (Math.abs(original.length - match.length) / maxLen > 0.1)
84
+ return 0;
85
+ const dist = getLevenshteinDistance(original, match);
29
86
  return ((maxLen - dist) / maxLen) * 100;
30
87
  }
31
88
  export const multiEdit = {
@@ -52,7 +109,7 @@ export const multiEdit = {
52
109
  required: ['file_path', 'edits']
53
110
  }
54
111
  },
55
- async execute(args) {
112
+ async execute(args, context) {
56
113
  try {
57
114
  if (!args || typeof args !== 'object') {
58
115
  return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
@@ -63,42 +120,55 @@ export const multiEdit = {
63
120
  if (!Array.isArray(args.edits) || args.edits.length === 0) {
64
121
  return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
65
122
  }
66
- const rawPath = args.file_path.trim();
67
- const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
68
- ? path.join(os.homedir(), rawPath.slice(2))
69
- : path.resolve(rawPath);
123
+ const expandedPath = expandHome(args.file_path);
124
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
125
+ || context?.workspaceRoot?.trim()
126
+ || context?.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)?.trim();
127
+ const target = path.isAbsolute(expandedPath)
128
+ ? path.resolve(expandedPath)
129
+ : path.resolve(baseRoot ? path.resolve(expandHome(baseRoot)) : process.cwd(), expandedPath);
130
+ const stat = await fs.lstat(target);
131
+ if (stat.isSymbolicLink()) {
132
+ return { success: false, error: `Refusing to edit symbolic link ${target}; edit a regular file in the selected workspace.` };
133
+ }
134
+ if (!stat.isFile()) {
135
+ return { success: false, error: `Target is not a regular file: ${target}` };
136
+ }
137
+ await assertWithinScope(target, context);
138
+ const originalMode = stat.mode & 0o777;
70
139
  const originalContent = await fs.readFile(target, 'utf8');
71
140
  let workingContent = originalContent;
72
141
  let replacements = 0;
73
142
  for (let i = 0; i < args.edits.length; i++) {
74
143
  const edit = args.edits[i];
75
- if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
144
+ if (!edit || typeof edit.old_string !== 'string' || edit.old_string.length === 0 || typeof edit.new_string !== 'string') {
76
145
  return {
77
146
  success: false,
78
- error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
147
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid non-empty old_string or new_string. Rollback complete.`
79
148
  };
80
149
  }
81
150
  // Try exact match first
82
151
  if (workingContent.includes(edit.old_string)) {
83
- workingContent = workingContent.replace(edit.old_string, edit.new_string);
152
+ workingContent = workingContent.replace(edit.old_string, () => edit.new_string);
84
153
  replacements++;
85
154
  continue;
86
155
  }
87
156
  // Fuzzy Match Fallback
88
157
  const lines = workingContent.split('\n');
89
158
  const oldLines = edit.old_string.split('\n');
90
- let bestMatch = null;
159
+ let bestIndex = -1;
91
160
  let highestConfidence = 0;
92
161
  for (let j = 0; j <= lines.length - oldLines.length; j++) {
93
162
  const chunk = lines.slice(j, j + oldLines.length).join('\n');
94
163
  const conf = calculateConfidence(edit.old_string, chunk);
95
164
  if (conf > highestConfidence) {
96
165
  highestConfidence = conf;
97
- bestMatch = chunk;
166
+ bestIndex = j;
98
167
  }
99
168
  }
100
- if (highestConfidence >= 90 && bestMatch) {
101
- workingContent = workingContent.replace(bestMatch, edit.new_string);
169
+ if (highestConfidence >= 90 && bestIndex !== -1) {
170
+ lines.splice(bestIndex, oldLines.length, edit.new_string);
171
+ workingContent = lines.join('\n');
102
172
  replacements++;
103
173
  }
104
174
  else {
@@ -108,8 +178,8 @@ export const multiEdit = {
108
178
  };
109
179
  }
110
180
  }
111
- // Commit the transaction atomically
112
- atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
181
+ // Commit the transaction atomically, preserving original file permissions
182
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8', mode: originalMode });
113
183
  return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
114
184
  }
115
185
  catch (e) {
@@ -19,31 +19,90 @@ export interface MultiEditResult {
19
19
  error?: string;
20
20
  }
21
21
 
22
+ export interface MultiEditContext {
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 assertWithinScope(target: string, context?: MultiEditContext): 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
+ if (Math.abs(original.length - match.length) / maxLen > 0.1) return 0;
105
+ const dist = getLevenshteinDistance(original, match);
47
106
  return ((maxLen - dist) / maxLen) * 100;
48
107
  }
49
108
 
@@ -72,7 +131,7 @@ export const multiEdit = {
72
131
  }
73
132
  },
74
133
 
75
- async execute(args: MultiEditArgs): Promise<MultiEditResult> {
134
+ async execute(args: MultiEditArgs, context?: MultiEditContext): Promise<MultiEditResult> {
76
135
  try {
77
136
  if (!args || typeof args !== 'object') {
78
137
  return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
@@ -84,27 +143,39 @@ export const multiEdit = {
84
143
  return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
85
144
  }
86
145
 
87
- const rawPath = args.file_path.trim();
88
- const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
89
- ? path.join(os.homedir(), rawPath.slice(2))
90
- : path.resolve(rawPath);
91
-
146
+ const expandedPath = expandHome(args.file_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 assertWithinScope(target, context);
162
+ const originalMode = stat.mode & 0o777;
92
163
  const originalContent = await fs.readFile(target, 'utf8');
93
164
  let workingContent = originalContent;
94
165
  let replacements = 0;
95
166
 
96
167
  for (let i = 0; i < args.edits.length; i++) {
97
168
  const edit = args.edits[i];
98
- if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
169
+ if (!edit || typeof edit.old_string !== 'string' || edit.old_string.length === 0 || typeof edit.new_string !== 'string') {
99
170
  return {
100
171
  success: false,
101
- error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
172
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid non-empty old_string or new_string. Rollback complete.`
102
173
  };
103
174
  }
104
175
 
105
176
  // Try exact match first
106
177
  if (workingContent.includes(edit.old_string)) {
107
- workingContent = workingContent.replace(edit.old_string, edit.new_string);
178
+ workingContent = workingContent.replace(edit.old_string, () => edit.new_string);
108
179
  replacements++;
109
180
  continue;
110
181
  }
@@ -112,7 +183,7 @@ export const multiEdit = {
112
183
  // Fuzzy Match Fallback
113
184
  const lines = workingContent.split('\n');
114
185
  const oldLines = edit.old_string.split('\n');
115
- let bestMatch: string | null = null;
186
+ let bestIndex = -1;
116
187
  let highestConfidence = 0;
117
188
 
118
189
  for (let j = 0; j <= lines.length - oldLines.length; j++) {
@@ -120,12 +191,13 @@ export const multiEdit = {
120
191
  const conf = calculateConfidence(edit.old_string, chunk);
121
192
  if (conf > highestConfidence) {
122
193
  highestConfidence = conf;
123
- bestMatch = chunk;
194
+ bestIndex = j;
124
195
  }
125
196
  }
126
197
 
127
- if (highestConfidence >= 90 && bestMatch) {
128
- workingContent = workingContent.replace(bestMatch, edit.new_string);
198
+ if (highestConfidence >= 90 && bestIndex !== -1) {
199
+ lines.splice(bestIndex, oldLines.length, edit.new_string);
200
+ workingContent = lines.join('\n');
129
201
  replacements++;
130
202
  } else {
131
203
  return {
@@ -135,8 +207,8 @@ export const multiEdit = {
135
207
  }
136
208
  }
137
209
 
138
- // Commit the transaction atomically
139
- atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
210
+ // Commit the transaction atomically, preserving original file permissions
211
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8', mode: originalMode });
140
212
  return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
141
213
  } catch (e: unknown) {
142
214
  return { success: false, error: e instanceof Error ? e.message : String(e) };