@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. 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,10 @@ 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';
27
+ import { activityRows } from './activityLayout.js';
24
28
 
25
29
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
26
30
  // minified output would otherwise become thousands of rows and lock the
@@ -314,7 +318,7 @@ export class ChatRenderer {
314
318
  this.rowSink = previousSink;
315
319
  this.forcedWidth = previousWidth;
316
320
  }
317
- return sink;
321
+ return sessionRows(sink, width).rows;
318
322
  }
319
323
 
320
324
  /**
@@ -338,16 +342,9 @@ export class ChatRenderer {
338
342
  return Number.isFinite(columns) && columns > 0 ? Math.max(40, columns) : terminalWidth();
339
343
  }
340
344
 
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
- */
345
+ /** Prose follows the current conversation column with a small text inset. */
349
346
  measure() {
350
- return readableWidth(this.width());
347
+ return chatProseWidth(this.width());
351
348
  }
352
349
 
353
350
  // -------------------------------------------------------------------------
@@ -358,36 +355,15 @@ export class ChatRenderer {
358
355
  * The context the CLI never showed. Which model is about to spend the user's
359
356
  * money, in which autonomy mode, over which paths.
360
357
  */
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
- */
358
+ /** Write the opening composition and report its companion composer width. */
372
359
  sessionHeader(info = {}) {
373
360
  // The status line shows the same facts during the turn, where the header
374
361
  // has already scrolled away. Mutation first: the closure below runs again
375
362
  // on every reflow and must not re-apply it.
376
363
  this.status.setSession(info);
377
364
 
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;
365
+ this.frame('session', () => this.renderSessionHeader(info));
366
+ return composerWidth(this.width());
391
367
  }
392
368
 
393
369
  renderSessionHeader(info = {}) {
@@ -398,9 +374,7 @@ export class ChatRenderer {
398
374
  // label/value rows, a command count, a blank and a separate key-hint row —
399
375
  // nineteen rows of chrome before the user could type. Both references open
400
376
  // 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();
377
+ const rows = ['', ...sessionBanner(info, width, { height: this.out?.rows }), ''];
404
378
 
405
379
  const hints = [
406
380
  `${info.commandCount || 0} commands`, '/help', 'enter send',
@@ -409,8 +383,8 @@ export class ChatRenderer {
409
383
  const separator = ` ${GLYPHS.dot} `;
410
384
  const kept = hints.slice();
411
385
  while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
412
- this.write(dim(kept.join(separator)));
413
- this.write();
386
+ rows.push(dim(kept.join(separator)), '');
387
+ for (const row of openingRows(rows, width, Number(this.out?.rows))) this.write(row);
414
388
  }
415
389
 
416
390
  /**
@@ -447,6 +421,7 @@ export class ChatRenderer {
447
421
  this.stepCount = 0;
448
422
  this.stepStartedAt = null;
449
423
  this.turnStartedAt = Date.now();
424
+ this._activeReasoning = false;
450
425
  this.status.reset();
451
426
  }
452
427
 
@@ -522,7 +497,9 @@ export class ChatRenderer {
522
497
  if (!text.trim()) return;
523
498
 
524
499
  this.frame('user', () => {
525
- const width = this.measure();
500
+ const width = this.transcript
501
+ ? sessionComposerWidth(this.width())
502
+ : composerWidth(this.measure());
526
503
  const blockWidth = Math.max(8, width - 1);
527
504
  const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.bar) - 1);
528
505
  const rows = barBlock(
@@ -534,7 +511,7 @@ export class ChatRenderer {
534
511
  this.write(row);
535
512
  }
536
513
  this.write();
537
- });
514
+ }, { messageText: text });
538
515
  }
539
516
 
540
517
  renderAssistantMessage(content) {
@@ -549,6 +526,7 @@ export class ChatRenderer {
549
526
  }
550
527
 
551
528
  renderSessionDivider(info = {}) {
529
+ this.transcript?.surface?.setSessionInfo?.(info);
552
530
  this.frame('session', () => {
553
531
  const width = this.measure();
554
532
  const title = safeDisplay(info.title || 'Session');
@@ -573,7 +551,10 @@ export class ChatRenderer {
573
551
  * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
574
552
  */
575
553
  renderSessionHistory(messages = [], sessionInfo = null) {
554
+ this.transcript?.surface?.leaveHome?.(true);
576
555
  this.clearTranscript();
556
+ this.latestPlan = [];
557
+ this.onPlanChange?.([]);
577
558
 
578
559
  if (sessionInfo && (sessionInfo.title || sessionInfo.id)) {
579
560
  this.renderSessionDivider(sessionInfo);
@@ -596,6 +577,12 @@ export class ChatRenderer {
596
577
  }
597
578
  }
598
579
  }
580
+
581
+ if (this.transcript?.surface?.viewport) {
582
+ this.transcript.surface.viewport.manual = false;
583
+ this.transcript.surface.viewport.unseen = 0;
584
+ this.transcript.surface.viewport.toBottom();
585
+ }
599
586
  }
600
587
 
601
588
  onAgentMessage(msg) {
@@ -609,7 +596,7 @@ export class ChatRenderer {
609
596
  this.write(line ? ' ' + line : '');
610
597
  }
611
598
  this.write();
612
- });
599
+ }, { messageText: String(msg.content || '') });
613
600
  }
614
601
 
615
602
  /**
@@ -634,6 +621,12 @@ export class ChatRenderer {
634
621
  const elapsedMs = Number(msg.elapsedMs) || 0;
635
622
  const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
636
623
 
624
+ const tailIsReasoning = !this.transcript
625
+ || this.transcript.frames?.at(-1)?.meta?.reasoning === true;
626
+ if (this._activeReasoning && !tailIsReasoning) {
627
+ this._activeReasoning = false;
628
+ }
629
+
637
630
  if (isStreaming) {
638
631
  if (!this._activeReasoning) {
639
632
  this._activeReasoning = true;
@@ -683,10 +676,15 @@ export class ChatRenderer {
683
676
  }
684
677
 
685
678
  onAgentActivity(msg) {
686
- const text = safeDisplay(msg.activity || msg.message || '').trim();
679
+ const text = String(msg.activity || msg.message || '').trim();
687
680
  if (!text) return;
688
681
  this.frame('notice', () => {
689
- this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(text)}`);
682
+ const prefix = `${GLYPHS.arrow || '▸'} `;
683
+ for (const [index, row] of activityRows(text, this.width(), prefix).entries()) {
684
+ this.write(index === 0
685
+ ? `${paint('accent', GLYPHS.arrow || '▸')} ${dim(row.slice(prefix.length))}`
686
+ : dim(row));
687
+ }
690
688
  }, { activity: true });
691
689
  }
692
690
 
@@ -694,7 +692,8 @@ export class ChatRenderer {
694
692
  if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
695
693
  const plan = msg.plan.slice();
696
694
  this.latestPlan = plan;
697
- if (this.onPlanChange) this.onPlanChange(plan);
695
+ const placement = this.onPlanChange?.(plan);
696
+ if (placement === 'sidebar') return;
698
697
  this.frame('plan', () => this.renderPlan(plan), { items: plan.length });
699
698
  }
700
699
 
@@ -771,7 +770,8 @@ export class ChatRenderer {
771
770
  this.renderOutputPreview(result);
772
771
  return;
773
772
  }
774
- this.write(` ${paint('danger', GLYPHS.cross)} ${paint('danger', truncate(safeDisplay(result.error || 'failed'), this.width() - 12, GLYPHS.ellipsis))} ${dim(elapsed)}`);
773
+ const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
774
+ for (const row of wrappedChatRows(detail, this.width(), ` ${paint('danger', GLYPHS.cross)} `, 'danger')) this.write(row);
775
775
  }, { success: Boolean(result.success) });
776
776
  }
777
777
 
@@ -1025,7 +1025,7 @@ export class ChatRenderer {
1025
1025
  const message = safeDisplay(msg.message || '');
1026
1026
  this.frame('error', () => {
1027
1027
  this.write();
1028
- this.write(`${badge('danger', 'ERROR')} ${paint('danger', message)}`);
1028
+ for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger')) this.write(row);
1029
1029
  this.write();
1030
1030
  });
1031
1031
  }
@@ -1033,7 +1033,7 @@ export class ChatRenderer {
1033
1033
  onBudgetWarning(msg) {
1034
1034
  const message = safeDisplay(msg.message || '');
1035
1035
  this.frame('notice', () => {
1036
- this.write(`${badge('warn', 'BUDGET')} ${paint('warn', message)}`);
1036
+ for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn')) this.write(row);
1037
1037
  }, { tone: 'warn' });
1038
1038
  }
1039
1039
 
@@ -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
+ }