@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
package/src/stallGuard.ts CHANGED
@@ -101,25 +101,41 @@ export const STALL_GUARD_CYCLE_HISTORY = 64;
101
101
  export const IDENTICAL_RESULT_STUB_MIN_CHARS = 512;
102
102
  export const RESEARCH_INSPECTION_NUDGE_AFTER = 25;
103
103
 
104
- function stableSortObject(value: unknown): unknown {
104
+ function stableSortObject(value: unknown, seen = new WeakSet<object>()): unknown {
105
105
  if (value === null || typeof value !== 'object') {
106
- return value;
106
+ return typeof value === 'bigint' ? value.toString() : value;
107
107
  }
108
- if (Array.isArray(value)) {
109
- return value.map(stableSortObject);
108
+ if (seen.has(value)) {
109
+ return '[Circular]';
110
110
  }
111
- const sorted: Record<string, unknown> = {};
112
- for (const key of Object.keys(value as Record<string, unknown>).sort()) {
113
- sorted[key] = stableSortObject((value as Record<string, unknown>)[key]);
111
+ seen.add(value);
112
+ try {
113
+ if (Array.isArray(value)) {
114
+ return value.map((item) => stableSortObject(item, seen));
115
+ }
116
+ const sorted: Record<string, unknown> = {};
117
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
118
+ sorted[key] = stableSortObject((value as Record<string, unknown>)[key], seen);
119
+ }
120
+ return sorted;
121
+ } finally {
122
+ seen.delete(value);
123
+ }
124
+ }
125
+
126
+ function safeJsonStringify(value: unknown): string {
127
+ try {
128
+ return JSON.stringify(stableSortObject(value)) ?? '';
129
+ } catch {
130
+ return String(value);
114
131
  }
115
- return sorted;
116
132
  }
117
133
 
118
134
  export function canonicalToolArgs(args: unknown): string {
119
135
  if (!args || typeof args !== 'object') {
120
- return JSON.stringify(args ?? {});
136
+ return safeJsonStringify(args ?? {});
121
137
  }
122
- return JSON.stringify(stableSortObject(args));
138
+ return safeJsonStringify(args);
123
139
  }
124
140
 
125
141
  export function buildToolCallSignature(toolName: string, args: unknown): ToolCallSignature {
@@ -130,7 +146,7 @@ export function buildToolCallSignature(toolName: string, args: unknown): ToolCal
130
146
 
131
147
  export function computeResultHash(result: unknown): string {
132
148
  if (result === null || result === undefined) return '';
133
- const str = typeof result === 'string' ? result : JSON.stringify(result);
149
+ const str = typeof result === 'string' ? result : safeJsonStringify(result);
134
150
  return createHash('sha256').update(str).digest('hex').slice(0, 24);
135
151
  }
136
152
 
@@ -158,15 +174,19 @@ export class StallGuardController {
158
174
  private _haltDecision: StallGuardDecision | null = null;
159
175
 
160
176
  constructor(config?: StallGuardConfig) {
177
+ const posInt = (value: number | undefined, fallback: number): number =>
178
+ typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
179
+ const nonNegInt = (value: number | undefined, fallback: number): number =>
180
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
161
181
  this.config = {
162
182
  warningsEnabled: config?.warningsEnabled ?? true,
163
183
  hardStopEnabled: config?.hardStopEnabled ?? false,
164
- identicalCallWarnAfter: config?.identicalCallWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
165
- identicalCallHaltAfter: config?.identicalCallHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
166
- cycleWarnAfter: config?.cycleWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
167
- cycleHaltAfter: config?.cycleHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
168
- researchNudgeAfter: config?.researchNudgeAfter ?? RESEARCH_INSPECTION_NUDGE_AFTER,
169
- stubMinChars: config?.stubMinChars ?? IDENTICAL_RESULT_STUB_MIN_CHARS
184
+ identicalCallWarnAfter: posInt(config?.identicalCallWarnAfter, STALL_GUARD_IDENTICAL_CALL_THRESHOLD),
185
+ identicalCallHaltAfter: posInt(config?.identicalCallHaltAfter, STALL_GUARD_IDENTICAL_CALL_HALT),
186
+ cycleWarnAfter: posInt(config?.cycleWarnAfter, STALL_GUARD_IDENTICAL_CALL_THRESHOLD),
187
+ cycleHaltAfter: posInt(config?.cycleHaltAfter, STALL_GUARD_IDENTICAL_CALL_HALT),
188
+ researchNudgeAfter: posInt(config?.researchNudgeAfter, RESEARCH_INSPECTION_NUDGE_AFTER),
189
+ stubMinChars: nonNegInt(config?.stubMinChars, IDENTICAL_RESULT_STUB_MIN_CHARS)
170
190
  };
171
191
  }
172
192
 
@@ -283,7 +303,7 @@ export class StallGuardController {
283
303
  ): IdenticalCallObservation {
284
304
  const signature = buildToolCallSignature(toolName, args);
285
305
  const sigKey = `${signature.toolName}:${signature.argsHash}`;
286
- const resultStr = typeof result === 'string' ? result : JSON.stringify(result ?? {});
306
+ const resultStr = typeof result === 'string' ? result : safeJsonStringify(result ?? {});
287
307
  const rHash = computeResultHash(resultStr);
288
308
  const repeatable = this.isRepeatable(toolName, args);
289
309
  const mutating = this.isMutating(toolName, args);
@@ -338,7 +358,9 @@ export class StallGuardController {
338
358
  }
339
359
 
340
360
  if (!repeatable && count >= this.config.identicalCallWarnAfter) {
341
- 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.]`;
361
+ if (this.config.warningsEnabled) {
362
+ 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.]`;
363
+ }
342
364
 
343
365
  if (this.config.hardStopEnabled && count >= this.config.identicalCallHaltAfter && !this._haltDecision) {
344
366
  decision = {
@@ -358,11 +380,13 @@ export class StallGuardController {
358
380
  this._callHistory.shift();
359
381
  }
360
382
 
361
- if (!notice) {
383
+ if (!notice && !decision) {
362
384
  const cycle = this.detectIdenticalCycle();
363
385
  if (cycle) {
364
386
  const { period, laps } = cycle;
365
- 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.]`;
387
+ if (this.config.warningsEnabled) {
388
+ 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.]`;
389
+ }
366
390
 
367
391
  if (this.config.hardStopEnabled && laps >= this.config.cycleHaltAfter && !this._haltDecision) {
368
392
  decision = {
@@ -379,7 +403,7 @@ export class StallGuardController {
379
403
  }
380
404
  }
381
405
 
382
- if (!notice && !this._researchNudgeEmitted && this._distinctInspectionCount >= this.config.researchNudgeAfter) {
406
+ if (this.config.warningsEnabled && !notice && !this._researchNudgeEmitted && this._distinctInspectionCount >= this.config.researchNudgeAfter) {
383
407
  this._researchNudgeEmitted = true;
384
408
  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.]`;
385
409
  }
@@ -38,12 +38,14 @@ function boundedMessage(value) {
38
38
  if (typeof content === 'string') {
39
39
  content = boundedText(content, MAX_CONTENT_BYTES);
40
40
  }
41
- else {
41
+ else if (content !== undefined && content !== null) {
42
42
  try {
43
43
  const serialized = JSON.stringify(content);
44
- content = Buffer.byteLength(serialized, 'utf8') <= MAX_CONTENT_BYTES
45
- ? JSON.parse(serialized)
46
- : '[structured content omitted: exceeds sidechain limit]';
44
+ content = typeof serialized === 'string'
45
+ ? (Buffer.byteLength(serialized, 'utf8') <= MAX_CONTENT_BYTES
46
+ ? JSON.parse(serialized)
47
+ : '[structured content omitted: exceeds sidechain limit]')
48
+ : '[unserializable content omitted]';
47
49
  }
48
50
  catch {
49
51
  content = '[unserializable content omitted]';
@@ -84,12 +84,14 @@ function boundedMessage(value: unknown): Record<string, unknown> | null {
84
84
  let content: unknown = input.content;
85
85
  if (typeof content === 'string') {
86
86
  content = boundedText(content, MAX_CONTENT_BYTES);
87
- } else {
87
+ } else if (content !== undefined && content !== null) {
88
88
  try {
89
89
  const serialized = JSON.stringify(content);
90
- content = Buffer.byteLength(serialized, 'utf8') <= MAX_CONTENT_BYTES
91
- ? JSON.parse(serialized) as unknown
92
- : '[structured content omitted: exceeds sidechain limit]';
90
+ content = typeof serialized === 'string'
91
+ ? (Buffer.byteLength(serialized, 'utf8') <= MAX_CONTENT_BYTES
92
+ ? JSON.parse(serialized) as unknown
93
+ : '[structured content omitted: exceeds sidechain limit]')
94
+ : '[unserializable content omitted]';
93
95
  } catch {
94
96
  content = '[unserializable content omitted]';
95
97
  }
package/src/textDiff.js CHANGED
@@ -101,6 +101,7 @@ export function unifiedDiff(before, after, pathLabel = 'file') {
101
101
  let index = 0;
102
102
  let oldLine = 1;
103
103
  let newLine = 1;
104
+ let lastHunkEnd = 0;
104
105
  while (index < ops.length) {
105
106
  const opIndex = ops[index];
106
107
  if (opIndex[0] === ' ') {
@@ -110,14 +111,18 @@ export function unifiedDiff(before, after, pathLabel = 'file') {
110
111
  continue;
111
112
  }
112
113
  // Walk back for leading context, then forward to the end of the change.
113
- const start = Math.max(0, index - CONTEXT);
114
+ const start = Math.max(lastHunkEnd, index - CONTEXT);
114
115
  let end = index;
115
116
  let quiet = 0;
116
117
  while (end < ops.length && quiet <= CONTEXT * 2) {
117
118
  quiet = ops[end][0] === ' ' ? quiet + 1 : 0;
118
119
  end++;
119
120
  }
121
+ if (quiet > CONTEXT) {
122
+ end -= quiet - CONTEXT;
123
+ }
120
124
  end = Math.min(ops.length, end);
125
+ lastHunkEnd = end;
121
126
  let oldStart = oldLine;
122
127
  let newStart = newLine;
123
128
  for (let k = start; k < index; k++) {
package/src/textDiff.ts CHANGED
@@ -111,6 +111,7 @@ export function unifiedDiff(before: string, after: string, pathLabel = 'file'):
111
111
  let index = 0;
112
112
  let oldLine = 1;
113
113
  let newLine = 1;
114
+ let lastHunkEnd = 0;
114
115
 
115
116
  while (index < ops.length) {
116
117
  const opIndex = ops[index]!;
@@ -122,14 +123,18 @@ export function unifiedDiff(before: string, after: string, pathLabel = 'file'):
122
123
  }
123
124
 
124
125
  // Walk back for leading context, then forward to the end of the change.
125
- const start = Math.max(0, index - CONTEXT);
126
+ const start = Math.max(lastHunkEnd, index - CONTEXT);
126
127
  let end = index;
127
128
  let quiet = 0;
128
129
  while (end < ops.length && quiet <= CONTEXT * 2) {
129
130
  quiet = ops[end]![0] === ' ' ? quiet + 1 : 0;
130
131
  end++;
131
132
  }
133
+ if (quiet > CONTEXT) {
134
+ end -= quiet - CONTEXT;
135
+ }
132
136
  end = Math.min(ops.length, end);
137
+ lastHunkEnd = end;
133
138
 
134
139
  let oldStart = oldLine;
135
140
  let newStart = newLine;
@@ -142,7 +142,13 @@ export class TimeMachine {
142
142
  : ''
143
143
  };
144
144
  }
145
- const error = typeof value.error === 'string' ? value.error : '';
145
+ const error = typeof value.error === 'string'
146
+ ? value.error
147
+ : result instanceof Error
148
+ ? result.message
149
+ : typeof value.message === 'string'
150
+ ? value.message
151
+ : '';
146
152
  const needsHuman = value.failureKind !== 'site_refusal'
147
153
  && (classification === 'permission' || value.requiresConsent === true || value.requiresApproval === true || value.authenticationRequired === true || /user denied|approval required|authentication required/i.test(error));
148
154
  const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
@@ -166,7 +166,13 @@ export class TimeMachine {
166
166
  };
167
167
  }
168
168
 
169
- const error = typeof value.error === 'string' ? value.error : '';
169
+ const error = typeof value.error === 'string'
170
+ ? value.error
171
+ : result instanceof Error
172
+ ? result.message
173
+ : typeof value.message === 'string'
174
+ ? value.message
175
+ : '';
170
176
  const needsHuman = value.failureKind !== 'site_refusal'
171
177
  && (classification === 'permission' || value.requiresConsent === true || value.requiresApproval === true || value.authenticationRequired === true || /user denied|approval required|authentication required/i.test(error));
172
178
  const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
@@ -9,8 +9,10 @@ function withUsageLock(fn) {
9
9
  usageQueue = run.then(() => { }, () => { });
10
10
  return run;
11
11
  }
12
+ let usageTempCounter = 0;
12
13
  function writeUsageFile(file, payload) {
13
- const temp = `${file}.tmp_${process.pid}`;
14
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
15
+ const temp = `${file}.tmp_${process.pid}_${++usageTempCounter}`;
14
16
  fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
15
17
  fs.renameSync(temp, file);
16
18
  }
@@ -133,15 +135,20 @@ export class TokenTracker {
133
135
  return 0.5;
134
136
  }
135
137
  calculateCost(promptTokens, completionTokens, usageDetail = null) {
136
- const [promptPrice, completionPrice] = this.getPricing(promptTokens);
137
- const cachedTokens = Math.min(Number(usageDetail?.cachedPromptTokens || 0), promptTokens);
138
- const writeTokens = Math.min(Number(usageDetail?.cacheWriteTokens || 0), promptTokens - cachedTokens);
139
- const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
140
- const writeMultiplier = Number(usageDetail?.cacheWriteMultiplier || 1.25);
138
+ const safePrompt = Number.isFinite(promptTokens) ? Math.max(0, Number(promptTokens)) : 0;
139
+ const safeCompletion = Number.isFinite(completionTokens) ? Math.max(0, Number(completionTokens)) : 0;
140
+ const [promptPrice, completionPrice] = this.getPricing(safePrompt);
141
+ const rawCached = Number(usageDetail?.cachedPromptTokens ?? 0);
142
+ const cachedTokens = Math.min(Number.isFinite(rawCached) ? Math.max(0, rawCached) : 0, safePrompt);
143
+ const rawWrite = Number(usageDetail?.cacheWriteTokens ?? 0);
144
+ const writeTokens = Math.min(Number.isFinite(rawWrite) ? Math.max(0, rawWrite) : 0, safePrompt - cachedTokens);
145
+ const fullPriceTokens = Math.max(0, safePrompt - cachedTokens - writeTokens);
146
+ const rawMult = Number(usageDetail?.cacheWriteMultiplier ?? 1.25);
147
+ const writeMultiplier = Number.isFinite(rawMult) && rawMult >= 0 ? rawMult : 1.25;
141
148
  const promptCost = (fullPriceTokens / 1_000_000) * promptPrice +
142
149
  (cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
143
150
  (writeTokens / 1_000_000) * promptPrice * writeMultiplier;
144
- const completionCost = (completionTokens / 1_000_000) * completionPrice;
151
+ const completionCost = (safeCompletion / 1_000_000) * completionPrice;
145
152
  return promptCost + completionCost;
146
153
  }
147
154
  getMediaPricing(provider = '', model = '', mediaType = 'image') {
@@ -184,22 +191,26 @@ export class TokenTracker {
184
191
  this.budget = this.config.tokenBudget || { enabled: false };
185
192
  this.applyEnforcedTaskLimit();
186
193
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
187
- const cost = unitPrice * (quantityUnits || 1);
194
+ const safeUnits = Number.isFinite(quantityUnits) ? Math.max(0, Number(quantityUnits)) : 1;
195
+ const cost = unitPrice * safeUnits;
188
196
  const equivalentTokens = Math.round(cost / 0.000002);
189
197
  this.taskTokens += equivalentTokens;
190
198
  this.sessionTokens = (this.sessionTokens || 0) + equivalentTokens;
191
199
  this.taskCostUsd += cost;
192
200
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
193
- const cumulative = await this.getCumulativeUsage();
194
- const daily = await this.getDailyUsage();
195
- daily.totalTokens += equivalentTokens;
196
- daily.totalCalls += 1;
197
- daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
198
- await this.saveDailyUsage(daily);
199
- cumulative.totalTokens += equivalentTokens;
200
- cumulative.totalCalls += 1;
201
- cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
202
- await this.saveCumulativeUsage(cumulative);
201
+ const { daily } = await withUsageLock(async () => {
202
+ const cumulative = await this.getCumulativeUsage();
203
+ const daily = await this.getDailyUsage();
204
+ daily.totalTokens += equivalentTokens;
205
+ daily.totalCalls += 1;
206
+ daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
207
+ await this.saveDailyUsage(daily);
208
+ cumulative.totalTokens += equivalentTokens;
209
+ cumulative.totalCalls += 1;
210
+ cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
211
+ await this.saveCumulativeUsage(cumulative);
212
+ return { daily };
213
+ });
203
214
  if (!this.budget.enabled) {
204
215
  return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
205
216
  }
@@ -306,16 +317,14 @@ export class TokenTracker {
306
317
  writeUsageFile(this.getCumulativeFile(), usage);
307
318
  }
308
319
  async resetDailyUsage() {
309
- const file = this.getDailyFile();
310
- if (fs.existsSync(file)) {
311
- fs.unlinkSync(file);
312
- }
320
+ await withUsageLock(async () => {
321
+ fs.rmSync(this.getDailyFile(), { force: true });
322
+ });
313
323
  }
314
324
  async resetCumulativeUsage() {
315
- const file = this.getCumulativeFile();
316
- if (fs.existsSync(file)) {
317
- fs.unlinkSync(file);
318
- }
325
+ await withUsageLock(async () => {
326
+ fs.rmSync(this.getCumulativeFile(), { force: true });
327
+ });
319
328
  }
320
329
  async getReportedUsage() {
321
330
  const daily = await this.getDailyUsage();
@@ -352,10 +361,16 @@ export class TokenTracker {
352
361
  return { allowed: true, used: this.taskTokens, limit, projected };
353
362
  }
354
363
  extendBudget(extraTokens) {
364
+ if (!Number.isFinite(extraTokens) || extraTokens <= 0)
365
+ return;
355
366
  if (this.budget && typeof this.budget === 'object') {
356
367
  const current = Number(this.budget.maxTokensPerTask || 0);
357
368
  if (current > 0) {
358
- this.budget.maxTokensPerTask = Math.max(current + extraTokens, this.taskTokens + extraTokens);
369
+ const next = Math.max(current + extraTokens, this.taskTokens + extraTokens);
370
+ this.budget.maxTokensPerTask = next;
371
+ if (this.enforcedTaskTokenLimit !== null) {
372
+ this.enforcedTaskTokenLimit = Math.floor(next);
373
+ }
359
374
  }
360
375
  }
361
376
  }
@@ -439,7 +454,7 @@ export class TokenTracker {
439
454
  this.taskTokens += freshStep;
440
455
  this.sessionTokens = (this.sessionTokens || 0) + freshStep;
441
456
  this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
442
- const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
457
+ const cost = this.calculateCost(pTokens, cTokens, usageDetail);
443
458
  this.taskCostUsd += cost;
444
459
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
445
460
  const { daily, cumulative } = await withUsageLock(async () => {
@@ -12,8 +12,10 @@ function withUsageLock<T>(fn: () => Promise<T>): Promise<T> {
12
12
  return run;
13
13
  }
14
14
 
15
+ let usageTempCounter = 0;
15
16
  function writeUsageFile(file: string, payload: unknown): void {
16
- const temp = `${file}.tmp_${process.pid}`;
17
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
18
+ const temp = `${file}.tmp_${process.pid}_${++usageTempCounter}`;
17
19
  fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
18
20
  fs.renameSync(temp, file);
19
21
  }
@@ -209,19 +211,24 @@ export class TokenTracker {
209
211
  }
210
212
 
211
213
  calculateCost(promptTokens: number, completionTokens: number, usageDetail: UsageDetail | null = null): number {
212
- const [promptPrice, completionPrice] = this.getPricing(promptTokens);
213
-
214
- const cachedTokens = Math.min(Number(usageDetail?.cachedPromptTokens || 0), promptTokens);
215
- const writeTokens = Math.min(Number(usageDetail?.cacheWriteTokens || 0), promptTokens - cachedTokens);
216
- const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
217
-
218
- const writeMultiplier = Number(usageDetail?.cacheWriteMultiplier || 1.25);
214
+ const safePrompt = Number.isFinite(promptTokens) ? Math.max(0, Number(promptTokens)) : 0;
215
+ const safeCompletion = Number.isFinite(completionTokens) ? Math.max(0, Number(completionTokens)) : 0;
216
+ const [promptPrice, completionPrice] = this.getPricing(safePrompt);
217
+
218
+ const rawCached = Number(usageDetail?.cachedPromptTokens ?? 0);
219
+ const cachedTokens = Math.min(Number.isFinite(rawCached) ? Math.max(0, rawCached) : 0, safePrompt);
220
+ const rawWrite = Number(usageDetail?.cacheWriteTokens ?? 0);
221
+ const writeTokens = Math.min(Number.isFinite(rawWrite) ? Math.max(0, rawWrite) : 0, safePrompt - cachedTokens);
222
+ const fullPriceTokens = Math.max(0, safePrompt - cachedTokens - writeTokens);
223
+
224
+ const rawMult = Number(usageDetail?.cacheWriteMultiplier ?? 1.25);
225
+ const writeMultiplier = Number.isFinite(rawMult) && rawMult >= 0 ? rawMult : 1.25;
219
226
  const promptCost =
220
227
  (fullPriceTokens / 1_000_000) * promptPrice +
221
228
  (cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
222
229
  (writeTokens / 1_000_000) * promptPrice * writeMultiplier;
223
230
 
224
- const completionCost = (completionTokens / 1_000_000) * completionPrice;
231
+ const completionCost = (safeCompletion / 1_000_000) * completionPrice;
225
232
  return promptCost + completionCost;
226
233
  }
227
234
 
@@ -269,7 +276,8 @@ export class TokenTracker {
269
276
  this.applyEnforcedTaskLimit();
270
277
 
271
278
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
272
- const cost = unitPrice * (quantityUnits || 1);
279
+ const safeUnits = Number.isFinite(quantityUnits) ? Math.max(0, Number(quantityUnits)) : 1;
280
+ const cost = unitPrice * safeUnits;
273
281
 
274
282
  const equivalentTokens = Math.round(cost / 0.000002);
275
283
 
@@ -278,17 +286,20 @@ export class TokenTracker {
278
286
  this.taskCostUsd += cost;
279
287
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
280
288
 
281
- const cumulative = await this.getCumulativeUsage();
282
- const daily = await this.getDailyUsage();
283
- daily.totalTokens += equivalentTokens;
284
- daily.totalCalls += 1;
285
- daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
286
- await this.saveDailyUsage(daily);
289
+ const { daily } = await withUsageLock(async () => {
290
+ const cumulative = await this.getCumulativeUsage();
291
+ const daily = await this.getDailyUsage();
292
+ daily.totalTokens += equivalentTokens;
293
+ daily.totalCalls += 1;
294
+ daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
295
+ await this.saveDailyUsage(daily);
287
296
 
288
- cumulative.totalTokens += equivalentTokens;
289
- cumulative.totalCalls += 1;
290
- cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
291
- await this.saveCumulativeUsage(cumulative);
297
+ cumulative.totalTokens += equivalentTokens;
298
+ cumulative.totalCalls += 1;
299
+ cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
300
+ await this.saveCumulativeUsage(cumulative);
301
+ return { daily };
302
+ });
292
303
 
293
304
  if (!this.budget.enabled) {
294
305
  return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
@@ -406,17 +417,15 @@ export class TokenTracker {
406
417
  }
407
418
 
408
419
  async resetDailyUsage(): Promise<void> {
409
- const file = this.getDailyFile();
410
- if (fs.existsSync(file)) {
411
- fs.unlinkSync(file);
412
- }
420
+ await withUsageLock(async () => {
421
+ fs.rmSync(this.getDailyFile(), { force: true });
422
+ });
413
423
  }
414
424
 
415
425
  async resetCumulativeUsage(): Promise<void> {
416
- const file = this.getCumulativeFile();
417
- if (fs.existsSync(file)) {
418
- fs.unlinkSync(file);
419
- }
426
+ await withUsageLock(async () => {
427
+ fs.rmSync(this.getCumulativeFile(), { force: true });
428
+ });
420
429
  }
421
430
 
422
431
  async getReportedUsage(): Promise<{
@@ -467,10 +476,15 @@ export class TokenTracker {
467
476
  }
468
477
 
469
478
  extendBudget(extraTokens: number): void {
479
+ if (!Number.isFinite(extraTokens) || extraTokens <= 0) return;
470
480
  if (this.budget && typeof this.budget === 'object') {
471
481
  const current = Number(this.budget.maxTokensPerTask || 0);
472
482
  if (current > 0) {
473
- this.budget.maxTokensPerTask = Math.max(current + extraTokens, this.taskTokens + extraTokens);
483
+ const next = Math.max(current + extraTokens, this.taskTokens + extraTokens);
484
+ this.budget.maxTokensPerTask = next;
485
+ if (this.enforcedTaskTokenLimit !== null) {
486
+ this.enforcedTaskTokenLimit = Math.floor(next);
487
+ }
474
488
  }
475
489
  }
476
490
  }
@@ -567,7 +581,7 @@ export class TokenTracker {
567
581
  this.sessionTokens = (this.sessionTokens || 0) + freshStep;
568
582
  this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
569
583
 
570
- const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
584
+ const cost = this.calculateCost(pTokens, cTokens, usageDetail);
571
585
  this.taskCostUsd += cost;
572
586
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
573
587
 
package/src/toolPacks.js CHANGED
@@ -377,7 +377,9 @@ export function routePacks(prompt, workspaceContext = null) {
377
377
  for (const packName of PACK_NAMES) {
378
378
  const matched = packName === 'reverse_engineering'
379
379
  ? isReverseEngineeringIntent(text)
380
- : INTENT_MATCHERS[packName].test(text);
380
+ : packName === 'web'
381
+ ? isWebIntent(text)
382
+ : INTENT_MATCHERS[packName].test(text);
381
383
  if (matched) {
382
384
  unlocked.add(packName);
383
385
  }
package/src/toolPacks.ts CHANGED
@@ -431,7 +431,9 @@ export function routePacks(
431
431
  for (const packName of PACK_NAMES) {
432
432
  const matched = packName === 'reverse_engineering'
433
433
  ? isReverseEngineeringIntent(text)
434
- : INTENT_MATCHERS[packName].test(text);
434
+ : packName === 'web'
435
+ ? isWebIntent(text)
436
+ : INTENT_MATCHERS[packName].test(text);
435
437
  if (matched) {
436
438
  unlocked.add(packName);
437
439
  }