@causyne/agent 1.20.0 → 1.20.5

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 (125) hide show
  1. package/README.md +0 -18
  2. package/package.json +1 -1
  3. package/src/acp/client.js +2 -1
  4. package/src/acp/client.ts +2 -1
  5. package/src/acp/server.js +5 -6
  6. package/src/acp/server.ts +4 -6
  7. package/src/agentLoop.d.ts +1 -0
  8. package/src/agentLoop.js +505 -241
  9. package/src/agentLoop.ts +527 -258
  10. package/src/agentPolicy.js +9 -0
  11. package/src/agentPolicy.ts +9 -0
  12. package/src/approvalPolicy.js +55 -0
  13. package/src/approvalPolicy.ts +66 -0
  14. package/src/browser/browserRuntime.js +217 -14
  15. package/src/browser/browserRuntime.ts +255 -14
  16. package/src/browser/causyneBrowser.js +1215 -68
  17. package/src/browser/causyneBrowser.ts +1340 -72
  18. package/src/cliMode.js +52 -29
  19. package/src/commands.js +141 -17
  20. package/src/config.js +22 -12
  21. package/src/continuum/ui/continuumPicker.js +18 -1
  22. package/src/continuum/ui/continuumPicker.ts +19 -1
  23. package/src/dynamicCatalogue.js +87 -20
  24. package/src/dynamicCatalogue.ts +85 -15
  25. package/src/launchIntent.js +40 -0
  26. package/src/launchIntent.ts +49 -0
  27. package/src/memoryManager.js +26 -2
  28. package/src/modelCatalogue.js +2 -0
  29. package/src/planCache.js +320 -11
  30. package/src/planCache.ts +402 -13
  31. package/src/providers/acp.js +67 -1
  32. package/src/providers/acp.ts +65 -2
  33. package/src/providers/antigravity.d.ts +5 -1
  34. package/src/providers/antigravity.js +643 -32
  35. package/src/providers/antigravity.ts +671 -33
  36. package/src/providers/base.d.ts +9 -0
  37. package/src/providers/factory.js +2 -0
  38. package/src/providers/pi.js +157 -0
  39. package/src/providers/pi.ts +144 -0
  40. package/src/provisioning/capabilityProvisioner.js +17 -0
  41. package/src/provisioning/capabilityTools.js +1 -1
  42. package/src/sandbox.js +30 -39
  43. package/src/sessionJournal.js +53 -10
  44. package/src/sessionJournal.ts +64 -10
  45. package/src/taskShape.js +9 -9
  46. package/src/taskShape.ts +9 -9
  47. package/src/timeMachine.js +124 -0
  48. package/src/timeMachine.ts +141 -0
  49. package/src/toolPacks.js +4 -10
  50. package/src/tools/archive.js +196 -59
  51. package/src/tools/archive.ts +220 -0
  52. package/src/tools/browserAutomator.js +78 -9
  53. package/src/tools/browserAutomator.ts +90 -9
  54. package/src/tools/desktopOpen.js +114 -31
  55. package/src/tools/desktopOpen.ts +144 -0
  56. package/src/tools/gitExec.js +5 -3
  57. package/src/tools/nativeEngine.js +4 -3
  58. package/src/tools/nativeEngine.ts +5 -3
  59. package/src/tools/openSourceToolProvisioner.js +5 -4
  60. package/src/tools/openSourceToolProvisioner.ts +5 -4
  61. package/src/tools/registry.js +3 -0
  62. package/src/tools/screenshot.js +55 -71
  63. package/src/tools/screenshot.ts +70 -0
  64. package/src/tools/sysRun.js +284 -117
  65. package/src/tools/sysRun.ts +347 -0
  66. package/src/tools/toolSelfRepair.js +109 -2
  67. package/src/tools/toolSelfRepair.ts +100 -2
  68. package/src/tools/updatePlan.js +49 -1
  69. package/src/tools/updatePlan.ts +43 -1
  70. package/src/tools/viewImage.js +93 -78
  71. package/src/tools/viewImage.ts +116 -0
  72. package/src/tools/webFetch.js +20 -6
  73. package/src/tools/webFetch.ts +26 -6
  74. package/src/tui/block.d.ts +1 -0
  75. package/src/tui/chatRenderer.d.ts +21 -0
  76. package/src/tui/chatRenderer.js +34 -47
  77. package/src/tui/clipboardSync.js +28 -1
  78. package/src/tui/clipboardSync.ts +26 -1
  79. package/src/tui/codeProgress.js +299 -0
  80. package/src/tui/codeProgress.ts +304 -0
  81. package/src/tui/codeStreamRenderer.js +116 -0
  82. package/src/tui/codeStreamRenderer.ts +124 -0
  83. package/src/tui/commandPresentation.js +11 -0
  84. package/src/tui/commandPresentation.ts +18 -0
  85. package/src/tui/completion.js +45 -13
  86. package/src/tui/composerControls.js +66 -0
  87. package/src/tui/composerControls.ts +78 -0
  88. package/src/tui/diff.d.ts +2 -0
  89. package/src/tui/home.js +4 -2
  90. package/src/tui/homeTransition.js +21 -0
  91. package/src/tui/homeTransition.ts +27 -0
  92. package/src/tui/homeView.js +62 -0
  93. package/src/tui/homeView.ts +91 -0
  94. package/src/tui/layout.js +46 -0
  95. package/src/tui/layout.ts +52 -0
  96. package/src/tui/messageActionPlacement.js +16 -0
  97. package/src/tui/messageActionPlacement.ts +25 -0
  98. package/src/tui/messageInteraction.js +221 -0
  99. package/src/tui/messageInteraction.ts +275 -0
  100. package/src/tui/modelPicker.js +4 -24
  101. package/src/tui/modelPicker.ts +4 -20
  102. package/src/tui/mouseHover.js +6 -0
  103. package/src/tui/mouseHover.ts +5 -0
  104. package/src/tui/prompt.js +152 -76
  105. package/src/tui/resizeRecovery.js +15 -0
  106. package/src/tui/resizeRecovery.ts +27 -0
  107. package/src/tui/scrollInteraction.js +97 -0
  108. package/src/tui/scrollInteraction.ts +189 -0
  109. package/src/tui/sessionLayout.js +12 -0
  110. package/src/tui/sessionLayout.ts +12 -0
  111. package/src/tui/sessionPicker.js +111 -16
  112. package/src/tui/sessionPicker.ts +121 -16
  113. package/src/tui/sessionSidebar.js +78 -0
  114. package/src/tui/sessionSidebar.ts +95 -0
  115. package/src/tui/setup.js +1 -1
  116. package/src/tui/setup.ts +1 -1
  117. package/src/tui/stageSurface.js +120 -58
  118. package/src/tui/text.d.ts +5 -0
  119. package/src/tui/textLayout.js +23 -0
  120. package/src/tui/textLayout.ts +28 -0
  121. package/src/tui/viewport.js +204 -279
  122. package/src/tui/viewport.ts +326 -0
  123. package/src/types/contracts.ts +54 -0
  124. package/src/utils/paths.js +5 -4
  125. package/src/utils/paths.ts +5 -5
@@ -10,7 +10,7 @@
10
10
 
11
11
  import readline from 'readline';
12
12
  import {
13
- paint, bold, dim, badge, GLYPHS, terminalWidth, readableWidth, HAS_COLOR, fileLink,
13
+ paint, bold, dim, badge, GLYPHS, terminalWidth, HAS_COLOR, fileLink,
14
14
  safeLink, HAS_HYPERLINKS
15
15
  } from './theme.js';
16
16
  import {
@@ -21,6 +21,9 @@ import { describeTool } from './toolDisplay.js';
21
21
  import { approvalDiff } from './diff.js';
22
22
  import { StatusLine } from './statusLine.js';
23
23
  import { barBlock } from './block.js';
24
+ import { composerWidth, openingRows, sessionRows } from './layout.js';
25
+ import { sessionComposerWidth } from './sessionSidebar.js';
26
+ import { chatProseWidth, wrappedChatRows } from './textLayout.js';
24
27
 
25
28
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
26
29
  // minified output would otherwise become thousands of rows and lock the
@@ -314,7 +317,7 @@ export class ChatRenderer {
314
317
  this.rowSink = previousSink;
315
318
  this.forcedWidth = previousWidth;
316
319
  }
317
- return sink;
320
+ return sessionRows(sink, width).rows;
318
321
  }
319
322
 
320
323
  /**
@@ -338,16 +341,9 @@ export class ChatRenderer {
338
341
  return Number.isFinite(columns) && columns > 0 ? Math.max(40, columns) : terminalWidth();
339
342
  }
340
343
 
341
- /**
342
- * The width PROSE is wrapped to — narrower than the terminal on a wide one.
343
- *
344
- * Chrome fills the window; paragraphs must not. See readableWidth() in
345
- * theme.js for why, and note the two are deliberately different so that
346
- * stretching the window widens the box without turning the agent's replies
347
- * into 200-character lines.
348
- */
344
+ /** Prose follows the current conversation column with a small text inset. */
349
345
  measure() {
350
- return readableWidth(this.width());
346
+ return chatProseWidth(this.width());
351
347
  }
352
348
 
353
349
  // -------------------------------------------------------------------------
@@ -358,36 +354,15 @@ export class ChatRenderer {
358
354
  * The context the CLI never showed. Which model is about to spend the user's
359
355
  * money, in which autonomy mode, over which paths.
360
356
  */
361
- /**
362
- * Returns the width of the widest row it wrote.
363
- *
364
- * The Stage lays its opening composition out to this, so the input box below
365
- * the banner ends where the banner's text ends instead of stretching past it.
366
- * MEASURED rather than guessed, because the banner is adaptive: it drops hints
367
- * and truncates the workspace list to fit whatever width it is given, so its
368
- * natural width depends on the user's own paths and cannot be a constant. At
369
- * 156 columns it comes out at 122 — and composing it AT 117 already hides
370
- * ~/Causyne, which is why the banner is never the thing that gets narrowed.
371
- */
357
+ /** Write the opening composition and report its companion composer width. */
372
358
  sessionHeader(info = {}) {
373
359
  // The status line shows the same facts during the turn, where the header
374
360
  // has already scrolled away. Mutation first: the closure below runs again
375
361
  // on every reflow and must not re-apply it.
376
362
  this.status.setSession(info);
377
363
 
378
- // Tap the rows on their way past, without disturbing either sink.
379
- const seen = [];
380
- const write = this.write.bind(this);
381
- this.write = (line = '') => { seen.push(line); return write(line); };
382
- try {
383
- this.frame('session', () => this.renderSessionHeader(info));
384
- } finally {
385
- this.write = write;
386
- }
387
-
388
- let widest = 0;
389
- for (const line of seen) widest = Math.max(widest, visibleWidth(String(line)));
390
- return widest;
364
+ this.frame('session', () => this.renderSessionHeader(info));
365
+ return composerWidth(this.width());
391
366
  }
392
367
 
393
368
  renderSessionHeader(info = {}) {
@@ -398,9 +373,7 @@ export class ChatRenderer {
398
373
  // label/value rows, a command count, a blank and a separate key-hint row —
399
374
  // nineteen rows of chrome before the user could type. Both references open
400
375
  // in eight or fewer, with the identity and the facts as a single object.
401
- this.write();
402
- for (const row of sessionBanner(info, width, { height: this.out?.rows })) this.write(row);
403
- this.write();
376
+ const rows = ['', ...sessionBanner(info, width, { height: this.out?.rows }), ''];
404
377
 
405
378
  const hints = [
406
379
  `${info.commandCount || 0} commands`, '/help', 'enter send',
@@ -409,8 +382,8 @@ export class ChatRenderer {
409
382
  const separator = ` ${GLYPHS.dot} `;
410
383
  const kept = hints.slice();
411
384
  while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
412
- this.write(dim(kept.join(separator)));
413
- this.write();
385
+ rows.push(dim(kept.join(separator)), '');
386
+ for (const row of openingRows(rows, width, Number(this.out?.rows))) this.write(row);
414
387
  }
415
388
 
416
389
  /**
@@ -522,7 +495,9 @@ export class ChatRenderer {
522
495
  if (!text.trim()) return;
523
496
 
524
497
  this.frame('user', () => {
525
- const width = this.measure();
498
+ const width = this.transcript
499
+ ? sessionComposerWidth(this.width())
500
+ : composerWidth(this.measure());
526
501
  const blockWidth = Math.max(8, width - 1);
527
502
  const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.bar) - 1);
528
503
  const rows = barBlock(
@@ -534,7 +509,7 @@ export class ChatRenderer {
534
509
  this.write(row);
535
510
  }
536
511
  this.write();
537
- });
512
+ }, { messageText: text });
538
513
  }
539
514
 
540
515
  renderAssistantMessage(content) {
@@ -549,6 +524,7 @@ export class ChatRenderer {
549
524
  }
550
525
 
551
526
  renderSessionDivider(info = {}) {
527
+ this.transcript?.surface?.setSessionInfo?.(info);
552
528
  this.frame('session', () => {
553
529
  const width = this.measure();
554
530
  const title = safeDisplay(info.title || 'Session');
@@ -573,7 +549,10 @@ export class ChatRenderer {
573
549
  * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
574
550
  */
575
551
  renderSessionHistory(messages = [], sessionInfo = null) {
552
+ this.transcript?.surface?.leaveHome?.(true);
576
553
  this.clearTranscript();
554
+ this.latestPlan = [];
555
+ this.onPlanChange?.([]);
577
556
 
578
557
  if (sessionInfo && (sessionInfo.title || sessionInfo.id)) {
579
558
  this.renderSessionDivider(sessionInfo);
@@ -596,6 +575,12 @@ export class ChatRenderer {
596
575
  }
597
576
  }
598
577
  }
578
+
579
+ if (this.transcript?.surface?.viewport) {
580
+ this.transcript.surface.viewport.manual = false;
581
+ this.transcript.surface.viewport.unseen = 0;
582
+ this.transcript.surface.viewport.toBottom();
583
+ }
599
584
  }
600
585
 
601
586
  onAgentMessage(msg) {
@@ -609,7 +594,7 @@ export class ChatRenderer {
609
594
  this.write(line ? ' ' + line : '');
610
595
  }
611
596
  this.write();
612
- });
597
+ }, { messageText: String(msg.content || '') });
613
598
  }
614
599
 
615
600
  /**
@@ -694,7 +679,8 @@ export class ChatRenderer {
694
679
  if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
695
680
  const plan = msg.plan.slice();
696
681
  this.latestPlan = plan;
697
- if (this.onPlanChange) this.onPlanChange(plan);
682
+ const placement = this.onPlanChange?.(plan);
683
+ if (placement === 'sidebar') return;
698
684
  this.frame('plan', () => this.renderPlan(plan), { items: plan.length });
699
685
  }
700
686
 
@@ -771,7 +757,8 @@ export class ChatRenderer {
771
757
  this.renderOutputPreview(result);
772
758
  return;
773
759
  }
774
- this.write(` ${paint('danger', GLYPHS.cross)} ${paint('danger', truncate(safeDisplay(result.error || 'failed'), this.width() - 12, GLYPHS.ellipsis))} ${dim(elapsed)}`);
760
+ const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
761
+ for (const row of wrappedChatRows(detail, this.width(), ` ${paint('danger', GLYPHS.cross)} `, 'danger')) this.write(row);
775
762
  }, { success: Boolean(result.success) });
776
763
  }
777
764
 
@@ -1025,7 +1012,7 @@ export class ChatRenderer {
1025
1012
  const message = safeDisplay(msg.message || '');
1026
1013
  this.frame('error', () => {
1027
1014
  this.write();
1028
- this.write(`${badge('danger', 'ERROR')} ${paint('danger', message)}`);
1015
+ for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger')) this.write(row);
1029
1016
  this.write();
1030
1017
  });
1031
1018
  }
@@ -1033,7 +1020,7 @@ export class ChatRenderer {
1033
1020
  onBudgetWarning(msg) {
1034
1021
  const message = safeDisplay(msg.message || '');
1035
1022
  this.frame('notice', () => {
1036
- this.write(`${badge('warn', 'BUDGET')} ${paint('warn', message)}`);
1023
+ for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn')) this.write(row);
1037
1024
  }, { tone: 'warn' });
1038
1025
  }
1039
1026
 
@@ -1,6 +1,6 @@
1
1
  // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
2
  // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
3
- import { execFileSync } from 'node:child_process';
3
+ import { execFileSync, spawnSync } from 'node:child_process';
4
4
  /**
5
5
  * Read system clipboard text synchronously without hanging or throwing.
6
6
  * Returns empty string if clipboard is empty, unavailable, or unsupported.
@@ -34,3 +34,30 @@ export function readClipboardSync() {
34
34
  }
35
35
  return '';
36
36
  }
37
+ /** Write text through stdin, never through a shell or a command argument. */
38
+ export function writeClipboardSync(value) {
39
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 4_000_000)
40
+ return false;
41
+ const candidates = process.platform === 'darwin'
42
+ ? [['pbcopy', []]]
43
+ : process.platform === 'win32'
44
+ ? [['powershell.exe', ['-NoProfile', '-Command', 'Set-Clipboard -Value ([Console]::In.ReadToEnd())']]]
45
+ : process.platform === 'linux'
46
+ ? [['wl-copy', []], ['xclip', ['-selection', 'clipboard', '-i']]]
47
+ : [];
48
+ for (const [command, args] of candidates) {
49
+ try {
50
+ const result = spawnSync(command, args, {
51
+ input: value,
52
+ encoding: 'utf8',
53
+ timeout: 1500,
54
+ windowsHide: true,
55
+ maxBuffer: 64 * 1024
56
+ });
57
+ if (!result.error && result.status === 0)
58
+ return true;
59
+ }
60
+ catch { /* Try the next available clipboard provider. */ }
61
+ }
62
+ return false;
63
+ }
@@ -1,7 +1,7 @@
1
1
  // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
2
  // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
3
3
 
4
- import { execFileSync } from 'node:child_process';
4
+ import { execFileSync, spawnSync } from 'node:child_process';
5
5
 
6
6
  /**
7
7
  * Read system clipboard text synchronously without hanging or throwing.
@@ -34,3 +34,28 @@ export function readClipboardSync(): string {
34
34
  }
35
35
  return '';
36
36
  }
37
+
38
+ /** Write text through stdin, never through a shell or a command argument. */
39
+ export function writeClipboardSync(value: string): boolean {
40
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 4_000_000) return false;
41
+ const candidates: Array<[string, string[]]> = process.platform === 'darwin'
42
+ ? [['pbcopy', []]]
43
+ : process.platform === 'win32'
44
+ ? [['powershell.exe', ['-NoProfile', '-Command', 'Set-Clipboard -Value ([Console]::In.ReadToEnd())']]]
45
+ : process.platform === 'linux'
46
+ ? [['wl-copy', []], ['xclip', ['-selection', 'clipboard', '-i']]]
47
+ : [];
48
+ for (const [command, args] of candidates) {
49
+ try {
50
+ const result = spawnSync(command, args, {
51
+ input: value,
52
+ encoding: 'utf8',
53
+ timeout: 1500,
54
+ windowsHide: true,
55
+ maxBuffer: 64 * 1024
56
+ });
57
+ if (!result.error && result.status === 0) return true;
58
+ } catch { /* Try the next available clipboard provider. */ }
59
+ }
60
+ return false;
61
+ }
@@ -0,0 +1,299 @@
1
+ import { panel } from './block.js';
2
+ import { safeDisplay, truncate, padEnd } from './text.js';
3
+ // The terminal theme is still a standalone JavaScript module in the TS migration.
4
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
5
+ import { COLOR_DEPTH, IS_LIGHT, paint } from './theme.js';
6
+ import { diffLines } from './diff.js';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ export const CODE_PANEL_LINES = 10;
10
+ const MAX_STREAM_PREVIEW_CHARS = 256_000;
11
+ const FILE_TOOLS = {
12
+ fs_write: 'Creating', fs_edit: 'Editing', MultiEdit: 'Editing',
13
+ 'fs.write': 'Creating', 'fs.edit': 'Editing',
14
+ fs_delete: 'Removing', fs_move: 'Moving',
15
+ write_file: 'Creating', edit_file: 'Editing', delete_file: 'Removing',
16
+ replace_file_content: 'Editing', multi_replace_file_content: 'Editing',
17
+ WriteFile: 'Creating', EditFile: 'Editing', DeleteFile: 'Removing',
18
+ ReplaceFileContent: 'Editing', MultiReplaceFileContent: 'Editing'
19
+ };
20
+ function stringField(value) {
21
+ return typeof value === 'string' ? value : '';
22
+ }
23
+ function codeFromArgs(args) {
24
+ const direct = args.content ?? args.Content ?? args.CodeContent ?? args.code ?? args.new_string ?? args.newText ?? args.replaceContent ?? args.ReplacementContent;
25
+ if (typeof direct === 'string')
26
+ return direct;
27
+ const edits = args.edits ?? args.ReplacementChunks;
28
+ if (Array.isArray(edits)) {
29
+ return edits.map((item) => {
30
+ if (!item || typeof item !== 'object')
31
+ return '';
32
+ const entry = item;
33
+ return stringField(entry.new_string ?? entry.newText ?? entry.replaceContent ?? entry.ReplacementContent ?? entry.content);
34
+ }).join('\n');
35
+ }
36
+ return '';
37
+ }
38
+ function previousCodeFromArgs(args) {
39
+ const direct = args.old_string ?? args.oldText ?? args.searchContent ?? args.SearchContent;
40
+ if (typeof direct === 'string')
41
+ return direct;
42
+ const edits = args.edits ?? args.ReplacementChunks;
43
+ if (!Array.isArray(edits))
44
+ return undefined;
45
+ const previous = edits.map((item) => {
46
+ if (!item || typeof item !== 'object')
47
+ return undefined;
48
+ const entry = item;
49
+ const value = entry.old_string ?? entry.oldText ?? entry.searchContent ?? entry.SearchContent;
50
+ return typeof value === 'string' ? value : undefined;
51
+ });
52
+ return previous.length && previous.every(value => value !== undefined) ? previous.join('\n') : undefined;
53
+ }
54
+ export function codeProgressFromAction(tool, args, id, phase = 'working', source = 'tool') {
55
+ const operation = FILE_TOOLS[tool];
56
+ if (!operation)
57
+ return null;
58
+ const path = stringField(args.path ?? args.Path ?? args.file_path ?? args.FilePath ?? args.AbsolutePath ?? args.TargetFile ?? args.source);
59
+ const destination = stringField(args.destination);
60
+ const label = path ? path.split(/[/\\]/).pop() || path : 'file';
61
+ const description = operation === 'Moving' && destination
62
+ ? `Moving ${label} to ${destination}`
63
+ : `${operation} ${label}`;
64
+ const before = previousCodeFromArgs(args);
65
+ const code = codeFromArgs(args);
66
+ return {
67
+ type: 'code_progress', id, phase, operation,
68
+ ...(path ? { path } : {}), description,
69
+ ...(code || before !== undefined ? { code } : {}), ...(before !== undefined ? { before } : {}), source
70
+ };
71
+ }
72
+ export class StreamingCodePreview {
73
+ buffer = '';
74
+ lastCode = '';
75
+ lastSentAt = 0;
76
+ truncated = false;
77
+ accept(chunk, now = Date.now()) {
78
+ if (!chunk)
79
+ return null;
80
+ this.buffer += chunk;
81
+ if (this.buffer.length > MAX_STREAM_PREVIEW_CHARS) {
82
+ this.buffer = this.buffer.slice(-MAX_STREAM_PREVIEW_CHARS);
83
+ this.truncated = true;
84
+ }
85
+ if (now - this.lastSentAt < 100 && !chunk.includes('\n'))
86
+ return null;
87
+ const code = this.draftCode();
88
+ if (!code.trim() || code === this.lastCode)
89
+ return null;
90
+ this.lastCode = code;
91
+ this.lastSentAt = now;
92
+ return { type: 'code_progress', id: 'model-draft', phase: 'draft',
93
+ operation: 'Drafting', description: 'Writing code from the model stream', code,
94
+ ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
95
+ }
96
+ flush() {
97
+ const code = this.draftCode();
98
+ if (!code.trim() || code === this.lastCode)
99
+ return null;
100
+ this.lastCode = code;
101
+ return { type: 'code_progress', id: 'model-draft', phase: 'draft',
102
+ operation: 'Drafting', description: 'Writing code from the model stream', code,
103
+ ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
104
+ }
105
+ draftCode() {
106
+ const fences = [...this.buffer.matchAll(/(?:^|\n)```[^\n]*\n([\s\S]*?)(?=\n```|$)/g)];
107
+ const fenced = fences.at(-1)?.[1] || '';
108
+ if (fenced.trim())
109
+ return fenced;
110
+ const start = this.buffer.lastIndexOf('<tool_call>');
111
+ if (start < 0)
112
+ return '';
113
+ const call = this.buffer.slice(start);
114
+ if (!/"name"\s*:\s*"(?:fs_write|fs_edit|MultiEdit|write_file|edit_file|create_file)"/.test(call))
115
+ return '';
116
+ const field = /"(?:content|new_string|replaceContent|newText)"\s*:\s*"/.exec(call);
117
+ if (!field || field.index === undefined)
118
+ return '';
119
+ const raw = call.slice(field.index + field[0].length);
120
+ let escaped = false;
121
+ let end = raw.length;
122
+ for (let i = 0; i < raw.length; i++) {
123
+ if (escaped) {
124
+ escaped = false;
125
+ continue;
126
+ }
127
+ if (raw[i] === '\\') {
128
+ escaped = true;
129
+ continue;
130
+ }
131
+ if (raw[i] === '"') {
132
+ end = i;
133
+ break;
134
+ }
135
+ }
136
+ const partial = raw.slice(0, end).replace(/\\$/u, '');
137
+ try {
138
+ return JSON.parse(`"${partial}"`);
139
+ }
140
+ catch {
141
+ return partial.replace(/\\n/g, '\n');
142
+ }
143
+ }
144
+ }
145
+ /** Observe only a file named by a native edit action. No model calls are made. */
146
+ export class NativeCodeObserver {
147
+ workspaceRoot;
148
+ emit;
149
+ active = new Map();
150
+ constructor(workspaceRoot, emit) {
151
+ this.workspaceRoot = workspaceRoot;
152
+ this.emit = emit;
153
+ }
154
+ handle(event) {
155
+ if (!event.path || !['Creating', 'Editing'].includes(event.operation))
156
+ return;
157
+ if (event.code !== undefined || event.phase === 'failed') {
158
+ this.stop(event.id);
159
+ return;
160
+ }
161
+ const target = path.resolve(this.workspaceRoot, event.path);
162
+ if (event.phase === 'working') {
163
+ this.stop(event.id);
164
+ const previous = this.read(target);
165
+ const timer = setInterval(() => this.poll(event.id), 100);
166
+ timer.unref();
167
+ this.active.set(event.id, { event, path: target, previous, lastShown: null, timer });
168
+ return;
169
+ }
170
+ if (event.phase === 'done') {
171
+ this.poll(event.id);
172
+ const entry = this.active.get(event.id);
173
+ const current = this.read(target);
174
+ if (current !== null && (current !== entry?.previous || event.operation === 'Creating')) {
175
+ this.emit({ ...event, code: current, ...(entry?.previous !== null && entry?.previous !== undefined ? { before: entry.previous } : {}) });
176
+ }
177
+ }
178
+ this.stop(event.id);
179
+ }
180
+ poll(id) {
181
+ const entry = this.active.get(id);
182
+ if (!entry)
183
+ return;
184
+ const current = this.read(entry.path);
185
+ if (current === null || current === entry.previous || current === entry.lastShown)
186
+ return;
187
+ entry.lastShown = current;
188
+ this.emit({ ...entry.event, code: current, ...(entry.previous !== null ? { before: entry.previous } : {}) });
189
+ }
190
+ dispose() {
191
+ for (const id of this.active.keys())
192
+ this.stop(id);
193
+ }
194
+ stop(id) {
195
+ const entry = this.active.get(id);
196
+ if (entry)
197
+ clearInterval(entry.timer);
198
+ this.active.delete(id);
199
+ }
200
+ read(file) {
201
+ try {
202
+ const name = path.basename(file).toLowerCase();
203
+ if (/^(\.env(?:\.|$)|.*\.(?:pem|key|p12|pfx)$)/u.test(name))
204
+ return null;
205
+ const stat = fs.lstatSync(file);
206
+ if (!stat.isFile() || stat.size > 256_000)
207
+ return null;
208
+ const bytes = fs.readFileSync(file);
209
+ if (bytes.includes(0))
210
+ return null;
211
+ return bytes.toString('utf8');
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ }
217
+ }
218
+ function splitCodeLines(code) {
219
+ if (!code)
220
+ return [];
221
+ const lines = code.replace(/\r\n?/g, '\n').split('\n');
222
+ if (lines.at(-1) === '')
223
+ lines.pop();
224
+ return lines;
225
+ }
226
+ function previewLines(event) {
227
+ if (event.code === undefined)
228
+ return [];
229
+ if (event.before !== undefined) {
230
+ const oldLines = splitCodeLines(event.before);
231
+ const newLines = splitCodeLines(event.code);
232
+ let prefix = 0;
233
+ while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix])
234
+ prefix++;
235
+ let suffix = 0;
236
+ while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix
237
+ && oldLines[oldLines.length - suffix - 1] === newLines[newLines.length - suffix - 1])
238
+ suffix++;
239
+ const changedOld = oldLines.slice(prefix, oldLines.length - suffix);
240
+ const changedNew = newLines.slice(prefix, newLines.length - suffix);
241
+ const result = diffLines(changedOld.join('\n'), changedNew.join('\n'));
242
+ // Diff only the changed middle so a small edit in a long file stays fast.
243
+ // A partial middle diff could mislabel lines, so leave that case neutral.
244
+ if (result.truncated)
245
+ return newLines.map(text => ({ kind: 'ctx', text }));
246
+ return [
247
+ ...oldLines.slice(0, prefix).map(text => ({ kind: 'ctx', text })),
248
+ ...result.ops,
249
+ ...oldLines.slice(oldLines.length - suffix).map(text => ({ kind: 'ctx', text }))
250
+ ];
251
+ }
252
+ const kind = event.operation === 'Removing' ? 'del'
253
+ : event.operation === 'Creating' || event.operation === 'Drafting' ? 'add' : 'ctx';
254
+ return splitCodeLines(event.code).map(text => ({ kind, text }));
255
+ }
256
+ export function codePreviewLineCount(event) {
257
+ return previewLines(event).length;
258
+ }
259
+ function highlightCode(kind, text, width) {
260
+ const marker = kind === 'add' ? '+' : kind === 'del' ? '-' : ' ';
261
+ const role = kind === 'add' ? 'success' : kind === 'del' ? 'danger' : 'muted';
262
+ const body = padEnd(truncate(safeDisplay(text), Math.max(1, width - 2)), Math.max(1, width - 2));
263
+ if (kind === 'ctx' || COLOR_DEPTH < 256)
264
+ return paint(role, marker) + ' ' + body;
265
+ // A low-contrast tint one step above the panel surface. The colored marker
266
+ // remains readable even when a terminal can only approximate the tint.
267
+ const background = COLOR_DEPTH >= 16777216
268
+ ? kind === 'add' ? (IS_LIGHT ? '48;2;231;239;220' : '48;2;32;42;32')
269
+ : (IS_LIGHT ? '48;2;245;230;230' : '48;2;47;32;34')
270
+ : kind === 'add' ? (IS_LIGHT ? '48;5;194' : '48;5;22')
271
+ : (IS_LIGHT ? '48;5;224' : '48;5;52');
272
+ return paint(role, marker) + `\x1b[${background}m ${body}\x1b[49m`;
273
+ }
274
+ /** Render a bounded, resize-safe panel. The terminal theme supplies rounded corners. */
275
+ export function renderCodeProgress(event, width, modelNote = '', startLine) {
276
+ const safeWidth = Math.max(12, Math.floor(width) || 80);
277
+ const inner = safeWidth - 4;
278
+ const title = `${event.phase === 'done' ? '✓ ' : event.phase === 'failed' ? '× ' : ''}code · ${event.operation.toLowerCase()}`;
279
+ const rows = [truncate(safeDisplay(event.description), inner)];
280
+ if (event.path)
281
+ rows.push(truncate(safeDisplay(event.path), inner));
282
+ if (modelNote)
283
+ rows.push(truncate(`model note: ${safeDisplay(modelNote)}`, inner));
284
+ const codeLines = previewLines(event);
285
+ const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
286
+ const start = startLine === undefined ? maxStart : Math.max(0, Math.min(Math.floor(startLine), maxStart));
287
+ const visible = codeLines.slice(start, start + CODE_PANEL_LINES);
288
+ if (visible.length) {
289
+ rows.push('');
290
+ for (const line of visible)
291
+ rows.push(highlightCode(line.kind, line.text, inner));
292
+ if (codeLines.length > CODE_PANEL_LINES) {
293
+ rows.push(truncate(`lines ${start + 1}-${start + visible.length} of ${codeLines.length} · scroll over code`, inner));
294
+ }
295
+ if (event.codeTruncated)
296
+ rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
297
+ }
298
+ return panel(rows, { width: safeWidth, title, role: event.phase === 'failed' ? 'danger' : 'rule' });
299
+ }