@narumitw/pi-starship 0.63.0 → 0.64.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.
Files changed (27) hide show
  1. package/README.md +15 -4
  2. package/dist/chunks/{chunk-63R6R5DH.ts → chunk-D563JANR.ts} +10 -5
  3. package/dist/chunks/{chunk-63R6R5DH.ts.map → chunk-D563JANR.ts.map} +2 -2
  4. package/dist/chunks/{chunk-Y24TJYG6.ts → chunk-UIKPE4UC.ts} +1 -1
  5. package/dist/chunks/{chunk-Y24TJYG6.ts.map → chunk-UIKPE4UC.ts.map} +2 -2
  6. package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts → command-configuration-menu-ZN2VXU4L.ts} +2 -2
  7. package/dist/chunks/{command-settings-chat-5AHP3JGV.ts → command-settings-chat-B2FCDVBH.ts} +563 -227
  8. package/dist/chunks/command-settings-chat-B2FCDVBH.ts.map +7 -0
  9. package/dist/chunks/{commands-IOG2PL67.ts → commands-SVLRVXUW.ts} +7 -6
  10. package/dist/chunks/commands-SVLRVXUW.ts.map +7 -0
  11. package/dist/index.ts +3 -2
  12. package/dist/index.ts.map +2 -2
  13. package/package.json +5 -5
  14. package/src/command-configuration.ts +2 -0
  15. package/src/command-profiles.ts +10 -3
  16. package/src/command-settings-chat.ts +17 -5
  17. package/src/commands.ts +1 -0
  18. package/src/pi-starship.ts +1 -0
  19. package/src/settings-chat-display.ts +11 -0
  20. package/src/settings-chat-fullscreen.ts +241 -0
  21. package/src/settings-chat-scroll.ts +17 -0
  22. package/src/settings-chat-tools.ts +207 -0
  23. package/src/settings-chat-transcript.ts +91 -72
  24. package/src/settings-chat-ui.ts +94 -183
  25. package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +0 -7
  26. package/dist/chunks/commands-IOG2PL67.ts.map +0 -7
  27. /package/dist/chunks/{command-configuration-menu-YOLN2SPR.ts.map → command-configuration-menu-ZN2VXU4L.ts.map} +0 -0
@@ -5,11 +5,11 @@ import {
5
5
  commitActiveDocument,
6
6
  commitOwnerCurrent,
7
7
  saveAsProfile
8
- } from "./chunk-63R6R5DH.ts";
8
+ } from "./chunk-D563JANR.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,407 @@ 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
+ import { createFullscreenHandoff } from "@narumitw/pi-tui-kit/fullscreen-handoff";
121
+ var SettingsChatTui = class extends TuiAltScreen {
122
+ addInputListener(listener) {
123
+ if (!this.guardInstalled) {
124
+ this.guardInstalled = true;
125
+ super.addInputListener((data) => this.guard?.(data));
126
+ }
127
+ return super.addInputListener(listener);
128
+ }
129
+ };
130
+ async function runSettingsChatFullscreen(ctx, owner, create, cancelledValue, dependencies = {}) {
131
+ const current = () => !owner.signal.aborted && !ctx.signal?.aborted && owner.isCurrent();
132
+ const canRestoreTerminal = () => (owner.canRestoreTerminal ?? owner.isSessionCurrent ?? owner.isCurrent)();
133
+ if (ctx.mode !== "tui" || !current()) return cancelledValue;
134
+ let mount;
135
+ let releaseHost;
136
+ let completedOutcome;
137
+ const outcome = await ctx.ui.custom(
138
+ (parent, theme, keybindings, done) => {
139
+ const controller = new AbortController();
140
+ let child;
141
+ let component;
142
+ let entry;
143
+ let finished = false;
144
+ let closing = false;
145
+ let cleanup;
146
+ let pasting = false;
147
+ let result = { value: cancelledValue };
148
+ const errors = [];
149
+ const handoff = createFullscreenHandoff(parent, {
150
+ isCurrent: () => !closing && current(),
151
+ canRestoreParent: canRestoreTerminal
152
+ });
153
+ const removers = [];
154
+ const attempt = (action) => {
155
+ try {
156
+ action();
157
+ } catch (error) {
158
+ errors.push(error);
159
+ }
160
+ };
161
+ const finish = (next) => {
162
+ if (closing) return cleanup;
163
+ closing = true;
164
+ result = next;
165
+ controller.abort();
166
+ cleanup = Promise.resolve().then(async () => {
167
+ await entry;
168
+ for (const remove of removers.splice(0)) attempt(remove);
169
+ attempt(() => component?.dispose?.());
170
+ try {
171
+ await handoff.restore();
172
+ } catch (error) {
173
+ errors.push(error);
174
+ }
175
+ try {
176
+ await component?.waitForPending?.();
177
+ } catch (error) {
178
+ errors.push(error);
179
+ }
180
+ attempt(() => {
181
+ if (!current() && !("error" in result)) result = { value: cancelledValue };
182
+ });
183
+ finished = true;
184
+ if ("error" in result) errors.unshift(result.error);
185
+ completedOutcome = errors.length ? { error: errors.length === 1 ? errors[0] : new AggregateError(errors, "Fullscreen cleanup failed") } : result;
186
+ done(completedOutcome);
187
+ });
188
+ return cleanup;
189
+ };
190
+ releaseHost = () => finish({ value: cancelledValue }) ?? Promise.resolve();
191
+ const cancel = () => finish({ value: cancelledValue });
192
+ const guard = (data) => {
193
+ if (closing) return { consume: true };
194
+ if (!current()) {
195
+ cancel();
196
+ return { consume: true };
197
+ }
198
+ const wasPasting = pasting;
199
+ for (const part of data.split("\x1B").slice(1)) {
200
+ if (part.startsWith("[200~")) pasting = true;
201
+ else if (part.startsWith("[201~")) pasting = false;
202
+ }
203
+ if (wasPasting || pasting || data.includes("\x1B[200~") || data.includes("\x1B[201~")) {
204
+ try {
205
+ child?.getFocusedComponent()?.handleInput?.(data);
206
+ child?.requestRender();
207
+ } catch (error) {
208
+ finish({ error });
209
+ }
210
+ return { consume: true };
211
+ }
212
+ if (!isKeyRelease(data) && matchesKey(data, "ctrl+c")) {
213
+ cancel();
214
+ return { consume: true };
215
+ }
216
+ };
217
+ for (const signal of /* @__PURE__ */ new Set([owner.signal, ctx.signal])) {
218
+ if (!signal) continue;
219
+ signal.addEventListener("abort", cancel, { once: true });
220
+ removers.push(() => signal.removeEventListener("abort", cancel));
221
+ }
222
+ const host = {
223
+ render: () => [],
224
+ invalidate() {
225
+ },
226
+ dispose() {
227
+ if (!finished) cancel();
228
+ }
229
+ };
230
+ mount = (handle) => {
231
+ handoff.setOverlayHandle(handle);
232
+ queueMicrotask(() => {
233
+ if (closing) return;
234
+ entry = (async () => {
235
+ try {
236
+ child = await handoff.enter(() => {
237
+ const createDefault = () => new SettingsChatTui(parent.terminal, parent.getShowHardwareCursor(), void 0, { mouse: true });
238
+ const created = dependencies.createTui?.(parent, createDefault) ?? createDefault();
239
+ child = created;
240
+ try {
241
+ if (created instanceof SettingsChatTui) created.guard = guard;
242
+ else removers.push(created.addInputListener(guard));
243
+ component = create({
244
+ tui: created,
245
+ theme,
246
+ keybindings,
247
+ signal: controller.signal,
248
+ complete: (value) => finish({ value })
249
+ });
250
+ if (!closing && current()) {
251
+ created.setLayoutRoot(component.getFullscreenLayout?.() ?? component);
252
+ created.setFocus(component);
253
+ }
254
+ return created;
255
+ } catch (error) {
256
+ controller.abort();
257
+ try {
258
+ created.stop({ preserveScreen: true });
259
+ } catch (cleanupError) {
260
+ throw new AggregateError([error, cleanupError], "Fullscreen child factory cleanup failed");
261
+ }
262
+ throw error;
263
+ }
264
+ });
265
+ if (!child && !closing) cancel();
266
+ } catch (error) {
267
+ if (closing) errors.push(error);
268
+ else finish({ error });
269
+ }
270
+ })();
271
+ });
272
+ };
273
+ if (!current()) cancel();
274
+ return host;
275
+ },
276
+ { overlay: true, onHandle: (handle) => mount?.(handle) }
277
+ ).catch(async (error) => {
278
+ await releaseHost?.();
279
+ if (completedOutcome && "error" in completedOutcome) {
280
+ throw new AggregateError([error, completedOutcome.error], "Fullscreen mount and cleanup failed");
281
+ }
282
+ throw error;
283
+ });
284
+ await releaseHost?.();
285
+ const completion = completedOutcome ?? outcome;
286
+ if (!completion) return cancelledValue;
287
+ if ("error" in completion) throw completion.error;
288
+ return completion.value;
289
+ }
290
+
291
+ // src/settings-chat-scroll.ts
292
+ import { ScrollView } from "@earendil-works/pi-tui";
293
+ var SettingsChatScrollView = class extends ScrollView {
294
+ anchor;
295
+ restoreAnchor;
296
+ updateLayout(contentHeight, viewportHeight, requestRender) {
297
+ const manual = !this.isFollowingEnd;
298
+ const target = manual && this.anchor ? this.restoreAnchor?.(this.anchor) : void 0;
299
+ super.updateLayout(contentHeight, viewportHeight, requestRender);
300
+ if (manual) this.scrollTo(target ?? this.scrollTop, { disableFollow: true });
301
+ }
302
+ };
303
+
304
+ // src/settings-chat-transcript.ts
305
+ import { stripVTControlCharacters } from "node:util";
306
+ import { AssistantMessageComponent, UserMessageComponent } from "@earendil-works/pi-coding-agent";
307
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument3 } from "@narumitw/pi-tui-kit/terminal-document";
308
+
309
+ // src/settings-chat-display.ts
123
310
  import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
124
- function displayValue(value) {
311
+ function settingsChatDisplayValue(value) {
125
312
  if (typeof value === "string") return sanitizeTerminalDocument(value);
126
- if (Array.isArray(value)) return value.map(displayValue);
313
+ if (Array.isArray(value)) return value.map(settingsChatDisplayValue);
127
314
  if (value && typeof value === "object") {
128
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, displayValue(item)]));
315
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, settingsChatDisplayValue(item)]));
129
316
  }
130
317
  return value;
131
318
  }
132
- function createSettingsChatTranscript(agent, tui, cwd) {
133
- const messages = /* @__PURE__ */ new Map();
134
- const tools = /* @__PURE__ */ new Map();
319
+
320
+ // src/settings-chat-tools.ts
321
+ import { resolve } from "node:path";
322
+ import {
323
+ createEditToolDefinition,
324
+ createReadToolDefinition,
325
+ createWriteToolDefinition,
326
+ ToolExecutionComponent
327
+ } from "@earendil-works/pi-coding-agent";
328
+ import { sanitizeTerminalDocument as sanitizeTerminalDocument2 } from "@narumitw/pi-tui-kit/terminal-document";
329
+ function createSettingsChatTools(tui, cwd, initialExpanded, editablePath) {
330
+ const rows = /* @__PURE__ */ new Map();
331
+ const pending = /* @__PURE__ */ new Set();
332
+ const edit = createEditToolDefinition(cwd);
333
+ const renderEditCall = edit.renderCall;
334
+ if (renderEditCall) {
335
+ edit.renderCall = (args, theme, context) => {
336
+ const path = typeof args?.path === "string" ? args.path : args && "file_path" in args ? args.file_path : void 0;
337
+ const allowed = editablePath !== void 0 && typeof path === "string" && resolve(cwd, path) === resolve(editablePath);
338
+ return renderEditCall(args, theme, { ...context, argsComplete: context.argsComplete && allowed });
339
+ };
340
+ }
135
341
  const definitions = {
136
342
  read: createReadToolDefinition(cwd),
137
343
  write: createWriteToolDefinition(cwd),
138
- edit: createEditToolDefinition(cwd)
344
+ edit
345
+ };
346
+ let disposed = false;
347
+ let expanded = initialExpanded;
348
+ const ensure = (id, name, args) => {
349
+ let row = rows.get(id);
350
+ if (!row) {
351
+ row = { name, args, complete: false, started: false, partial: true };
352
+ rows.set(id, row);
353
+ }
354
+ if (!row.component) {
355
+ const toolName = row.name;
356
+ const definition = toolName === "read" || toolName === "write" || toolName === "edit" ? definitions[toolName] : void 0;
357
+ const ownedRow = row;
358
+ const toolUi = new Proxy(tui, {
359
+ get(target, property) {
360
+ if (property === "requestRender")
361
+ return () => {
362
+ if (!disposed && rows.get(id) === ownedRow && ownedRow.component === component) target.requestRender();
363
+ };
364
+ const value = Reflect.get(target, property, target);
365
+ return typeof value === "function" ? value.bind(target) : value;
366
+ }
367
+ });
368
+ const Component = class extends ToolExecutionComponent {
369
+ setExpanded(value) {
370
+ ownedRow.expanded = value;
371
+ super.setExpanded(value);
372
+ }
373
+ };
374
+ const component = new Component(
375
+ sanitizeTerminalDocument2(toolName),
376
+ sanitizeTerminalDocument2(id),
377
+ settingsChatDisplayValue(row.args),
378
+ { showImages: false, outputPad: 1 },
379
+ definition,
380
+ toolUi,
381
+ sanitizeTerminalDocument2(cwd)
382
+ );
383
+ row.component = component;
384
+ component.setExpanded(row.expanded ?? expanded);
385
+ if (row.complete && (!row.result || row.partial)) component.setArgsComplete();
386
+ if (row.started) component.markExecutionStarted();
387
+ if (row.result) component.updateResult(settingsChatDisplayValue(row.result), row.partial);
388
+ }
389
+ return row;
390
+ };
391
+ const updateArgs = (call) => {
392
+ const row = ensure(call.id, call.name, call.arguments);
393
+ row.args = call.arguments;
394
+ row.component?.updateArgs(settingsChatDisplayValue(call.arguments));
395
+ return row;
396
+ };
397
+ const completeArgs = (row) => {
398
+ if (row.complete) return;
399
+ row.complete = true;
400
+ row.component?.setArgsComplete();
401
+ };
402
+ const result = (row, value, partial = false) => {
403
+ row.result = value;
404
+ row.partial = partial;
405
+ row.component?.updateResult(settingsChatDisplayValue(value), partial);
406
+ };
407
+ const failure = (message) => ({
408
+ content: [
409
+ { type: "text", text: message.stopReason === "aborted" ? "Operation aborted" : message.errorMessage || "Error" }
410
+ ],
411
+ isError: true
412
+ });
413
+ return {
414
+ onEvent(event) {
415
+ if (disposed) return;
416
+ if (event.type === "message_update" && event.message.role === "assistant") {
417
+ for (const call of event.message.content) {
418
+ if (call.type !== "toolCall") continue;
419
+ updateArgs(call);
420
+ pending.add(call.id);
421
+ }
422
+ }
423
+ if (event.type === "message_end" && event.message.role === "assistant") {
424
+ const failed = event.message.stopReason === "aborted" || event.message.stopReason === "error";
425
+ for (const call of event.message.content) {
426
+ if (call.type !== "toolCall") continue;
427
+ updateArgs(call);
428
+ pending.add(call.id);
429
+ }
430
+ for (const id of pending) {
431
+ const row = rows.get(id);
432
+ if (!row) continue;
433
+ if (failed) result(row, failure(event.message));
434
+ else completeArgs(row);
435
+ }
436
+ if (failed) pending.clear();
437
+ }
438
+ if (event.type === "tool_execution_start" && !("parentToolCallId" in event && event.parentToolCallId)) {
439
+ const row = ensure(event.toolCallId, event.toolName, event.args);
440
+ pending.add(event.toolCallId);
441
+ row.started = true;
442
+ row.component?.markExecutionStarted();
443
+ }
444
+ if (event.type === "tool_execution_update") {
445
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : void 0;
446
+ if (row) result(row, { ...event.partialResult, isError: false }, true);
447
+ }
448
+ if (event.type === "tool_execution_end") {
449
+ const row = pending.has(event.toolCallId) ? rows.get(event.toolCallId) : void 0;
450
+ if (row) result(row, { ...event.result, isError: event.isError, durationMs: event.durationMs });
451
+ pending.delete(event.toolCallId);
452
+ }
453
+ if (event.type === "agent_end") pending.clear();
454
+ },
455
+ render(call, message, historyResult, width) {
456
+ const row = ensure(call.id, call.name, call.arguments);
457
+ if (historyResult && row.historyResult !== historyResult) {
458
+ row.historyResult = historyResult;
459
+ result(row, historyResult);
460
+ }
461
+ if (!historyResult && !row.result && (message.stopReason === "aborted" || message.stopReason === "error"))
462
+ result(row, failure(message));
463
+ return row.component?.render(width) ?? [];
464
+ },
465
+ handleMouse(id, event) {
466
+ if (disposed) return void 0;
467
+ return rows.get(id)?.component?.handleMouse(event);
468
+ },
469
+ retain(ids) {
470
+ for (const id of rows.keys())
471
+ if (!ids.has(id)) {
472
+ rows.delete(id);
473
+ pending.delete(id);
474
+ }
475
+ },
476
+ toggle() {
477
+ if (!disposed) {
478
+ expanded = !expanded;
479
+ for (const row of rows.values()) {
480
+ row.expanded = expanded;
481
+ row.component?.setExpanded(expanded);
482
+ }
483
+ tui.requestRender();
484
+ }
485
+ return expanded;
486
+ },
487
+ invalidate() {
488
+ for (const row of rows.values()) row.component = void 0;
489
+ },
490
+ dispose() {
491
+ disposed = true;
492
+ pending.clear();
493
+ rows.clear();
494
+ }
139
495
  };
496
+ }
497
+
498
+ // src/settings-chat-transcript.ts
499
+ function createSettingsChatTranscript(agent, tui, cwd, initialExpanded = false, editablePath) {
500
+ const messages = /* @__PURE__ */ new Map();
501
+ const tools = createSettingsChatTools(tui, cwd, initialExpanded, editablePath);
140
502
  const identities = /* @__PURE__ */ new WeakMap();
141
503
  let streamingIdentity;
142
504
  const initial = agent.state.streamingMessage;
@@ -145,6 +507,8 @@ function createSettingsChatTranscript(agent, tui, cwd) {
145
507
  identities.set(initial, streamingIdentity);
146
508
  }
147
509
  const unsubscribe = agent.subscribe((event) => {
510
+ if (disposed) return;
511
+ tools.onEvent(event);
148
512
  if (event.type === "agent_end") streamingIdentity = void 0;
149
513
  if ((event.type === "message_start" || event.type === "message_update" || event.type === "message_end") && event.message.role === "assistant") {
150
514
  if (event.type === "message_start") streamingIdentity = /* @__PURE__ */ Symbol();
@@ -154,12 +518,14 @@ function createSettingsChatTranscript(agent, tui, cwd) {
154
518
  }
155
519
  });
156
520
  let spans = [];
521
+ let toolSpans = [];
522
+ let renderedWidth = 0;
157
523
  let streaming;
158
524
  let disposed = false;
159
- let expanded = true;
160
525
  return {
161
526
  render(width) {
162
527
  spans = [];
528
+ toolSpans = [];
163
529
  if (disposed || width <= 0) return [];
164
530
  const results = new Map(
165
531
  agent.state.messages.flatMap(
@@ -170,40 +536,27 @@ function createSettingsChatTranscript(agent, tui, cwd) {
170
536
  const activeMessages = /* @__PURE__ */ new Set();
171
537
  const activeTools = /* @__PURE__ */ new Set();
172
538
  const lines = [];
539
+ renderedWidth = width;
540
+ const recordSpan = (message, start) => {
541
+ let offset = 0;
542
+ let text = "";
543
+ const offsets = lines.slice(start).map((line) => {
544
+ const before = offset;
545
+ const content = stripVTControlCharacters(line).replace(/\s/gu, "");
546
+ text += content;
547
+ offset += content.length;
548
+ return before;
549
+ });
550
+ spans.push({ message, start, end: lines.length, offsets, text });
551
+ };
173
552
  const appendAssistant = (message, component) => {
174
553
  lines.push(...component.render(width));
175
554
  for (const call of message.content) {
176
555
  if (call.type !== "toolCall") continue;
177
556
  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));
557
+ const start = lines.length;
558
+ lines.push(...tools.render(call, message, results.get(call.id), width));
559
+ toolSpans.push({ id: call.id, start, end: lines.length });
207
560
  }
208
561
  };
209
562
  for (const message of visible) {
@@ -215,49 +568,80 @@ function createSettingsChatTranscript(agent, tui, cwd) {
215
568
  start = lines.length;
216
569
  if (!component) {
217
570
  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));
571
+ component = new UserMessageComponent(sanitizeTerminalDocument3(text));
219
572
  messages.set(message, component);
220
573
  }
221
574
  lines.push(...component.render(width));
222
575
  } else if (message.role === "assistant") {
223
576
  if (!component) {
224
- component = new AssistantMessageComponent(displayValue(message), true);
577
+ component = new AssistantMessageComponent(settingsChatDisplayValue(message), true);
225
578
  messages.set(message, component);
226
579
  }
227
580
  appendAssistant(message, component);
228
581
  }
229
- spans.push({ message: identities.get(message) ?? message, start, end: lines.length });
582
+ recordSpan(identities.get(message) ?? message, start);
230
583
  }
231
584
  const partial = agent.state.streamingMessage;
232
585
  if (partial?.role === "assistant") {
233
586
  streaming ??= new AssistantMessageComponent(void 0, true);
234
- streaming.updateContent(displayValue(partial), true);
587
+ streaming.updateContent(settingsChatDisplayValue(partial), true);
235
588
  const start = lines.length;
236
- lines.push(...streaming.render(width));
237
- spans.push({ message: identities.get(partial) ?? partial, start, end: lines.length });
589
+ appendAssistant(partial, streaming);
590
+ recordSpan(identities.get(partial) ?? partial, start);
238
591
  } else streaming = void 0;
239
592
  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);
593
+ tools.retain(activeTools);
241
594
  return lines;
242
595
  },
596
+ handleMouse(event) {
597
+ if (disposed) return void 0;
598
+ const span = toolSpans.find((item) => event.y >= item.start && event.y < item.end);
599
+ return span ? tools.handleMouse(span.id, { ...event, y: event.y - span.start, height: span.end - span.start }) : void 0;
600
+ },
243
601
  anchorAt(row) {
244
602
  const span = spans.find((item) => row < item.end);
245
- return span ? { message: span.message, row: row - span.start } : void 0;
603
+ return span ? {
604
+ message: span.message,
605
+ row: row - span.start,
606
+ width: renderedWidth,
607
+ offset: span.offsets[Math.max(0, row - span.start)] ?? 0,
608
+ text: span.text.slice(
609
+ span.offsets[Math.max(0, row - span.start)] ?? 0,
610
+ span.offsets[Math.max(0, row - span.start) + 1]
611
+ )
612
+ } : void 0;
246
613
  },
247
614
  rowAt(anchor) {
248
615
  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;
616
+ if (!span) return 0;
617
+ let row = anchor.row;
618
+ const currentText = span.text.slice(span.offsets[Math.max(0, row)], span.offsets[Math.max(0, row) + 1]);
619
+ if (anchor.width !== renderedWidth || currentText !== anchor.text) {
620
+ let offset = anchor.offset;
621
+ if (anchor.text) {
622
+ let match = span.text.indexOf(anchor.text);
623
+ let best = -1;
624
+ while (match >= 0) {
625
+ if (best < 0 || Math.abs(match - anchor.offset) < Math.abs(best - anchor.offset)) best = match;
626
+ match = span.text.indexOf(anchor.text, match + 1);
627
+ }
628
+ if (best >= 0) offset = best;
629
+ }
630
+ row = 0;
631
+ for (let index = 0; index < span.offsets.length; index++) {
632
+ if (span.offsets[index] > offset) break;
633
+ row = index;
634
+ }
635
+ }
636
+ return Math.max(0, span.start + Math.min(row, span.end - span.start - 1));
250
637
  },
251
638
  toggleTools() {
252
- if (disposed) return;
253
- expanded = !expanded;
254
- for (const { component } of tools.values()) component.setExpanded(expanded);
255
- tui.requestRender();
639
+ return tools.toggle();
256
640
  },
257
641
  invalidate() {
258
642
  if (disposed) return;
259
643
  messages.clear();
260
- tools.clear();
644
+ tools.invalidate();
261
645
  streaming = void 0;
262
646
  },
263
647
  dispose() {
@@ -266,8 +650,9 @@ function createSettingsChatTranscript(agent, tui, cwd) {
266
650
  unsubscribe();
267
651
  streamingIdentity = void 0;
268
652
  spans = [];
653
+ toolSpans = [];
269
654
  messages.clear();
270
- tools.clear();
655
+ tools.dispose();
271
656
  streaming = void 0;
272
657
  }
273
658
  };
@@ -293,47 +678,10 @@ function saveKeyReserved(data, keybindings) {
293
678
  }
294
679
  function settingsChatSaveShortcut(keybindings) {
295
680
  return SAVE_SHORTCUTS.find(({ key, inputs }) => {
296
- const matching = inputs.filter((data) => matchesKey(data, key));
681
+ const matching = inputs.filter((data) => matchesKey2(data, key));
297
682
  return matching.length > 0 && matching.every((data) => !saveKeyReserved(data, keybindings));
298
683
  })?.key;
299
684
  }
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
685
  var SettingsChatEditor = class extends CustomEditor {
338
686
  constructor(tui, chromeTheme, labels, chatKeys) {
339
687
  super(
@@ -352,40 +700,11 @@ var SettingsChatEditor = class extends CustomEditor {
352
700
  );
353
701
  this.chromeTheme = chromeTheme;
354
702
  this.labels = labels;
355
- this.chatKeys = chatKeys;
356
703
  }
357
704
  chromeTheme;
358
705
  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
706
  /** Bypass app shortcuts while the native Editor owns a bracketed paste. */
387
707
  handlePasteInput(data) {
388
- this.awaitingJump = void 0;
389
708
  Editor.prototype.handleInput.call(this, data);
390
709
  }
391
710
  renderTopBorder(width, hiddenLineCount) {
@@ -403,14 +722,28 @@ var SettingsChatEditor = class extends CustomEditor {
403
722
  }).render(width)[0] ?? "";
404
723
  }
405
724
  };
725
+ var ROOT_VIEWPORT_ACTIONS = [
726
+ "tui.altScreen.search",
727
+ "tui.altScreen.pageUp",
728
+ "tui.altScreen.pageDown",
729
+ "tui.altScreen.halfPageUp",
730
+ "tui.altScreen.halfPageDown",
731
+ "tui.altScreen.lineUp",
732
+ "tui.altScreen.lineDown",
733
+ "tui.altScreen.previousPrompt",
734
+ "tui.altScreen.nextPrompt",
735
+ "tui.altScreen.top",
736
+ "tui.altScreen.bottom"
737
+ ];
406
738
  function settingsChatStopInput(data, keybindings) {
407
739
  const editorKeys = getKeybindings();
408
740
  const parsed = parseKey(data);
409
741
  const textKey = parsed?.startsWith("shift+") ? parsed.slice(6) : parsed;
410
742
  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");
743
+ 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
744
  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));
745
+ const viewport = ROOT_VIEWPORT_ACTIONS.some((action) => editorKeys.matches(data, action));
746
+ return !viewport && !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey2(data, Key.escape));
414
747
  }
415
748
  function createSettingsChatComponent(options) {
416
749
  const { agent, draft, state, tui, theme, keybindings, signal } = options;
@@ -418,16 +751,6 @@ function createSettingsChatComponent(options) {
418
751
  let inPaste = false;
419
752
  let pending;
420
753
  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
754
  const queued = [];
432
755
  const editor = new SettingsChatEditor(
433
756
  tui,
@@ -443,12 +766,17 @@ function createSettingsChatComponent(options) {
443
766
  },
444
767
  keybindings
445
768
  );
446
- editor.onTranscriptPage = (direction) => scrollHistory(direction * Math.max(1, historyRows));
447
769
  editor.setText(state.input);
448
770
  const render = () => {
449
771
  if (!disposed && !signal.aborted) tui.requestRender();
450
772
  };
451
- const transcript = createSettingsChatTranscript(agent, tui, draft.directory);
773
+ const transcript = createSettingsChatTranscript(
774
+ agent,
775
+ tui,
776
+ draft.directory,
777
+ state.toolsExpanded ?? false,
778
+ draft.path
779
+ );
452
780
  const unsubscribe = agent.subscribe((event) => {
453
781
  if (event.type === "message_start") {
454
782
  const index = queued.findIndex((item) => item.message === event.message);
@@ -517,26 +845,21 @@ function createSettingsChatComponent(options) {
517
845
  editor.onSubmit = (input) => submit(input, "steer");
518
846
  editor.onAction("app.message.followUp", () => submit(editor.getExpandedText().trim(), "followUp"));
519
847
  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
- },
848
+ editor.onAction("app.tools.expand", () => {
849
+ state.toolsExpanded = transcript.toggleTools();
850
+ });
851
+ const dock = {
528
852
  render(width) {
529
- historyRows = 0;
530
853
  if (disposed || signal.aborted || width <= 0) return [];
531
854
  const rows = Math.max(0, Math.floor(Number.isFinite(tui.terminal.rows) ? tui.terminal.rows : 24));
532
855
  if (rows === 0) return [];
533
- const input = editor.render(width);
856
+ const input = editor.render(Math.max(3, width)).map((line) => truncateToWidth(line, width, ""));
534
857
  const cursor = Math.max(
535
858
  0,
536
859
  input.findIndex((line) => line.includes(CURSOR_MARKER))
537
860
  );
538
861
  const preview = options.preview(width);
539
- const diagnostics = sanitizeTerminalDocument2(state.error || agent.state.errorMessage || draft.diagnostics).split("\n").filter(Boolean).slice(0, 3);
862
+ const diagnostics = sanitizeTerminalDocument4(state.error || agent.state.errorMessage || draft.diagnostics).split("\n").filter(Boolean).slice(0, 3);
540
863
  const details = diagnostics.map((line) => theme.fg("muted", line));
541
864
  if (input.length + preview.length > rows) {
542
865
  return renderBoundedFrame({
@@ -556,40 +879,66 @@ function createSettingsChatComponent(options) {
556
879
  ].slice(0, Math.min(3, rows - input.length - preview.length - detailLines.length)).map(
557
880
  (item) => theme.fg(
558
881
  "dim",
559
- `${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument2(item.text).replace(/\n/gu, " ")}`
882
+ `${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument4(item.text).replace(/\n/gu, " ")}`
560
883
  )
561
884
  );
562
885
  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
- );
886
+ return content.map((line) => truncateToWidth(line, width, ""));
887
+ },
888
+ invalidate() {
889
+ editor.invalidate();
890
+ }
891
+ };
892
+ const history = {
893
+ render(width) {
894
+ scroll.anchor = scroll.isFollowingEnd ? void 0 : transcript.anchorAt(scroll.scrollTop);
895
+ return transcript.render(width);
896
+ },
897
+ invalidate() {
898
+ transcript.invalidate();
899
+ },
900
+ handleMouse: (event) => transcript.handleMouse(event)
901
+ };
902
+ const scroll = new SettingsChatScrollView(history, {
903
+ primary: true,
904
+ follow: "end",
905
+ scrollbar: "auto",
906
+ scrollbarTrackStyle: (text) => theme.fg("scrollbarTrack", text),
907
+ scrollbarThumbStyle: (text) => theme.fg("scrollbarThumb", text)
908
+ });
909
+ scroll.restoreAnchor = (anchor) => transcript.rowAt(anchor);
910
+ const layout = new VStack([
911
+ { component: scroll, basis: 0, grow: 1, minSize: 0 },
912
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
913
+ ]);
914
+ return {
915
+ getFullscreenLayout() {
916
+ return layout;
917
+ },
918
+ get focused() {
919
+ return editor.focused;
920
+ },
921
+ set focused(value) {
922
+ editor.focused = value;
923
+ },
924
+ render(width) {
925
+ if (disposed || signal.aborted || width <= 0 || tui.terminal.rows <= 0) return [];
926
+ return layout.render(width);
578
927
  },
579
928
  invalidate() {
580
929
  editor.invalidate();
581
930
  transcript.invalidate();
582
931
  },
583
932
  handleInput(data) {
584
- if (disposed || signal.aborted || isKeyRelease(data)) return;
933
+ if (disposed || signal.aborted || isKeyRelease2(data)) return;
585
934
  const saveKey = !pending && draft.candidate ? settingsChatSaveShortcut(keybindings) : void 0;
586
935
  if (inPaste || data.includes("\x1B[200~")) {
587
936
  inPaste = !data.includes("\x1B[201~");
588
937
  editor.handlePasteInput(data);
589
- } else if (matchesKey(data, Key.ctrl("c"))) {
938
+ } else if (matchesKey2(data, Key.ctrl("c"))) {
590
939
  abort();
591
940
  options.complete("discard");
592
- } else if (saveKey && matchesKey(data, saveKey) && !saveKeyReserved(data, keybindings)) {
941
+ } else if (saveKey && matchesKey2(data, saveKey) && !saveKeyReserved(data, keybindings)) {
593
942
  state.input = editor.getExpandedText();
594
943
  options.complete("save");
595
944
  } else if (settingsChatStopInput(data, keybindings)) {
@@ -601,12 +950,6 @@ function createSettingsChatComponent(options) {
601
950
  } else editor.handleInput(data);
602
951
  render();
603
952
  },
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
953
  dispose() {
611
954
  if (disposed) return;
612
955
  disposed = true;
@@ -614,6 +957,8 @@ function createSettingsChatComponent(options) {
614
957
  signal.removeEventListener("abort", abort);
615
958
  unsubscribe();
616
959
  transcript.dispose();
960
+ scroll.setScrollbarActive(false);
961
+ scroll.setScrollbar("hidden");
617
962
  abort();
618
963
  },
619
964
  async waitForPending() {
@@ -623,33 +968,13 @@ function createSettingsChatComponent(options) {
623
968
  };
624
969
  }
625
970
  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";
971
+ state.toolsExpanded ??= ctx.ui.getToolsExpanded?.() ?? false;
972
+ return runSettingsChatFullscreen(
973
+ ctx,
974
+ owner,
975
+ ({ tui, theme, keybindings, signal, complete }) => createSettingsChatComponent({ agent, draft, state, tui, theme, keybindings, signal, preview, complete }),
976
+ "discard"
977
+ );
653
978
  }
654
979
 
655
980
  // src/settings-draft.ts
@@ -666,7 +991,7 @@ import {
666
991
  writeFileSync
667
992
  } from "node:fs";
668
993
  import { tmpdir } from "node:os";
669
- import { isAbsolute, join as join2, relative, resolve } from "node:path";
994
+ import { isAbsolute, join as join2, relative, resolve as resolve2 } from "node:path";
670
995
  import {
671
996
  createEditTool,
672
997
  createReadTool,
@@ -696,7 +1021,7 @@ function createSettingsDraft(options) {
696
1021
  };
697
1022
  const assertDraft = (target) => {
698
1023
  assertCurrent();
699
- if (resolve(target) !== path || realpathSync(directory) !== directory || realpathSync(path) !== path) {
1024
+ if (resolve2(target) !== path || realpathSync(directory) !== directory || realpathSync(path) !== path) {
700
1025
  throw new Error("Only the owned settings draft can be changed");
701
1026
  }
702
1027
  };
@@ -741,13 +1066,13 @@ function createSettingsDraft(options) {
741
1066
  }
742
1067
  const readAllowed = (target) => {
743
1068
  assertCurrent();
744
- if (resolve(target) === resolve(options.settingsPath)) {
1069
+ if (resolve2(target) === resolve2(options.settingsPath)) {
745
1070
  if (!baseline) throw new Error("The active settings file was missing when this preview started");
746
1071
  return Buffer.from(baseline);
747
1072
  }
748
- if (resolve(target) === path) return readDraft();
749
- if (snapshots.has(resolve(target))) {
750
- const content = snapshots.get(resolve(target));
1073
+ if (resolve2(target) === path) return readDraft();
1074
+ if (snapshots.has(resolve2(target))) {
1075
+ const content = snapshots.get(resolve2(target));
751
1076
  if (content === void 0)
752
1077
  throw new Error(
753
1078
  "No exact loaded settings document is available; read active-state.json for its source and diagnostics"
@@ -986,10 +1311,12 @@ async function showSettingsAgentChat(ctx, options, base) {
986
1311
  return captureCommitExpectation(options);
987
1312
  });
988
1313
  if (!expected || base.signal.aborted || !base.isCurrent()) return "close";
1314
+ const chatLifetime = new AbortController();
989
1315
  const owner = {
990
- signal: base.signal,
991
- isCurrent: () => commitOwnerCurrent(options, base, expected),
992
- isSessionCurrent: base.isSessionCurrent ?? base.isCurrent
1316
+ signal: AbortSignal.any([base.signal, chatLifetime.signal]),
1317
+ isCurrent: () => !chatLifetime.signal.aborted && commitOwnerCurrent(options, base, expected),
1318
+ isSessionCurrent: base.isSessionCurrent ?? base.isCurrent,
1319
+ canRestoreTerminal: base.canRestoreTerminal
993
1320
  };
994
1321
  const packageRoot = starshipPackageRoot();
995
1322
  const draft = createSettingsDraft({
@@ -1004,12 +1331,15 @@ async function showSettingsAgentChat(ctx, options, base) {
1004
1331
  });
1005
1332
  let agent;
1006
1333
  let closing;
1334
+ let activeChat;
1007
1335
  const cleanup = () => {
1008
1336
  if (closing) return closing;
1337
+ chatLifetime.abort();
1009
1338
  agent?.abort();
1339
+ const pendingChat = activeChat;
1010
1340
  closing = (async () => {
1011
1341
  try {
1012
- await agent?.waitForIdle();
1342
+ await Promise.all([agent?.waitForIdle(), pendingChat]);
1013
1343
  } finally {
1014
1344
  agent?.reset();
1015
1345
  draft.dispose();
@@ -1031,7 +1361,13 @@ async function showSettingsAgentChat(ctx, options, base) {
1031
1361
  if (!owner.isCurrent()) return "close";
1032
1362
  agent = createSettingsAgent(ctx, draft, packageRoot);
1033
1363
  while (owner.isCurrent()) {
1034
- const action = await showSettingsChat(ctx, agent, draft, state, owner, preview);
1364
+ activeChat = showSettingsChat(ctx, agent, draft, state, owner, preview);
1365
+ let action;
1366
+ try {
1367
+ action = await activeChat;
1368
+ } finally {
1369
+ activeChat = void 0;
1370
+ }
1035
1371
  if (!owner.isCurrent() || action === "discard") return "close";
1036
1372
  if (!draft.candidate) continue;
1037
1373
  const candidate = draft.candidate;
@@ -1052,7 +1388,7 @@ async function showSettingsAgentChat(ctx, options, base) {
1052
1388
  const confirmed = await ctx.ui.confirm(
1053
1389
  "Apply saved profile?",
1054
1390
  [
1055
- `Profile saved: ${sanitizeTerminalDocument3(saved.name)}. Apply it to the current footer without reload?`,
1391
+ `Profile saved: ${sanitizeTerminalDocument5(saved.name)}. Apply it to the current footer without reload?`,
1056
1392
  "This replaces the complete active settings document. Declining keeps the profile and leaves active settings unchanged.",
1057
1393
  "Applying can run enabled module commands and network requests; review their configuration before accepting.",
1058
1394
  "The previous file is retained in History. Detected concurrent edits block replacement.",
@@ -1073,7 +1409,7 @@ async function showSettingsAgentChat(ctx, options, base) {
1073
1409
  } catch (error) {
1074
1410
  if (!base.signal.aborted && base.isCurrent())
1075
1411
  ctx.ui.notify(
1076
- `Profile was saved as ${sanitizeTerminalDocument3(saved.name)}. Settings were not applied: ${sanitizeTerminalDocument3(error instanceof Error ? error.message : String(error))}`,
1412
+ `Profile was saved as ${sanitizeTerminalDocument5(saved.name)}. Settings were not applied: ${sanitizeTerminalDocument5(error instanceof Error ? error.message : String(error))}`,
1077
1413
  "error"
1078
1414
  );
1079
1415
  }
@@ -1121,4 +1457,4 @@ async function reviewText(ctx, owner, title, content, toml) {
1121
1457
  export {
1122
1458
  showSettingsAgentChat
1123
1459
  };
1124
- //# sourceMappingURL=command-settings-chat-5AHP3JGV.ts.map
1460
+ //# sourceMappingURL=command-settings-chat-B2FCDVBH.ts.map