@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
@@ -18,15 +18,91 @@ function decodeEntities(text) {
18
18
  return Number.isInteger(codePoint) && codePoint > 0 && codePoint <= 0x10ffff &&
19
19
  !(codePoint >= 0xd800 && codePoint <= 0xdfff) ? String.fromCodePoint(codePoint) : full;
20
20
  }
21
- return named[normalized] ?? full;
21
+ return Object.hasOwn(named, normalized) ? named[normalized] : full;
22
22
  });
23
23
  }
24
+ const SKIP_CONTENT_TAGS = new Set(['script', 'style', 'svg', 'noscript']);
25
+ const BLOCK_CLOSE_TAGS = new Set(['p', 'div', 'article', 'section', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'tr']);
24
26
  export function htmlToReadableText(html) {
25
- return decodeEntities(String(html ?? ''))
26
- .replace(/<(script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
27
- .replace(/<\s*br\s*\/?>/gi, '\n')
28
- .replace(/<\/(p|div|article|section|li|h[1-6]|tr)>/gi, '\n')
29
- .replace(/<[^>]+>/g, ' ')
27
+ const src = String(html ?? '');
28
+ const parts = [];
29
+ let skipTag = null;
30
+ let i = 0;
31
+ while (i < src.length) {
32
+ const lt = src.indexOf('<', i);
33
+ if (lt === -1) {
34
+ if (!skipTag)
35
+ parts.push(src.slice(i));
36
+ break;
37
+ }
38
+ if (!skipTag && lt > i) {
39
+ parts.push(src.slice(i, lt));
40
+ }
41
+ // HTML comments: <!-- ... -->
42
+ if (src.startsWith('<!--', lt)) {
43
+ const commentEnd = src.indexOf('-->', lt + 4);
44
+ i = commentEnd === -1 ? src.length : commentEnd + 3;
45
+ if (!skipTag)
46
+ parts.push(' ');
47
+ continue;
48
+ }
49
+ let gt = lt + 1;
50
+ let quote = null;
51
+ while (gt < src.length) {
52
+ const ch = src[gt];
53
+ if (quote) {
54
+ if (ch === quote)
55
+ quote = null;
56
+ }
57
+ else if (ch === '"' || ch === "'") {
58
+ quote = ch;
59
+ }
60
+ else if (ch === '>') {
61
+ break;
62
+ }
63
+ gt++;
64
+ }
65
+ if (gt >= src.length) {
66
+ // Unclosed '<': emit remaining literal text if not inside a skipped element
67
+ if (!skipTag)
68
+ parts.push(src.slice(lt));
69
+ break;
70
+ }
71
+ const rawTag = src.slice(lt + 1, gt).trim();
72
+ const isClosing = rawTag.startsWith('/');
73
+ const isSelfClosing = !isClosing && rawTag.endsWith('/');
74
+ let nameStart = isClosing ? 1 : 0;
75
+ while (nameStart < rawTag.length && (rawTag[nameStart] === ' ' || rawTag[nameStart] === '\t' || rawTag[nameStart] === '\n' || rawTag[nameStart] === '\r')) {
76
+ nameStart++;
77
+ }
78
+ let nameEnd = nameStart;
79
+ while (nameEnd < rawTag.length) {
80
+ const code = rawTag.charCodeAt(nameEnd);
81
+ const isAlphaNum = (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
82
+ if (!isAlphaNum)
83
+ break;
84
+ nameEnd++;
85
+ }
86
+ const tagName = rawTag.slice(nameStart, nameEnd).toLowerCase();
87
+ if (skipTag) {
88
+ if (isClosing && tagName === skipTag) {
89
+ skipTag = null;
90
+ parts.push(' ');
91
+ }
92
+ }
93
+ else if (!isClosing && !isSelfClosing && SKIP_CONTENT_TAGS.has(tagName)) {
94
+ skipTag = tagName;
95
+ parts.push(' ');
96
+ }
97
+ else if (tagName === 'br' || (isClosing && BLOCK_CLOSE_TAGS.has(tagName))) {
98
+ parts.push('\n');
99
+ }
100
+ else {
101
+ parts.push(' ');
102
+ }
103
+ i = gt + 1;
104
+ }
105
+ return decodeEntities(parts.join(''))
30
106
  .replace(/[ \t]+/g, ' ')
31
107
  .replace(/ *\n */g, '\n')
32
108
  .replace(/\n{3,}/g, '\n\n')
@@ -208,10 +284,16 @@ export const webFetch = {
208
284
  async execute(args, sandbox) {
209
285
  const controller = new AbortController();
210
286
  const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
287
+ const requestSignal = sandbox?.signal ? AbortSignal.any([sandbox.signal, controller.signal]) : controller.signal;
211
288
  try {
212
- if (!args.url)
289
+ if (!args || typeof args !== 'object' || typeof args.url !== 'string' || !args.url.trim()) {
213
290
  return { success: false, error: 'url is required' };
214
- const workspace = path.resolve(sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd());
291
+ }
292
+ const rawWorkspace = sandbox?.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)?.trim()
293
+ ?? sandbox?.parentLoop?.workspaceRoot?.trim()
294
+ ?? sandbox?.workspaceRoot?.trim()
295
+ ?? process.cwd();
296
+ const workspace = path.resolve(rawWorkspace);
215
297
  if (args.method !== undefined && typeof args.method !== 'string') {
216
298
  return { success: false, error: 'HTTP method must be a string' };
217
299
  }
@@ -222,6 +304,16 @@ export const webFetch = {
222
304
  if (args.outputFile !== undefined && (typeof args.outputFile !== 'string' || !args.outputFile.trim())) {
223
305
  return { success: false, error: 'Download outputFile must be a non-empty string' };
224
306
  }
307
+ if (args.outputFile) {
308
+ const trimmedOut = args.outputFile.trim();
309
+ if (trimmedOut.endsWith('/') || trimmedOut.endsWith('\\')) {
310
+ return { success: false, error: 'Download outputFile must point to a file, not a directory' };
311
+ }
312
+ const preTarget = path.resolve(workspace, trimmedOut);
313
+ if (!isWithin(workspace, preTarget)) {
314
+ return { success: false, error: 'Download target must stay inside the selected workspace' };
315
+ }
316
+ }
225
317
  if (method === 'HEAD' && args.outputFile) {
226
318
  return { success: false, error: 'HEAD responses cannot be downloaded as resource files' };
227
319
  }
@@ -230,7 +322,7 @@ export const webFetch = {
230
322
  Accept: 'text/html,application/xhtml+xml,application/json,text/plain,*/*;q=0.8',
231
323
  ...validatedHeaders(args.headers)
232
324
  };
233
- const request = { method, headers, signal: controller.signal };
325
+ const request = { method, headers, signal: requestSignal };
234
326
  if (args.body !== undefined) {
235
327
  if (typeof args.body !== 'string')
236
328
  return { success: false, error: 'HTTP request body must be a string' };
@@ -329,8 +421,11 @@ export const webFetch = {
329
421
  return { success: true, output, status: response.status, finalUrl: finalUrl.href, contentType };
330
422
  }
331
423
  catch (error) {
424
+ if (sandbox?.signal?.aborted) {
425
+ return { success: false, error: 'Request aborted' };
426
+ }
332
427
  const message = error instanceof Error ? error.message : String(error);
333
- const timedOut = error instanceof Error && (error.name === 'AbortError' || message === 'This operation was aborted');
428
+ const timedOut = controller.signal.aborted || (error instanceof Error && (error.name === 'AbortError' || message === 'This operation was aborted'));
334
429
  return { success: false, error: timedOut ? `Request timed out after ${REQUEST_TIMEOUT_MS}ms` : message };
335
430
  }
336
431
  finally {
@@ -21,16 +21,90 @@ function decodeEntities(text: string): string {
21
21
  return Number.isInteger(codePoint) && codePoint > 0 && codePoint <= 0x10ffff &&
22
22
  !(codePoint >= 0xd800 && codePoint <= 0xdfff) ? String.fromCodePoint(codePoint) : full;
23
23
  }
24
- return named[normalized] ?? full;
24
+ return Object.hasOwn(named, normalized) ? named[normalized]! : full;
25
25
  });
26
26
  }
27
27
 
28
+ const SKIP_CONTENT_TAGS = new Set(['script', 'style', 'svg', 'noscript']);
29
+ const BLOCK_CLOSE_TAGS = new Set(['p', 'div', 'article', 'section', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'tr']);
30
+
28
31
  export function htmlToReadableText(html: string): string {
29
- return decodeEntities(String(html ?? ''))
30
- .replace(/<(script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
31
- .replace(/<\s*br\s*\/?>/gi, '\n')
32
- .replace(/<\/(p|div|article|section|li|h[1-6]|tr)>/gi, '\n')
33
- .replace(/<[^>]+>/g, ' ')
32
+ const src = String(html ?? '');
33
+ const parts: string[] = [];
34
+ let skipTag: string | null = null;
35
+ let i = 0;
36
+
37
+ while (i < src.length) {
38
+ const lt = src.indexOf('<', i);
39
+ if (lt === -1) {
40
+ if (!skipTag) parts.push(src.slice(i));
41
+ break;
42
+ }
43
+ if (!skipTag && lt > i) {
44
+ parts.push(src.slice(i, lt));
45
+ }
46
+
47
+ // HTML comments: <!-- ... -->
48
+ if (src.startsWith('<!--', lt)) {
49
+ const commentEnd = src.indexOf('-->', lt + 4);
50
+ i = commentEnd === -1 ? src.length : commentEnd + 3;
51
+ if (!skipTag) parts.push(' ');
52
+ continue;
53
+ }
54
+
55
+ let gt = lt + 1;
56
+ let quote: string | null = null;
57
+ while (gt < src.length) {
58
+ const ch = src[gt]!;
59
+ if (quote) {
60
+ if (ch === quote) quote = null;
61
+ } else if (ch === '"' || ch === "'") {
62
+ quote = ch;
63
+ } else if (ch === '>') {
64
+ break;
65
+ }
66
+ gt++;
67
+ }
68
+ if (gt >= src.length) {
69
+ // Unclosed '<': emit remaining literal text if not inside a skipped element
70
+ if (!skipTag) parts.push(src.slice(lt));
71
+ break;
72
+ }
73
+
74
+ const rawTag = src.slice(lt + 1, gt).trim();
75
+ const isClosing = rawTag.startsWith('/');
76
+ const isSelfClosing = !isClosing && rawTag.endsWith('/');
77
+ let nameStart = isClosing ? 1 : 0;
78
+ while (nameStart < rawTag.length && (rawTag[nameStart] === ' ' || rawTag[nameStart] === '\t' || rawTag[nameStart] === '\n' || rawTag[nameStart] === '\r')) {
79
+ nameStart++;
80
+ }
81
+ let nameEnd = nameStart;
82
+ while (nameEnd < rawTag.length) {
83
+ const code = rawTag.charCodeAt(nameEnd);
84
+ const isAlphaNum = (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
85
+ if (!isAlphaNum) break;
86
+ nameEnd++;
87
+ }
88
+ const tagName = rawTag.slice(nameStart, nameEnd).toLowerCase();
89
+
90
+ if (skipTag) {
91
+ if (isClosing && tagName === skipTag) {
92
+ skipTag = null;
93
+ parts.push(' ');
94
+ }
95
+ } else if (!isClosing && !isSelfClosing && SKIP_CONTENT_TAGS.has(tagName)) {
96
+ skipTag = tagName;
97
+ parts.push(' ');
98
+ } else if (tagName === 'br' || (isClosing && BLOCK_CLOSE_TAGS.has(tagName))) {
99
+ parts.push('\n');
100
+ } else {
101
+ parts.push(' ');
102
+ }
103
+
104
+ i = gt + 1;
105
+ }
106
+
107
+ return decodeEntities(parts.join(''))
34
108
  .replace(/[ \t]+/g, ' ')
35
109
  .replace(/ *\n */g, '\n')
36
110
  .replace(/\n{3,}/g, '\n\n')
@@ -207,13 +281,20 @@ export const webFetch = {
207
281
 
208
282
  async execute(
209
283
  args: { url?: string; method?: string; headers?: unknown; body?: string; outputFile?: string },
210
- sandbox?: { workspacePaths?: string[]; workspaceRoot?: string }
284
+ sandbox?: { workspacePaths?: string[]; workspaceRoot?: string; signal?: AbortSignal; parentLoop?: { workspaceRoot?: string } }
211
285
  ) {
212
286
  const controller = new AbortController();
213
287
  const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
288
+ const requestSignal = sandbox?.signal ? AbortSignal.any([sandbox.signal, controller.signal]) : controller.signal;
214
289
  try {
215
- if (!args.url) return { success: false, error: 'url is required' };
216
- const workspace = path.resolve(sandbox?.workspacePaths?.[0] ?? sandbox?.workspaceRoot ?? process.cwd());
290
+ if (!args || typeof args !== 'object' || typeof args.url !== 'string' || !args.url.trim()) {
291
+ return { success: false, error: 'url is required' };
292
+ }
293
+ const rawWorkspace = sandbox?.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)?.trim()
294
+ ?? sandbox?.parentLoop?.workspaceRoot?.trim()
295
+ ?? sandbox?.workspaceRoot?.trim()
296
+ ?? process.cwd();
297
+ const workspace = path.resolve(rawWorkspace);
217
298
  if (args.method !== undefined && typeof args.method !== 'string') {
218
299
  return { success: false, error: 'HTTP method must be a string' };
219
300
  }
@@ -224,6 +305,16 @@ export const webFetch = {
224
305
  if (args.outputFile !== undefined && (typeof args.outputFile !== 'string' || !args.outputFile.trim())) {
225
306
  return { success: false, error: 'Download outputFile must be a non-empty string' };
226
307
  }
308
+ if (args.outputFile) {
309
+ const trimmedOut = args.outputFile.trim();
310
+ if (trimmedOut.endsWith('/') || trimmedOut.endsWith('\\')) {
311
+ return { success: false, error: 'Download outputFile must point to a file, not a directory' };
312
+ }
313
+ const preTarget = path.resolve(workspace, trimmedOut);
314
+ if (!isWithin(workspace, preTarget)) {
315
+ return { success: false, error: 'Download target must stay inside the selected workspace' };
316
+ }
317
+ }
227
318
  if (method === 'HEAD' && args.outputFile) {
228
319
  return { success: false, error: 'HEAD responses cannot be downloaded as resource files' };
229
320
  }
@@ -232,7 +323,7 @@ export const webFetch = {
232
323
  Accept: 'text/html,application/xhtml+xml,application/json,text/plain,*/*;q=0.8',
233
324
  ...validatedHeaders(args.headers)
234
325
  };
235
- const request: RequestInit = { method, headers, signal: controller.signal };
326
+ const request: RequestInit = { method, headers, signal: requestSignal };
236
327
  if (args.body !== undefined) {
237
328
  if (typeof args.body !== 'string') return { success: false, error: 'HTTP request body must be a string' };
238
329
  if (method === 'GET' || method === 'HEAD') return { success: false, error: `${method} requests cannot contain a body` };
@@ -330,8 +421,11 @@ export const webFetch = {
330
421
  : readable;
331
422
  return { success: true, output, status: response.status, finalUrl: finalUrl.href, contentType };
332
423
  } catch (error) {
424
+ if (sandbox?.signal?.aborted) {
425
+ return { success: false, error: 'Request aborted' };
426
+ }
333
427
  const message = error instanceof Error ? error.message : String(error);
334
- const timedOut = error instanceof Error && (error.name === 'AbortError' || message === 'This operation was aborted');
428
+ const timedOut = controller.signal.aborted || (error instanceof Error && (error.name === 'AbortError' || message === 'This operation was aborted'));
335
429
  return { success: false, error: timedOut ? `Request timed out after ${REQUEST_TIMEOUT_MS}ms` : message };
336
430
  } finally {
337
431
  clearTimeout(timer);
package/src/tui/banner.js CHANGED
@@ -138,7 +138,7 @@ export function detect(o = {}, stream = process.stdout) {
138
138
  else {
139
139
  const f = env['FORCE_COLOR'];
140
140
  if (f !== undefined && f !== '')
141
- color = FORCE[f] ?? '16';
141
+ color = Object.hasOwn(FORCE, f) ? FORCE[f] : '16';
142
142
  else if (env['NO_COLOR'] || env['CAUSYNE_NO_COLOR'] === '1')
143
143
  color = 'none';
144
144
  else if (!tty || env['TERM'] === 'dumb')
@@ -351,7 +351,8 @@ export function providerLabel(provider) {
351
351
  'acp/copilot': 'Copilot (ACP)', 'acp/kimi': 'Kimi (ACP)',
352
352
  'acp/goose': 'Goose (ACP)', 'acp/hermes': 'Hermes (ACP)'
353
353
  };
354
- return known[raw.toLowerCase()] ?? raw;
354
+ const key = raw.toLowerCase();
355
+ return Object.hasOwn(known, key) ? known[key] : raw;
355
356
  }
356
357
  function sessionInfo(info) {
357
358
  const provider = providerLabel(info.provider);
package/src/tui/banner.ts CHANGED
@@ -174,7 +174,7 @@ export function detect(o: BannerOptions = {}, stream: TermStream = process.stdou
174
174
  else if (typeof want === 'string' && VALID_COLORS.has(want as ColorMode)) color = want as ColorMode;
175
175
  else {
176
176
  const f = env['FORCE_COLOR'];
177
- if (f !== undefined && f !== '') color = FORCE[f] ?? '16';
177
+ if (f !== undefined && f !== '') color = Object.hasOwn(FORCE, f) ? FORCE[f]! : '16';
178
178
  else if (env['NO_COLOR'] || env['CAUSYNE_NO_COLOR'] === '1') color = 'none';
179
179
  else if (!tty || env['TERM'] === 'dumb') color = 'none';
180
180
  else {
@@ -350,7 +350,8 @@ export function providerLabel(provider: unknown): string {
350
350
  'acp/copilot': 'Copilot (ACP)', 'acp/kimi': 'Kimi (ACP)',
351
351
  'acp/goose': 'Goose (ACP)', 'acp/hermes': 'Hermes (ACP)'
352
352
  };
353
- return known[raw.toLowerCase()] ?? raw;
353
+ const key = raw.toLowerCase();
354
+ return Object.hasOwn(known, key) ? known[key]! : raw;
354
355
  }
355
356
 
356
357
  function sessionInfo(info: BannerInfo): BannerInfo {
@@ -36,7 +36,9 @@ export function runWithStageWrite(fn) {
36
36
  function chunkToText(chunk, encodingOrCb) {
37
37
  if (typeof chunk === 'string')
38
38
  return chunk;
39
- const encoding = typeof encodingOrCb === 'string' ? encodingOrCb : 'utf8';
39
+ const encoding = typeof encodingOrCb === 'string' && Buffer.isEncoding(encodingOrCb)
40
+ ? encodingOrCb
41
+ : 'utf8';
40
42
  if (Buffer.isBuffer(chunk))
41
43
  return chunk.toString(encoding);
42
44
  if (chunk instanceof Uint8Array)
@@ -48,7 +50,7 @@ export function isAnyStageReservedOnStdout() {
48
50
  return true;
49
51
  }
50
52
  for (const host of activeStageHosts) {
51
- if (host.stage?.reserved && (!host.out || host.out === process.stdout)) {
53
+ if (host?.stage?.reserved && (!host.out || host.out === process.stdout)) {
52
54
  return true;
53
55
  }
54
56
  }
@@ -116,6 +118,8 @@ export function setStageConsoleGuardActive(active) {
116
118
  * Register a StageSurface host so raw console writes are suppressed while its Stage is reserved.
117
119
  */
118
120
  export function registerStageConsoleGuard(host) {
121
+ if (!host || typeof host !== 'object')
122
+ return () => { };
119
123
  ensureConsoleGuardInstalled();
120
124
  activeStageHosts.add(host);
121
125
  return () => {
@@ -128,6 +132,8 @@ const noticeTimers = new WeakMap();
128
132
  * if nothing else has overwritten `host.notice` in the meantime.
129
133
  */
130
134
  export function setTransientNotice(host, message, ttlMs = 4000) {
135
+ if (!host || typeof host !== 'object')
136
+ return;
131
137
  const existing = noticeTimers.get(host);
132
138
  if (existing) {
133
139
  clearTimeout(existing);
@@ -137,7 +143,8 @@ export function setTransientNotice(host, message, ttlMs = 4000) {
137
143
  ? safeDisplay(message).replace(/\s+/g, ' ').trim()
138
144
  : '';
139
145
  host.notice = cleanMessage;
140
- host.scheduleDraw();
146
+ if (typeof host.scheduleDraw === 'function')
147
+ host.scheduleDraw();
141
148
  const safeTtlMs = !Number.isFinite(ttlMs)
142
149
  ? (Number.isNaN(ttlMs) ? 4000 : 0)
143
150
  : Math.min(Math.floor(ttlMs), 2_147_483_647);
@@ -147,7 +154,8 @@ export function setTransientNotice(host, message, ttlMs = 4000) {
147
154
  noticeTimers.delete(host);
148
155
  if (host.notice === cleanMessage) {
149
156
  host.notice = '';
150
- host.scheduleDraw();
157
+ if (typeof host.scheduleDraw === 'function')
158
+ host.scheduleDraw();
151
159
  }
152
160
  }, safeTtlMs);
153
161
  timer.unref?.();
@@ -51,7 +51,10 @@ export function runWithStageWrite<T>(fn: () => T): T {
51
51
 
52
52
  function chunkToText(chunk: unknown, encodingOrCb?: unknown): string {
53
53
  if (typeof chunk === 'string') return chunk;
54
- const encoding = typeof encodingOrCb === 'string' ? encodingOrCb as BufferEncoding : 'utf8';
54
+ const encoding: BufferEncoding =
55
+ typeof encodingOrCb === 'string' && Buffer.isEncoding(encodingOrCb)
56
+ ? encodingOrCb
57
+ : 'utf8';
55
58
  if (Buffer.isBuffer(chunk)) return chunk.toString(encoding);
56
59
  if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString(encoding);
57
60
  return String(chunk ?? '');
@@ -62,7 +65,7 @@ export function isAnyStageReservedOnStdout(): boolean {
62
65
  return true;
63
66
  }
64
67
  for (const host of activeStageHosts) {
65
- if (host.stage?.reserved && (!host.out || host.out === process.stdout)) {
68
+ if (host?.stage?.reserved && (!host.out || host.out === process.stdout)) {
66
69
  return true;
67
70
  }
68
71
  }
@@ -131,6 +134,7 @@ export function setStageConsoleGuardActive(active: boolean): void {
131
134
  * Register a StageSurface host so raw console writes are suppressed while its Stage is reserved.
132
135
  */
133
136
  export function registerStageConsoleGuard(host: ConsoleGuardStageHost): () => void {
137
+ if (!host || typeof host !== 'object') return () => {};
134
138
  ensureConsoleGuardInstalled();
135
139
  activeStageHosts.add(host);
136
140
  return () => {
@@ -145,6 +149,7 @@ const noticeTimers = new WeakMap<TransientNoticeHost, ReturnType<typeof setTimeo
145
149
  * if nothing else has overwritten `host.notice` in the meantime.
146
150
  */
147
151
  export function setTransientNotice(host: TransientNoticeHost, message: string, ttlMs = 4000): void {
152
+ if (!host || typeof host !== 'object') return;
148
153
  const existing = noticeTimers.get(host);
149
154
  if (existing) {
150
155
  clearTimeout(existing);
@@ -154,7 +159,7 @@ export function setTransientNotice(host: TransientNoticeHost, message: string, t
154
159
  ? safeDisplay(message).replace(/\s+/g, ' ').trim()
155
160
  : '';
156
161
  host.notice = cleanMessage;
157
- host.scheduleDraw();
162
+ if (typeof host.scheduleDraw === 'function') host.scheduleDraw();
158
163
  const safeTtlMs = !Number.isFinite(ttlMs)
159
164
  ? (Number.isNaN(ttlMs) ? 4000 : 0)
160
165
  : Math.min(Math.floor(ttlMs), 2_147_483_647);
@@ -164,7 +169,7 @@ export function setTransientNotice(host: TransientNoticeHost, message: string, t
164
169
  noticeTimers.delete(host);
165
170
  if (host.notice === cleanMessage) {
166
171
  host.notice = '';
167
- host.scheduleDraw();
172
+ if (typeof host.scheduleDraw === 'function') host.scheduleDraw();
168
173
  }
169
174
  }, safeTtlMs);
170
175
  timer.unref?.();
@@ -3,7 +3,7 @@ import { revokeAllAlways } from '../approvalGrants.js';
3
3
  // @ts-expect-error Legacy checkpoints module has no TypeScript declarations yet.
4
4
  import { undoLast } from '../checkpoints.js';
5
5
  import { writeClipboardSync } from './clipboardSync.js';
6
- import { registerStageConsoleGuard, setTransientNotice } from './consoleGuard.js';
6
+ import { setTransientNotice } from './consoleGuard.js';
7
7
  import { detectLinkAtPoint, openDetectedLink } from './smartLinkClick.js';
8
8
  import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
9
9
  import { safeDisplay, stripAnsi, truncate, padEnd, visibleWidth } from './text.js';
@@ -102,7 +102,7 @@ export class MessageActionsLayer extends Layer {
102
102
  this.onPick(this.items[this.list.selected] ?? null);
103
103
  return 'close';
104
104
  }
105
- if (!event.ctrl && !event.alt && keyName && (keyName.length === 1 || keyName === 'space' || keyName === 'backspace')) {
105
+ if (!event.ctrl && !event.alt && !event.meta && keyName && (keyName === 'char' || keyName === 'paste' || keyName.length === 1 || keyName === 'space' || keyName === 'backspace')) {
106
106
  this.settled = true;
107
107
  this.onPick(null);
108
108
  return 'dismiss';
@@ -235,7 +235,6 @@ export function messageAt(surface, point) {
235
235
  }
236
236
  /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
237
237
  export function markHoveredMessage(rows, surface, contentWidth) {
238
- registerStageConsoleGuard(surface);
239
238
  if (!Array.isArray(rows) || rows.length === 0 || !surface?.transcript?.flatten)
240
239
  return;
241
240
  const safeContentWidth = Number.isFinite(contentWidth) && contentWidth > 0 ? Math.floor(contentWidth) : 1;
@@ -9,7 +9,7 @@ import { revokeAllAlways } from '../approvalGrants.js';
9
9
  // @ts-expect-error Legacy checkpoints module has no TypeScript declarations yet.
10
10
  import { undoLast } from '../checkpoints.js';
11
11
  import { writeClipboardSync } from './clipboardSync.js';
12
- import { registerStageConsoleGuard, setTransientNotice } from './consoleGuard.js';
12
+ import { setTransientNotice } from './consoleGuard.js';
13
13
  import { detectLinkAtPoint, openDetectedLink } from './smartLinkClick.js';
14
14
  import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
15
15
  import { safeDisplay, stripAnsi, truncate, padEnd, visibleWidth } from './text.js';
@@ -156,7 +156,7 @@ export class MessageActionsLayer extends Layer {
156
156
  this.onPick(this.items[this.list.selected] ?? null);
157
157
  return 'close';
158
158
  }
159
- if (!event.ctrl && !event.alt && keyName && (keyName.length === 1 || keyName === 'space' || keyName === 'backspace')) {
159
+ if (!event.ctrl && !event.alt && !(event as { meta?: boolean }).meta && keyName && (keyName === 'char' || keyName === 'paste' || keyName.length === 1 || keyName === 'space' || keyName === 'backspace')) {
160
160
  this.settled = true;
161
161
  this.onPick(null);
162
162
  return 'dismiss';
@@ -326,7 +326,6 @@ export function messageAt(surface: MessageSurface | null, point: MousePoint): Me
326
326
  export function markHoveredMessage(
327
327
  rows: string[], surface: MessageSurface, contentWidth: number
328
328
  ): void {
329
- registerStageConsoleGuard(surface);
330
329
  if (!Array.isArray(rows) || rows.length === 0 || !surface?.transcript?.flatten) return;
331
330
  const safeContentWidth = Number.isFinite(contentWidth) && contentWidth > 0 ? Math.floor(contentWidth) : 1;
332
331
  const id = surface.hoveredMessageFrameId;
@@ -420,6 +420,7 @@ export class ModelPickerLayer extends SelectLayer {
420
420
  }
421
421
  if (action === 'cancel') {
422
422
  this.settled = true;
423
+ this.onPick?.(null);
423
424
  return 'close';
424
425
  }
425
426
  return action ? 'handled' : null;
@@ -513,6 +513,7 @@ export class ModelPickerLayer extends SelectLayer {
513
513
 
514
514
  if (action === 'cancel') {
515
515
  this.settled = true;
516
+ this.onPick?.(null);
516
517
  return 'close';
517
518
  }
518
519
  return action ? 'handled' : null;
@@ -156,10 +156,12 @@ export class Layer {
156
156
  const maxH = vh - 4 >= 5 ? vh - 4 : vh;
157
157
  const wanted = Math.max(3, Math.min(safePreferred, layerHeight));
158
158
  const height = Math.min(wanted, Math.max(3, maxH));
159
+ const slackY = Math.max(0, vh - height);
160
+ const topGap = slackY > 0 ? Math.min(slackY, Math.max(1, Math.floor(slackY / 4))) : 0;
159
161
  return {
160
162
  x: vx + Math.floor((vw - width) / 2),
161
163
  // A quarter down reads as centred; dead centre sits visually too low.
162
- y: vy + Math.max(1, Math.floor((vh - height) / 4)),
164
+ y: vy + topGap,
163
165
  width,
164
166
  height
165
167
  };
@@ -208,10 +208,12 @@ export class Layer {
208
208
  const maxH = vh - 4 >= 5 ? vh - 4 : vh;
209
209
  const wanted = Math.max(3, Math.min(safePreferred, layerHeight));
210
210
  const height = Math.min(wanted, Math.max(3, maxH));
211
+ const slackY = Math.max(0, vh - height);
212
+ const topGap = slackY > 0 ? Math.min(slackY, Math.max(1, Math.floor(slackY / 4))) : 0;
211
213
  return {
212
214
  x: vx + Math.floor((vw - width) / 2),
213
215
  // A quarter down reads as centred; dead centre sits visually too low.
214
- y: vy + Math.max(1, Math.floor((vh - height) / 4)),
216
+ y: vy + topGap,
215
217
  width,
216
218
  height
217
219
  };
@@ -171,8 +171,9 @@ export function formatSessionsTextReport(sessions, activeId, currentWorkspace, l
171
171
  }
172
172
  }
173
173
  const formatRow = (s) => {
174
- const when = Number.isFinite(s.updatedAt)
175
- ? new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ')
174
+ const dt = Number.isFinite(s.updatedAt) ? new Date(s.updatedAt) : null;
175
+ const when = dt && Number.isFinite(dt.getTime())
176
+ ? dt.toISOString().slice(0, 16).replace('T', ' ')
176
177
  : 'unknown date';
177
178
  const where = s.workspace ? shortenWorkspacePath(s.workspace) : '(no workspace)';
178
179
  const mark = s.id === activeId ? '*' : ' ';
@@ -240,8 +240,9 @@ export function formatSessionsTextReport(
240
240
  }
241
241
 
242
242
  const formatRow = (s: Omit<SessionRecord, 'messages'> & { messageCount: number }): string => {
243
- const when = Number.isFinite(s.updatedAt)
244
- ? new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ')
243
+ const dt = Number.isFinite(s.updatedAt) ? new Date(s.updatedAt) : null;
244
+ const when = dt && Number.isFinite(dt.getTime())
245
+ ? dt.toISOString().slice(0, 16).replace('T', ' ')
245
246
  : 'unknown date';
246
247
  const where = s.workspace ? shortenWorkspacePath(s.workspace) : '(no workspace)';
247
248
  const mark = s.id === activeId ? '*' : ' ';
@@ -385,7 +385,13 @@ export class SessionPickerLayer extends SelectLayer {
385
385
  const selected = Math.max(0, Math.min(Math.floor(this.list.selected || 0), entries.length - 1));
386
386
  const window = renderSessionRows(entries, offset, selected, this.lastWidth, available, this.renderOptions(entries));
387
387
  const page = Math.max(1, window.lastIndex - offset + 1);
388
- this.list.move(event.name === 'pageup' ? -page : page, available);
388
+ const target = Math.max(0, Math.min(entries.length - 1, selected + (event.name === 'pageup' ? -page : page)));
389
+ if (typeof this.list.moveTo === 'function') {
390
+ this.list.moveTo(target, available);
391
+ }
392
+ else {
393
+ this.list.move(target - selected, available);
394
+ }
389
395
  return 'handled';
390
396
  }
391
397
  const previousQuery = this.list.query;
@@ -473,7 +473,12 @@ export class SessionPickerLayer extends SelectLayer {
473
473
  const selected = Math.max(0, Math.min(Math.floor(this.list.selected || 0), entries.length - 1));
474
474
  const window = renderSessionRows(entries, offset, selected, this.lastWidth, available, this.renderOptions(entries));
475
475
  const page = Math.max(1, window.lastIndex - offset + 1);
476
- this.list.move(event.name === 'pageup' ? -page : page, available);
476
+ const target = Math.max(0, Math.min(entries.length - 1, selected + (event.name === 'pageup' ? -page : page)));
477
+ if (typeof this.list.moveTo === 'function') {
478
+ this.list.moveTo(target, available);
479
+ } else {
480
+ this.list.move(target - selected, available);
481
+ }
477
482
  return 'handled';
478
483
  }
479
484
  const previousQuery = this.list.query;
@@ -43,6 +43,7 @@ export function cleanToolOutputPreview(payload, toolName = '') {
43
43
  if (!trimmed || trimmed.startsWith(DECAY_MARKER))
44
44
  return '';
45
45
  let text = payload
46
+ .replace(/\r\n?/g, '\n')
46
47
  .replace(/\x1b\[(?:[12]K|\d*G)/g, '\n')
47
48
  .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
48
49
  // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
@@ -127,9 +128,7 @@ function recoverBrokenJsonOutput(raw, spillPath) {
127
128
  if (outputMatch?.[1]) {
128
129
  const body = outputMatch[1]
129
130
  .replace(/"\s*\}\s*$/, '')
130
- .replace(/\\n/g, '\n')
131
- .replace(/\\"/g, '"')
132
- .replace(/\\\\/g, '\\');
131
+ .replace(/\\([\\nrt"])/g, (_m, ch) => ch === 'n' ? '\n' : ch === 'r' ? '\r' : ch === 't' ? '\t' : ch);
133
132
  return {
134
133
  success,
135
134
  output: body,