@causyne/agent 1.20.68 → 1.20.70

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.
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Causyne Agent — OpenRouter Free Provider
3
+ *
4
+ * Implements genuine zero-cost hosted model inference via the official
5
+ * OpenRouter Free router (`openrouter/free`) and verified zero-cost models.
6
+ * Enforces strict zero-cost boundaries, default data_collection: "deny",
7
+ * streaming SSE, and safe tool-call parsing without paid model fallbacks.
8
+ */
9
+
10
+ import { LLMProvider } from './base.js';
11
+ import { canonicalModelId } from '../modelIds.js';
12
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
13
+ import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
14
+
15
+ export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
16
+ export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
17
+ export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
18
+
19
+ export class FreeModeCostGuardError extends Error {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = 'FreeModeCostGuardError';
23
+ }
24
+ }
25
+
26
+ export class OpenRouterRateLimitError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = 'OpenRouterRateLimitError';
30
+ }
31
+ }
32
+
33
+ export class OpenRouterPrivacyConstraintError extends Error {
34
+ constructor(message: string) {
35
+ super(message);
36
+ this.name = 'OpenRouterPrivacyConstraintError';
37
+ }
38
+ }
39
+
40
+ export class OpenRouterProvider extends LLMProvider {
41
+ public dataCollection: 'deny' | 'allow';
42
+ public freeOnly: boolean;
43
+
44
+ constructor(config: Record<string, any> = {}) {
45
+ super(config);
46
+ this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
47
+ this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
48
+ this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
49
+ this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
50
+
51
+ // Verify model cost constraint upon instantiation
52
+ if (this.freeOnly) {
53
+ this.assertFreeModel(this.model);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Determine whether a model identifier represents a zero-cost free route.
59
+ */
60
+ public isFreeModel(modelId: string): boolean {
61
+ const clean = (modelId || '').trim().toLowerCase();
62
+ if (clean === 'openrouter/free' || clean === 'free') return true;
63
+ if (clean.endsWith(':free')) return true;
64
+ return false;
65
+ }
66
+
67
+ /**
68
+ * Enforce that the requested model is strictly zero-cost.
69
+ */
70
+ public assertFreeModel(modelId: string): void {
71
+ if (!this.isFreeModel(modelId)) {
72
+ throw new FreeModeCostGuardError(
73
+ `Model '${modelId}' is not an authorized free model. Free mode strictly forbids paid models to prevent unintended charges.`
74
+ );
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Execute chat completion with OpenRouter, supporting streaming, tools, and privacy tags.
80
+ */
81
+ public override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
82
+ if (this.freeOnly) {
83
+ this.assertFreeModel(this.model);
84
+ }
85
+
86
+ const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
87
+ if (!apiKey) {
88
+ throw new Error(
89
+ 'OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.'
90
+ );
91
+ }
92
+
93
+ const preparedMessages = this.prepareMessages(messages);
94
+ const shouldStream = typeof options.onChunk === 'function';
95
+
96
+ const payload: Record<string, any> = {
97
+ model: this.model,
98
+ messages: preparedMessages,
99
+ temperature: options.temperature ?? 0.1,
100
+ stream: shouldStream,
101
+ provider: {
102
+ data_collection: this.dataCollection
103
+ }
104
+ };
105
+
106
+ if (options['jsonMode']) {
107
+ payload['response_format'] = { type: 'json_object' };
108
+ }
109
+
110
+ if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
111
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
112
+ payload['tools'] = scanReport.adaptedTools;
113
+ payload['tool_choice'] = 'auto';
114
+ }
115
+
116
+ const headers: Record<string, string> = {
117
+ 'Content-Type': 'application/json',
118
+ 'Authorization': `Bearer ${apiKey}`,
119
+ 'HTTP-Referer': 'https://causyne.com',
120
+ 'X-Title': 'Causyne Agent'
121
+ };
122
+
123
+ let response: Response;
124
+ const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
125
+ const fetchInit: RequestInit = {
126
+ method: 'POST',
127
+ headers,
128
+ body: JSON.stringify(payload)
129
+ };
130
+ if (options.signal) {
131
+ fetchInit.signal = options.signal;
132
+ }
133
+
134
+ try {
135
+ response = await fetch(endpoint, fetchInit);
136
+ } catch (err: any) {
137
+ if (err?.name === 'AbortError' || options.signal?.aborted) {
138
+ throw err;
139
+ }
140
+ throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
141
+ }
142
+
143
+ if (!response.ok) {
144
+ const errorText = await response.text().catch(() => '');
145
+ this.handleHttpErrors(response.status, errorText);
146
+ }
147
+
148
+ if (shouldStream && response.body) {
149
+ return this.handleStreamingResponse(response, options);
150
+ } else {
151
+ return this.handleJsonResponse(response);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Map HTTP error codes into user-friendly and security-preserving exceptions.
157
+ */
158
+ private handleHttpErrors(status: number, errorText: string): never {
159
+ if (status === 429) {
160
+ throw new OpenRouterRateLimitError(
161
+ 'OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.'
162
+ );
163
+ }
164
+
165
+ const lowered = (errorText || '').toLowerCase();
166
+ if (status === 400 || status === 404) {
167
+ if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
168
+ throw new OpenRouterPrivacyConstraintError(
169
+ `No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
170
+ `You can retry shortly, or inspect your preference with /openrouter status.`
171
+ );
172
+ }
173
+ if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
174
+ throw new OpenRouterRateLimitError(
175
+ 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.'
176
+ );
177
+ }
178
+ }
179
+
180
+ throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
181
+ }
182
+
183
+ /**
184
+ * Process a non-streaming JSON response from OpenRouter.
185
+ */
186
+ private async handleJsonResponse(response: Response): Promise<ChatResponse> {
187
+ const data = (await response.json()) as any;
188
+ let content = '';
189
+ let toolCalls: ChatResponseToolCall[] = [];
190
+ let reasoningContent = '';
191
+
192
+ if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
193
+ const message = data.choices[0].message;
194
+ content = message.content || '';
195
+ toolCalls = this.normalizeToolCalls(message.tool_calls);
196
+ reasoningContent = message.reasoning || message.reasoning_content || '';
197
+ }
198
+
199
+ const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
200
+ const usage: ChatResponseUsage = this.normalizeUsage(rawUsage);
201
+
202
+ return {
203
+ content,
204
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
205
+ reasoningContent: reasoningContent || undefined,
206
+ usage
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Process a streaming SSE response from OpenRouter.
212
+ */
213
+ private async handleStreamingResponse(response: Response, options: ChatOptions): Promise<ChatResponse> {
214
+ const reader = response.body!.getReader();
215
+ const decoder = new TextDecoder('utf-8');
216
+
217
+ let content = '';
218
+ let reasoningContent = '';
219
+ let buffer = '';
220
+ const toolCallsMap = new Map<number, { id: string; name: string; arguments: string }>();
221
+ let rawUsage: any = null;
222
+
223
+ try {
224
+ while (true) {
225
+ if (options.signal?.aborted) {
226
+ await reader.cancel().catch(() => {});
227
+ break;
228
+ }
229
+
230
+ const { done, value } = await reader.read();
231
+ if (done) break;
232
+
233
+ buffer += decoder.decode(value, { stream: true });
234
+ const lines = buffer.split('\n');
235
+ buffer = lines.pop() || '';
236
+
237
+ for (const line of lines) {
238
+ const trimmed = line.trim();
239
+ if (!trimmed || trimmed.startsWith(':')) continue; // Skip comments/keepalive
240
+ if (trimmed === 'data: [DONE]') continue;
241
+
242
+ if (trimmed.startsWith('data: ')) {
243
+ const jsonStr = trimmed.slice(6);
244
+ let parsed: any;
245
+ try {
246
+ parsed = JSON.parse(jsonStr);
247
+ } catch {
248
+ continue;
249
+ }
250
+
251
+ if (parsed.usage) {
252
+ rawUsage = parsed.usage;
253
+ }
254
+
255
+ const choice = parsed.choices?.[0];
256
+ if (!choice) continue;
257
+
258
+ const delta = choice.delta;
259
+ if (delta) {
260
+ // 1. Text chunk
261
+ if (delta.content) {
262
+ content += delta.content;
263
+ if (options.onChunk) {
264
+ options.onChunk(delta.content);
265
+ }
266
+ }
267
+
268
+ // 2. Reasoning chunk
269
+ const reasoning = delta.reasoning || delta.reasoning_content;
270
+ if (reasoning) {
271
+ reasoningContent += reasoning;
272
+ if (options.onReasoningChunk) {
273
+ options.onReasoningChunk(reasoning);
274
+ }
275
+ }
276
+
277
+ // 3. Tool calls assembly
278
+ if (Array.isArray(delta.tool_calls)) {
279
+ for (const tc of delta.tool_calls) {
280
+ const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
281
+ let existing = toolCallsMap.get(idx);
282
+ if (!existing) {
283
+ existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
284
+ toolCallsMap.set(idx, existing);
285
+ }
286
+ if (tc.id) existing.id = tc.id;
287
+ if (tc.function?.name) existing.name += tc.function.name;
288
+ if (tc.function?.arguments) existing.arguments += tc.function.arguments;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+ } finally {
296
+ reader.releaseLock();
297
+ }
298
+
299
+ const toolCalls: ChatResponseToolCall[] = [];
300
+ for (const item of toolCallsMap.values()) {
301
+ if (item.name) {
302
+ toolCalls.push({
303
+ id: item.id,
304
+ type: 'function',
305
+ function: {
306
+ name: item.name,
307
+ arguments: item.arguments || '{}'
308
+ }
309
+ });
310
+ }
311
+ }
312
+
313
+ const usage: ChatResponseUsage = this.normalizeUsage(
314
+ rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
315
+ );
316
+
317
+ return {
318
+ content,
319
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
320
+ reasoningContent: reasoningContent || undefined,
321
+ usage
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Safely normalize tool calls from provider message.
327
+ */
328
+ private normalizeToolCalls(rawCalls: any[]): ChatResponseToolCall[] {
329
+ if (!Array.isArray(rawCalls)) return [];
330
+ const normalized: ChatResponseToolCall[] = [];
331
+
332
+ for (let i = 0; i < rawCalls.length; i++) {
333
+ const tc = rawCalls[i];
334
+ if (!tc || typeof tc !== 'object') continue;
335
+
336
+ const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
337
+ const name = tc.function?.name || tc.name || '';
338
+ if (!name || typeof name !== 'string') continue;
339
+
340
+ let args = tc.function?.arguments;
341
+ if (typeof args !== 'string') {
342
+ try {
343
+ args = JSON.stringify(args || {});
344
+ } catch {
345
+ args = '{}';
346
+ }
347
+ }
348
+
349
+ normalized.push({
350
+ id,
351
+ type: 'function',
352
+ function: {
353
+ name,
354
+ arguments: args
355
+ }
356
+ });
357
+ }
358
+
359
+ return normalized;
360
+ }
361
+ }
@@ -7,6 +7,9 @@ const originalConsole = {
7
7
  warn: console.warn.bind(console),
8
8
  error: console.error.bind(console)
9
9
  };
10
+ const originalStderrWrite = process.stderr?.write
11
+ ? process.stderr.write.bind(process.stderr)
12
+ : null;
10
13
  export function isAnyStageReservedOnStdout() {
11
14
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
12
15
  return true;
@@ -35,6 +38,18 @@ function ensureConsoleGuardInstalled() {
35
38
  console.info = wrap(originalConsole.info);
36
39
  console.warn = wrap(originalConsole.warn);
37
40
  console.error = wrap(originalConsole.error);
41
+ if (originalStderrWrite && process.stderr) {
42
+ process.stderr.write = ((chunk, encodingOrCb, cb) => {
43
+ if (isAnyStageReservedOnStdout()) {
44
+ if (typeof encodingOrCb === 'function')
45
+ encodingOrCb();
46
+ else if (typeof cb === 'function')
47
+ cb();
48
+ return true;
49
+ }
50
+ return originalStderrWrite(chunk, encodingOrCb, cb);
51
+ });
52
+ }
38
53
  }
39
54
  /**
40
55
  * Track TUI Stage open/close lifecycle so raw console writes cannot corrupt the composer box.
@@ -19,6 +19,10 @@ const originalConsole = {
19
19
  error: console.error.bind(console)
20
20
  };
21
21
 
22
+ const originalStderrWrite = process.stderr?.write
23
+ ? process.stderr.write.bind(process.stderr)
24
+ : null;
25
+
22
26
  export function isAnyStageReservedOnStdout(): boolean {
23
27
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
24
28
  return true;
@@ -49,6 +53,17 @@ function ensureConsoleGuardInstalled(): void {
49
53
  console.info = wrap(originalConsole.info);
50
54
  console.warn = wrap(originalConsole.warn);
51
55
  console.error = wrap(originalConsole.error);
56
+
57
+ if (originalStderrWrite && process.stderr) {
58
+ process.stderr.write = ((chunk: unknown, encodingOrCb?: unknown, cb?: unknown): boolean => {
59
+ if (isAnyStageReservedOnStdout()) {
60
+ if (typeof encodingOrCb === 'function') (encodingOrCb as () => void)();
61
+ else if (typeof cb === 'function') (cb as () => void)();
62
+ return true;
63
+ }
64
+ return (originalStderrWrite as (...a: unknown[]) => boolean)(chunk, encodingOrCb, cb);
65
+ }) as typeof process.stderr.write;
66
+ }
52
67
  }
53
68
 
54
69
  /**
package/src/tui/home.js CHANGED
@@ -148,6 +148,7 @@ export const PROVIDERS = [
148
148
  { id: 'moonshot', label: 'Moonshot', hint: 'Kimi', category: 'BYOK (Cloud API)' },
149
149
  { id: 'xai', label: 'xAI', hint: 'Grok', category: 'BYOK (Cloud API)' },
150
150
  { id: 'openai-compatible', label: 'OpenAI-compatible endpoint', hint: 'custom base URL', category: 'BYOK (Custom)' },
151
+ { id: 'openrouter', label: 'OpenRouter (Free Models)', hint: 'free inference router · openrouter/free', category: 'Free Cloud Models' },
151
152
  { id: 'ollama', label: 'Ollama', hint: 'local / offline', category: 'BYOK (Local Server)' },
152
153
  { id: 'antigravity', label: 'Google Antigravity (AGY)', hint: resolveAgyBinary() ? 'local AGY · Gemini & Claude (ready)' : 'local AGY · (not installed)', category: 'ACP (Peer Agent)' },
153
154
  PI_SETUP_PROVIDER,
@@ -136,11 +136,21 @@ export function buildModelPickerItems(config, overview, options = {}) {
136
136
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
137
137
  const catTitle = p.id === 'ollama'
138
138
  ? `BYOK · ${p.label}`
139
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
139
+ : p.id === 'openrouter'
140
+ ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
141
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
140
142
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
141
143
  for (const m of models) {
142
144
  const isCurrent = isCurrentProvider && activeModel === m;
143
- const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
145
+ const desc = isCurrent
146
+ ? (p.id === 'openrouter' ? '● active (free)' : '● active')
147
+ : p.id === 'ollama'
148
+ ? 'local'
149
+ : p.id === 'openrouter'
150
+ ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
151
+ : p.isConfigured
152
+ ? 'configured'
153
+ : 'needs API key';
144
154
  items.push({
145
155
  id: `${p.id}/${m}`,
146
156
  label: m,
@@ -198,12 +198,22 @@ export function buildModelPickerItems(
198
198
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
199
199
  const catTitle = p.id === 'ollama'
200
200
  ? `BYOK · ${p.label}`
201
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
201
+ : p.id === 'openrouter'
202
+ ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
203
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
202
204
 
203
205
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
204
206
  for (const m of models) {
205
207
  const isCurrent = isCurrentProvider && activeModel === m;
206
- const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
208
+ const desc = isCurrent
209
+ ? (p.id === 'openrouter' ? '● active (free)' : '● active')
210
+ : p.id === 'ollama'
211
+ ? 'local'
212
+ : p.id === 'openrouter'
213
+ ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
214
+ : p.isConfigured
215
+ ? 'configured'
216
+ : 'needs API key';
207
217
  items.push({
208
218
  id: `${p.id}/${m}`,
209
219
  label: m,
package/src/tui/prompt.js CHANGED
@@ -461,6 +461,7 @@ export class ChatPrompt {
461
461
  openLayer(layer) {
462
462
  this.closeLayer();
463
463
  this.layer = layer;
464
+ if (this.surface?.stage) this.surface.stage.invalidate();
464
465
  this.draw();
465
466
  return layer;
466
467
  }
@@ -473,6 +474,7 @@ export class ChatPrompt {
473
474
  // is torn down without one would otherwise leave its promise pending forever
474
475
  // and hang the turn.
475
476
  if (typeof layer.answer === 'function') layer.answer(false);
477
+ if (this.surface?.stage) this.surface.stage.invalidate();
476
478
  this.draw();
477
479
  }
478
480
 
@@ -748,6 +750,7 @@ export class ChatPrompt {
748
750
  this.busy = busy;
749
751
  resetTurnInterruptState(this, busy);
750
752
  if (busy) this.startTick(); else this.stopTick();
753
+ if (this.surface?.stage) this.surface.stage.invalidate();
751
754
  this.draw();
752
755
  }
753
756
 
package/src/tui/stage.js CHANGED
@@ -44,6 +44,8 @@ export const MIN_STAGE_ROWS = 16;
44
44
  // which is what stops a scroll from tearing.
45
45
  const SYNC_ON = '\x1b[?2026h';
46
46
  const SYNC_OFF = '\x1b[?2026l';
47
+ const NOWRAP_ON = '\x1b[?7l';
48
+ const NOWRAP_OFF = '\x1b[?7h';
47
49
  const HIDE_CURSOR = '\x1b[?25l';
48
50
  const SHOW_CURSOR = '\x1b[?25h';
49
51
  const ERASE_LINE = '\x1b[K';
@@ -238,7 +240,7 @@ export class Stage {
238
240
  // the same bet and calls it out as its main anti-flicker mechanism.
239
241
  if (changed.length === 0 && !caretMoved) return 0;
240
242
 
241
- this.write(SYNC_ON + HIDE_CURSOR);
243
+ this.write(SYNC_ON + HIDE_CURSOR + NOWRAP_ON);
242
244
  for (const i of changed) {
243
245
  this.moveTo(i);
244
246
  this.write('\r' + next[i] + ERASE_LINE);
@@ -246,7 +248,7 @@ export class Stage {
246
248
  this.moveTo(target.row);
247
249
  this.write('\r');
248
250
  if (target.col > 0) this.write(`\x1b[${target.col}C`);
249
- this.write((target.hideCursor ? HIDE_CURSOR : SHOW_CURSOR + '\x1b[6 q') + SYNC_OFF);
251
+ this.write(NOWRAP_OFF + (target.hideCursor ? HIDE_CURSOR : SHOW_CURSOR + '\x1b[6 q') + SYNC_OFF);
250
252
 
251
253
  this.prev = next;
252
254
  this.caret = target;
@@ -35,6 +35,7 @@ import { placeHome, placeDialog } from './homeView.js';
35
35
  import { sidebarVisible, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
36
36
  import { sessionStageHeight, alignTranscriptRows } from './sessionLayout.js';
37
37
  import { hasSessionTurns, collectSessionTurns, buildTurnRailCells, renderTurnPreviewCard, overlayTurnPreviewCard, resolveActiveTurnIndex } from './turnRail.js';
38
+ import { registerStageConsoleGuard, setStageConsoleGuardActive } from './consoleGuard.js';
38
39
 
39
40
  // Rows of evicted transcript held for the exit log. Eviction only happens after
40
41
  // MAX_FRAMES, so this is a bound on a pathological session, not a working limit.
@@ -193,6 +194,9 @@ export class StageSurface {
193
194
  this.lastPromptRows = [];
194
195
  this.lastPromptCaret = null;
195
196
  this.messageActionOverlay = null;
197
+ this.unregisterConsoleGuard = null;
198
+ this.wasModal = false;
199
+ this.lastBlockLength = 0;
196
200
  }
197
201
 
198
202
  get width() {
@@ -250,6 +254,9 @@ export class StageSurface {
250
254
  // the user had typed anything, and 73 of the 77 claimed rows were empty.
251
255
  // present() grows it to fit what there actually is.
252
256
  if (!this.stage.reserve(1)) return false;
257
+ this.unregisterConsoleGuard?.();
258
+ this.unregisterConsoleGuard = registerStageConsoleGuard(this);
259
+ if (this.out === process.stdout) setStageConsoleGuardActive(true);
253
260
  if (!this.homeInfo) this.enableMouse();
254
261
  this.armTeardown();
255
262
  return true;
@@ -304,6 +311,11 @@ export class StageSurface {
304
311
  // Mouse first, unconditionally: it is the one piece of state that outlives
305
312
  // the process and damages the terminal the user goes back to.
306
313
  this.disableMouse();
314
+ if (this.unregisterConsoleGuard) {
315
+ this.unregisterConsoleGuard();
316
+ this.unregisterConsoleGuard = null;
317
+ if (this.out === process.stdout) setStageConsoleGuardActive(false);
318
+ }
307
319
  if (!this.stage.reserved) { this.disarmTeardown(); return false; }
308
320
  const rows = this.snapshot();
309
321
  this.stage.collapse();
@@ -325,6 +337,11 @@ export class StageSurface {
325
337
  suspend() {
326
338
  if (!this.stage.reserved) return false;
327
339
  this.disableMouse();
340
+ if (this.unregisterConsoleGuard) {
341
+ this.unregisterConsoleGuard();
342
+ this.unregisterConsoleGuard = null;
343
+ if (this.out === process.stdout) setStageConsoleGuardActive(false);
344
+ }
328
345
  this.stage.collapse();
329
346
  return true;
330
347
  }
@@ -332,6 +349,9 @@ export class StageSurface {
332
349
  resume() {
333
350
  if (this.stage.reserved) return false;
334
351
  if (!this.stage.reserve()) return false;
352
+ this.unregisterConsoleGuard?.();
353
+ this.unregisterConsoleGuard = registerStageConsoleGuard(this);
354
+ if (this.out === process.stdout) setStageConsoleGuardActive(true);
335
355
  this.stage.invalidate();
336
356
  this.enableMouse();
337
357
  return true;
@@ -372,6 +392,9 @@ export class StageSurface {
372
392
  * the contract in transcript.js.
373
393
  */
374
394
  commit(kind, produce, meta = null) {
395
+ if (kind === 'error' || kind === 'turn' || kind === 'approval') {
396
+ this.stage.invalidate();
397
+ }
375
398
  return this.transcript.append({ kind, produce, meta });
376
399
  }
377
400
 
@@ -386,6 +409,12 @@ export class StageSurface {
386
409
  this.lastPromptCaret = caret;
387
410
  }
388
411
 
412
+ const isModal = Boolean(caret?.modal);
413
+ if (isModal !== this.wasModal) {
414
+ this.wasModal = isModal;
415
+ this.stage.invalidate();
416
+ }
417
+
389
418
  if (this.homeInfo || (caret?.modal && !caret?.inline)) {
390
419
  if (this.stage.height < this.stage.maxHeight) {
391
420
  this.stage.grow(this.stage.maxHeight - this.stage.height);
@@ -429,6 +458,11 @@ export class StageSurface {
429
458
  caretRow = Math.max(0, caretRow - cut);
430
459
  }
431
460
 
461
+ if (this.lastBlockLength > 0 && this.lastBlockLength !== block.length) {
462
+ this.stage.invalidate();
463
+ }
464
+ this.lastBlockLength = block.length;
465
+
432
466
  const budget = Math.max(0, height - block.length);
433
467
  let rows = [];
434
468
  if (budget > 0) {
@@ -685,7 +719,7 @@ export class StageSurface {
685
719
  row = ` ${leftCell} ${row}`;
686
720
  }
687
721
  }
688
- rows[i] = `${padEnd(row, contentWidth)} ${rightCell}`;
722
+ rows[i] = `${padEnd(truncate(row, contentWidth, ''), contentWidth)} ${rightCell}`;
689
723
  }
690
724
  return rows;
691
725
  }
package/src/tui/text.js CHANGED
@@ -32,14 +32,37 @@ export function stripAnsi(text) {
32
32
  */
33
33
  function isWideCodePoint(code) {
34
34
  return ((code >= 0x1100 && code <= 0x115f) || // Hangul Jamo
35
+ code === 0x231a || code === 0x231b || // Watch, Hourglass
36
+ (code >= 0x23e9 && code <= 0x23fa) || // Media control & clock symbols
37
+ code === 0x25fd || code === 0x25fe || // Medium small squares
38
+ code === 0x2614 || code === 0x2615 || // Umbrella with rain, Hot beverage
39
+ (code >= 0x2648 && code <= 0x2653) || // Zodiac symbols
40
+ code === 0x267f || code === 0x2693 || code === 0x26a1 || // Wheelchair, Anchor, High voltage (⚡)
41
+ code === 0x26aa || code === 0x26ab || code === 0x26bd || code === 0x26be ||
42
+ code === 0x26c4 || code === 0x26c5 || code === 0x26ce || code === 0x26d4 ||
43
+ code === 0x26ea || code === 0x26f2 || code === 0x26f3 || code === 0x26f5 ||
44
+ code === 0x26fa || code === 0x26fd ||
45
+ code === 0x2705 || code === 0x270a || code === 0x270b || code === 0x2728 || // ✅ ✊ ✋ ✨
46
+ code === 0x274c || code === 0x274e || (code >= 0x2753 && code <= 0x2755) ||
47
+ code === 0x2757 || (code >= 0x2795 && code <= 0x2797) || code === 0x27b0 || code === 0x27bf ||
48
+ code === 0x2b1b || code === 0x2b1c || code === 0x2b50 || code === 0x2b55 ||
35
49
  (code >= 0x2e80 && code <= 0xa4cf) || // CJK radicals … Yi
36
50
  (code >= 0xac00 && code <= 0xd7a3) || // Hangul syllables
37
51
  (code >= 0xf900 && code <= 0xfaff) || // CJK compatibility ideographs
38
52
  (code >= 0xfe30 && code <= 0xfe6f) || // CJK compatibility forms
39
53
  (code >= 0xff00 && code <= 0xff60) || // Fullwidth forms
40
54
  (code >= 0xffe0 && code <= 0xffe6) ||
41
- (code >= 0x1f300 && code <= 0x1f64f) || // emoji
42
- (code >= 0x1f900 && code <= 0x1f9ff));
55
+ code === 0x1f004 || code === 0x1f0cf || code === 0x1f18e ||
56
+ (code >= 0x1f191 && code <= 0x1f19a) ||
57
+ (code >= 0x1f1e6 && code <= 0x1f251) ||
58
+ (code >= 0x1f300 && code <= 0x1f64f) || // Misc Symbols, Pictographs & Emoticons
59
+ (code >= 0x1f680 && code <= 0x1f6ff) || // Transport & Map Symbols
60
+ (code >= 0x1f700 && code <= 0x1f7ff) || // Alchemical & Geometric Shapes Extended
61
+ (code >= 0x1f800 && code <= 0x1f8ff) || // Supplemental Arrows-C
62
+ (code >= 0x1f900 && code <= 0x1f9ff) || // Supplemental Symbols & Pictographs
63
+ (code >= 0x1fa00 && code <= 0x1faff) || // Symbols & Pictographs Extended-A
64
+ (code >= 0x20000 && code <= 0x3ffff) // Supplementary Ideographic Planes
65
+ );
43
66
  }
44
67
  /**
45
68
  * The East Asian AMBIGUOUS class (UAX #11).