@narumitw/pi-notes 0.0.0

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,582 @@
1
+ import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Editor,
4
+ type EditorTheme,
5
+ Key,
6
+ Markdown,
7
+ matchesKey,
8
+ type TUI,
9
+ truncateToWidth,
10
+ visibleWidth,
11
+ } from "@earendil-works/pi-tui";
12
+ import { runCustomInteraction } from "@narumitw/pi-tui-kit/custom-interaction";
13
+ import { hardWrapTerminalDocument, sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
14
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
15
+ import { createNotesChildSession, type NotesChildSession } from "./child-session.js";
16
+ import { MAX_TRANSCRIPT_CHARS, MAX_TRANSCRIPT_MESSAGES, WIDE_WORKSPACE_COLUMNS } from "./constants.js";
17
+ import type { NoteSnapshot, NotesStorage } from "./storage.js";
18
+
19
+ type CreateChildSession = typeof createNotesChildSession;
20
+ type Pane = "chat" | "preview";
21
+
22
+ export interface NotesWorkspaceDependencies {
23
+ createChildSession?: CreateChildSession;
24
+ }
25
+
26
+ export interface OpenNotesWorkspaceOptions {
27
+ ctx: ExtensionCommandContext;
28
+ agentDir: string;
29
+ storage: NotesStorage;
30
+ notePath: string;
31
+ thinkingLevel: Parameters<CreateChildSession>[0]["thinkingLevel"];
32
+ signal: AbortSignal;
33
+ isCurrent(): boolean;
34
+ dependencies?: NotesWorkspaceDependencies;
35
+ }
36
+
37
+ export async function openNotesWorkspace(options: OpenNotesWorkspaceOptions): Promise<void> {
38
+ const interaction = await runCustomInteraction<"closed">(options.ctx, {
39
+ signal: options.signal,
40
+ isCurrent: options.isCurrent,
41
+ create: ({ tui, theme, keybindings, signal, complete }) =>
42
+ new NotesWorkspace({
43
+ tui,
44
+ theme,
45
+ keybindings,
46
+ signal,
47
+ complete,
48
+ agentDir: options.agentDir,
49
+ storage: options.storage,
50
+ notePath: options.notePath,
51
+ parentModel: options.ctx.model,
52
+ thinkingLevel: options.thinkingLevel,
53
+ createChildSession: options.dependencies?.createChildSession ?? createNotesChildSession,
54
+ }),
55
+ onError: (ctx, error) => safeNotify(ctx, `Pi Notes workspace failed: ${safeErrorMessage(error)}`, "error"),
56
+ });
57
+ if (interaction.kind === "error") throw interaction.error;
58
+ }
59
+
60
+ interface NotesWorkspaceOptions {
61
+ tui: TUI;
62
+ theme: Theme;
63
+ keybindings: KeybindingsManager;
64
+ signal: AbortSignal;
65
+ complete(value: "closed"): void;
66
+ agentDir: string;
67
+ storage: NotesStorage;
68
+ notePath: string;
69
+ parentModel: OpenNotesWorkspaceOptions["ctx"]["model"];
70
+ thinkingLevel: OpenNotesWorkspaceOptions["thinkingLevel"];
71
+ createChildSession: CreateChildSession;
72
+ }
73
+
74
+ export class NotesWorkspace {
75
+ private readonly tui: TUI;
76
+ private readonly theme: Theme;
77
+ private readonly keybindings: KeybindingsManager;
78
+ private readonly options: NotesWorkspaceOptions;
79
+ private readonly editor: Editor;
80
+ private readonly lifetime = new AbortController();
81
+ private readonly pending = new Set<Promise<unknown>>();
82
+ private removeUpstreamAbort = () => {};
83
+ private child: NotesChildSession | undefined;
84
+ private unsubscribe = () => {};
85
+ private note: NoteSnapshot | undefined;
86
+ private status = "Opening embedded note session…";
87
+ private error: string | undefined;
88
+ private pane: Pane = "chat";
89
+ private transcriptScroll = 0;
90
+ private previewScroll = 0;
91
+ private transcriptRows = 1;
92
+ private previewRows = 1;
93
+ private transcriptLineCount = 0;
94
+ private previewLineCount = 0;
95
+ private followTranscript = true;
96
+ private disposed = false;
97
+ private finished = false;
98
+ private generation = 0;
99
+ private promptTask: Promise<unknown> | undefined;
100
+ private promptPreflightPending = false;
101
+ private stopPromise: Promise<void> | undefined;
102
+ private _focused = false;
103
+ private inPaste = false;
104
+
105
+ constructor(options: NotesWorkspaceOptions) {
106
+ this.options = options;
107
+ this.tui = options.tui;
108
+ this.theme = options.theme;
109
+ this.keybindings = options.keybindings;
110
+ const editorTheme: EditorTheme = {
111
+ borderColor: (text) => this.theme.fg("accent", text),
112
+ selectList: {
113
+ selectedPrefix: (text) => this.theme.fg("accent", text),
114
+ selectedText: (text) => this.theme.fg("accent", text),
115
+ description: (text) => this.theme.fg("muted", text),
116
+ scrollInfo: (text) => this.theme.fg("dim", text),
117
+ noMatch: (text) => this.theme.fg("warning", text),
118
+ },
119
+ };
120
+ this.editor = new Editor(this.tui, editorTheme);
121
+ this.editor.disableSubmit = true;
122
+ this.editor.onChange = () => {
123
+ this.error = undefined;
124
+ this.tui.requestRender();
125
+ };
126
+ this.editor.onSubmit = (text) => this.submit(text);
127
+
128
+ const abort = () => this.dispose();
129
+ options.signal.addEventListener("abort", abort, { once: true });
130
+ this.removeUpstreamAbort = () => options.signal.removeEventListener("abort", abort);
131
+ if (options.signal.aborted) abort();
132
+ else this.track(this.start());
133
+ }
134
+
135
+ get focused(): boolean {
136
+ return this._focused;
137
+ }
138
+
139
+ set focused(value: boolean) {
140
+ this._focused = value;
141
+ this.editor.focused = value && this.pane === "chat";
142
+ }
143
+
144
+ render(width: number): string[] {
145
+ const safeWidth = Math.max(1, width);
146
+ const availableRows = Math.max(1, this.tui.terminal.rows - 4);
147
+ const title = truncateToWidth(
148
+ this.theme.fg("accent", this.theme.bold(`Pi Notes · ${sanitizeTerminalText(this.options.notePath)}`)),
149
+ safeWidth,
150
+ );
151
+ const hint = truncateToWidth(this.theme.fg("muted", this.hintText()), safeWidth);
152
+ const bodyRows = Math.max(1, availableRows - 2);
153
+ const body =
154
+ safeWidth >= WIDE_WORKSPACE_COLUMNS
155
+ ? this.renderWide(safeWidth, bodyRows)
156
+ : this.renderNarrow(safeWidth, bodyRows);
157
+ return [title, ...body, hint].slice(0, availableRows).map((line) => truncateToWidth(line, safeWidth));
158
+ }
159
+
160
+ handleInput(data: string): void {
161
+ if (this.disposed || this.finished) return;
162
+ if (this.handlePaste(data)) return;
163
+ if (matchesKey(data, Key.ctrl("c"))) {
164
+ this.close();
165
+ return;
166
+ }
167
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
168
+ this.close();
169
+ return;
170
+ }
171
+ if (this.keybindings.matches(data, "tui.input.tab")) {
172
+ this.pane = this.pane === "chat" ? "preview" : "chat";
173
+ this.editor.focused = this._focused && this.pane === "chat";
174
+ this.tui.requestRender();
175
+ return;
176
+ }
177
+ if (this.keybindings.matches(data, "tui.select.pageUp")) {
178
+ this.scroll(-1);
179
+ return;
180
+ }
181
+ if (this.keybindings.matches(data, "tui.select.pageDown")) {
182
+ this.scroll(1);
183
+ return;
184
+ }
185
+ if (this.pane !== "chat") return;
186
+ this.editor.handleInput(data);
187
+ this.tui.requestRender();
188
+ }
189
+
190
+ invalidate(): void {
191
+ this.editor.invalidate();
192
+ }
193
+
194
+ dispose(): void {
195
+ if (this.disposed) return;
196
+ this.disposed = true;
197
+ this.generation += 1;
198
+ this.removeUpstreamAbort();
199
+ this.removeUpstreamAbort = () => {};
200
+ this.lifetime.abort(new DOMException("Notes workspace disposed", "AbortError"));
201
+ this.unsubscribe();
202
+ this.unsubscribe = () => {};
203
+ this.stopPromise = this.stopChild();
204
+ }
205
+
206
+ async waitForPending(): Promise<void> {
207
+ const pending = [...this.pending];
208
+ // Pi prompt preflight has no cancellation parameter; do not let an uncooperative auth check block teardown.
209
+ if (
210
+ this.promptPreflightPending &&
211
+ this.promptTask &&
212
+ (this.disposed || this.finished || this.options.signal.aborted)
213
+ ) {
214
+ const promptIndex = pending.indexOf(this.promptTask);
215
+ if (promptIndex >= 0) pending.splice(promptIndex, 1);
216
+ }
217
+ await Promise.allSettled(pending);
218
+ await this.stopPromise;
219
+ }
220
+
221
+ private async start(): Promise<void> {
222
+ const generation = this.generation;
223
+ try {
224
+ const note = await this.options.storage.readNote(this.options.notePath, this.signal());
225
+ if (!this.isCurrent(generation)) return;
226
+ this.note = note;
227
+ const child = await this.options.createChildSession({
228
+ agentDir: this.options.agentDir,
229
+ storage: this.options.storage,
230
+ notePath: this.options.notePath,
231
+ parentModel: this.options.parentModel,
232
+ thinkingLevel: this.options.thinkingLevel,
233
+ signal: this.signal(),
234
+ onNoteChanged: (changed) => {
235
+ if (!this.isCurrent(generation)) return;
236
+ this.note = changed;
237
+ this.previewScroll = Math.min(this.previewScroll, this.maxPreviewScroll());
238
+ this.tui.requestRender();
239
+ },
240
+ });
241
+ if (!this.isCurrent(generation)) {
242
+ child.session.dispose();
243
+ return;
244
+ }
245
+ this.child = child;
246
+ this.unsubscribe = child.session.subscribe((event) => {
247
+ if (!this.isCurrent(generation)) return;
248
+ if (event.type === "agent_start") this.status = "Agent is working…";
249
+ else if (event.type === "tool_execution_start")
250
+ this.status = `Running ${sanitizeTerminalText(event.toolName)}…`;
251
+ else if (event.type === "agent_settled") this.status = "Ready";
252
+ this.tui.requestRender();
253
+ });
254
+ this.status = child.resumed ? "Ready · resumed note conversation" : "Ready · new note conversation";
255
+ this.error = child.recoveryWarning ?? child.modelFallbackMessage;
256
+ this.editor.disableSubmit = false;
257
+ this.tui.requestRender();
258
+ } catch (error) {
259
+ if (!this.isCurrent(generation) || isAbortError(error)) return;
260
+ this.status = "Unavailable";
261
+ this.error = safeErrorMessage(error);
262
+ this.editor.disableSubmit = true;
263
+ this.tui.requestRender();
264
+ }
265
+ }
266
+
267
+ private submit(rawText: string): void {
268
+ const text = rawText.trim();
269
+ const session = this.child?.session;
270
+ if (!text || !session || session.isStreaming || this.disposed) {
271
+ if (!text) this.error = "Message cannot be empty";
272
+ this.tui.requestRender();
273
+ return;
274
+ }
275
+ const generation = this.generation;
276
+ this.editor.disableSubmit = true;
277
+ this.status = "Sending…";
278
+ this.error = undefined;
279
+ this.promptPreflightPending = true;
280
+ let task!: Promise<void>;
281
+ task = session
282
+ .prompt(text, {
283
+ expandPromptTemplates: false,
284
+ preflightResult: (accepted) => {
285
+ if (this.promptTask === task) this.promptPreflightPending = false;
286
+ if (!this.isCurrent(generation)) return;
287
+ if (!accepted) {
288
+ const currentDraft = this.editor.getExpandedText();
289
+ this.editor.setText(currentDraft ? `${text}\n\n${currentDraft}` : text);
290
+ this.tui.requestRender();
291
+ return;
292
+ }
293
+ this.status = "Agent is working…";
294
+ this.followTranscript = true;
295
+ this.tui.requestRender();
296
+ },
297
+ })
298
+ .then(async () => {
299
+ if (!this.isCurrent(generation)) return;
300
+ const note = await this.options.storage.readNote(this.options.notePath, this.signal());
301
+ if (!this.isCurrent(generation)) return;
302
+ this.note = note;
303
+ this.status = "Ready";
304
+ })
305
+ .catch((error: unknown) => {
306
+ if (!this.isCurrent(generation) || isAbortError(error)) return;
307
+ this.status = "Ready";
308
+ this.error = safeErrorMessage(error);
309
+ })
310
+ .finally(() => {
311
+ if (this.promptTask === task) {
312
+ this.promptTask = undefined;
313
+ this.promptPreflightPending = false;
314
+ }
315
+ if (!this.isCurrent(generation)) return;
316
+ this.editor.disableSubmit = false;
317
+ this.tui.requestRender();
318
+ });
319
+ this.promptTask = task;
320
+ this.track(task);
321
+ this.tui.requestRender();
322
+ }
323
+
324
+ private renderWide(width: number, rows: number): string[] {
325
+ const separator = " │ ";
326
+ const leftWidth = Math.max(1, Math.floor((width - visibleWidth(separator)) * 0.52));
327
+ const rightWidth = Math.max(1, width - leftWidth - visibleWidth(separator));
328
+ const left = this.renderChat(leftWidth, rows);
329
+ const right = this.renderPreview(rightWidth, rows);
330
+ const lines: string[] = [];
331
+ for (let index = 0; index < rows; index += 1) {
332
+ lines.push(
333
+ `${padLine(left[index] ?? "", leftWidth)}${this.theme.fg("borderMuted", separator)}${padLine(right[index] ?? "", rightWidth)}`,
334
+ );
335
+ }
336
+ return lines;
337
+ }
338
+
339
+ private renderNarrow(width: number, rows: number): string[] {
340
+ return this.pane === "chat" ? this.renderChat(width, rows) : this.renderPreview(width, rows);
341
+ }
342
+
343
+ private renderChat(width: number, rows: number): string[] {
344
+ const editorLines = this.editor.render(width);
345
+ const header = truncateToWidth(
346
+ this.theme.fg(this.pane === "chat" ? "accent" : "muted", `Chat · ${this.status}`),
347
+ width,
348
+ );
349
+ const errorLines = this.error
350
+ ? hardWrapTerminalDocument(`Error: ${this.error}`, Math.max(1, width)).map((line) =>
351
+ this.theme.fg("warning", line),
352
+ )
353
+ : [];
354
+ const viewportRows = Math.max(0, rows - editorLines.length - errorLines.length - 1);
355
+ const transcript = this.renderTranscript(width);
356
+ this.transcriptLineCount = transcript.length;
357
+ this.transcriptRows = Math.max(1, viewportRows);
358
+ if (this.followTranscript) this.transcriptScroll = this.maxTranscriptScroll();
359
+ this.transcriptScroll = clamp(this.transcriptScroll, 0, this.maxTranscriptScroll());
360
+ const visible = transcript.slice(this.transcriptScroll, this.transcriptScroll + viewportRows);
361
+ return [header, ...visible, ...errorLines, ...editorLines].slice(-rows);
362
+ }
363
+
364
+ private renderPreview(width: number, rows: number): string[] {
365
+ const header = truncateToWidth(
366
+ this.theme.fg(this.pane === "preview" ? "accent" : "muted", `Preview · ${this.note?.size ?? 0} bytes`),
367
+ width,
368
+ );
369
+ const bodyRows = Math.max(0, rows - 1);
370
+ const markdown = this.note?.content
371
+ ? new Markdown(sanitizeTerminalDocument(this.note.content), 0, 0, markdownTheme(this.theme))
372
+ : undefined;
373
+ const content = markdown?.render(width) ?? [this.theme.fg("muted", "(Empty note)")];
374
+ this.previewLineCount = content.length;
375
+ this.previewRows = Math.max(1, bodyRows);
376
+ this.previewScroll = clamp(this.previewScroll, 0, this.maxPreviewScroll());
377
+ return [header, ...content.slice(this.previewScroll, this.previewScroll + bodyRows)];
378
+ }
379
+
380
+ private renderTranscript(width: number): string[] {
381
+ const session = this.child?.session;
382
+ if (!session) return [this.theme.fg("muted", "Preparing the embedded agent…")];
383
+ const messages = [...session.messages];
384
+ const streaming = session.state.streamingMessage;
385
+ if (streaming && messages.at(-1) !== streaming) messages.push(streaming);
386
+ const selected = messages.slice(-MAX_TRANSCRIPT_MESSAGES);
387
+ const sections: Array<{ role: string; text: string }> = [];
388
+ let remainingCharacters = MAX_TRANSCRIPT_CHARS;
389
+ for (let index = selected.length - 1; index >= 0 && remainingCharacters > 0; index -= 1) {
390
+ const message = selected[index] as unknown;
391
+ const section = transcriptSection(message);
392
+ if (!section) continue;
393
+ if (section.text.length > remainingCharacters) {
394
+ const marker = "[Earlier content omitted]\n".slice(0, remainingCharacters);
395
+ const available = remainingCharacters - marker.length;
396
+ sections.unshift({
397
+ ...section,
398
+ text: `${marker}${available > 0 ? section.text.slice(-available) : ""}`,
399
+ });
400
+ remainingCharacters = 0;
401
+ break;
402
+ }
403
+ sections.unshift(section);
404
+ remainingCharacters -= section.text.length;
405
+ }
406
+ if (sections.length === 0) return [this.theme.fg("muted", "Ask the agent to work on this note.")];
407
+ const lines: string[] = [];
408
+ for (const section of sections) {
409
+ lines.push(this.theme.fg("accent", this.theme.bold(section.role)));
410
+ for (const line of hardWrapTerminalDocument(section.text, Math.max(1, width - 2))) {
411
+ lines.push(truncateToWidth(` ${line}`, width));
412
+ }
413
+ }
414
+ return lines;
415
+ }
416
+
417
+ private scroll(direction: -1 | 1): void {
418
+ if (this.pane === "preview") {
419
+ this.previewScroll = clamp(
420
+ this.previewScroll + direction * Math.max(1, this.previewRows - 1),
421
+ 0,
422
+ this.maxPreviewScroll(),
423
+ );
424
+ } else {
425
+ this.transcriptScroll = clamp(
426
+ this.transcriptScroll + direction * Math.max(1, this.transcriptRows - 1),
427
+ 0,
428
+ this.maxTranscriptScroll(),
429
+ );
430
+ this.followTranscript = this.transcriptScroll === this.maxTranscriptScroll();
431
+ }
432
+ this.tui.requestRender();
433
+ }
434
+
435
+ private maxTranscriptScroll(): number {
436
+ return Math.max(0, this.transcriptLineCount - this.transcriptRows);
437
+ }
438
+
439
+ private maxPreviewScroll(): number {
440
+ return Math.max(0, this.previewLineCount - this.previewRows);
441
+ }
442
+
443
+ private hintText(): string {
444
+ return "Submit sends · Switch-pane action changes Chat/Preview · Page actions scroll · Cancel closes · Ctrl+C hard-cancels";
445
+ }
446
+
447
+ private handlePaste(data: string): boolean {
448
+ const start = data.includes("\u001b[200~");
449
+ const wasPasting = this.inPaste;
450
+ if (start) this.inPaste = true;
451
+ if (!start && !wasPasting) return false;
452
+ this.pane = "chat";
453
+ this.editor.focused = this._focused;
454
+ this.editor.handleInput(data);
455
+ if (data.includes("\u001b[201~")) this.inPaste = false;
456
+ this.tui.requestRender();
457
+ return true;
458
+ }
459
+
460
+ private close(): void {
461
+ if (this.finished) return;
462
+ this.finished = true;
463
+ this.generation += 1;
464
+ this.lifetime.abort(new DOMException("Notes workspace closed", "AbortError"));
465
+ this.unsubscribe();
466
+ this.unsubscribe = () => {};
467
+ void this.stopChild();
468
+ this.options.complete("closed");
469
+ }
470
+
471
+ private async stopChild(): Promise<void> {
472
+ if (this.stopPromise) return this.stopPromise;
473
+ const session = this.child?.session;
474
+ this.child = undefined;
475
+ this.stopPromise = (async () => {
476
+ if (!session) return;
477
+ try {
478
+ await session.abort();
479
+ } finally {
480
+ session.dispose();
481
+ }
482
+ })();
483
+ return this.stopPromise;
484
+ }
485
+
486
+ private signal(): AbortSignal {
487
+ return this.options.signal.aborted
488
+ ? this.options.signal
489
+ : AbortSignal.any([this.options.signal, this.lifetime.signal]);
490
+ }
491
+
492
+ private isCurrent(generation: number): boolean {
493
+ return !this.disposed && !this.finished && !this.options.signal.aborted && generation === this.generation;
494
+ }
495
+
496
+ private track<T>(promise: Promise<T>): Promise<T> {
497
+ this.pending.add(promise);
498
+ void promise.then(
499
+ () => this.pending.delete(promise),
500
+ () => this.pending.delete(promise),
501
+ );
502
+ return promise;
503
+ }
504
+ }
505
+
506
+ function transcriptSection(message: unknown): { role: string; text: string } | undefined {
507
+ if (!message || typeof message !== "object") return undefined;
508
+ const record = message as { role?: unknown; content?: unknown };
509
+ const role =
510
+ record.role === "user"
511
+ ? "You"
512
+ : record.role === "assistant"
513
+ ? "Agent"
514
+ : record.role === "toolResult"
515
+ ? "Tool"
516
+ : undefined;
517
+ if (!role) return undefined;
518
+ const text = messageText(record.content);
519
+ return text ? { role, text } : undefined;
520
+ }
521
+
522
+ function messageText(content: unknown): string {
523
+ if (typeof content === "string") return sanitizeTerminalDocument(content);
524
+ if (!Array.isArray(content)) return "";
525
+ const parts: string[] = [];
526
+ for (const value of content) {
527
+ if (!value || typeof value !== "object") continue;
528
+ const block = value as { type?: unknown; text?: unknown; name?: unknown; arguments?: unknown; content?: unknown };
529
+ if ((block.type === "text" || block.type === "thinking") && typeof block.text === "string") {
530
+ parts.push(block.text);
531
+ } else if (block.type === "toolCall" && typeof block.name === "string") {
532
+ parts.push(`Tool call: ${block.name}`);
533
+ } else if (block.type === "toolResult") {
534
+ parts.push(typeof block.name === "string" ? `Tool result: ${block.name}` : "Tool result");
535
+ }
536
+ }
537
+ return sanitizeTerminalDocument(parts.join("\n"));
538
+ }
539
+
540
+ function markdownTheme(theme: Theme) {
541
+ return {
542
+ heading: (text: string) => theme.fg("mdHeading", theme.bold(text)),
543
+ link: (text: string) => theme.fg("mdLink", text),
544
+ linkUrl: (text: string) => theme.fg("mdLinkUrl", text),
545
+ code: (text: string) => theme.fg("mdCode", text),
546
+ codeBlock: (text: string) => theme.fg("mdCodeBlock", text),
547
+ codeBlockBorder: (text: string) => theme.fg("mdCodeBlockBorder", text),
548
+ quote: (text: string) => theme.fg("mdQuote", text),
549
+ quoteBorder: (text: string) => theme.fg("mdQuoteBorder", text),
550
+ hr: (text: string) => theme.fg("mdHr", text),
551
+ listBullet: (text: string) => theme.fg("mdListBullet", text),
552
+ bold: (text: string) => theme.bold(text),
553
+ italic: (text: string) => theme.italic(text),
554
+ strikethrough: (text: string) => theme.strikethrough(text),
555
+ underline: (text: string) => theme.underline(text),
556
+ };
557
+ }
558
+
559
+ function padLine(line: string, width: number): string {
560
+ const truncated = truncateToWidth(line, width);
561
+ return `${truncated}${" ".repeat(Math.max(0, width - visibleWidth(truncated)))}`;
562
+ }
563
+
564
+ function clamp(value: number, minimum: number, maximum: number): number {
565
+ return Math.max(minimum, Math.min(value, maximum));
566
+ }
567
+
568
+ function safeErrorMessage(error: unknown): string {
569
+ return sanitizeTerminalText(error instanceof Error ? error.message : String(error)).slice(0, 500);
570
+ }
571
+
572
+ function isAbortError(error: unknown): boolean {
573
+ return error instanceof Error && (error.name === "AbortError" || /aborted|disposed/iu.test(error.message));
574
+ }
575
+
576
+ function safeNotify(ctx: ExtensionCommandContext, message: string, level: "info" | "warning" | "error"): void {
577
+ try {
578
+ ctx.ui.notify(sanitizeTerminalText(message), level);
579
+ } catch {
580
+ // Session replacement can invalidate the parent UI during workspace cleanup.
581
+ }
582
+ }