@causyne/agent 1.20.72 → 1.20.74

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.
@@ -10,6 +10,23 @@ const originalConsole = {
10
10
  const originalStderrWrite = process.stderr?.write
11
11
  ? process.stderr.write.bind(process.stderr)
12
12
  : null;
13
+ const originalStdoutWrite = process.stdout?.write
14
+ ? process.stdout.write.bind(process.stdout)
15
+ : null;
16
+ let stageInternalWriting = false;
17
+ /**
18
+ * Run a write operation with permission to write to stdout during Stage sessions.
19
+ */
20
+ export function runWithStageWrite(fn) {
21
+ const prev = stageInternalWriting;
22
+ stageInternalWriting = true;
23
+ try {
24
+ return fn();
25
+ }
26
+ finally {
27
+ stageInternalWriting = prev;
28
+ }
29
+ }
13
30
  export function isAnyStageReservedOnStdout() {
14
31
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
15
32
  return true;
@@ -50,6 +67,22 @@ function ensureConsoleGuardInstalled() {
50
67
  return originalStderrWrite(chunk, encodingOrCb, cb);
51
68
  });
52
69
  }
70
+ if (originalStdoutWrite && process.stdout) {
71
+ process.stdout.write = ((chunk, encodingOrCb, cb) => {
72
+ if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
73
+ // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
74
+ const text = String(chunk ?? '');
75
+ if (text.includes('\n')) {
76
+ if (typeof encodingOrCb === 'function')
77
+ encodingOrCb();
78
+ else if (typeof cb === 'function')
79
+ cb();
80
+ return true;
81
+ }
82
+ }
83
+ return originalStdoutWrite(chunk, encodingOrCb, cb);
84
+ });
85
+ }
53
86
  }
54
87
  /**
55
88
  * Track TUI Stage open/close lifecycle so raw console writes cannot corrupt the composer box.
@@ -23,6 +23,25 @@ const originalStderrWrite = process.stderr?.write
23
23
  ? process.stderr.write.bind(process.stderr)
24
24
  : null;
25
25
 
26
+ const originalStdoutWrite = process.stdout?.write
27
+ ? process.stdout.write.bind(process.stdout)
28
+ : null;
29
+
30
+ let stageInternalWriting = false;
31
+
32
+ /**
33
+ * Run a write operation with permission to write to stdout during Stage sessions.
34
+ */
35
+ export function runWithStageWrite<T>(fn: () => T): T {
36
+ const prev = stageInternalWriting;
37
+ stageInternalWriting = true;
38
+ try {
39
+ return fn();
40
+ } finally {
41
+ stageInternalWriting = prev;
42
+ }
43
+ }
44
+
26
45
  export function isAnyStageReservedOnStdout(): boolean {
27
46
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
28
47
  return true;
@@ -64,6 +83,21 @@ function ensureConsoleGuardInstalled(): void {
64
83
  return (originalStderrWrite as (...a: unknown[]) => boolean)(chunk, encodingOrCb, cb);
65
84
  }) as typeof process.stderr.write;
66
85
  }
86
+
87
+ if (originalStdoutWrite && process.stdout) {
88
+ process.stdout.write = ((chunk: unknown, encodingOrCb?: unknown, cb?: unknown): boolean => {
89
+ if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
90
+ // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
91
+ const text = String(chunk ?? '');
92
+ if (text.includes('\n')) {
93
+ if (typeof encodingOrCb === 'function') (encodingOrCb as () => void)();
94
+ else if (typeof cb === 'function') (cb as () => void)();
95
+ return true;
96
+ }
97
+ }
98
+ return (originalStdoutWrite as (...a: unknown[]) => boolean)(chunk, encodingOrCb, cb);
99
+ }) as typeof process.stdout.write;
100
+ }
67
101
  }
68
102
 
69
103
  /**
@@ -10,17 +10,19 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
10
10
  import { fuzzyFilter } from './selectList.js';
11
11
  import { loadConfig, saveConfig } from '../config.js';
12
12
  import { startLoopbackAuth, saveOpenRouterKey, disconnectOpenRouter } from '../auth/openrouterAuth.js';
13
+ import { setTransientNotice } from './consoleGuard.js';
13
14
  import { getAvailableProvidersOverview, resolveAvailableProvidersOverview, resolveAvailableModels } from '../dynamicCatalogue.js';
14
- async function showConfiguringAnimation(providerLabel) {
15
- if (!process.stdout.isTTY)
15
+ async function showConfiguringAnimation(providerLabel, promptHost) {
16
+ if (promptHost && typeof promptHost.scheduleDraw === 'function') {
17
+ promptHost.notice = `Configuring ${providerLabel} in secure local vault…`;
18
+ promptHost.scheduleDraw();
19
+ await new Promise(r => setTimeout(r, 120));
20
+ promptHost.notice = `✓ ${providerLabel} credentials saved.`;
21
+ promptHost.scheduleDraw();
16
22
  return;
17
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
18
- const text = `Configuring ${providerLabel} in secure local vault…`;
19
- for (let i = 0; i < 5; i++) {
20
- const f = frames[i % frames.length];
21
- process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
22
- await new Promise(r => setTimeout(r, 60));
23
23
  }
24
+ if (!process.stdout.isTTY)
25
+ return;
24
26
  process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
25
27
  }
26
28
  /**
@@ -536,10 +538,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
536
538
  if (!cleanInput) {
537
539
  // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
538
540
  try {
539
- if (process.stdout.isTTY) {
540
- process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
541
- process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
542
- }
541
+ setTransientNotice(prompt, '● Opening browser for OpenRouter OAuth authorization… (Waiting on 127.0.0.1)', 120_000);
543
542
  const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
544
543
  saveOpenRouterKey(apiKey, { setAsActive: true, store });
545
544
  const updatedConfig = store.loadConfig();
@@ -550,9 +549,17 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
550
549
  }
551
550
  }
552
551
  notifyPrompt('openrouter', target.modelId);
552
+ setTransientNotice(prompt, `✓ Connected to OpenRouter successfully! Using OpenRouter Free / ${target.modelId}.`, 5000);
553
+ if (prompt.surface?.stage) {
554
+ prompt.surface.stage.invalidate();
555
+ }
556
+ if (typeof prompt.scheduleDraw === 'function') {
557
+ prompt.scheduleDraw();
558
+ }
553
559
  return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
554
560
  }
555
561
  catch (err) {
562
+ setTransientNotice(prompt, `✕ OpenRouter authorization failed: ${err?.message || err}`, 6000);
556
563
  return (`✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
557
564
  `Solutions:\n` +
558
565
  `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
@@ -562,7 +569,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
562
569
  }
563
570
  }
564
571
  // User pasted an API key
565
- await showConfiguringAnimation('OpenRouter');
572
+ await showConfiguringAnimation('OpenRouter', prompt);
566
573
  saveOpenRouterKey(cleanInput, { setAsActive: true, store });
567
574
  const updatedConfig = store.loadConfig();
568
575
  if (options.loop) {
@@ -628,7 +635,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
628
635
  return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
629
636
  }
630
637
  const cleanKey = enteredKey.trim();
631
- await showConfiguringAnimation(target.providerLabel);
638
+ await showConfiguringAnimation(target.providerLabel, prompt);
632
639
  config['provider'] = target.providerId;
633
640
  config['model'] = target.modelId;
634
641
  config['apiKey'] = cleanKey;
@@ -11,6 +11,7 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
11
11
  import { fuzzyFilter } from './selectList.js';
12
12
  import { loadConfig, saveConfig } from '../config.js';
13
13
  import { startLoopbackAuth, saveOpenRouterKey, disconnectOpenRouter } from '../auth/openrouterAuth.js';
14
+ import { setTransientNotice } from './consoleGuard.js';
14
15
  import {
15
16
  getAvailableProvidersOverview,
16
17
  resolveAvailableProvidersOverview,
@@ -66,15 +67,16 @@ export interface BuildModelPickerOptions {
66
67
  maxAcpPerPeer?: number | undefined;
67
68
  }
68
69
 
69
- async function showConfiguringAnimation(providerLabel: string): Promise<void> {
70
- if (!process.stdout.isTTY) return;
71
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
72
- const text = `Configuring ${providerLabel} in secure local vault…`;
73
- for (let i = 0; i < 5; i++) {
74
- const f = frames[i % frames.length];
75
- process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
76
- await new Promise(r => setTimeout(r, 60));
70
+ async function showConfiguringAnimation(providerLabel: string, promptHost?: any): Promise<void> {
71
+ if (promptHost && typeof promptHost.scheduleDraw === 'function') {
72
+ promptHost.notice = `Configuring ${providerLabel} in secure local vault…`;
73
+ promptHost.scheduleDraw();
74
+ await new Promise(r => setTimeout(r, 120));
75
+ promptHost.notice = `✓ ${providerLabel} credentials saved.`;
76
+ promptHost.scheduleDraw();
77
+ return;
77
78
  }
79
+ if (!process.stdout.isTTY) return;
78
80
  process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
79
81
  }
80
82
 
@@ -647,10 +649,7 @@ export async function runInteractiveModelPicker(
647
649
  if (!cleanInput) {
648
650
  // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
649
651
  try {
650
- if (process.stdout.isTTY) {
651
- process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
652
- process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
653
- }
652
+ setTransientNotice(prompt as any, '● Opening browser for OpenRouter OAuth authorization… (Waiting on 127.0.0.1)', 120_000);
654
653
  const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
655
654
  saveOpenRouterKey(apiKey, { setAsActive: true, store });
656
655
 
@@ -662,8 +661,16 @@ export async function runInteractiveModelPicker(
662
661
  }
663
662
  }
664
663
  notifyPrompt('openrouter', target.modelId);
664
+ setTransientNotice(prompt as any, `✓ Connected to OpenRouter successfully! Using OpenRouter Free / ${target.modelId}.`, 5000);
665
+ if ((prompt as any).surface?.stage) {
666
+ (prompt as any).surface.stage.invalidate();
667
+ }
668
+ if (typeof (prompt as any).scheduleDraw === 'function') {
669
+ (prompt as any).scheduleDraw();
670
+ }
665
671
  return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
666
672
  } catch (err: any) {
673
+ setTransientNotice(prompt as any, `✕ OpenRouter authorization failed: ${err?.message || err}`, 6000);
667
674
  return (
668
675
  `✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
669
676
  `Solutions:\n` +
@@ -676,7 +683,7 @@ export async function runInteractiveModelPicker(
676
683
  }
677
684
 
678
685
  // User pasted an API key
679
- await showConfiguringAnimation('OpenRouter');
686
+ await showConfiguringAnimation('OpenRouter', prompt);
680
687
  saveOpenRouterKey(cleanInput, { setAsActive: true, store });
681
688
  const updatedConfig = store.loadConfig();
682
689
  if (options.loop) {
@@ -747,7 +754,7 @@ export async function runInteractiveModelPicker(
747
754
  }
748
755
 
749
756
  const cleanKey = enteredKey.trim();
750
- await showConfiguringAnimation(target.providerLabel);
757
+ await showConfiguringAnimation(target.providerLabel, prompt);
751
758
 
752
759
  config['provider'] = target.providerId;
753
760
  config['model'] = target.modelId;
package/src/tui/stage.js CHANGED
@@ -33,6 +33,7 @@
33
33
  // Pure Node: no dependency, no shell.
34
34
 
35
35
  import { visibleWidth, truncate } from './text.js';
36
+ import { runWithStageWrite } from './consoleGuard.js';
36
37
 
37
38
  // Below this the band cannot hold a viewport plus an input box plus a footer,
38
39
  // and a cramped stage is worse than honest scrollback. The fallback is not a
@@ -133,7 +134,11 @@ export class Stage {
133
134
  write(text) {
134
135
  if (!text) return;
135
136
  this.stats.bytes += text.length;
136
- this.out.write(text);
137
+ if (typeof runWithStageWrite === 'function') {
138
+ runWithStageWrite(() => this.out.write(text));
139
+ } else {
140
+ this.out.write(text);
141
+ }
137
142
  }
138
143
 
139
144
  /**
@@ -392,9 +392,6 @@ export class StageSurface {
392
392
  * the contract in transcript.js.
393
393
  */
394
394
  commit(kind, produce, meta = null) {
395
- if (kind === 'error' || kind === 'turn' || kind === 'approval') {
396
- this.stage.invalidate();
397
- }
398
395
  return this.transcript.append({ kind, produce, meta });
399
396
  }
400
397
 
@@ -441,17 +438,23 @@ export class StageSurface {
441
438
  // entered from Home occupies the available height at every terminal width.
442
439
  // Its short transcript is placed next to the input below.
443
440
  const contentRows = this.transcript.height(contentWidth);
444
- const desired = sessionStageHeight(this.stage.maxHeight, block.length, contentRows, this.fullSession || caret?.inline);
441
+ const minFloor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
442
+ const neededWithFloor = Math.min(this.stage.maxHeight, block.length + minFloor);
443
+ const desired = Math.max(
444
+ sessionStageHeight(this.stage.maxHeight, block.length, contentRows, this.fullSession || caret?.inline),
445
+ neededWithFloor
446
+ );
445
447
  if (desired > this.stage.height) this.stage.grow(desired - this.stage.height);
446
448
 
447
449
  const height = this.stage.height;
448
450
 
449
- // An active prompt block or modal dialog is the focal point of user interaction.
450
- // Never slice the top border, title, or input area when the block fits within the stage height.
451
- // The transcript viewport receives the remaining vertical budget (height - block.length).
452
- const maxBlock = this.messageActionOverlay?.panel.length
453
- ? Math.max(1, height - this.messageActionOverlay.panel.length)
454
- : height;
451
+ // The prompt may not eat the whole band — but only once there is a
452
+ // transcript for it to eat. Trim from the TOP when it would: the status
453
+ // footer and the caret row are the last rows and the ones worth keeping,
454
+ // and an input box that has scrolled its own oldest row off is a smaller lie
455
+ // than a transcript that has vanished.
456
+ const floor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
457
+ const maxBlock = Math.max(1, height - floor);
455
458
  if (block.length > maxBlock) {
456
459
  const cut = block.length - maxBlock;
457
460
  block = block.slice(cut);