@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
@@ -130,13 +130,37 @@ const SYSTEM_ADMIN_PATTERN = /\b(kill process|kill port|check port|port \d+|lsof
130
130
  const SIMPLE_FILE_OP_PATTERN = /\b(list (the )?files|show files|count files|rename file(s)?|delete file(s)?|move file(s)?|clean (up )?folder|read (the )?(?:note|file)|summarize (?:its )?content)\b/i;
131
131
  // Media generation intent (explicit creation of 3D, video, audio, or synthesized speech)
132
132
  const EXPLICIT_MEDIA_GENERATION_PATTERN = /\b(blender|3d model|render 3d|render frame|render animation|da vinci|resolve|photoshop|premiere|after\s*effects|illustrator|indesign|media\s*encoder|uxp|audio synth|synthesizer|text to speech|tts|voiceover|dubbing)\b|\.(blend\d*|psd|prproj|aep|ai|indd|ccx)\b/i;
133
- // Explicit web engineering intent
134
- const EXPLICIT_WEB_ENGINEERING_PATTERN = /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*(?:\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|webgl|canvas|cad view|cad viewer|cad style view|3d view|3d viewer|3d configurator|3d visualizer)\b|(?:threejs|three\.js|thre\.?js|3js|babylon\.?js|pixi\.js|d3\.js|p5\.js|chart\.js)\b)/i;
133
+ function matchesOrdered(text, first, second) {
134
+ const m = first.exec(text);
135
+ return m !== null && second.test(text.slice(m.index + m[0].length));
136
+ }
137
+ // Explicit web engineering intent (linear-time two-phase match to avoid polynomial ReDoS)
138
+ const WEB_VERB_RE = /\b(?:build|create|make|design|develop|implement|redesign|buat\w*)\b/i;
139
+ const WEB_TARGET_RE = /(?:\b(?:web|website|webpage|webapp|landing page|dashboard|ui|frontend|webgl|canvas|cad view|cad viewer|cad style view|3d view|3d viewer|3d configurator|3d visualizer)\b|(?:threejs|three\.js|thre\.?js|3js|babylon\.?js|pixi\.js|d3\.js|p5\.js|chart\.js)\b)/i;
140
+ const EXPLICIT_WEB_ENGINEERING_PATTERN = {
141
+ test(text) {
142
+ return matchesOrdered(text, WEB_VERB_RE, WEB_TARGET_RE);
143
+ }
144
+ };
135
145
  // Explicit game development intent
136
- const EXPLICIT_GAME_DEV_PATTERN = /(?:\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)[\s\S]*(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b|\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
146
+ const GAME_STANDALONE_RE = /(?:\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
147
+ const GAME_VERB_RE = /\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)/i;
148
+ const GAME_TARGET_RE = /(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b/i;
149
+ const EXPLICIT_GAME_DEV_PATTERN = {
150
+ test(text) {
151
+ return GAME_STANDALONE_RE.test(text) || matchesOrdered(text, GAME_VERB_RE, GAME_TARGET_RE);
152
+ }
153
+ };
137
154
  // Explicit reverse engineering and binary analysis intent is defined in toolPacks.ts (isReverseEngineeringIntent).
138
155
  // Explicit software and systems engineering intent (backend, APIs, refactoring, algorithms, testing, architecture, CLI tools, Android/mobile)
139
- const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN = /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b)/i;
156
+ const SWE_STANDALONE_RE = /\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b/i;
157
+ const SWE_VERB_RE = /\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b/i;
158
+ const SWE_TARGET_RE = /\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b/i;
159
+ const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN = {
160
+ test(text) {
161
+ return SWE_STANDALONE_RE.test(text) || matchesOrdered(text, SWE_VERB_RE, SWE_TARGET_RE);
162
+ }
163
+ };
140
164
  /**
141
165
  * Select tools to preload based on prompt intent. This is never an allowlist:
142
166
  * tool_search can add capabilities as the task develops.
@@ -177,19 +177,41 @@ const SIMPLE_FILE_OP_PATTERN =
177
177
  const EXPLICIT_MEDIA_GENERATION_PATTERN =
178
178
  /\b(blender|3d model|render 3d|render frame|render animation|da vinci|resolve|photoshop|premiere|after\s*effects|illustrator|indesign|media\s*encoder|uxp|audio synth|synthesizer|text to speech|tts|voiceover|dubbing)\b|\.(blend\d*|psd|prproj|aep|ai|indd|ccx)\b/i;
179
179
 
180
- // Explicit web engineering intent
181
- const EXPLICIT_WEB_ENGINEERING_PATTERN =
182
- /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*(?:\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|webgl|canvas|cad view|cad viewer|cad style view|3d view|3d viewer|3d configurator|3d visualizer)\b|(?:threejs|three\.js|thre\.?js|3js|babylon\.?js|pixi\.js|d3\.js|p5\.js|chart\.js)\b)/i;
180
+ function matchesOrdered(text: string, first: RegExp, second: RegExp): boolean {
181
+ const m = first.exec(text);
182
+ return m !== null && second.test(text.slice(m.index + m[0].length));
183
+ }
184
+
185
+ // Explicit web engineering intent (linear-time two-phase match to avoid polynomial ReDoS)
186
+ const WEB_VERB_RE = /\b(?:build|create|make|design|develop|implement|redesign|buat\w*)\b/i;
187
+ const WEB_TARGET_RE = /(?:\b(?:web|website|webpage|webapp|landing page|dashboard|ui|frontend|webgl|canvas|cad view|cad viewer|cad style view|3d view|3d viewer|3d configurator|3d visualizer)\b|(?:threejs|three\.js|thre\.?js|3js|babylon\.?js|pixi\.js|d3\.js|p5\.js|chart\.js)\b)/i;
188
+ const EXPLICIT_WEB_ENGINEERING_PATTERN = {
189
+ test(text: string): boolean {
190
+ return matchesOrdered(text, WEB_VERB_RE, WEB_TARGET_RE);
191
+ }
192
+ };
183
193
 
184
194
  // Explicit game development intent
185
- const EXPLICIT_GAME_DEV_PATTERN =
186
- /(?:\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)[\s\S]*(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b|\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
195
+ const GAME_STANDALONE_RE = /(?:\b(?:game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive)\b|\b3d\s*(?:game|app|simulator|simulation|scene|city|world|view|body|human|anatomy|model|mesh|character|rendering|visualization|experience|space|environment)\b|\bin 3d\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
196
+ const GAME_VERB_RE = /\b(?:build|create|make|design|develop|scaffold|render|animate|code|program|buat\w*|bikin\w*)/i;
197
+ const GAME_TARGET_RE = /(?:game|simulation|simulator|simulasi|interactive|3d|three\.?js|threejs|webgl|canvas3d|babylonjs|godot|unity|unreal|platformer|rpg|arcade)\b/i;
198
+ const EXPLICIT_GAME_DEV_PATTERN = {
199
+ test(text: string): boolean {
200
+ return GAME_STANDALONE_RE.test(text) || matchesOrdered(text, GAME_VERB_RE, GAME_TARGET_RE);
201
+ }
202
+ };
187
203
 
188
204
  // Explicit reverse engineering and binary analysis intent is defined in toolPacks.ts (isReverseEngineeringIntent).
189
205
 
190
206
  // Explicit software and systems engineering intent (backend, APIs, refactoring, algorithms, testing, architecture, CLI tools, Android/mobile)
191
- const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN =
192
- /(?:\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b[\s\S]*\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b|\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b)/i;
207
+ const SWE_STANDALONE_RE = /\b(?:python|rust|golang|c\+\+|cpp|java|kotlin|swift|csharp|typescript|javascript|ruby|php|sql|bash|shell|docker|k8s|kubernetes|gradle|compose|android|apk|aab)\b/i;
208
+ const SWE_VERB_RE = /\b(?:build|create|code|program|develop|refactor|debug|fix|implement|test|optimize|write|add|modify|migrate|architect|architecture|engineer|benchmark|profile|audit|scaffold|bump|export)\b/i;
209
+ const SWE_TARGET_RE = /\b(?:api|backend|service|microservice|server|database|schema|endpoint|controller|auth|test|spec|algorithm|function|module|class|feature|script|pipeline|codebase|repo|repository|bug|issue|engine|tool|cli|library|sdk|migration|handler|worker|queue|stream|app|application|compose|jetpack|android|gradle|package|apk|aab|bundle|version)\b/i;
210
+ const EXPLICIT_SOFTWARE_ENGINEERING_PATTERN = {
211
+ test(text: string): boolean {
212
+ return SWE_STANDALONE_RE.test(text) || matchesOrdered(text, SWE_VERB_RE, SWE_TARGET_RE);
213
+ }
214
+ };
193
215
 
194
216
  /**
195
217
  * Select tools to preload based on prompt intent. This is never an allowlist:
package/src/stallGuard.js CHANGED
@@ -63,24 +63,41 @@ export const STALL_GUARD_MAX_CYCLE_PERIOD = 4;
63
63
  export const STALL_GUARD_CYCLE_HISTORY = 64;
64
64
  export const IDENTICAL_RESULT_STUB_MIN_CHARS = 512;
65
65
  export const RESEARCH_INSPECTION_NUDGE_AFTER = 25;
66
- function stableSortObject(value) {
66
+ function stableSortObject(value, seen = new WeakSet()) {
67
67
  if (value === null || typeof value !== 'object') {
68
- return value;
68
+ return typeof value === 'bigint' ? value.toString() : value;
69
69
  }
70
- if (Array.isArray(value)) {
71
- return value.map(stableSortObject);
70
+ if (seen.has(value)) {
71
+ return '[Circular]';
72
72
  }
73
- const sorted = {};
74
- for (const key of Object.keys(value).sort()) {
75
- sorted[key] = stableSortObject(value[key]);
73
+ seen.add(value);
74
+ try {
75
+ if (Array.isArray(value)) {
76
+ return value.map((item) => stableSortObject(item, seen));
77
+ }
78
+ const sorted = {};
79
+ for (const key of Object.keys(value).sort()) {
80
+ sorted[key] = stableSortObject(value[key], seen);
81
+ }
82
+ return sorted;
83
+ }
84
+ finally {
85
+ seen.delete(value);
86
+ }
87
+ }
88
+ function safeJsonStringify(value) {
89
+ try {
90
+ return JSON.stringify(stableSortObject(value)) ?? '';
91
+ }
92
+ catch {
93
+ return String(value);
76
94
  }
77
- return sorted;
78
95
  }
79
96
  export function canonicalToolArgs(args) {
80
97
  if (!args || typeof args !== 'object') {
81
- return JSON.stringify(args ?? {});
98
+ return safeJsonStringify(args ?? {});
82
99
  }
83
- return JSON.stringify(stableSortObject(args));
100
+ return safeJsonStringify(args);
84
101
  }
85
102
  export function buildToolCallSignature(toolName, args) {
86
103
  const canonical = canonicalToolArgs(args);
@@ -90,7 +107,7 @@ export function buildToolCallSignature(toolName, args) {
90
107
  export function computeResultHash(result) {
91
108
  if (result === null || result === undefined)
92
109
  return '';
93
- const str = typeof result === 'string' ? result : JSON.stringify(result);
110
+ const str = typeof result === 'string' ? result : safeJsonStringify(result);
94
111
  return createHash('sha256').update(str).digest('hex').slice(0, 24);
95
112
  }
96
113
  function ordinal(n) {
@@ -116,15 +133,17 @@ export class StallGuardController {
116
133
  _researchNudgeEmitted = false;
117
134
  _haltDecision = null;
118
135
  constructor(config) {
136
+ const posInt = (value, fallback) => typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
137
+ const nonNegInt = (value, fallback) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
119
138
  this.config = {
120
139
  warningsEnabled: config?.warningsEnabled ?? true,
121
140
  hardStopEnabled: config?.hardStopEnabled ?? false,
122
- identicalCallWarnAfter: config?.identicalCallWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
123
- identicalCallHaltAfter: config?.identicalCallHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
124
- cycleWarnAfter: config?.cycleWarnAfter ?? STALL_GUARD_IDENTICAL_CALL_THRESHOLD,
125
- cycleHaltAfter: config?.cycleHaltAfter ?? STALL_GUARD_IDENTICAL_CALL_HALT,
126
- researchNudgeAfter: config?.researchNudgeAfter ?? RESEARCH_INSPECTION_NUDGE_AFTER,
127
- stubMinChars: config?.stubMinChars ?? IDENTICAL_RESULT_STUB_MIN_CHARS
141
+ identicalCallWarnAfter: posInt(config?.identicalCallWarnAfter, STALL_GUARD_IDENTICAL_CALL_THRESHOLD),
142
+ identicalCallHaltAfter: posInt(config?.identicalCallHaltAfter, STALL_GUARD_IDENTICAL_CALL_HALT),
143
+ cycleWarnAfter: posInt(config?.cycleWarnAfter, STALL_GUARD_IDENTICAL_CALL_THRESHOLD),
144
+ cycleHaltAfter: posInt(config?.cycleHaltAfter, STALL_GUARD_IDENTICAL_CALL_HALT),
145
+ researchNudgeAfter: posInt(config?.researchNudgeAfter, RESEARCH_INSPECTION_NUDGE_AFTER),
146
+ stubMinChars: nonNegInt(config?.stubMinChars, IDENTICAL_RESULT_STUB_MIN_CHARS)
128
147
  };
129
148
  }
130
149
  get haltDecision() {
@@ -220,7 +239,7 @@ export class StallGuardController {
220
239
  observeCall(toolName, args = {}, result, toolCallId = '', failed = false) {
221
240
  const signature = buildToolCallSignature(toolName, args);
222
241
  const sigKey = `${signature.toolName}:${signature.argsHash}`;
223
- const resultStr = typeof result === 'string' ? result : JSON.stringify(result ?? {});
242
+ const resultStr = typeof result === 'string' ? result : safeJsonStringify(result ?? {});
224
243
  const rHash = computeResultHash(resultStr);
225
244
  const repeatable = this.isRepeatable(toolName, args);
226
245
  const mutating = this.isMutating(toolName, args);
@@ -269,7 +288,9 @@ export class StallGuardController {
269
288
  });
270
289
  }
271
290
  if (!repeatable && count >= this.config.identicalCallWarnAfter) {
272
- 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.]`;
291
+ if (this.config.warningsEnabled) {
292
+ 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.]`;
293
+ }
273
294
  if (this.config.hardStopEnabled && count >= this.config.identicalCallHaltAfter && !this._haltDecision) {
274
295
  decision = {
275
296
  action: 'halt',
@@ -286,11 +307,13 @@ export class StallGuardController {
286
307
  if (this._callHistory.length > STALL_GUARD_CYCLE_HISTORY) {
287
308
  this._callHistory.shift();
288
309
  }
289
- if (!notice) {
310
+ if (!notice && !decision) {
290
311
  const cycle = this.detectIdenticalCycle();
291
312
  if (cycle) {
292
313
  const { period, laps } = cycle;
293
- 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.]`;
314
+ if (this.config.warningsEnabled) {
315
+ 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.]`;
316
+ }
294
317
  if (this.config.hardStopEnabled && laps >= this.config.cycleHaltAfter && !this._haltDecision) {
295
318
  decision = {
296
319
  action: 'halt',
@@ -305,7 +328,7 @@ export class StallGuardController {
305
328
  }
306
329
  }
307
330
  }
308
- if (!notice && !this._researchNudgeEmitted && this._distinctInspectionCount >= this.config.researchNudgeAfter) {
331
+ if (this.config.warningsEnabled && !notice && !this._researchNudgeEmitted && this._distinctInspectionCount >= this.config.researchNudgeAfter) {
309
332
  this._researchNudgeEmitted = true;
310
333
  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.]`;
311
334
  }
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 () => {