@narumitw/pi-starship 0.63.0 → 0.64.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.
@@ -5,11 +5,11 @@ import {
5
5
  commitActiveDocument,
6
6
  commitOwnerCurrent,
7
7
  saveAsProfile
8
- } from "./chunk-63R6R5DH.ts";
8
+ } from "./chunk-DIHVBO5Z.ts";
9
9
  import {
10
10
  assertProfileUnchanged,
11
11
  configurationPresentation
12
- } from "./chunk-Y24TJYG6.ts";
12
+ } from "./chunk-UIKPE4UC.ts";
13
13
  import {
14
14
  BUILT_IN_EXAMPLE,
15
15
  MODULE_DEFINITIONS,
@@ -21,7 +21,7 @@ import "./chunk-KP33I6BR.ts";
21
21
  // src/command-settings-chat.ts
22
22
  import { withFileMutationQueue as withFileMutationQueue2 } from "@earendil-works/pi-coding-agent";
23
23
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
24
- import { sanitizeTerminalDocument as sanitizeTerminalDocument3 } from "@narumitw/pi-tui-kit/terminal-document";
24
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument5 } from "@narumitw/pi-tui-kit/terminal-document";
25
25
 
26
26
  // src/settings-agent.ts
27
27
  import { randomUUID } from "node:crypto";
@@ -98,45 +98,424 @@ import {
98
98
  } from "@earendil-works/pi-coding-agent";
99
99
  import {
100
100
  CURSOR_MARKER,
101
- decodeKittyPrintable,
102
101
  Editor,
103
102
  getKeybindings,
104
- isKeyRelease,
103
+ isKeyRelease as isKeyRelease2,
105
104
  Key,
106
- matchesKey,
105
+ matchesKey as matchesKey2,
107
106
  parseKey,
108
107
  TUI_KEYBINDINGS,
109
- truncateToWidth
108
+ truncateToWidth,
109
+ VStack
110
110
  } from "@earendil-works/pi-tui";
111
- import { HorizontalRule, renderBoundedFrame, runCustomInteraction } from "@narumitw/pi-tui-kit";
112
- import { sanitizeTerminalDocument as sanitizeTerminalDocument2 } from "@narumitw/pi-tui-kit/terminal-document";
111
+ import { HorizontalRule, renderBoundedFrame } from "@narumitw/pi-tui-kit";
112
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument4 } from "@narumitw/pi-tui-kit/terminal-document";
113
113
 
114
- // src/settings-chat-transcript.ts
114
+ // src/settings-chat-fullscreen.ts
115
115
  import {
116
- AssistantMessageComponent,
117
- createEditToolDefinition,
118
- createReadToolDefinition,
119
- createWriteToolDefinition,
120
- ToolExecutionComponent,
121
- UserMessageComponent
122
- } from "@earendil-works/pi-coding-agent";
116
+ isKeyRelease,
117
+ matchesKey,
118
+ TuiAltScreen
119
+ } from "@earendil-works/pi-tui";
120
+ var SettingsChatTui = class extends TuiAltScreen {
121
+ addInputListener(listener) {
122
+ if (!this.guardInstalled) {
123
+ this.guardInstalled = true;
124
+ super.addInputListener((data) => this.guard?.(data));
125
+ }
126
+ return super.addInputListener(listener);
127
+ }
128
+ };
129
+ async function runSettingsChatFullscreen(ctx, owner, create, cancelledValue, dependencies = {}) {
130
+ const current = () => !owner.signal.aborted && !ctx.signal?.aborted && owner.isCurrent();
131
+ const canRestoreTerminal = () => (owner.canRestoreTerminal ?? owner.isSessionCurrent ?? owner.isCurrent)();
132
+ if (ctx.mode !== "tui" || !current()) return cancelledValue;
133
+ let mount;
134
+ let releaseHost;
135
+ let completedOutcome;
136
+ const outcome = await ctx.ui.custom(
137
+ (parent, theme, keybindings, done) => {
138
+ const controller = new AbortController();
139
+ let child;
140
+ let component;
141
+ let overlay;
142
+ let parentStopped = false;
143
+ let entry;
144
+ let entryDrainStarted = false;
145
+ let finished = false;
146
+ let closing = false;
147
+ let cleanup;
148
+ let pasting = false;
149
+ let result = { value: cancelledValue };
150
+ const errors = [];
151
+ const removers = [];
152
+ const attempt = (action) => {
153
+ try {
154
+ action();
155
+ } catch (error) {
156
+ errors.push(error);
157
+ }
158
+ };
159
+ const finish = (next) => {
160
+ if (closing) return cleanup;
161
+ closing = true;
162
+ result = next;
163
+ controller.abort();
164
+ cleanup = Promise.resolve().then(async () => {
165
+ await entry;
166
+ if (parentStopped) {
167
+ try {
168
+ await parent.terminal.drainInput?.();
169
+ } catch (error) {
170
+ errors.push(error);
171
+ }
172
+ }
173
+ if (entryDrainStarted && !parentStopped) {
174
+ parentStopped = true;
175
+ attempt(() => parent.stop({ preserveScreen: true }));
176
+ }
177
+ for (const remove of removers.splice(0)) attempt(remove);
178
+ attempt(() => component?.dispose?.());
179
+ if (child) attempt(() => child?.stop({ preserveScreen: true }));
180
+ if (parentStopped) {
181
+ attempt(() => overlay?.setHidden(true));
182
+ attempt(() => {
183
+ if (canRestoreTerminal()) {
184
+ attempt(() => parent.start());
185
+ attempt(() => parent.renderNow(false));
186
+ }
187
+ });
188
+ }
189
+ try {
190
+ await component?.waitForPending?.();
191
+ } catch (error) {
192
+ errors.push(error);
193
+ }
194
+ attempt(() => {
195
+ if (!current() && !("error" in result)) result = { value: cancelledValue };
196
+ });
197
+ finished = true;
198
+ if ("error" in result) errors.unshift(result.error);
199
+ completedOutcome = errors.length ? { error: errors.length === 1 ? errors[0] : new AggregateError(errors, "Fullscreen cleanup failed") } : result;
200
+ done(completedOutcome);
201
+ });
202
+ return cleanup;
203
+ };
204
+ releaseHost = () => finish({ value: cancelledValue }) ?? Promise.resolve();
205
+ const cancel = () => finish({ value: cancelledValue });
206
+ const guard = (data) => {
207
+ if (closing) return { consume: true };
208
+ if (!current()) {
209
+ cancel();
210
+ return { consume: true };
211
+ }
212
+ const wasPasting = pasting;
213
+ for (const part of data.split("\x1B").slice(1)) {
214
+ if (part.startsWith("[200~")) pasting = true;
215
+ else if (part.startsWith("[201~")) pasting = false;
216
+ }
217
+ if (wasPasting || pasting || data.includes("\x1B[200~") || data.includes("\x1B[201~")) {
218
+ try {
219
+ child?.getFocusedComponent()?.handleInput?.(data);
220
+ child?.requestRender();
221
+ } catch (error) {
222
+ finish({ error });
223
+ }
224
+ return { consume: true };
225
+ }
226
+ if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) {
227
+ cancel();
228
+ return { consume: true };
229
+ }
230
+ };
231
+ for (const signal of /* @__PURE__ */ new Set([owner.signal, ctx.signal])) {
232
+ if (!signal) continue;
233
+ signal.addEventListener("abort", cancel, { once: true });
234
+ removers.push(() => signal.removeEventListener("abort", cancel));
235
+ }
236
+ const host = {
237
+ render: () => [],
238
+ invalidate() {
239
+ },
240
+ dispose() {
241
+ if (!finished) cancel();
242
+ }
243
+ };
244
+ mount = (handle) => {
245
+ overlay = handle;
246
+ queueMicrotask(() => {
247
+ if (closing) return;
248
+ entry = (async () => {
249
+ try {
250
+ if (!current()) {
251
+ cancel();
252
+ return;
253
+ }
254
+ entryDrainStarted = parent.terminal.drainInput !== void 0;
255
+ await parent.terminal.drainInput?.();
256
+ if (closing) return;
257
+ if (!current()) {
258
+ cancel();
259
+ return;
260
+ }
261
+ parentStopped = true;
262
+ parent.stop({ preserveScreen: true });
263
+ if (closing) return;
264
+ const createDefault = () => new SettingsChatTui(parent.terminal, parent.getShowHardwareCursor(), void 0, { mouse: true });
265
+ child = dependencies.createTui?.(parent, createDefault) ?? createDefault();
266
+ if (child instanceof SettingsChatTui) child.guard = guard;
267
+ else removers.push(child.addInputListener(guard));
268
+ component = create({
269
+ tui: child,
270
+ theme,
271
+ keybindings,
272
+ signal: controller.signal,
273
+ complete: (value) => finish({ value })
274
+ });
275
+ if (closing) return;
276
+ if (!current()) {
277
+ cancel();
278
+ return;
279
+ }
280
+ child.setLayoutRoot(component.getFullscreenLayout?.() ?? component);
281
+ child.setFocus(component);
282
+ child.start();
283
+ } catch (error) {
284
+ if (closing) errors.push(error);
285
+ else finish({ error });
286
+ }
287
+ })();
288
+ });
289
+ };
290
+ if (!current()) cancel();
291
+ return host;
292
+ },
293
+ { overlay: true, onHandle: (handle) => mount?.(handle) }
294
+ ).catch(async (error) => {
295
+ await releaseHost?.();
296
+ if (completedOutcome && "error" in completedOutcome) {
297
+ throw new AggregateError([error, completedOutcome.error], "Fullscreen mount and cleanup failed");
298
+ }
299
+ throw error;
300
+ });
301
+ await releaseHost?.();
302
+ const completion = completedOutcome ?? outcome;
303
+ if (!completion) return cancelledValue;
304
+ if ("error" in completion) throw completion.error;
305
+ return completion.value;
306
+ }
307
+
308
+ // src/settings-chat-scroll.ts
309
+ import { ScrollView } from "@earendil-works/pi-tui";
310
+ var SettingsChatScrollView = class extends ScrollView {
311
+ anchor;
312
+ restoreAnchor;
313
+ updateLayout(contentHeight, viewportHeight, requestRender) {
314
+ const manual = !this.isFollowingEnd;
315
+ const target = manual && this.anchor ? this.restoreAnchor?.(this.anchor) : void 0;
316
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
317
+ if (manual) this.scrollTo(target ?? this.scrollTop, { disableFollow: true });
318
+ }
319
+ };
320
+
321
+ // src/settings-chat-transcript.ts
322
+ import { stripVTControlCharacters } from "node:util";
323
+ import { AssistantMessageComponent, UserMessageComponent } from "@earendil-works/pi-coding-agent";
324
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument3 } from "@narumitw/pi-tui-kit/terminal-document";
325
+
326
+ // src/settings-chat-display.ts
123
327
  import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
124
- function displayValue(value) {
328
+ function settingsChatDisplayValue(value) {
125
329
  if (typeof value === "string") return sanitizeTerminalDocument(value);
126
- if (Array.isArray(value)) return value.map(displayValue);
330
+ if (Array.isArray(value)) return value.map(settingsChatDisplayValue);
127
331
  if (value && typeof value === "object") {
128
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, displayValue(item)]));
332
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, settingsChatDisplayValue(item)]));
129
333
  }
130
334
  return value;
131
335
  }
132
- function createSettingsChatTranscript(agent, tui, cwd) {
133
- const messages = /* @__PURE__ */ new Map();
134
- const tools = /* @__PURE__ */ new Map();
336
+
337
+ // src/settings-chat-tools.ts
338
+ import { resolve } from "node:path";
339
+ import {
340
+ createEditToolDefinition,
341
+ createReadToolDefinition,
342
+ createWriteToolDefinition,
343
+ ToolExecutionComponent
344
+ } from "@earendil-works/pi-coding-agent";
345
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument2 } from "@narumitw/pi-tui-kit/terminal-document";
346
+ function createSettingsChatTools(tui, cwd, initialExpanded, editablePath) {
347
+ const rows = /* @__PURE__ */ new Map();
348
+ const pending = /* @__PURE__ */ new Set();
349
+ const edit = createEditToolDefinition(cwd);
350
+ const renderEditCall = edit.renderCall;
351
+ if (renderEditCall) {
352
+ edit.renderCall = (args, theme, context) => {
353
+ const path = typeof args?.path === "string" ? args.path : args && "file_path" in args ? args.file_path : void 0;
354
+ const allowed = editablePath !== void 0 && typeof path === "string" && resolve(cwd, path) === resolve(editablePath);
355
+ return renderEditCall(args, theme, { ...context, argsComplete: context.argsComplete && allowed });
356
+ };
357
+ }
135
358
  const definitions = {
136
359
  read: createReadToolDefinition(cwd),
137
360
  write: createWriteToolDefinition(cwd),
138
- edit: createEditToolDefinition(cwd)
361
+ edit
362
+ };
363
+ let disposed = false;
364
+ let expanded = initialExpanded;
365
+ const ensure = (id, name, args) => {
366
+ let row = rows.get(id);
367
+ if (!row) {
368
+ row = { name, args, complete: false, started: false, partial: true };
369
+ rows.set(id, row);
370
+ }
371
+ if (!row.component) {
372
+ const toolName = row.name;
373
+ const definition = toolName === "read" || toolName === "write" || toolName === "edit" ? definitions[toolName] : void 0;
374
+ const ownedRow = row;
375
+ const toolUi = new Proxy(tui, {
376
+ get(target, property) {
377
+ if (property === "requestRender")
378
+ return () => {
379
+ if (!disposed && rows.get(id) === ownedRow && ownedRow.component === component) target.requestRender();
380
+ };
381
+ const value = Reflect.get(target, property, target);
382
+ return typeof value === "function" ? value.bind(target) : value;
383
+ }
384
+ });
385
+ const Component = class extends ToolExecutionComponent {
386
+ setExpanded(value) {
387
+ ownedRow.expanded = value;
388
+ super.setExpanded(value);
389
+ }
390
+ };
391
+ const component = new Component(
392
+ sanitizeTerminalDocument2(toolName),
393
+ sanitizeTerminalDocument2(id),
394
+ settingsChatDisplayValue(row.args),
395
+ { showImages: false, outputPad: 1 },
396
+ definition,
397
+ toolUi,
398
+ sanitizeTerminalDocument2(cwd)
399
+ );
400
+ row.component = component;
401
+ component.setExpanded(row.expanded ?? expanded);
402
+ if (row.complete && (!row.result || row.partial)) component.setArgsComplete();
403
+ if (row.started) component.markExecutionStarted();
404
+ if (row.result) component.updateResult(settingsChatDisplayValue(row.result), row.partial);
405
+ }
406
+ return row;
407
+ };
408
+ const updateArgs = (call) => {
409
+ const row = ensure(call.id, call.name, call.arguments);
410
+ row.args = call.arguments;
411
+ row.component?.updateArgs(settingsChatDisplayValue(call.arguments));
412
+ return row;
413
+ };
414
+ const completeArgs = (row) => {
415
+ if (row.complete) return;
416
+ row.complete = true;
417
+ row.component?.setArgsComplete();
418
+ };
419
+ const result = (row, value, partial = false) => {
420
+ row.result = value;
421
+ row.partial = partial;
422
+ row.component?.updateResult(settingsChatDisplayValue(value), partial);
423
+ };
424
+ const failure = (message) => ({
425
+ content: [
426
+ { type: "text", text: message.stopReason === "aborted" ? "Operation aborted" : message.errorMessage || "Error" }
427
+ ],
428
+ isError: true
429
+ });
430
+ return {
431
+ onEvent(event) {
432
+ if (disposed) return;
433
+ if (event.type === "message_update" && event.message.role === "assistant") {
434
+ for (const call of event.message.content) {
435
+ if (call.type !== "toolCall") continue;
436
+ updateArgs(call);
437
+ pending.add(call.id);
438
+ }
439
+ }
440
+ if (event.type === "message_end" && event.message.role === "assistant") {
441
+ const failed = event.message.stopReason === "aborted" || event.message.stopReason === "error";
442
+ for (const call of event.message.content) {
443
+ if (call.type !== "toolCall") continue;
444
+ updateArgs(call);
445
+ pending.add(call.id);
446
+ }
447
+ for (const id of pending) {
448
+ const row = rows.get(id);
449
+ if (!row) continue;
450
+ if (failed) result(row, failure(event.message));
451
+ else completeArgs(row);
452
+ }
453
+ if (failed) pending.clear();
454
+ }
455
+ if (event.type === "tool_execution_start" && !("parentToolCallId" in event && event.parentToolCallId)) {
456
+ const row = ensure(event.toolCallId, event.toolName, event.args);
457
+ pending.add(event.toolCallId);
458
+ row.started = true;
459
+ row.component?.markExecutionStarted();
460
+ }
461
+ if (event.type === "tool_execution_update") {
462
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : void 0;
463
+ if (row) result(row, { ...event.partialResult, isError: false }, true);
464
+ }
465
+ if (event.type === "tool_execution_end") {
466
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : void 0;
467
+ if (row) result(row, { ...event.result, isError: event.isError, durationMs: event.durationMs });
468
+ pending.delete(event.toolCallId);
469
+ }
470
+ if (event.type === "agent_end") pending.clear();
471
+ },
472
+ render(call, message, historyResult, width) {
473
+ const row = ensure(call.id, call.name, call.arguments);
474
+ if (historyResult && row.historyResult !== historyResult) {
475
+ row.historyResult = historyResult;
476
+ result(row, historyResult);
477
+ }
478
+ if (!historyResult && !row.result && (message.stopReason === "aborted" || message.stopReason === "error"))
479
+ result(row, failure(message));
480
+ return row.component?.render(width) ?? [];
481
+ },
482
+ handleMouse(id, event) {
483
+ if (disposed) return void 0;
484
+ return rows.get(id)?.component?.handleMouse(event);
485
+ },
486
+ retain(ids) {
487
+ for (const id of rows.keys())
488
+ if (!ids.has(id)) {
489
+ rows.delete(id);
490
+ pending.delete(id);
491
+ }
492
+ },
493
+ toggle() {
494
+ if (!disposed) {
495
+ expanded = !expanded;
496
+ for (const row of rows.values()) {
497
+ row.expanded = expanded;
498
+ row.component?.setExpanded(expanded);
499
+ }
500
+ tui.requestRender();
501
+ }
502
+ return expanded;
503
+ },
504
+ invalidate() {
505
+ for (const row of rows.values()) row.component = void 0;
506
+ },
507
+ dispose() {
508
+ disposed = true;
509
+ pending.clear();
510
+ rows.clear();
511
+ }
139
512
  };
513
+ }
514
+
515
+ // src/settings-chat-transcript.ts
516
+ function createSettingsChatTranscript(agent, tui, cwd, initialExpanded = false, editablePath) {
517
+ const messages = /* @__PURE__ */ new Map();
518
+ const tools = createSettingsChatTools(tui, cwd, initialExpanded, editablePath);
140
519
  const identities = /* @__PURE__ */ new WeakMap();
141
520
  let streamingIdentity;
142
521
  const initial = agent.state.streamingMessage;
@@ -145,6 +524,8 @@ function createSettingsChatTranscript(agent, tui, cwd) {
145
524
  identities.set(initial, streamingIdentity);
146
525
  }
147
526
  const unsubscribe = agent.subscribe((event) => {
527
+ if (disposed) return;
528
+ tools.onEvent(event);
148
529
  if (event.type === "agent_end") streamingIdentity = void 0;
149
530
  if ((event.type === "message_start" || event.type === "message_update" || event.type === "message_end") && event.message.role === "assistant") {
150
531
  if (event.type === "message_start") streamingIdentity = /* @__PURE__ */ Symbol();
@@ -154,12 +535,14 @@ function createSettingsChatTranscript(agent, tui, cwd) {
154
535
  }
155
536
  });
156
537
  let spans = [];
538
+ let toolSpans = [];
539
+ let renderedWidth = 0;
157
540
  let streaming;
158
541
  let disposed = false;
159
- let expanded = true;
160
542
  return {
161
543
  render(width) {
162
544
  spans = [];
545
+ toolSpans = [];
163
546
  if (disposed || width <= 0) return [];
164
547
  const results = new Map(
165
548
  agent.state.messages.flatMap(
@@ -170,40 +553,27 @@ function createSettingsChatTranscript(agent, tui, cwd) {
170
553
  const activeMessages = /* @__PURE__ */ new Set();
171
554
  const activeTools = /* @__PURE__ */ new Set();
172
555
  const lines = [];
556
+ renderedWidth = width;
557
+ const recordSpan = (message, start) => {
558
+ let offset = 0;
559
+ let text = "";
560
+ const offsets = lines.slice(start).map((line) => {
561
+ const before = offset;
562
+ const content = stripVTControlCharacters(line).replace(/\s/gu, "");
563
+ text += content;
564
+ offset += content.length;
565
+ return before;
566
+ });
567
+ spans.push({ message, start, end: lines.length, offsets, text });
568
+ };
173
569
  const appendAssistant = (message, component) => {
174
570
  lines.push(...component.render(width));
175
571
  for (const call of message.content) {
176
572
  if (call.type !== "toolCall") continue;
177
573
  activeTools.add(call.id);
178
- let tool = tools.get(call.id);
179
- if (!tool) {
180
- const definition = call.name === "read" || call.name === "write" || call.name === "edit" ? definitions[call.name] : void 0;
181
- const component2 = new ToolExecutionComponent(
182
- sanitizeTerminalDocument(call.name),
183
- sanitizeTerminalDocument(call.id),
184
- displayValue(call.arguments),
185
- { showImages: false, outputPad: 1 },
186
- definition,
187
- tui,
188
- sanitizeTerminalDocument(cwd)
189
- );
190
- component2.setExpanded(expanded);
191
- component2.setArgsComplete();
192
- component2.markExecutionStarted();
193
- tool = { component: component2 };
194
- tools.set(call.id, tool);
195
- }
196
- const result = results.get(call.id);
197
- if (result && tool.result !== result) {
198
- tool.component.updateResult({
199
- content: displayValue(result.content),
200
- details: displayValue(result.details),
201
- isError: result.isError,
202
- durationMs: result.durationMs
203
- });
204
- tool.result = result;
205
- }
206
- lines.push(...tool.component.render(width));
574
+ const start = lines.length;
575
+ lines.push(...tools.render(call, message, results.get(call.id), width));
576
+ toolSpans.push({ id: call.id, start, end: lines.length });
207
577
  }
208
578
  };
209
579
  for (const message of visible) {
@@ -215,49 +585,80 @@ function createSettingsChatTranscript(agent, tui, cwd) {
215
585
  start = lines.length;
216
586
  if (!component) {
217
587
  const text = typeof message.content === "string" ? message.content : message.content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
218
- component = new UserMessageComponent(sanitizeTerminalDocument(text));
588
+ component = new UserMessageComponent(sanitizeTerminalDocument3(text));
219
589
  messages.set(message, component);
220
590
  }
221
591
  lines.push(...component.render(width));
222
592
  } else if (message.role === "assistant") {
223
593
  if (!component) {
224
- component = new AssistantMessageComponent(displayValue(message), true);
594
+ component = new AssistantMessageComponent(settingsChatDisplayValue(message), true);
225
595
  messages.set(message, component);
226
596
  }
227
597
  appendAssistant(message, component);
228
598
  }
229
- spans.push({ message: identities.get(message) ?? message, start, end: lines.length });
599
+ recordSpan(identities.get(message) ?? message, start);
230
600
  }
231
601
  const partial = agent.state.streamingMessage;
232
602
  if (partial?.role === "assistant") {
233
603
  streaming ??= new AssistantMessageComponent(void 0, true);
234
- streaming.updateContent(displayValue(partial), true);
604
+ streaming.updateContent(settingsChatDisplayValue(partial), true);
235
605
  const start = lines.length;
236
- lines.push(...streaming.render(width));
237
- spans.push({ message: identities.get(partial) ?? partial, start, end: lines.length });
606
+ appendAssistant(partial, streaming);
607
+ recordSpan(identities.get(partial) ?? partial, start);
238
608
  } else streaming = void 0;
239
609
  for (const message of messages.keys()) if (!activeMessages.has(message)) messages.delete(message);
240
- for (const id of tools.keys()) if (!activeTools.has(id)) tools.delete(id);
610
+ tools.retain(activeTools);
241
611
  return lines;
242
612
  },
613
+ handleMouse(event) {
614
+ if (disposed) return void 0;
615
+ const span = toolSpans.find((item) => event.y >= item.start && event.y < item.end);
616
+ return span ? tools.handleMouse(span.id, { ...event, y: event.y - span.start, height: span.end - span.start }) : void 0;
617
+ },
243
618
  anchorAt(row) {
244
619
  const span = spans.find((item) => row < item.end);
245
- return span ? { message: span.message, row: row - span.start } : void 0;
620
+ return span ? {
621
+ message: span.message,
622
+ row: row - span.start,
623
+ width: renderedWidth,
624
+ offset: span.offsets[Math.max(0, row - span.start)] ?? 0,
625
+ text: span.text.slice(
626
+ span.offsets[Math.max(0, row - span.start)] ?? 0,
627
+ span.offsets[Math.max(0, row - span.start) + 1]
628
+ )
629
+ } : void 0;
246
630
  },
247
631
  rowAt(anchor) {
248
632
  const span = spans.find((item) => item.message === anchor.message);
249
- return span ? Math.max(0, span.start + Math.min(anchor.row, span.end - span.start - 1)) : 0;
633
+ if (!span) return 0;
634
+ let row = anchor.row;
635
+ const currentText = span.text.slice(span.offsets[Math.max(0, row)], span.offsets[Math.max(0, row) + 1]);
636
+ if (anchor.width !== renderedWidth || currentText !== anchor.text) {
637
+ let offset = anchor.offset;
638
+ if (anchor.text) {
639
+ let match = span.text.indexOf(anchor.text);
640
+ let best = -1;
641
+ while (match >= 0) {
642
+ if (best < 0 || Math.abs(match - anchor.offset) < Math.abs(best - anchor.offset)) best = match;
643
+ match = span.text.indexOf(anchor.text, match + 1);
644
+ }
645
+ if (best >= 0) offset = best;
646
+ }
647
+ row = 0;
648
+ for (let index = 0; index < span.offsets.length; index++) {
649
+ if (span.offsets[index] > offset) break;
650
+ row = index;
651
+ }
652
+ }
653
+ return Math.max(0, span.start + Math.min(row, span.end - span.start - 1));
250
654
  },
251
655
  toggleTools() {
252
- if (disposed) return;
253
- expanded = !expanded;
254
- for (const { component } of tools.values()) component.setExpanded(expanded);
255
- tui.requestRender();
656
+ return tools.toggle();
256
657
  },
257
658
  invalidate() {
258
659
  if (disposed) return;
259
660
  messages.clear();
260
- tools.clear();
661
+ tools.invalidate();
261
662
  streaming = void 0;
262
663
  },
263
664
  dispose() {
@@ -266,8 +667,9 @@ function createSettingsChatTranscript(agent, tui, cwd) {
266
667
  unsubscribe();
267
668
  streamingIdentity = void 0;
268
669
  spans = [];
670
+ toolSpans = [];
269
671
  messages.clear();
270
- tools.clear();
672
+ tools.dispose();
271
673
  streaming = void 0;
272
674
  }
273
675
  };
@@ -293,47 +695,10 @@ function saveKeyReserved(data, keybindings) {
293
695
  }
294
696
  function settingsChatSaveShortcut(keybindings) {
295
697
  return SAVE_SHORTCUTS.find(({ key, inputs }) => {
296
- const matching = inputs.filter((data) => matchesKey(data, key));
698
+ const matching = inputs.filter((data) => matchesKey2(data, key));
297
699
  return matching.length > 0 && matching.every((data) => !saveKeyReserved(data, keybindings));
298
700
  })?.key;
299
701
  }
300
- var BEFORE_PAGE_ACTIONS = [
301
- "tui.input.copy",
302
- "tui.editor.undo",
303
- "tui.input.tab",
304
- "tui.editor.deleteToLineEnd",
305
- "tui.editor.deleteToLineStart",
306
- "tui.editor.deleteWordBackward",
307
- "tui.editor.deleteWordForward",
308
- "tui.editor.deleteCharBackward",
309
- "tui.editor.deleteCharForward",
310
- "tui.editor.yank",
311
- "tui.editor.yankPop",
312
- "tui.editor.historyPrevious",
313
- "tui.editor.historyNext",
314
- "tui.editor.cursorLineStart",
315
- "tui.editor.cursorLineEnd",
316
- "tui.editor.cursorWordLeft",
317
- "tui.editor.cursorWordRight",
318
- "tui.input.newLine",
319
- "tui.input.submit",
320
- "tui.editor.cursorUp",
321
- "tui.editor.cursorDown",
322
- "tui.editor.cursorRight",
323
- "tui.editor.cursorLeft"
324
- ];
325
- function nativeJumpPrintable(data) {
326
- if (decodeKittyPrintable(data) !== void 0 || data.charCodeAt(0) >= 32) return true;
327
- if (!data.startsWith("\x1B[27;")) return false;
328
- const match = /^(\d+);(\d+)~$/u.exec(data.slice(5));
329
- if (!match) return false;
330
- const modifier = Number(match[1]) - 1;
331
- const codepoint = Number(match[2]);
332
- return (modifier & ~(1 | 64 | 128)) === 0 && codepoint >= 32 && codepoint <= 1114111;
333
- }
334
- function nativeBeforePage(data) {
335
- return BEFORE_PAGE_ACTIONS.some((action) => getKeybindings().matches(data, action)) || matchesKey(data, "shift+backspace") || matchesKey(data, "shift+delete") || data.charCodeAt(0) === 10 || data === "\x1B\r" || data === "\x1B[13;2~" || data.length > 1 && data.includes("\x1B") && data.includes("\r");
336
- }
337
702
  var SettingsChatEditor = class extends CustomEditor {
338
703
  constructor(tui, chromeTheme, labels, chatKeys) {
339
704
  super(
@@ -352,40 +717,11 @@ var SettingsChatEditor = class extends CustomEditor {
352
717
  );
353
718
  this.chromeTheme = chromeTheme;
354
719
  this.labels = labels;
355
- this.chatKeys = chatKeys;
356
720
  }
357
721
  chromeTheme;
358
722
  labels;
359
- chatKeys;
360
- onTranscriptPage;
361
- awaitingJump;
362
- handleInput(data) {
363
- const kb = getKeybindings();
364
- const interrupt = this.chatKeys.matches(data, "app.interrupt");
365
- const appConsumes = this.chatKeys.matches(data, "app.clipboard.pasteImage") || interrupt && this.onEscape !== void 0 || !interrupt && this.chatKeys.matches(data, "app.exit") && this.getText().length === 0;
366
- const history = this.chatKeys.matches(data, "tui.editor.historyPrevious") || this.chatKeys.matches(data, "tui.editor.historyNext");
367
- const registeredAction = !interrupt && !history && (this.chatKeys.matches(data, "app.message.followUp") || this.chatKeys.matches(data, "app.message.dequeue") || this.chatKeys.matches(data, "app.tools.expand"));
368
- if (appConsumes || registeredAction) {
369
- super.handleInput(data);
370
- return;
371
- }
372
- const jump = kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward");
373
- const pendingJump = this.awaitingJump;
374
- const jumpConsumes = pendingJump !== void 0 && (jump || nativeJumpPrintable(data));
375
- this.awaitingJump = void 0;
376
- const earlier = nativeBeforePage(data);
377
- const direction = kb.matches(data, "tui.editor.pageUp") ? -1 : kb.matches(data, "tui.editor.pageDown") ? 1 : void 0;
378
- if (!interrupt && !jumpConsumes && !earlier && direction !== void 0 && this.onTranscriptPage) {
379
- if (pendingJump !== void 0) Editor.prototype.handleInput.call(this, pendingJump);
380
- this.onTranscriptPage(direction);
381
- return;
382
- }
383
- if (!jumpConsumes && !earlier && direction === void 0 && jump) this.awaitingJump = data;
384
- super.handleInput(data);
385
- }
386
723
  /** Bypass app shortcuts while the native Editor owns a bracketed paste. */
387
724
  handlePasteInput(data) {
388
- this.awaitingJump = void 0;
389
725
  Editor.prototype.handleInput.call(this, data);
390
726
  }
391
727
  renderTopBorder(width, hiddenLineCount) {
@@ -403,14 +739,28 @@ var SettingsChatEditor = class extends CustomEditor {
403
739
  }).render(width)[0] ?? "";
404
740
  }
405
741
  };
742
+ var ROOT_VIEWPORT_ACTIONS = [
743
+ "tui.altScreen.search",
744
+ "tui.altScreen.pageUp",
745
+ "tui.altScreen.pageDown",
746
+ "tui.altScreen.halfPageUp",
747
+ "tui.altScreen.halfPageDown",
748
+ "tui.altScreen.lineUp",
749
+ "tui.altScreen.lineDown",
750
+ "tui.altScreen.previousPrompt",
751
+ "tui.altScreen.nextPrompt",
752
+ "tui.altScreen.top",
753
+ "tui.altScreen.bottom"
754
+ ];
406
755
  function settingsChatStopInput(data, keybindings) {
407
756
  const editorKeys = getKeybindings();
408
757
  const parsed = parseKey(data);
409
758
  const textKey = parsed?.startsWith("shift+") ? parsed.slice(6) : parsed;
410
759
  const printable = data.charCodeAt(0) >= 32 || textKey !== void 0 && (Array.from(textKey).length === 1 || textKey === "space");
411
- const nativeEditing = printable || matchesKey(data, "shift+backspace") || matchesKey(data, "shift+delete") || data.charCodeAt(0) === 10 || data === "\x1B\r" || data === "\x1B[13;2~" || data.includes("\x1B") && data.includes("\r");
760
+ const nativeEditing = printable || matchesKey2(data, "shift+backspace") || matchesKey2(data, "shift+delete") || data.charCodeAt(0) === 10 || data === "\x1B\r" || data === "\x1B[13;2~" || data.includes("\x1B") && data.includes("\r");
412
761
  const editing = nativeEditing || Object.keys(TUI_KEYBINDINGS).filter((key) => key.startsWith("tui.editor.") || key.startsWith("tui.input.")).some((key) => editorKeys.matches(data, key));
413
- return !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape));
762
+ const viewport = ROOT_VIEWPORT_ACTIONS.some((action) => editorKeys.matches(data, action));
763
+ return !viewport && !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey2(data, Key.escape));
414
764
  }
415
765
  function createSettingsChatComponent(options) {
416
766
  const { agent, draft, state, tui, theme, keybindings, signal } = options;
@@ -418,16 +768,6 @@ function createSettingsChatComponent(options) {
418
768
  let inPaste = false;
419
769
  let pending;
420
770
  let stopping = false;
421
- let historyTop;
422
- let historyAnchor;
423
- let historyRows = 0;
424
- let historyMaximum = 0;
425
- const scrollHistory = (delta) => {
426
- const next = Math.max(0, Math.min(historyMaximum, (historyTop ?? historyMaximum) + delta));
427
- historyTop = next === historyMaximum ? void 0 : next;
428
- historyAnchor = historyTop === void 0 ? void 0 : transcript.anchorAt(historyTop);
429
- render();
430
- };
431
771
  const queued = [];
432
772
  const editor = new SettingsChatEditor(
433
773
  tui,
@@ -443,12 +783,17 @@ function createSettingsChatComponent(options) {
443
783
  },
444
784
  keybindings
445
785
  );
446
- editor.onTranscriptPage = (direction) => scrollHistory(direction * Math.max(1, historyRows));
447
786
  editor.setText(state.input);
448
787
  const render = () => {
449
788
  if (!disposed && !signal.aborted) tui.requestRender();
450
789
  };
451
- const transcript = createSettingsChatTranscript(agent, tui, draft.directory);
790
+ const transcript = createSettingsChatTranscript(
791
+ agent,
792
+ tui,
793
+ draft.directory,
794
+ state.toolsExpanded ?? false,
795
+ draft.path
796
+ );
452
797
  const unsubscribe = agent.subscribe((event) => {
453
798
  if (event.type === "message_start") {
454
799
  const index = queued.findIndex((item) => item.message === event.message);
@@ -517,26 +862,21 @@ function createSettingsChatComponent(options) {
517
862
  editor.onSubmit = (input) => submit(input, "steer");
518
863
  editor.onAction("app.message.followUp", () => submit(editor.getExpandedText().trim(), "followUp"));
519
864
  editor.onAction("app.message.dequeue", restoreQueue);
520
- editor.onAction("app.tools.expand", () => transcript.toggleTools());
521
- return {
522
- get focused() {
523
- return editor.focused;
524
- },
525
- set focused(value) {
526
- editor.focused = value;
527
- },
865
+ editor.onAction("app.tools.expand", () => {
866
+ state.toolsExpanded = transcript.toggleTools();
867
+ });
868
+ const dock = {
528
869
  render(width) {
529
- historyRows = 0;
530
870
  if (disposed || signal.aborted || width <= 0) return [];
531
871
  const rows = Math.max(0, Math.floor(Number.isFinite(tui.terminal.rows) ? tui.terminal.rows : 24));
532
872
  if (rows === 0) return [];
533
- const input = editor.render(width);
873
+ const input = editor.render(Math.max(3, width)).map((line) => truncateToWidth(line, width, ""));
534
874
  const cursor = Math.max(
535
875
  0,
536
876
  input.findIndex((line) => line.includes(CURSOR_MARKER))
537
877
  );
538
878
  const preview = options.preview(width);
539
- const diagnostics = sanitizeTerminalDocument2(state.error || agent.state.errorMessage || draft.diagnostics).split("\n").filter(Boolean).slice(0, 3);
879
+ const diagnostics = sanitizeTerminalDocument4(state.error || agent.state.errorMessage || draft.diagnostics).split("\n").filter(Boolean).slice(0, 3);
540
880
  const details = diagnostics.map((line) => theme.fg("muted", line));
541
881
  if (input.length + preview.length > rows) {
542
882
  return renderBoundedFrame({
@@ -556,40 +896,66 @@ function createSettingsChatComponent(options) {
556
896
  ].slice(0, Math.min(3, rows - input.length - preview.length - detailLines.length)).map(
557
897
  (item) => theme.fg(
558
898
  "dim",
559
- `${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument2(item.text).replace(/\n/gu, " ")}`
899
+ `${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument4(item.text).replace(/\n/gu, " ")}`
560
900
  )
561
901
  );
562
902
  const content = [...queueLines, ...input, ...detailLines, ...preview];
563
- const available = rows - content.length;
564
- historyRows = available;
565
- if (available === 0) return content.map((line) => truncateToWidth(line, width, ""));
566
- const lines = transcript.render(width);
567
- historyMaximum = Math.max(0, lines.length - available);
568
- if (historyTop !== void 0) {
569
- historyTop = Math.min(historyAnchor ? transcript.rowAt(historyAnchor) : historyTop, historyMaximum);
570
- if (historyTop === historyMaximum) historyTop = void 0;
571
- }
572
- const top = historyTop ?? historyMaximum;
573
- historyAnchor = historyTop === void 0 ? void 0 : transcript.anchorAt(top);
574
- const history = lines.slice(top, top + available);
575
- return [...history, ...Array.from({ length: available - history.length }, () => ""), ...content].map(
576
- (line) => truncateToWidth(line, width, "")
577
- );
903
+ return content.map((line) => truncateToWidth(line, width, ""));
904
+ },
905
+ invalidate() {
906
+ editor.invalidate();
907
+ }
908
+ };
909
+ const history = {
910
+ render(width) {
911
+ scroll.anchor = scroll.isFollowingEnd ? void 0 : transcript.anchorAt(scroll.scrollTop);
912
+ return transcript.render(width);
913
+ },
914
+ invalidate() {
915
+ transcript.invalidate();
916
+ },
917
+ handleMouse: (event) => transcript.handleMouse(event)
918
+ };
919
+ const scroll = new SettingsChatScrollView(history, {
920
+ primary: true,
921
+ follow: "end",
922
+ scrollbar: "auto",
923
+ scrollbarTrackStyle: (text) => theme.fg("scrollbarTrack", text),
924
+ scrollbarThumbStyle: (text) => theme.fg("scrollbarThumb", text)
925
+ });
926
+ scroll.restoreAnchor = (anchor) => transcript.rowAt(anchor);
927
+ const layout = new VStack([
928
+ { component: scroll, basis: 0, grow: 1, minSize: 0 },
929
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
930
+ ]);
931
+ return {
932
+ getFullscreenLayout() {
933
+ return layout;
934
+ },
935
+ get focused() {
936
+ return editor.focused;
937
+ },
938
+ set focused(value) {
939
+ editor.focused = value;
940
+ },
941
+ render(width) {
942
+ if (disposed || signal.aborted || width <= 0 || tui.terminal.rows <= 0) return [];
943
+ return layout.render(width);
578
944
  },
579
945
  invalidate() {
580
946
  editor.invalidate();
581
947
  transcript.invalidate();
582
948
  },
583
949
  handleInput(data) {
584
- if (disposed || signal.aborted || isKeyRelease(data)) return;
950
+ if (disposed || signal.aborted || isKeyRelease2(data)) return;
585
951
  const saveKey = !pending && draft.candidate ? settingsChatSaveShortcut(keybindings) : void 0;
586
952
  if (inPaste || data.includes("\x1B[200~")) {
587
953
  inPaste = !data.includes("\x1B[201~");
588
954
  editor.handlePasteInput(data);
589
- } else if (matchesKey(data, Key.ctrl("c"))) {
955
+ } else if (matchesKey2(data, Key.ctrl("c"))) {
590
956
  abort();
591
957
  options.complete("discard");
592
- } else if (saveKey && matchesKey(data, saveKey) && !saveKeyReserved(data, keybindings)) {
958
+ } else if (saveKey && matchesKey2(data, saveKey) && !saveKeyReserved(data, keybindings)) {
593
959
  state.input = editor.getExpandedText();
594
960
  options.complete("save");
595
961
  } else if (settingsChatStopInput(data, keybindings)) {
@@ -601,12 +967,6 @@ function createSettingsChatComponent(options) {
601
967
  } else editor.handleInput(data);
602
968
  render();
603
969
  },
604
- handleMouse(event) {
605
- if (disposed || signal.aborted || inPaste || historyRows === 0 || event.type !== "wheel" || !event.wheelDelta)
606
- return void 0;
607
- scrollHistory(event.wheelDelta < 0 ? -3 : 3);
608
- return { handled: true, render: true };
609
- },
610
970
  dispose() {
611
971
  if (disposed) return;
612
972
  disposed = true;
@@ -614,6 +974,8 @@ function createSettingsChatComponent(options) {
614
974
  signal.removeEventListener("abort", abort);
615
975
  unsubscribe();
616
976
  transcript.dispose();
977
+ scroll.setScrollbarActive(false);
978
+ scroll.setScrollbar("hidden");
617
979
  abort();
618
980
  },
619
981
  async waitForPending() {
@@ -623,33 +985,13 @@ function createSettingsChatComponent(options) {
623
985
  };
624
986
  }
625
987
  async function showSettingsChat(ctx, agent, draft, state, owner, preview) {
626
- const fullscreenContext = {
627
- ...ctx,
628
- ui: {
629
- ...ctx.ui,
630
- custom: (factory) => ctx.ui.custom(factory, {
631
- overlay: true,
632
- overlayOptions: { width: "100%", maxHeight: "100%", anchor: "top-left", margin: 0 }
633
- })
634
- }
635
- };
636
- const result = await runCustomInteraction(fullscreenContext, {
637
- signal: owner.signal,
638
- isCurrent: owner.isCurrent,
639
- create: ({ tui, theme, keybindings, signal, complete }) => createSettingsChatComponent({
640
- agent,
641
- draft,
642
- state,
643
- tui,
644
- theme,
645
- keybindings,
646
- signal,
647
- preview,
648
- complete
649
- })
650
- });
651
- if (result.kind === "error") throw result.error;
652
- return result.kind === "completed" ? result.value : "discard";
988
+ state.toolsExpanded ??= ctx.ui.getToolsExpanded?.() ?? false;
989
+ return runSettingsChatFullscreen(
990
+ ctx,
991
+ owner,
992
+ ({ tui, theme, keybindings, signal, complete }) => createSettingsChatComponent({ agent, draft, state, tui, theme, keybindings, signal, preview, complete }),
993
+ "discard"
994
+ );
653
995
  }
654
996
 
655
997
  // src/settings-draft.ts
@@ -666,7 +1008,7 @@ import {
666
1008
  writeFileSync
667
1009
  } from "node:fs";
668
1010
  import { tmpdir } from "node:os";
669
- import { isAbsolute, join as join2, relative, resolve } from "node:path";
1011
+ import { isAbsolute, join as join2, relative, resolve as resolve2 } from "node:path";
670
1012
  import {
671
1013
  createEditTool,
672
1014
  createReadTool,
@@ -696,7 +1038,7 @@ function createSettingsDraft(options) {
696
1038
  };
697
1039
  const assertDraft = (target) => {
698
1040
  assertCurrent();
699
- if (resolve(target) !== path || realpathSync(directory) !== directory || realpathSync(path) !== path) {
1041
+ if (resolve2(target) !== path || realpathSync(directory) !== directory || realpathSync(path) !== path) {
700
1042
  throw new Error("Only the owned settings draft can be changed");
701
1043
  }
702
1044
  };
@@ -741,13 +1083,13 @@ function createSettingsDraft(options) {
741
1083
  }
742
1084
  const readAllowed = (target) => {
743
1085
  assertCurrent();
744
- if (resolve(target) === resolve(options.settingsPath)) {
1086
+ if (resolve2(target) === resolve2(options.settingsPath)) {
745
1087
  if (!baseline) throw new Error("The active settings file was missing when this preview started");
746
1088
  return Buffer.from(baseline);
747
1089
  }
748
- if (resolve(target) === path) return readDraft();
749
- if (snapshots.has(resolve(target))) {
750
- const content = snapshots.get(resolve(target));
1090
+ if (resolve2(target) === path) return readDraft();
1091
+ if (snapshots.has(resolve2(target))) {
1092
+ const content = snapshots.get(resolve2(target));
751
1093
  if (content === void 0)
752
1094
  throw new Error(
753
1095
  "No exact loaded settings document is available; read active-state.json for its source and diagnostics"
@@ -986,10 +1328,12 @@ async function showSettingsAgentChat(ctx, options, base) {
986
1328
  return captureCommitExpectation(options);
987
1329
  });
988
1330
  if (!expected || base.signal.aborted || !base.isCurrent()) return "close";
1331
+ const chatLifetime = new AbortController();
989
1332
  const owner = {
990
- signal: base.signal,
991
- isCurrent: () => commitOwnerCurrent(options, base, expected),
992
- isSessionCurrent: base.isSessionCurrent ?? base.isCurrent
1333
+ signal: AbortSignal.any([base.signal, chatLifetime.signal]),
1334
+ isCurrent: () => !chatLifetime.signal.aborted && commitOwnerCurrent(options, base, expected),
1335
+ isSessionCurrent: base.isSessionCurrent ?? base.isCurrent,
1336
+ canRestoreTerminal: base.canRestoreTerminal
993
1337
  };
994
1338
  const packageRoot = starshipPackageRoot();
995
1339
  const draft = createSettingsDraft({
@@ -1004,12 +1348,15 @@ async function showSettingsAgentChat(ctx, options, base) {
1004
1348
  });
1005
1349
  let agent;
1006
1350
  let closing;
1351
+ let activeChat;
1007
1352
  const cleanup = () => {
1008
1353
  if (closing) return closing;
1354
+ chatLifetime.abort();
1009
1355
  agent?.abort();
1356
+ const pendingChat = activeChat;
1010
1357
  closing = (async () => {
1011
1358
  try {
1012
- await agent?.waitForIdle();
1359
+ await Promise.all([agent?.waitForIdle(), pendingChat]);
1013
1360
  } finally {
1014
1361
  agent?.reset();
1015
1362
  draft.dispose();
@@ -1031,7 +1378,13 @@ async function showSettingsAgentChat(ctx, options, base) {
1031
1378
  if (!owner.isCurrent()) return "close";
1032
1379
  agent = createSettingsAgent(ctx, draft, packageRoot);
1033
1380
  while (owner.isCurrent()) {
1034
- const action = await showSettingsChat(ctx, agent, draft, state, owner, preview);
1381
+ activeChat = showSettingsChat(ctx, agent, draft, state, owner, preview);
1382
+ let action;
1383
+ try {
1384
+ action = await activeChat;
1385
+ } finally {
1386
+ activeChat = void 0;
1387
+ }
1035
1388
  if (!owner.isCurrent() || action === "discard") return "close";
1036
1389
  if (!draft.candidate) continue;
1037
1390
  const candidate = draft.candidate;
@@ -1052,7 +1405,7 @@ async function showSettingsAgentChat(ctx, options, base) {
1052
1405
  const confirmed = await ctx.ui.confirm(
1053
1406
  "Apply saved profile?",
1054
1407
  [
1055
- `Profile saved: ${sanitizeTerminalDocument3(saved.name)}. Apply it to the current footer without reload?`,
1408
+ `Profile saved: ${sanitizeTerminalDocument5(saved.name)}. Apply it to the current footer without reload?`,
1056
1409
  "This replaces the complete active settings document. Declining keeps the profile and leaves active settings unchanged.",
1057
1410
  "Applying can run enabled module commands and network requests; review their configuration before accepting.",
1058
1411
  "The previous file is retained in History. Detected concurrent edits block replacement.",
@@ -1073,7 +1426,7 @@ async function showSettingsAgentChat(ctx, options, base) {
1073
1426
  } catch (error) {
1074
1427
  if (!base.signal.aborted && base.isCurrent())
1075
1428
  ctx.ui.notify(
1076
- `Profile was saved as ${sanitizeTerminalDocument3(saved.name)}. Settings were not applied: ${sanitizeTerminalDocument3(error instanceof Error ? error.message : String(error))}`,
1429
+ `Profile was saved as ${sanitizeTerminalDocument5(saved.name)}. Settings were not applied: ${sanitizeTerminalDocument5(error instanceof Error ? error.message : String(error))}`,
1077
1430
  "error"
1078
1431
  );
1079
1432
  }
@@ -1121,4 +1474,4 @@ async function reviewText(ctx, owner, title, content, toml) {
1121
1474
  export {
1122
1475
  showSettingsAgentChat
1123
1476
  };
1124
- //# sourceMappingURL=command-settings-chat-5AHP3JGV.ts.map
1477
+ //# sourceMappingURL=command-settings-chat-KLUVZXMO.ts.map