@vecteur/cli 0.9.1 → 0.11.1

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/src/terminal.js CHANGED
@@ -1,46 +1,116 @@
1
1
  import { ComposerInput } from "./input.js";
2
2
  import { command, completions, SHORTCUTS } from "./commands.js";
3
3
  import { Session } from "./session.js";
4
- import { terminalText as safe, taskLines } from "./format.js";
4
+ import { terminalText as safe, humanRunSections } from "./format.js";
5
+ import { blockText } from "./blocks.js";
5
6
  import { preferences } from "./preferences.js";
6
7
  import { openBrowser } from "./browser.js";
7
8
  import { readFileSync } from "node:fs";
8
9
  import { homedir } from "node:os";
10
+ import { stripVTControlCharacters } from "node:util";
11
+ import stringWidth from "string-width";
9
12
 
10
- /** The only stdout writer. It never clears the screen/scrollback or enters alternate screen. */
13
+ const measure = value => /^[\x20-\x7e]*$/.test(value) ? value.length : stringWidth(value);
14
+
15
+ /**
16
+ * The only stdout writer. It never clears the screen/scrollback or enters alternate screen.
17
+ * Rich mode parks the cursor (hidden) at column 1 of the first live row: everything from there
18
+ * down is the live region, so one erase-below removes exactly it, even after the terminal has
19
+ * reflowed it on resize. A cursor-position report places that row; blank rows between the
20
+ * transcript and the bottom-anchored composer are cursor movement, never printed history.
21
+ */
11
22
  export class TerminalWriter {
12
- constructor(stdout, plain) { this.stdout = stdout; this.plain = plain; this.height = 0; }
23
+ constructor(stdout, plain) {
24
+ this.stdout = stdout; this.plain = plain; this.drawn = false; this.frame = null;
25
+ this.row = null; this.awaiting = 0; this.since = 0;
26
+ }
13
27
  erase() {
14
- if (!this.height) return "";
15
- const move = `\x1b[${this.height}A\r`, bytes = move + "\x1b[2K\n".repeat(this.height) + move;
16
- this.height = 0;
17
- return bytes;
28
+ if (!this.drawn) return "";
29
+ this.drawn = false;
30
+ return "\r\x1b[J";
18
31
  }
19
- clearLive() { const bytes = this.erase(); if (bytes) this.stdout.write(bytes); }
20
- progress(view) {
32
+ clearLive() { this.frame = null; const bytes = this.erase(); if (bytes) this.stdout.write(bytes); }
33
+ // Display rows the terminal used for appended text; rich lines are narrower than the window.
34
+ advance(text) {
35
+ const columns = Math.max(1, this.stdout.columns ?? 80);
36
+ const rows = text.split("\n").reduce((sum, line) => sum + Math.max(1, Math.ceil(measure(stripVTControlCharacters(line)) / columns)), 0);
37
+ if (this.awaiting) this.since += rows;
38
+ else if (this.row) this.row = Math.min(this.stdout.rows ?? 24, this.row + rows);
39
+ }
40
+ progress(view, { controlsOnly = false } = {}) {
21
41
  const subject = view.run?.subject?.id;
22
- if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; this.lastQuestion = null; }
42
+ if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; this.lastQuestion = null; this.controls = new Map(); }
23
43
  if (!subject || view.run.terminal) return;
24
- if (view.run.progress && view.run.progress !== this.lastProgress) {
44
+ if (!controlsOnly && view.run.progress && view.run.progress !== this.lastProgress) {
25
45
  this.append(safe(`${view.run.progress} · ${view.run.elapsed ?? "Elapsed unavailable"}`)); this.lastProgress = view.run.progress;
26
46
  }
47
+ for (const block of view.run.blocks ?? []) {
48
+ if (block.kind !== "control") continue;
49
+ const signature = JSON.stringify(block.payload);
50
+ if (this.controls.get(block.key) === signature) continue;
51
+ this.controls.set(block.key, signature);
52
+ this.append(safe(`Controls:\n${blockText(block)}`));
53
+ }
54
+ if (controlsOnly) return;
27
55
  const question = view.run.question;
28
56
  if (question?.id !== this.lastQuestion) {
29
57
  this.lastQuestion = question?.id;
30
58
  if (question) this.append(safe(`Vecteur needs your answer — /answer\n${question.questions.map(row => row.question).join("\n")}`));
31
59
  }
32
60
  }
33
- append(text) { this.stdout.write(`${this.erase()}${text.replace(/\n+$/, "")}\n`); }
34
- draw(text) {
61
+ /** Scrollback text, then the given live frame in the same write: the composer never blinks out. */
62
+ append(text, frame = null) {
63
+ const body = text.replace(/\n+$/, "");
64
+ let bytes = `${this.erase()}${body}\n`;
65
+ if (!this.plain) this.advance(body);
66
+ if (frame) { this.frame = frame; bytes += this.render(); }
67
+ this.stdout.write(bytes);
68
+ }
69
+ draw(frame) {
35
70
  if (this.plain) return;
71
+ this.frame = typeof frame === "string" ? { top: [], bottom: frame.replace(/\n+$/, "").split("\n") } : frame;
36
72
  // One write per frame: erase and redraw land together, so the spinner never flickers.
37
- const lines = text.replace(/\n+$/, "");
38
- this.stdout.write(`${this.erase()}${lines}\n`); this.height = lines.split("\n").length;
73
+ const bytes = this.render();
74
+ if (bytes) this.stdout.write(bytes);
75
+ }
76
+ render() {
77
+ if (this.plain || !this.frame || this.awaiting) return "";
78
+ const rows = this.stdout.rows ?? 24;
79
+ const lines = [...this.frame.top, ...this.frame.bottom].slice(-Math.max(1, rows - 1));
80
+ const gap = this.row ? Math.max(0, rows - this.row + 1 - lines.length) : 0;
81
+ const at = Math.max(0, lines.length - this.frame.bottom.length);
82
+ const body = [...lines.slice(0, at), ...Array(gap).fill(""), ...lines.slice(at)];
83
+ const up = body.length - 1;
84
+ if (this.row) this.row = Math.max(1, Math.min(this.row, rows - body.length + 1));
85
+ const erase = this.erase(); this.drawn = true;
86
+ return `${erase}${body.join("\n")}${up ? `\x1b[${up}A` : ""}\r`;
87
+ }
88
+ /** Ask the terminal where the live region starts; frames wait for the answer (or 300 ms). */
89
+ locate(query = "") {
90
+ if (this.plain) return;
91
+ this.awaiting++; this.since = 0;
92
+ this.stdout.write(`${query}\x1b[6n`);
93
+ clearTimeout(this.locateTimer);
94
+ this.locateTimer = setTimeout(() => { this.awaiting = 0; this.row = null; this.onLocated?.(); }, 300);
95
+ }
96
+ located(row, column) {
97
+ if (!this.awaiting || --this.awaiting) return;
98
+ clearTimeout(this.locateTimer);
99
+ const rows = this.stdout.rows ?? 24;
100
+ let bytes = "";
101
+ // Another program left the cursor mid-line: start the live region on the next row.
102
+ if (column > 1 && !this.since) { bytes = "\r\n"; row++; }
103
+ this.row = Math.max(1, Math.min(rows, row + this.since));
104
+ if (bytes) this.stdout.write(bytes);
105
+ this.onLocated?.();
39
106
  }
40
107
  resized(plain) {
41
- // Reflow can collapse old wrapped lines: their old height is no longer a safe erase bound.
42
- this.height = 0; this.plain = plain; this.stdout.write("\n");
108
+ // Reflow moved the old frame but not the parked cursor: erase below it, then re-locate.
109
+ const bytes = this.drawn ? "\r\x1b[J" : "";
110
+ this.drawn = false; this.frame = null; this.row = null; this.plain = plain;
111
+ if (bytes) this.stdout.write(bytes);
43
112
  }
113
+ close() { clearTimeout(this.locateTimer); this.awaiting = 0; }
44
114
  }
45
115
 
46
116
  export async function startTerminal(options = {}, { stdin = process.stdin, stdout = process.stdout, env = process.env } = {}) {
@@ -49,8 +119,16 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
49
119
  if (!options.plain) throw error;
50
120
  prefs = { plain: true, reducedMotion: true };
51
121
  }
52
- let rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
122
+ let rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
123
+ let pasteMode = false;
124
+ const syncPasteMode = () => {
125
+ if (pasteMode === rich) return;
126
+ pasteMode = rich;
127
+ stdout.write(pasteMode ? "\x1b[?2004h" : "\x1b[?2004l");
128
+ };
53
129
  const color = !options.noColor && env.NO_COLOR === undefined;
130
+ // Colour roles start palette-relative; a terminal that reports its own colours gets exact blends.
131
+ let theme = color; const reported = {};
54
132
  const layout = await import("./tui/view.js");
55
133
  const isPlain = () => !rich || ((stdout.columns ?? 80) < 40 || (stdout.rows ?? 24) < 8);
56
134
  const writer = new TerminalWriter(stdout, isPlain());
@@ -65,8 +143,11 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
65
143
  // While a vendor owns the TTY (handoff) Vecteur writes nothing: frames, clocks, streamed
66
144
  // steps and messages wait, and are flushed once when the vendor exits.
67
145
  let vendorOwnsTerminal = false, resizedDuringHandoff = false; const heldMessages = [];
68
- // Rich scrollback streams each finished step as one line; the answer block then skips them.
69
- const streamed = { run: null, events: 0, steps: 0 };
146
+ // Immutable event blocks commit once; mutable controls have their own live/final section.
147
+ const streamed = { run: null, keys: new Set() };
148
+ // The identity header is live until the first transcript block, then committed once.
149
+ let headerLive = true, cursorHidden = false;
150
+ const directory = () => session.cwd === homedir() || session.cwd.startsWith(homedir() + "/") ? "~" + session.cwd.slice(homedir().length) : session.cwd;
70
151
  const history = []; let historyIndex = 0, historyDraft = "", historyAccount;
71
152
  const syncInput = (value, cursor = value === input.text ? input.cursor : value.length) => { suppressed = true; input.set(value); input.cursor = cursor; suppressed = false; };
72
153
  const focusChanged = () => {
@@ -82,39 +163,64 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
82
163
  if (!input.text || /^[\d, ]+$/.test(input.text)) return prompt.options;
83
164
  return prompt.options.filter(item => item.label.toLowerCase().includes(input.text.toLowerCase()));
84
165
  };
85
- const frameView = () => ({ ...session.view(), version, channel,
166
+ const frameView = () => ({ ...session.view(), version, channel, header: headerLive, directory: directory(),
86
167
  focus: localPicker ?? session.prompt, choices: choices(), selected,
87
168
  palette: palette(), paletteSelected, loginAction });
169
+ const live = () => layout.richLayout(frameView(), input.text, input.cursor,
170
+ { columns: stdout.columns ?? 80, rows: stdout.rows ?? 24, color: theme, tick: prefs.reducedMotion ? null : tick });
88
171
  const draw = () => {
89
172
  clearTimeout(frameTimer); frameTimer = null;
90
173
  if (vendorOwnsTerminal) return;
91
- if (!session.closed && !writer.plain) writer.draw(layout.richFrame(frameView(), input.text, input.cursor,
92
- { columns: stdout.columns ?? 80, rows: stdout.rows ?? 24, color, tick: prefs.reducedMotion ? null : tick }));
174
+ if (!session.closed && !writer.plain) writer.draw(live());
175
+ };
176
+ // The real cursor stays hidden in rich mode (the composer draws its own caret) and always
177
+ // returns on exit, error, plain fallback and vendor handoff.
178
+ const showCursor = visible => {
179
+ if (env.TERM === "dumb" || !stdout.isTTY || visible !== cursorHidden) return;
180
+ cursorHidden = !visible; stdout.write(visible ? "\x1b[0m\x1b[?25h" : "\x1b[?25l");
181
+ };
182
+ const restoreCursor = () => showCursor(true);
183
+ const commitHeader = () => {
184
+ if (writer.plain || !headerLive) return;
185
+ headerLive = false; writer.append(layout.richHeader(frameView(), stdout.columns ?? 80, theme).join("\n"));
186
+ };
187
+ // Transcript blocks (asks, answers, steps, usage) commit the header above them; notices printed
188
+ // before the first ask stay above the live identity, which keeps owning the current facts.
189
+ const print = (text, transcript = true) => {
190
+ if (transcript) commitHeader();
191
+ writer.append(text, writer.plain || session.closed || vendorOwnsTerminal ? null : live());
93
192
  };
193
+ writer.onLocated = () => {
194
+ input.expectReports = false;
195
+ if (theme && reported.fg && reported.bg && theme === color) {
196
+ theme = layout.paletteTheme(reported, ["truecolor", "24bit"].includes(env.COLORTERM));
197
+ }
198
+ draw();
199
+ };
200
+ const locate = (query = "") => { if (!writer.plain) { input.expectReports ||= !!query; writer.locate(query); } };
94
201
  const schedule = () => { if (!frameTimer && !vendorOwnsTerminal) frameTimer = setTimeout(() => { frameTimer = null; draw(); }, 40); };
95
- const printPlainPrompt = prompt => writer.append(safe(`${prompt.title}\n${prompt.options.map((row, i) => `${i + 1}. ${row.label}`).join("\n")}\nEnter a choice; Esc returns to your draft.`));
202
+ const printPlainPrompt = prompt => writer.append(safe(`${prompt.card ?? prompt.title}\n${prompt.options.map((row, i) => `${i + 1}. ${row.label}`).join("\n")}\nEnter a choice; Esc returns to your draft.`));
96
203
  const maybeUpdate = () => {
97
204
  if (updateChecked || session.closed || session.offline || session.busy || session.prompt || session.loginChallenge || session.run?.open || session.registry?.state().pendingRun || session.registry?.state().pendingCreate || !session.release) return;
98
205
  updateChecked = true;
99
206
  void import("./update.js").then(({ interactiveUpdate }) => interactiveUpdate(session, { automatic: true })).catch(error => session.report(error));
100
207
  };
208
+ const commitBlocks = (runId, blocks) => {
209
+ if (streamed.run !== runId) { streamed.run = runId; streamed.keys = new Set(); }
210
+ for (const block of blocks) {
211
+ if (!block.committed || ["control", "terminal"].includes(block.kind) || streamed.keys.has(block.key)) continue;
212
+ print(writer.plain ? blockText(block) : layout.richMessage({ kind: "block", block }, stdout.columns ?? 80, theme));
213
+ streamed.keys.add(block.key);
214
+ }
215
+ };
101
216
  session.on("change", view => {
102
217
  if (vendorOwnsTerminal) return;
103
218
  const ticking = !writer.plain && !view.offline && session.run?.open;
104
219
  if (ticking && !clockTimer) clockTimer = setInterval(() => { tick++; draw(); }, prefs.reducedMotion ? 1000 : 200);
105
220
  if (!ticking) { clearInterval(clockTimer); clockTimer = null; }
106
221
  const run = session.run;
107
- if (!writer.plain && run?.open && Array.isArray(run.events)) {
108
- if (streamed.run !== run.run_id) Object.assign(streamed, { run: run.run_id, events: 0, steps: 0 });
109
- for (; streamed.events < run.events.length; streamed.events++) {
110
- const event = run.events[streamed.events];
111
- if (event?.kind !== "step_finished") continue;
112
- const [row] = taskLines([event]);
113
- if (!row) continue;
114
- if (!streamed.steps++) writer.append("");
115
- writer.append(layout.richMessage({ kind: "step", text: row.split("\n").map(part => part.trim().replace(/^[▸·]\s*/, "")).filter(Boolean).join(" · ") }, stdout.columns ?? 80, color));
116
- }
117
- }
222
+ if (!writer.plain && (stdout.rows ?? 24) < 18) writer.progress(view, { controlsOnly: true });
223
+ if (run?.open && Array.isArray(run.events)) commitBlocks(run.run_id, view.run.blocks);
118
224
  if (process.connected && process.send && env.VECTEUR_UPDATE_SESSION && session.release?.compatible
119
225
  && session.registry && (!view.busy || view.prompt)) {
120
226
  const nonce = env.VECTEUR_UPDATE_SESSION; delete env.VECTEUR_UPDATE_SESSION;
@@ -133,7 +239,9 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
133
239
  if (view.prompt && !activePrompt) snapshot = { text: input.text.startsWith("/") ? session.draft : input.text, cursor: input.cursor, undo: input.undo, killed: input.killed };
134
240
  activePrompt = view.prompt; selected = 0; focusChanged();
135
241
  if (activePrompt) {
136
- input.undo = []; input.killed = ""; syncInput(""); if (writer.plain) printPlainPrompt(activePrompt);
242
+ input.undo = []; input.killed = ""; syncInput("");
243
+ if (writer.plain) printPlainPrompt(activePrompt);
244
+ else if (activePrompt.card) print(layout.richMessage({ kind: "notice", text: `${activePrompt.card}\n${activePrompt.options.map((row,i)=>`${i+1}. ${row.label}`).join("\n")}` }, stdout.columns ?? 80, theme), false);
137
245
  } else {
138
246
  const restored = snapshot && snapshot.text === session.draft ? snapshot : { text: session.draft, cursor: session.draft.length };
139
247
  syncInput(restored.text, Math.min(restored.cursor, restored.text.length)); input.undo = restored.undo ?? []; input.killed = restored.killed ?? ""; snapshot = null;
@@ -145,14 +253,24 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
145
253
  schedule(); queueMicrotask(maybeUpdate);
146
254
  });
147
255
  session.on("preferences", value => {
148
- prefs = value; rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
149
- writer.resized(isPlain()); session.change(); draw();
256
+ prefs = value; rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
257
+ syncPasteMode();
258
+ writer.resized(isPlain()); showCursor(writer.plain); locate(); session.change(); draw();
150
259
  });
151
260
  session.on("message", message => {
152
261
  if (vendorOwnsTerminal) { heldMessages.push(message); return; }
153
- writer.append(writer.plain ? safe(message.text) : layout.richMessage(message, stdout.columns ?? 80, color,
154
- { stepsShown: message.runId && message.runId === streamed.run ? streamed.steps : 0 }));
155
- plainDraft = ""; draw();
262
+ // Flush the terminal prefix too: unmatched calls close only in the final direct record.
263
+ if (message.kind === "answer" && message.sections?.blocks) commitBlocks(message.runId, message.sections.blocks);
264
+ const shownKeys = new Set(message.runId === streamed.run ? streamed.keys : []);
265
+ if (message.runId === writer.subject) {
266
+ for (const block of message.sections?.blocks ?? []) if (block.kind === "control"
267
+ && writer.controls?.get(block.key) === JSON.stringify(block.payload)) shownKeys.add(block.key);
268
+ }
269
+ const text = writer.plain ? message.kind === "answer" && message.sections
270
+ ? safe(humanRunSections(message.sections, { shownKeys })) : safe(message.text)
271
+ : layout.richMessage(message, stdout.columns ?? 80, theme, { shownKeys });
272
+ print(text, ["user", "answer", "turn-footer"].includes(message.kind));
273
+ plainDraft = "";
156
274
  });
157
275
  session.on("copy", answer => {
158
276
  if (vendorOwnsTerminal) return;
@@ -218,7 +336,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
218
336
  clearTimeout(frameTimer); frameTimer = null; clearInterval(clockTimer); clockTimer = null;
219
337
  stdin.off("data", onData); stdin.setRawMode(false); stdin.pause();
220
338
  process.off("SIGINT", onSignal);
221
- writer.clearLive(); if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
339
+ writer.clearLive(); commitHeader(); showCursor(true); if (pasteMode) stdout.write("\x1b[?2004l");
222
340
  const { VENDORS, executingServer, runVendor, vendorArgv } = await import("./vendors.js");
223
341
  writer.append(`Opening your ${VENDORS[vendor]} terminal with Vecteur attached for this session only. Exit it to return.`);
224
342
  let note;
@@ -228,9 +346,11 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
228
346
  finally {
229
347
  vendorOwnsTerminal = false;
230
348
  process.once("SIGINT", onSignal);
231
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
349
+ if (pasteMode) stdout.write("\x1b[?2004h");
232
350
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData);
233
351
  }
352
+ // The vendor's output is history now; find where it left the cursor before drawing again.
353
+ writer.resized(isPlain()); showCursor(writer.plain); locate();
234
354
  if (resizedDuringHandoff) { resizedDuringHandoff = false; onResize(); }
235
355
  for (const message of heldMessages.splice(0)) session.emit("message", message);
236
356
  session.message(note); session.change();
@@ -248,6 +368,16 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
248
368
  selected = 0; focusChanged(); syncInput(""); if (writer.plain) printPlainPrompt(localPicker); draw();
249
369
  });
250
370
  input.on("complete", () => {
371
+ const mention = /(?:^|\s)@([^\s]*)$/.exec(input.text.slice(0,input.cursor));
372
+ if (mention && !session.prompt) {
373
+ const completionText=input.text, completionCursor=input.cursor;
374
+ void session.completeFiles(mention[1]).then(paths => {
375
+ if(input.text!==completionText || input.cursor!==completionCursor)return;
376
+ if (paths.length === 1) { input.replace(input.cursor-mention[1].length,input.cursor,paths[0]); draw(); }
377
+ else if (paths.length) session.message(paths.map(p=>'@'+p).join('\n'));
378
+ }).catch(error=>session.report(error));
379
+ return;
380
+ }
251
381
  const row = palette()[paletteSelected]; if (row) { syncInput(`/${row.name}${row.argument ? " " : ""}`); draw(); }
252
382
  });
253
383
  const cancel = () => {
@@ -295,36 +425,41 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
295
425
  return false;
296
426
  };
297
427
  input.on("details", () => { if (!session.prompt) void execute("/details"); });
298
- input.on("redraw", () => { writer.clearLive(); draw(); });
428
+ input.on("redraw", () => { writer.clearLive(); locate(); draw(); });
429
+ input.on("report", report => {
430
+ const position = /^\x1b\[(\d+);(\d+)R$/.exec(report);
431
+ if (position) { writer.located(Number(position[1]), Number(position[2])); return; }
432
+ const value = /^\x1b\]1([01]);rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(report);
433
+ if (value) reported[value[1] === "0" ? "fg" : "bg"] = value.slice(2).map(hex => Math.round(parseInt(hex, 16) / (16 ** hex.length - 1) * 255));
434
+ });
299
435
  input.on("exit", () => { try { session.close(); } catch (error) { session.report(error); } });
300
436
  const onData = chunk => {
301
- if (env.TERM === "dumb" && !input.pasting && (String(chunk).match(/[\r\n]/g)?.length ?? 0) > 1) {
302
- input.insert(String(chunk).replace(/\r\n?/g, "\n")); return;
303
- }
304
- input.feed(chunk);
437
+ input.feed(chunk, { unbracketed: !pasteMode });
305
438
  };
306
439
  const onResize = () => {
307
440
  // The vendor owns the TTY: not one byte; the new geometry is applied once on restore.
308
441
  if (vendorOwnsTerminal) { resizedDuringHandoff = true; return; }
309
442
  const plain = isPlain(), changed = plain !== writer.plain;
310
- writer.resized(plain); lastPlainIdentity = "";
311
- if (changed) writer.append(plain ? "Plain view — terminal is small; all actions remain available." : "Rich view restored.");
443
+ writer.resized(plain); lastPlainIdentity = ""; showCursor(plain); locate();
444
+ if (changed) print(plain ? "Plain view — terminal is small; all actions remain available." : "Rich view restored.", false);
312
445
  session.change(); draw();
313
446
  };
314
447
  const onSignal = () => { try { session.close(); } catch {} };
315
448
  const done = new Promise(resolve => session.once("close", resolve));
316
449
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData); stdout.on("resize", onResize);
317
450
  process.once("SIGTERM", onSignal); process.once("SIGHUP", onSignal); process.once("SIGINT", onSignal);
318
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
319
- writer.append(writer.plain ? `Vecteur ${version}${channel === "preview" ? " · Preview" : ""} · ${safe(session.origin)}` : layout.welcome(version, session.origin, stdout.columns ?? 80, color, channel,
320
- session.cwd.startsWith(homedir() + "/") ? "~" + session.cwd.slice(homedir().length) : session.cwd));
451
+ syncPasteMode();
452
+ process.on("exit", restoreCursor);
453
+ if (writer.plain) writer.append(`Vecteur ${version}${channel === "preview" ? " · Preview" : ""} · ${safe(session.origin)}`);
454
+ else { showCursor(false); locate(color ? "\x1b]10;?\x1b\\\x1b]11;?\x1b\\" : ""); }
321
455
  draw();
322
456
  void session.initialize().then(() => { if (!input.text) syncInput(session.draft); draw(); }).catch(error => session.report(error));
323
457
  try { await done; }
324
458
  finally {
325
459
  clearTimeout(frameTimer); clearInterval(clockTimer); input.close(); stdin.off("data", onData); stdout.off("resize", onResize);
326
460
  process.off("SIGTERM", onSignal); process.off("SIGHUP", onSignal); process.off("SIGINT", onSignal);
327
- writer.clearLive(); if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
461
+ writer.clearLive(); writer.close(); commitHeader(); showCursor(true); process.off("exit", restoreCursor);
462
+ if (pasteMode) stdout.write("\x1b[?2004l");
328
463
  stdin.setRawMode(false); stdin.pause();
329
464
  stdout.write(session.restart ? "Restarting Vecteur…\n" : session.run?.open ? "Detached. The cloud Run continues; run vecteur here to follow it.\n" : "Session closed.\n");
330
465
  }