@causyne/agent 1.19.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.
- package/README.md +0 -18
- package/package.json +1 -1
- package/src/acp/client.js +2 -1
- package/src/acp/client.ts +2 -1
- package/src/acp/server.js +5 -6
- package/src/acp/server.ts +4 -6
- package/src/agentLoop.d.ts +1 -0
- package/src/agentLoop.js +505 -241
- package/src/agentLoop.ts +527 -258
- package/src/agentPolicy.js +9 -0
- package/src/agentPolicy.ts +9 -0
- package/src/approvalPolicy.js +55 -0
- package/src/approvalPolicy.ts +66 -0
- package/src/browser/browserRuntime.js +217 -14
- package/src/browser/browserRuntime.ts +255 -14
- package/src/browser/causyneBrowser.js +1215 -68
- package/src/browser/causyneBrowser.ts +1340 -72
- package/src/cliMode.js +66 -37
- package/src/commands.js +343 -72
- package/src/config.js +22 -12
- package/src/continuum/ingest.js +1 -1
- package/src/continuum/ingest.ts +1 -1
- package/src/continuum/ui/continuumPicker.js +18 -1
- package/src/continuum/ui/continuumPicker.ts +19 -1
- package/src/dynamicCatalogue.js +87 -20
- package/src/dynamicCatalogue.ts +85 -15
- package/src/launchIntent.js +40 -0
- package/src/launchIntent.ts +49 -0
- package/src/memoryManager.js +36 -8
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +67 -1
- package/src/providers/acp.ts +65 -2
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +643 -32
- package/src/providers/antigravity.ts +671 -33
- package/src/providers/base.d.ts +9 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +157 -0
- package/src/providers/pi.ts +144 -0
- package/src/provisioning/capabilityProvisioner.js +17 -0
- package/src/provisioning/capabilityTools.js +1 -1
- package/src/sandbox.js +30 -39
- package/src/sessionJournal.js +66 -10
- package/src/sessionJournal.ts +84 -10
- package/src/taskShape.js +9 -9
- package/src/taskShape.ts +9 -9
- package/src/timeMachine.js +124 -0
- package/src/timeMachine.ts +141 -0
- package/src/toolPacks.js +4 -10
- package/src/tools/archive.js +196 -59
- package/src/tools/archive.ts +220 -0
- package/src/tools/browserAutomator.js +78 -9
- package/src/tools/browserAutomator.ts +90 -9
- package/src/tools/desktopOpen.js +114 -31
- package/src/tools/desktopOpen.ts +144 -0
- package/src/tools/gitExec.js +5 -3
- package/src/tools/nativeEngine.js +4 -3
- package/src/tools/nativeEngine.ts +5 -3
- package/src/tools/openSourceToolProvisioner.js +5 -4
- package/src/tools/openSourceToolProvisioner.ts +5 -4
- package/src/tools/registry.js +3 -0
- package/src/tools/screenshot.js +55 -71
- package/src/tools/screenshot.ts +70 -0
- package/src/tools/sysRun.js +284 -117
- package/src/tools/sysRun.ts +347 -0
- package/src/tools/toolSelfRepair.js +109 -2
- package/src/tools/toolSelfRepair.ts +100 -2
- package/src/tools/updatePlan.js +49 -1
- package/src/tools/updatePlan.ts +43 -1
- package/src/tools/viewImage.js +93 -78
- package/src/tools/viewImage.ts +116 -0
- package/src/tools/webFetch.js +20 -6
- package/src/tools/webFetch.ts +26 -6
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +21 -0
- package/src/tui/chatRenderer.js +118 -45
- package/src/tui/clipboardSync.js +28 -1
- package/src/tui/clipboardSync.ts +26 -1
- package/src/tui/codeProgress.js +299 -0
- package/src/tui/codeProgress.ts +304 -0
- package/src/tui/codeStreamRenderer.js +116 -0
- package/src/tui/codeStreamRenderer.ts +124 -0
- package/src/tui/commandPresentation.js +11 -0
- package/src/tui/commandPresentation.ts +18 -0
- package/src/tui/completion.js +45 -13
- package/src/tui/composerControls.js +66 -0
- package/src/tui/composerControls.ts +78 -0
- package/src/tui/diff.d.ts +2 -0
- package/src/tui/home.js +4 -2
- package/src/tui/homeTransition.js +21 -0
- package/src/tui/homeTransition.ts +27 -0
- package/src/tui/homeView.js +62 -0
- package/src/tui/homeView.ts +91 -0
- package/src/tui/layout.js +46 -0
- package/src/tui/layout.ts +52 -0
- package/src/tui/messageActionPlacement.js +16 -0
- package/src/tui/messageActionPlacement.ts +25 -0
- package/src/tui/messageInteraction.js +221 -0
- package/src/tui/messageInteraction.ts +275 -0
- package/src/tui/modelPicker.js +13 -0
- package/src/tui/modelPicker.ts +12 -0
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +199 -52
- package/src/tui/resizeRecovery.js +15 -0
- package/src/tui/resizeRecovery.ts +27 -0
- package/src/tui/scrollInteraction.js +97 -0
- package/src/tui/scrollInteraction.ts +189 -0
- package/src/tui/sessionLayout.js +12 -0
- package/src/tui/sessionLayout.ts +12 -0
- package/src/tui/sessionPicker.js +280 -0
- package/src/tui/sessionPicker.ts +364 -0
- package/src/tui/sessionSidebar.js +78 -0
- package/src/tui/sessionSidebar.ts +95 -0
- package/src/tui/setup.js +1 -1
- package/src/tui/setup.ts +1 -1
- package/src/tui/stageSurface.js +128 -57
- package/src/tui/statusLine.js +5 -5
- package/src/tui/text.d.ts +5 -0
- package/src/tui/textLayout.js +23 -0
- package/src/tui/textLayout.ts +28 -0
- package/src/tui/viewport.js +204 -279
- package/src/tui/viewport.ts +326 -0
- package/src/types/contracts.ts +54 -0
- package/src/utils/paths.js +5 -4
- package/src/utils/paths.ts +5 -5
package/src/tui/chatRenderer.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import readline from 'readline';
|
|
12
12
|
import {
|
|
13
|
-
paint, bold, dim, badge, GLYPHS, terminalWidth,
|
|
13
|
+
paint, bold, dim, badge, GLYPHS, terminalWidth, HAS_COLOR, fileLink,
|
|
14
14
|
safeLink, HAS_HYPERLINKS
|
|
15
15
|
} from './theme.js';
|
|
16
16
|
import {
|
|
@@ -20,6 +20,10 @@ import { sessionBanner } from './banner.js';
|
|
|
20
20
|
import { describeTool } from './toolDisplay.js';
|
|
21
21
|
import { approvalDiff } from './diff.js';
|
|
22
22
|
import { StatusLine } from './statusLine.js';
|
|
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';
|
|
23
27
|
|
|
24
28
|
// Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
|
|
25
29
|
// minified output would otherwise become thousands of rows and lock the
|
|
@@ -313,7 +317,7 @@ export class ChatRenderer {
|
|
|
313
317
|
this.rowSink = previousSink;
|
|
314
318
|
this.forcedWidth = previousWidth;
|
|
315
319
|
}
|
|
316
|
-
return sink;
|
|
320
|
+
return sessionRows(sink, width).rows;
|
|
317
321
|
}
|
|
318
322
|
|
|
319
323
|
/**
|
|
@@ -337,16 +341,9 @@ export class ChatRenderer {
|
|
|
337
341
|
return Number.isFinite(columns) && columns > 0 ? Math.max(40, columns) : terminalWidth();
|
|
338
342
|
}
|
|
339
343
|
|
|
340
|
-
/**
|
|
341
|
-
* The width PROSE is wrapped to — narrower than the terminal on a wide one.
|
|
342
|
-
*
|
|
343
|
-
* Chrome fills the window; paragraphs must not. See readableWidth() in
|
|
344
|
-
* theme.js for why, and note the two are deliberately different so that
|
|
345
|
-
* stretching the window widens the box without turning the agent's replies
|
|
346
|
-
* into 200-character lines.
|
|
347
|
-
*/
|
|
344
|
+
/** Prose follows the current conversation column with a small text inset. */
|
|
348
345
|
measure() {
|
|
349
|
-
return
|
|
346
|
+
return chatProseWidth(this.width());
|
|
350
347
|
}
|
|
351
348
|
|
|
352
349
|
// -------------------------------------------------------------------------
|
|
@@ -357,36 +354,15 @@ export class ChatRenderer {
|
|
|
357
354
|
* The context the CLI never showed. Which model is about to spend the user's
|
|
358
355
|
* money, in which autonomy mode, over which paths.
|
|
359
356
|
*/
|
|
360
|
-
/**
|
|
361
|
-
* Returns the width of the widest row it wrote.
|
|
362
|
-
*
|
|
363
|
-
* The Stage lays its opening composition out to this, so the input box below
|
|
364
|
-
* the banner ends where the banner's text ends instead of stretching past it.
|
|
365
|
-
* MEASURED rather than guessed, because the banner is adaptive: it drops hints
|
|
366
|
-
* and truncates the workspace list to fit whatever width it is given, so its
|
|
367
|
-
* natural width depends on the user's own paths and cannot be a constant. At
|
|
368
|
-
* 156 columns it comes out at 122 — and composing it AT 117 already hides
|
|
369
|
-
* ~/Causyne, which is why the banner is never the thing that gets narrowed.
|
|
370
|
-
*/
|
|
357
|
+
/** Write the opening composition and report its companion composer width. */
|
|
371
358
|
sessionHeader(info = {}) {
|
|
372
359
|
// The status line shows the same facts during the turn, where the header
|
|
373
360
|
// has already scrolled away. Mutation first: the closure below runs again
|
|
374
361
|
// on every reflow and must not re-apply it.
|
|
375
362
|
this.status.setSession(info);
|
|
376
363
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
const write = this.write.bind(this);
|
|
380
|
-
this.write = (line = '') => { seen.push(line); return write(line); };
|
|
381
|
-
try {
|
|
382
|
-
this.frame('session', () => this.renderSessionHeader(info));
|
|
383
|
-
} finally {
|
|
384
|
-
this.write = write;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
let widest = 0;
|
|
388
|
-
for (const line of seen) widest = Math.max(widest, visibleWidth(String(line)));
|
|
389
|
-
return widest;
|
|
364
|
+
this.frame('session', () => this.renderSessionHeader(info));
|
|
365
|
+
return composerWidth(this.width());
|
|
390
366
|
}
|
|
391
367
|
|
|
392
368
|
renderSessionHeader(info = {}) {
|
|
@@ -397,9 +373,7 @@ export class ChatRenderer {
|
|
|
397
373
|
// label/value rows, a command count, a blank and a separate key-hint row —
|
|
398
374
|
// nineteen rows of chrome before the user could type. Both references open
|
|
399
375
|
// in eight or fewer, with the identity and the facts as a single object.
|
|
400
|
-
this.
|
|
401
|
-
for (const row of sessionBanner(info, width, { height: this.out?.rows })) this.write(row);
|
|
402
|
-
this.write();
|
|
376
|
+
const rows = ['', ...sessionBanner(info, width, { height: this.out?.rows }), ''];
|
|
403
377
|
|
|
404
378
|
const hints = [
|
|
405
379
|
`${info.commandCount || 0} commands`, '/help', 'enter send',
|
|
@@ -408,8 +382,8 @@ export class ChatRenderer {
|
|
|
408
382
|
const separator = ` ${GLYPHS.dot} `;
|
|
409
383
|
const kept = hints.slice();
|
|
410
384
|
while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
|
|
411
|
-
|
|
412
|
-
this.write();
|
|
385
|
+
rows.push(dim(kept.join(separator)), '');
|
|
386
|
+
for (const row of openingRows(rows, width, Number(this.out?.rows))) this.write(row);
|
|
413
387
|
}
|
|
414
388
|
|
|
415
389
|
/**
|
|
@@ -512,6 +486,103 @@ export class ChatRenderer {
|
|
|
512
486
|
// Frames
|
|
513
487
|
// -------------------------------------------------------------------------
|
|
514
488
|
|
|
489
|
+
renderUserMessage(content) {
|
|
490
|
+
const text = typeof content === 'string'
|
|
491
|
+
? content
|
|
492
|
+
: (Array.isArray(content)
|
|
493
|
+
? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
|
|
494
|
+
: String(content || ''));
|
|
495
|
+
if (!text.trim()) return;
|
|
496
|
+
|
|
497
|
+
this.frame('user', () => {
|
|
498
|
+
const width = this.transcript
|
|
499
|
+
? sessionComposerWidth(this.width())
|
|
500
|
+
: composerWidth(this.measure());
|
|
501
|
+
const blockWidth = Math.max(8, width - 1);
|
|
502
|
+
const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.bar) - 1);
|
|
503
|
+
const rows = barBlock(
|
|
504
|
+
wrapBlock(safeDisplay(text), innerWidth),
|
|
505
|
+
{ width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
|
|
506
|
+
);
|
|
507
|
+
this.write();
|
|
508
|
+
for (const row of rows) {
|
|
509
|
+
this.write(row);
|
|
510
|
+
}
|
|
511
|
+
this.write();
|
|
512
|
+
}, { messageText: text });
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
renderAssistantMessage(content) {
|
|
516
|
+
const text = typeof content === 'string'
|
|
517
|
+
? content
|
|
518
|
+
: (Array.isArray(content)
|
|
519
|
+
? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
|
|
520
|
+
: String(content || ''));
|
|
521
|
+
if (!text.trim()) return;
|
|
522
|
+
|
|
523
|
+
this.onAgentMessage({ content: text });
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
renderSessionDivider(info = {}) {
|
|
527
|
+
this.transcript?.surface?.setSessionInfo?.(info);
|
|
528
|
+
this.frame('session', () => {
|
|
529
|
+
const width = this.measure();
|
|
530
|
+
const title = safeDisplay(info.title || 'Session');
|
|
531
|
+
const count = info.messagesCount ?? 0;
|
|
532
|
+
const countText = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
|
|
533
|
+
const badgeText = `${title}${countText}`;
|
|
534
|
+
const ruleWidth = Math.max(2, Math.floor((width - visibleWidth(badgeText) - 4) / 2));
|
|
535
|
+
this.write();
|
|
536
|
+
this.write(`${paint('rule', GLYPHS.hLine.repeat(ruleWidth))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(ruleWidth))}`);
|
|
537
|
+
this.write();
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
clearTranscript() {
|
|
542
|
+
if (this.transcript && typeof this.transcript.clear === 'function') {
|
|
543
|
+
this.transcript.clear();
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Render conversation history frames from a selected or resumed session.
|
|
549
|
+
* Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
|
|
550
|
+
*/
|
|
551
|
+
renderSessionHistory(messages = [], sessionInfo = null) {
|
|
552
|
+
this.transcript?.surface?.leaveHome?.(true);
|
|
553
|
+
this.clearTranscript();
|
|
554
|
+
this.latestPlan = [];
|
|
555
|
+
this.onPlanChange?.([]);
|
|
556
|
+
|
|
557
|
+
if (sessionInfo && (sessionInfo.title || sessionInfo.id)) {
|
|
558
|
+
this.renderSessionDivider(sessionInfo);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
for (const msg of messages) {
|
|
562
|
+
if (!msg) continue;
|
|
563
|
+
const role = String(msg.role || '').toLowerCase();
|
|
564
|
+
if (role === 'user') {
|
|
565
|
+
this.renderUserMessage(msg.content);
|
|
566
|
+
} else if (role === 'assistant') {
|
|
567
|
+
this.renderAssistantMessage(msg.content);
|
|
568
|
+
} else if (role === 'system') {
|
|
569
|
+
const text = typeof msg.content === 'string' ? msg.content : '';
|
|
570
|
+
if (text.startsWith('[Continuum Context')) {
|
|
571
|
+
this.frame('notice', () => {
|
|
572
|
+
const firstLine = text.split('\n')[0] || '[Continuum Context]';
|
|
573
|
+
this.write(`${paint('accent', GLYPHS.bullet)} ${dim(firstLine)}`);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
}
|
|
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
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
515
586
|
onAgentMessage(msg) {
|
|
516
587
|
const content = safeDisplay(msg.content || '');
|
|
517
588
|
this.frame('assistant', () => {
|
|
@@ -523,7 +594,7 @@ export class ChatRenderer {
|
|
|
523
594
|
this.write(line ? ' ' + line : '');
|
|
524
595
|
}
|
|
525
596
|
this.write();
|
|
526
|
-
});
|
|
597
|
+
}, { messageText: String(msg.content || '') });
|
|
527
598
|
}
|
|
528
599
|
|
|
529
600
|
/**
|
|
@@ -608,7 +679,8 @@ export class ChatRenderer {
|
|
|
608
679
|
if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
|
|
609
680
|
const plan = msg.plan.slice();
|
|
610
681
|
this.latestPlan = plan;
|
|
611
|
-
|
|
682
|
+
const placement = this.onPlanChange?.(plan);
|
|
683
|
+
if (placement === 'sidebar') return;
|
|
612
684
|
this.frame('plan', () => this.renderPlan(plan), { items: plan.length });
|
|
613
685
|
}
|
|
614
686
|
|
|
@@ -685,7 +757,8 @@ export class ChatRenderer {
|
|
|
685
757
|
this.renderOutputPreview(result);
|
|
686
758
|
return;
|
|
687
759
|
}
|
|
688
|
-
|
|
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);
|
|
689
762
|
}, { success: Boolean(result.success) });
|
|
690
763
|
}
|
|
691
764
|
|
|
@@ -939,7 +1012,7 @@ export class ChatRenderer {
|
|
|
939
1012
|
const message = safeDisplay(msg.message || '');
|
|
940
1013
|
this.frame('error', () => {
|
|
941
1014
|
this.write();
|
|
942
|
-
this.
|
|
1015
|
+
for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger')) this.write(row);
|
|
943
1016
|
this.write();
|
|
944
1017
|
});
|
|
945
1018
|
}
|
|
@@ -947,7 +1020,7 @@ export class ChatRenderer {
|
|
|
947
1020
|
onBudgetWarning(msg) {
|
|
948
1021
|
const message = safeDisplay(msg.message || '');
|
|
949
1022
|
this.frame('notice', () => {
|
|
950
|
-
this.
|
|
1023
|
+
for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn')) this.write(row);
|
|
951
1024
|
}, { tone: 'warn' });
|
|
952
1025
|
}
|
|
953
1026
|
|
package/src/tui/clipboardSync.js
CHANGED
|
@@ -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
|
+
}
|
package/src/tui/clipboardSync.ts
CHANGED
|
@@ -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
|
+
}
|