@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
@@ -6,6 +6,7 @@ export const SESSION_DIR = path.join(causyneHome(), 'sessions');
6
6
  const LEGACY_HISTORY = path.join(causyneHome(), 'memory', 'chat_history.json');
7
7
  const POINTER_FILE = path.join(SESSION_DIR, 'active.json');
8
8
  export const RESUME_WINDOW_MS = 12 * 60 * 60 * 1000;
9
+ export const ORPHAN_EMPTY_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
9
10
  export const MAX_SESSIONS = 50;
10
11
  const MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024;
11
12
  const MAX_EVENT_BYTES = 8 * 1024 * 1024;
@@ -34,8 +35,11 @@ function validMessage(value) {
34
35
  function validMessages(value) {
35
36
  return Array.isArray(value) && value.every(validMessage);
36
37
  }
38
+ function isValidTimestamp(value) {
39
+ return typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 8.64e15;
40
+ }
37
41
  function parseEvent(value) {
38
- if (!isObject(value) || value.version !== 1 || typeof value.type !== 'string' || typeof value.at !== 'number')
42
+ if (!isObject(value) || value.version !== 1 || typeof value.type !== 'string' || !isValidTimestamp(value.at))
39
43
  return null;
40
44
  if (value.type === 'session.created') {
41
45
  const session = value.session;
@@ -44,7 +48,7 @@ function parseEvent(value) {
44
48
  || typeof session.workspace !== 'string'
45
49
  || typeof session.workspaceKey !== 'string'
46
50
  || typeof session.title !== 'string'
47
- || typeof session.createdAt !== 'number')
51
+ || !isValidTimestamp(session.createdAt))
48
52
  return null;
49
53
  return value;
50
54
  }
@@ -236,7 +240,9 @@ function sessionTitle(title, messages, createdAt) {
236
240
  const text = message.content.trim();
237
241
  return text.length > 12 && !NON_TASK_MESSAGE.test(text) && !text.startsWith('[decayed]');
238
242
  });
239
- return prompt ? titleFrom(prompt.content) : `New session - ${new Date(createdAt).toISOString().replace('T', ' ').slice(0, 16)} UTC`;
243
+ const dt = new Date(createdAt);
244
+ const iso = Number.isFinite(dt.getTime()) ? dt.toISOString() : new Date(0).toISOString();
245
+ return prompt ? titleFrom(prompt.content) : `New session - ${iso.replace('T', ' ').slice(0, 16)} UTC`;
240
246
  }
241
247
  export function listSessions() {
242
248
  try {
@@ -261,6 +267,47 @@ export function listSessions() {
261
267
  return [];
262
268
  }
263
269
  }
270
+ /**
271
+ * Removes abandoned 0-message session files older than `maxAgeMs` (default 24h).
272
+ * Never removes:
273
+ * - any session with 1 or more messages (real conversation history)
274
+ * - the currently active session or `preserveId`
275
+ * - recent empty sessions younger than `maxAgeMs`
276
+ */
277
+ export function pruneEmptyOrphanSessions(options = {}) {
278
+ try {
279
+ ensureDir();
280
+ const maxAgeMs = typeof options.maxAgeMs === 'number' && Number.isFinite(options.maxAgeMs) && options.maxAgeMs >= 0
281
+ ? options.maxAgeMs
282
+ : ORPHAN_EMPTY_SESSION_TTL_MS;
283
+ const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
284
+ const activeId = getActiveSessionId();
285
+ const preserveId = options.preserveId ? safeSessionId(options.preserveId) : null;
286
+ let removed = 0;
287
+ for (const row of listSessions()) {
288
+ if (row.messageCount > 0)
289
+ continue;
290
+ if (row.id === activeId || (preserveId && row.id === preserveId))
291
+ continue;
292
+ if (now - row.updatedAt < maxAgeMs)
293
+ continue;
294
+ let removedSession = false;
295
+ for (const file of [sessionTranscriptFile(row.id), legacySessionFile(row.id), `${legacySessionFile(row.id)}.migrated`]) {
296
+ try {
297
+ fs.unlinkSync(file);
298
+ removedSession = true;
299
+ }
300
+ catch { /* absent files need no action */ }
301
+ }
302
+ if (removedSession)
303
+ removed += 1;
304
+ }
305
+ return removed;
306
+ }
307
+ catch {
308
+ return 0;
309
+ }
310
+ }
264
311
  export function pruneSessions(max = MAX_SESSIONS) {
265
312
  let removed = 0;
266
313
  for (const row of listSessions().slice(max)) {
@@ -334,6 +381,11 @@ export function resolveSession(workspace, options = {}) {
334
381
  const workspaceText = String(workspace ?? '');
335
382
  ensureDir();
336
383
  migrateLegacyHistory(workspaceText);
384
+ const preserveCandidate = options.preferredId || getActiveSessionId();
385
+ try {
386
+ pruneEmptyOrphanSessions({ preserveId: preserveCandidate });
387
+ }
388
+ catch { /* housekeeping must never block session resolution */ }
337
389
  if (options.forceNew) {
338
390
  return createSession(workspaceText);
339
391
  }
@@ -56,6 +56,7 @@ export const SESSION_DIR = path.join(causyneHome(), 'sessions');
56
56
  const LEGACY_HISTORY = path.join(causyneHome(), 'memory', 'chat_history.json');
57
57
  const POINTER_FILE = path.join(SESSION_DIR, 'active.json');
58
58
  export const RESUME_WINDOW_MS = 12 * 60 * 60 * 1000;
59
+ export const ORPHAN_EMPTY_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
59
60
  export const MAX_SESSIONS = 50;
60
61
  const MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024;
61
62
  const MAX_EVENT_BYTES = 8 * 1024 * 1024;
@@ -92,8 +93,12 @@ function validMessages(value: unknown): value is SessionMessage[] {
92
93
  return Array.isArray(value) && value.every(validMessage);
93
94
  }
94
95
 
96
+ function isValidTimestamp(value: unknown): value is number {
97
+ return typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 8.64e15;
98
+ }
99
+
95
100
  function parseEvent(value: unknown): SessionEvent | null {
96
- if (!isObject(value) || value.version !== 1 || typeof value.type !== 'string' || typeof value.at !== 'number') return null;
101
+ if (!isObject(value) || value.version !== 1 || typeof value.type !== 'string' || !isValidTimestamp(value.at)) return null;
97
102
  if (value.type === 'session.created') {
98
103
  const session = value.session;
99
104
  if (!isObject(session)
@@ -101,7 +106,7 @@ function parseEvent(value: unknown): SessionEvent | null {
101
106
  || typeof session.workspace !== 'string'
102
107
  || typeof session.workspaceKey !== 'string'
103
108
  || typeof session.title !== 'string'
104
- || typeof session.createdAt !== 'number') return null;
109
+ || !isValidTimestamp(session.createdAt)) return null;
105
110
  return value as unknown as SessionCreatedEvent;
106
111
  }
107
112
  if (value.type === 'messages.appended') {
@@ -270,7 +275,9 @@ function sessionTitle(title: string, messages: SessionMessage[], createdAt: numb
270
275
  const text = message.content.trim();
271
276
  return text.length > 12 && !NON_TASK_MESSAGE.test(text) && !text.startsWith('[decayed]');
272
277
  });
273
- return prompt ? titleFrom(prompt.content) : `New session - ${new Date(createdAt).toISOString().replace('T', ' ').slice(0, 16)} UTC`;
278
+ const dt = new Date(createdAt);
279
+ const iso = Number.isFinite(dt.getTime()) ? dt.toISOString() : new Date(0).toISOString();
280
+ return prompt ? titleFrom(prompt.content) : `New session - ${iso.replace('T', ' ').slice(0, 16)} UTC`;
274
281
  }
275
282
 
276
283
  export function listSessions(): Array<Omit<SessionRecord, 'messages'> & { messageCount: number }> {
@@ -294,6 +301,50 @@ export function listSessions(): Array<Omit<SessionRecord, 'messages'> & { messag
294
301
  }
295
302
  }
296
303
 
304
+ export interface PruneEmptyOrphanOptions {
305
+ maxAgeMs?: number | undefined;
306
+ preserveId?: string | null | undefined;
307
+ now?: number | undefined;
308
+ }
309
+
310
+ /**
311
+ * Removes abandoned 0-message session files older than `maxAgeMs` (default 24h).
312
+ * Never removes:
313
+ * - any session with 1 or more messages (real conversation history)
314
+ * - the currently active session or `preserveId`
315
+ * - recent empty sessions younger than `maxAgeMs`
316
+ */
317
+ export function pruneEmptyOrphanSessions(options: PruneEmptyOrphanOptions = {}): number {
318
+ try {
319
+ ensureDir();
320
+ const maxAgeMs = typeof options.maxAgeMs === 'number' && Number.isFinite(options.maxAgeMs) && options.maxAgeMs >= 0
321
+ ? options.maxAgeMs
322
+ : ORPHAN_EMPTY_SESSION_TTL_MS;
323
+ const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
324
+ const activeId = getActiveSessionId();
325
+ const preserveId = options.preserveId ? safeSessionId(options.preserveId) : null;
326
+
327
+ let removed = 0;
328
+ for (const row of listSessions()) {
329
+ if (row.messageCount > 0) continue;
330
+ if (row.id === activeId || (preserveId && row.id === preserveId)) continue;
331
+ if (now - row.updatedAt < maxAgeMs) continue;
332
+
333
+ let removedSession = false;
334
+ for (const file of [sessionTranscriptFile(row.id), legacySessionFile(row.id), `${legacySessionFile(row.id)}.migrated`]) {
335
+ try {
336
+ fs.unlinkSync(file);
337
+ removedSession = true;
338
+ } catch { /* absent files need no action */ }
339
+ }
340
+ if (removedSession) removed += 1;
341
+ }
342
+ return removed;
343
+ } catch {
344
+ return 0;
345
+ }
346
+ }
347
+
297
348
  export function pruneSessions(max = MAX_SESSIONS): number {
298
349
  let removed = 0;
299
350
  for (const row of listSessions().slice(max)) {
@@ -371,6 +422,10 @@ export function resolveSession(workspace: unknown, options: ResolveSessionOption
371
422
  const workspaceText = String(workspace ?? '');
372
423
  ensureDir();
373
424
  migrateLegacyHistory(workspaceText);
425
+ const preserveCandidate = options.preferredId || getActiveSessionId();
426
+ try {
427
+ pruneEmptyOrphanSessions({ preserveId: preserveCandidate });
428
+ } catch { /* housekeeping must never block session resolution */ }
374
429
  if (options.forceNew) {
375
430
  return createSession(workspaceText);
376
431
  }
@@ -251,12 +251,18 @@ export function listSkillResourcePaths(root, domain, name, limit = MAX_ADVERTISE
251
251
  if (out.length >= bound || depth > 3)
252
252
  return;
253
253
  const directory = path.join(skillDir, ...relative.split('/'));
254
- if (!inspectDirectory(directory, true))
254
+ let entries;
255
+ try {
256
+ if (!inspectDirectory(directory, true))
257
+ return;
258
+ entries = fs.readdirSync(directory, { withFileTypes: true })
259
+ .filter(item => !item.name.startsWith('.'))
260
+ .sort((a, b) => a.name.localeCompare(b.name))
261
+ .slice(0, 128);
262
+ }
263
+ catch {
255
264
  return;
256
- const entries = fs.readdirSync(directory, { withFileTypes: true })
257
- .filter(item => !item.name.startsWith('.'))
258
- .sort((a, b) => a.name.localeCompare(b.name))
259
- .slice(0, 128);
265
+ }
260
266
  for (const entry of entries) {
261
267
  if (out.length >= bound)
262
268
  break;
@@ -266,9 +272,14 @@ export function listSkillResourcePaths(root, domain, name, limit = MAX_ADVERTISE
266
272
  if (entry.isDirectory())
267
273
  walk(next, depth + 1);
268
274
  else if (entry.isFile() && TEXT_EXTENSIONS.has(path.posix.extname(next).toLowerCase())) {
269
- const stat = fs.lstatSync(path.join(directory, entry.name));
270
- if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink())
271
- out.push(next);
275
+ try {
276
+ const stat = fs.lstatSync(path.join(directory, entry.name));
277
+ if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink())
278
+ out.push(next);
279
+ }
280
+ catch {
281
+ // Skip vanished or unreadable support file
282
+ }
272
283
  }
273
284
  }
274
285
  };
@@ -266,19 +266,28 @@ export function listSkillResourcePaths(
266
266
  const walk = (relative: string, depth: number): void => {
267
267
  if (out.length >= bound || depth > 3) return;
268
268
  const directory = path.join(skillDir, ...relative.split('/'));
269
- if (!inspectDirectory(directory, true)) return;
270
- const entries = fs.readdirSync(directory, { withFileTypes: true })
271
- .filter(item => !item.name.startsWith('.'))
272
- .sort((a, b) => a.name.localeCompare(b.name))
273
- .slice(0, 128);
269
+ let entries: fs.Dirent[];
270
+ try {
271
+ if (!inspectDirectory(directory, true)) return;
272
+ entries = fs.readdirSync(directory, { withFileTypes: true })
273
+ .filter(item => !item.name.startsWith('.'))
274
+ .sort((a, b) => a.name.localeCompare(b.name))
275
+ .slice(0, 128);
276
+ } catch {
277
+ return;
278
+ }
274
279
  for (const entry of entries) {
275
280
  if (out.length >= bound) break;
276
281
  if (entry.isSymbolicLink()) continue;
277
282
  const next = `${relative}/${entry.name}`;
278
283
  if (entry.isDirectory()) walk(next, depth + 1);
279
284
  else if (entry.isFile() && TEXT_EXTENSIONS.has(path.posix.extname(next).toLowerCase())) {
280
- const stat = fs.lstatSync(path.join(directory, entry.name));
281
- if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink()) out.push(next);
285
+ try {
286
+ const stat = fs.lstatSync(path.join(directory, entry.name));
287
+ if (stat.size <= MAX_SKILL_RESOURCE_BYTES && !stat.isSymbolicLink()) out.push(next);
288
+ } catch {
289
+ // Skip vanished or unreadable support file
290
+ }
282
291
  }
283
292
  }
284
293
  };
@@ -144,7 +144,7 @@ export function detectWorkspaceDomains(workspaceRoot) {
144
144
  }
145
145
  export { MAX_INDEXED_SKILLS, UNIVERSAL_DOMAINS };
146
146
  export function ensureSkillRepo(domain) {
147
- if (compiledSkillsCatalog[domain]) {
147
+ if (Object.hasOwn(compiledSkillsCatalog, domain) && compiledSkillsCatalog[domain]) {
148
148
  return true;
149
149
  }
150
150
  return false;
@@ -310,10 +310,10 @@ export function readCompiledSkill(domain, skillId) {
310
310
  .find((skill) => skill.domain === domain && skill.id === skillId);
311
311
  if (pluginSkill)
312
312
  return pluginSkill.content;
313
- const domainSkills = compiledSkillsCatalog[domain];
313
+ const domainSkills = Object.hasOwn(compiledSkillsCatalog, domain) ? compiledSkillsCatalog[domain] : undefined;
314
314
  if (!domainSkills)
315
315
  return `Error: Domain ${domain} not found in compiled skills.`;
316
- const skillData = domainSkills[skillId];
316
+ const skillData = Object.hasOwn(domainSkills, skillId) ? domainSkills[skillId] : undefined;
317
317
  if (!skillData)
318
318
  return `Error: Skill ${skillId} not found in domain ${domain}.`;
319
319
  return skillData.content;
@@ -169,7 +169,7 @@ export function detectWorkspaceDomains(workspaceRoot?: string): string[] {
169
169
  export { MAX_INDEXED_SKILLS, UNIVERSAL_DOMAINS };
170
170
 
171
171
  export function ensureSkillRepo(domain: string): boolean {
172
- if (compiledSkillsCatalog[domain]) {
172
+ if (Object.hasOwn(compiledSkillsCatalog, domain) && compiledSkillsCatalog[domain]) {
173
173
  return true;
174
174
  }
175
175
  return false;
@@ -345,10 +345,10 @@ export function readCompiledSkill(domain: string, skillId: string): string {
345
345
  .find((skill) => skill.domain === domain && skill.id === skillId);
346
346
  if (pluginSkill) return pluginSkill.content;
347
347
 
348
- const domainSkills = compiledSkillsCatalog[domain];
348
+ const domainSkills = Object.hasOwn(compiledSkillsCatalog, domain) ? compiledSkillsCatalog[domain] : undefined;
349
349
  if (!domainSkills) return `Error: Domain ${domain} not found in compiled skills.`;
350
350
 
351
- const skillData = domainSkills[skillId];
351
+ const skillData = Object.hasOwn(domainSkills, skillId) ? domainSkills[skillId] : undefined;
352
352
  if (!skillData) return `Error: Skill ${skillId} not found in domain ${domain}.`;
353
353
 
354
354
  return skillData.content;
@@ -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
  }