@narumitw/pi-starship 0.60.1 → 0.63.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.
Files changed (115) hide show
  1. package/README.md +67 -9
  2. package/dist/chunks/chunk-63R6R5DH.ts +679 -0
  3. package/dist/chunks/chunk-63R6R5DH.ts.map +7 -0
  4. package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-A65IOGL6.ts} +858 -1007
  5. package/dist/chunks/chunk-A65IOGL6.ts.map +7 -0
  6. package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
  7. package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
  8. package/dist/chunks/chunk-KP33I6BR.ts +579 -0
  9. package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
  10. package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
  11. package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
  12. package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
  13. package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
  14. package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
  15. package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
  16. package/dist/chunks/chunk-Y24TJYG6.ts +1586 -0
  17. package/dist/chunks/chunk-Y24TJYG6.ts.map +7 -0
  18. package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
  19. package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
  20. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts +147 -0
  21. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts.map +7 -0
  22. package/dist/chunks/command-settings-chat-5AHP3JGV.ts +1124 -0
  23. package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +7 -0
  24. package/dist/chunks/commands-IOG2PL67.ts +1026 -0
  25. package/dist/chunks/commands-IOG2PL67.ts.map +7 -0
  26. package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
  27. package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
  28. package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
  29. package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
  30. package/dist/chunks/directory-OX6BWJZA.ts +31 -0
  31. package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
  32. package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
  33. package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
  34. package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
  35. package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
  36. package/dist/chunks/languages-CBQNNYXM.ts +262 -0
  37. package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
  38. package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
  39. package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
  40. package/dist/chunks/system-574MHB4R.ts +165 -0
  41. package/dist/chunks/system-574MHB4R.ts.map +7 -0
  42. package/dist/index.ts +670 -206
  43. package/dist/index.ts.map +4 -4
  44. package/package.json +5 -1
  45. package/skills/configure-pi-starship/SKILL.md +17 -1
  46. package/skills/configure-pi-starship/references/configuration.md +119 -32
  47. package/skills/configure-pi-starship/references/module-catalog.md +278 -25
  48. package/skills/configure-pi-starship/references/modules.md +213 -36
  49. package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
  50. package/src/command-commit.ts +41 -7
  51. package/src/command-configuration-menu.ts +155 -0
  52. package/src/command-configuration.ts +15 -94
  53. package/src/command-preview.ts +3 -3
  54. package/src/command-settings-chat.ts +168 -0
  55. package/src/commands.ts +76 -124
  56. package/src/config/module-options.ts +112 -0
  57. package/src/config.ts +23 -59
  58. package/src/effective-config.ts +5 -4
  59. package/src/format/bounded-regex.ts +66 -0
  60. package/src/format/version.ts +24 -0
  61. package/src/modules/catalog.ts +10 -0
  62. package/src/modules/cloud.ts +1 -0
  63. package/src/modules/deployment.ts +8 -0
  64. package/src/modules/development.ts +20 -2
  65. package/src/modules/directory.ts +171 -51
  66. package/src/modules/execution.ts +2 -0
  67. package/src/modules/git/branch.ts +19 -4
  68. package/src/modules/git/commit.ts +9 -2
  69. package/src/modules/git/metrics.ts +9 -4
  70. package/src/modules/git/runtime.ts +122 -33
  71. package/src/modules/git/state.ts +23 -2
  72. package/src/modules/git/status-templates.ts +58 -0
  73. package/src/modules/git/status.ts +96 -30
  74. package/src/modules/jujutsu.ts +225 -0
  75. package/src/modules/languages.ts +26 -2
  76. package/src/modules/package.ts +1 -0
  77. package/src/modules/render.ts +42 -16
  78. package/src/modules/system.ts +54 -0
  79. package/src/modules/time-format.ts +188 -0
  80. package/src/modules/time.ts +11 -5
  81. package/src/modules/types.ts +42 -4
  82. package/src/pi-starship.ts +198 -88
  83. package/src/profile-store.ts +5 -0
  84. package/src/runtime/cloud.ts +3 -0
  85. package/src/runtime/command.ts +1 -1
  86. package/src/runtime/deployment.ts +120 -4
  87. package/src/runtime/development.ts +86 -13
  88. package/src/runtime/directory.ts +33 -0
  89. package/src/runtime/execution.ts +12 -2
  90. package/src/runtime/helpers.ts +57 -8
  91. package/src/runtime/jujutsu.ts +225 -0
  92. package/src/runtime/languages.ts +106 -19
  93. package/src/runtime/package.ts +3 -0
  94. package/src/runtime/system.ts +202 -0
  95. package/src/runtime/types.ts +3 -0
  96. package/src/runtime/version-requirements.ts +30 -0
  97. package/src/runtime/workspace.ts +12 -1
  98. package/src/settings-agent.ts +80 -0
  99. package/src/settings-chat-transcript.ts +192 -0
  100. package/src/settings-chat-ui.ts +526 -0
  101. package/src/settings-draft.ts +260 -0
  102. package/src/settings-snapshots.ts +41 -0
  103. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  104. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  105. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  106. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  107. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  108. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  109. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  110. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  111. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  112. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  113. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  114. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  115. package/src/command-inspector.ts +0 -41
@@ -0,0 +1,526 @@
1
+ import type { Agent } from "@earendil-works/pi-agent-core";
2
+ import type { UserMessage } from "@earendil-works/pi-ai";
3
+ import {
4
+ CustomEditor,
5
+ type ExtensionCommandContext,
6
+ type KeybindingsManager,
7
+ type Theme,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import {
10
+ CURSOR_MARKER,
11
+ decodeKittyPrintable,
12
+ Editor,
13
+ getKeybindings,
14
+ isKeyRelease,
15
+ Key,
16
+ matchesKey,
17
+ parseKey,
18
+ type TUI,
19
+ TUI_KEYBINDINGS,
20
+ type TuiMouseEvent,
21
+ truncateToWidth,
22
+ } from "@earendil-works/pi-tui";
23
+ import { HorizontalRule, renderBoundedFrame, runCustomInteraction } from "@narumitw/pi-tui-kit";
24
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
25
+ import type { WorkflowOwner } from "./command-configuration.js";
26
+ import { createSettingsChatTranscript, type SettingsChatAnchor } from "./settings-chat-transcript.js";
27
+ import type { SettingsDraft } from "./settings-draft.js";
28
+
29
+ export type SettingsChatAction = "save" | "discard";
30
+
31
+ const SAVE_SHORTCUTS = [
32
+ { key: "ctrl+s", inputs: ["\x13", "\x1b[115;5u", "\x1b[27;5;115~"] },
33
+ { key: "f2", inputs: ["\x1bOQ", "\x1b[12~", "\x1b[[B"] },
34
+ ] as const;
35
+
36
+ /** Never replace native editing, cancellation, or registered message actions. */
37
+ function saveKeyReserved(data: string, keybindings: Pick<KeybindingsManager, "matches">): boolean {
38
+ const editorKeys = getKeybindings();
39
+ return (
40
+ (Object.keys(TUI_KEYBINDINGS) as Array<keyof typeof TUI_KEYBINDINGS>).some(
41
+ (action) => editorKeys.matches(data, action) || keybindings.matches(data, action),
42
+ ) ||
43
+ (
44
+ [
45
+ "app.clipboard.pasteImage",
46
+ "app.interrupt",
47
+ "app.exit",
48
+ "app.message.followUp",
49
+ "app.message.dequeue",
50
+ "app.tools.expand",
51
+ ] as const
52
+ ).some((action) => keybindings.matches(data, action))
53
+ );
54
+ }
55
+
56
+ /** Check supported input encodings through Pi's matcher before displaying a save hint. */
57
+ export function settingsChatSaveShortcut(
58
+ keybindings: Pick<KeybindingsManager, "matches">,
59
+ ): "ctrl+s" | "f2" | undefined {
60
+ return SAVE_SHORTCUTS.find(({ key, inputs }) => {
61
+ const matching = inputs.filter((data) => matchesKey(data, key));
62
+ return matching.length > 0 && matching.every((data) => !saveKeyReserved(data, keybindings));
63
+ })?.key;
64
+ }
65
+
66
+ export interface ChatViewState {
67
+ input: string;
68
+ error: string;
69
+ }
70
+
71
+ // Installed Editor.handleInput actions before pageUp/pageDown, in native order.
72
+ // No autocomplete provider is installed in this chat. Jump triggers come AFTER paging.
73
+ const BEFORE_PAGE_ACTIONS = [
74
+ "tui.input.copy",
75
+ "tui.editor.undo",
76
+ "tui.input.tab",
77
+ "tui.editor.deleteToLineEnd",
78
+ "tui.editor.deleteToLineStart",
79
+ "tui.editor.deleteWordBackward",
80
+ "tui.editor.deleteWordForward",
81
+ "tui.editor.deleteCharBackward",
82
+ "tui.editor.deleteCharForward",
83
+ "tui.editor.yank",
84
+ "tui.editor.yankPop",
85
+ "tui.editor.historyPrevious",
86
+ "tui.editor.historyNext",
87
+ "tui.editor.cursorLineStart",
88
+ "tui.editor.cursorLineEnd",
89
+ "tui.editor.cursorWordLeft",
90
+ "tui.editor.cursorWordRight",
91
+ "tui.input.newLine",
92
+ "tui.input.submit",
93
+ "tui.editor.cursorUp",
94
+ "tui.editor.cursorDown",
95
+ "tui.editor.cursorRight",
96
+ "tui.editor.cursorLeft",
97
+ ] as const;
98
+
99
+ /** Match Editor's printable jump targets without a Jiti-incompatible package subpath. */
100
+ function nativeJumpPrintable(data: string): boolean {
101
+ if (decodeKittyPrintable(data) !== undefined || data.charCodeAt(0) >= 32) return true;
102
+ // Editor also accepts plain/Shift modifyOtherKeys text, ignoring Caps/Num Lock bits.
103
+ if (!data.startsWith("\x1b[27;")) return false;
104
+ const match = /^(\d+);(\d+)~$/u.exec(data.slice(5));
105
+ if (!match) return false;
106
+ const modifier = Number(match[1]) - 1;
107
+ const codepoint = Number(match[2]);
108
+ return (modifier & ~(1 | 64 | 128)) === 0 && codepoint >= 32 && codepoint <= 0x10ffff;
109
+ }
110
+
111
+ function nativeBeforePage(data: string): boolean {
112
+ return (
113
+ BEFORE_PAGE_ACTIONS.some((action) => getKeybindings().matches(data, action)) ||
114
+ matchesKey(data, "shift+backspace") ||
115
+ matchesKey(data, "shift+delete") ||
116
+ data.charCodeAt(0) === 10 ||
117
+ data === "\x1b\r" ||
118
+ data === "\x1b[13;2~" ||
119
+ (data.length > 1 && data.includes("\x1b") && data.includes("\r"))
120
+ );
121
+ }
122
+
123
+ /** Add labels only to the public Editor border hooks; native scroll indicators keep priority. */
124
+ export class SettingsChatEditor extends CustomEditor {
125
+ onTranscriptPage?: (direction: -1 | 1) => void;
126
+ private awaitingJump: string | undefined;
127
+ constructor(
128
+ tui: TUI,
129
+ private readonly chromeTheme: Theme,
130
+ private readonly labels: () => { top: string; bottom: string },
131
+ private readonly chatKeys: KeybindingsManager,
132
+ ) {
133
+ super(
134
+ tui,
135
+ {
136
+ borderColor: (text) => chromeTheme.fg("borderMuted", text),
137
+ selectList: {
138
+ selectedPrefix: (text) => chromeTheme.fg("accent", text),
139
+ selectedText: (text) => chromeTheme.fg("accent", text),
140
+ description: (text) => chromeTheme.fg("muted", text),
141
+ scrollInfo: (text) => chromeTheme.fg("dim", text),
142
+ noMatch: (text) => chromeTheme.fg("warning", text),
143
+ },
144
+ },
145
+ chatKeys,
146
+ );
147
+ }
148
+ handleInput(data: string): void {
149
+ const kb = getKeybindings();
150
+ // These CustomEditor branches consume input before reaching Editor, even
151
+ // without a handler. Explicit history bypasses registered message actions.
152
+ const interrupt = this.chatKeys.matches(data, "app.interrupt");
153
+ const appConsumes =
154
+ this.chatKeys.matches(data, "app.clipboard.pasteImage") ||
155
+ (interrupt && this.onEscape !== undefined) ||
156
+ (!interrupt && this.chatKeys.matches(data, "app.exit") && this.getText().length === 0);
157
+ const history =
158
+ this.chatKeys.matches(data, "tui.editor.historyPrevious") ||
159
+ this.chatKeys.matches(data, "tui.editor.historyNext");
160
+ const registeredAction =
161
+ !interrupt &&
162
+ !history &&
163
+ (this.chatKeys.matches(data, "app.message.followUp") ||
164
+ this.chatKeys.matches(data, "app.message.dequeue") ||
165
+ this.chatKeys.matches(data, "app.tools.expand"));
166
+ if (appConsumes || registeredAction) {
167
+ super.handleInput(data);
168
+ return;
169
+ }
170
+ const jump = kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward");
171
+ const pendingJump = this.awaitingJump;
172
+ const jumpConsumes = pendingJump !== undefined && (jump || nativeJumpPrintable(data));
173
+ this.awaitingJump = undefined;
174
+ const earlier = nativeBeforePage(data);
175
+ const direction = kb.matches(data, "tui.editor.pageUp")
176
+ ? -1
177
+ : kb.matches(data, "tui.editor.pageDown")
178
+ ? 1
179
+ : undefined;
180
+ // The chat registers no interrupt handler. CustomEditor forwards it to
181
+ // Editor, then returns; retain that branch and its jump-state transition.
182
+ if (!interrupt && !jumpConsumes && !earlier && direction !== undefined && this.onTranscriptPage) {
183
+ // Repeating the trigger cancels native jump mode without moving the editor.
184
+ if (pendingJump !== undefined) Editor.prototype.handleInput.call(this, pendingJump);
185
+ this.onTranscriptPage(direction);
186
+ return;
187
+ }
188
+ if (!jumpConsumes && !earlier && direction === undefined && jump) this.awaitingJump = data;
189
+ super.handleInput(data);
190
+ }
191
+ /** Bypass app shortcuts while the native Editor owns a bracketed paste. */
192
+ handlePasteInput(data: string): void {
193
+ this.awaitingJump = undefined;
194
+ Editor.prototype.handleInput.call(this, data);
195
+ }
196
+ protected renderTopBorder(width: number, hiddenLineCount: number): string {
197
+ return hiddenLineCount > 0
198
+ ? super.renderTopBorder(width, hiddenLineCount)
199
+ : this.labeledBorder(width, this.labels().top);
200
+ }
201
+ protected renderBottomBorder(width: number, hiddenLineCount: number): string {
202
+ return hiddenLineCount > 0
203
+ ? super.renderBottomBorder(width, hiddenLineCount)
204
+ : this.labeledBorder(width, this.labels().bottom);
205
+ }
206
+ private labeledBorder(width: number, label: string): string {
207
+ return (
208
+ new HorizontalRule({
209
+ label,
210
+ labelAlignment: "left",
211
+ ruleStyle: this.borderColor,
212
+ labelStyle: (text) => this.chromeTheme.fg("dim", text),
213
+ }).render(width)[0] ?? ""
214
+ );
215
+ }
216
+ }
217
+
218
+ /** Editor actions win collisions. Escape remains a stop fallback for unusable cancel settings. */
219
+ export function settingsChatStopInput(data: string, keybindings: Pick<KeybindingsManager, "matches">): boolean {
220
+ const editorKeys = getKeybindings();
221
+ const parsed = parseKey(data);
222
+ const textKey = parsed?.startsWith("shift+") ? parsed.slice(6) : parsed;
223
+ const printable =
224
+ data.charCodeAt(0) >= 32 || (textKey !== undefined && (Array.from(textKey).length === 1 || textKey === "space"));
225
+ // These native Editor branches remain active even when their configurable actions are remapped.
226
+ const nativeEditing =
227
+ printable ||
228
+ matchesKey(data, "shift+backspace") ||
229
+ matchesKey(data, "shift+delete") ||
230
+ data.charCodeAt(0) === 10 ||
231
+ data === "\x1b\r" ||
232
+ data === "\x1b[13;2~" ||
233
+ (data.includes("\x1b") && data.includes("\r"));
234
+ const editing =
235
+ nativeEditing ||
236
+ (Object.keys(TUI_KEYBINDINGS) as Array<keyof typeof TUI_KEYBINDINGS>)
237
+ .filter((key) => key.startsWith("tui.editor.") || key.startsWith("tui.input."))
238
+ .some((key) => editorKeys.matches(data, key));
239
+ return !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape));
240
+ }
241
+
242
+ export function createSettingsChatComponent(options: {
243
+ agent: Agent;
244
+ draft: SettingsDraft;
245
+ state: ChatViewState;
246
+ tui: TUI;
247
+ theme: Theme;
248
+ keybindings: KeybindingsManager;
249
+ signal: AbortSignal;
250
+ preview(width: number): string[];
251
+ complete(value: SettingsChatAction): void;
252
+ }) {
253
+ const { agent, draft, state, tui, theme, keybindings, signal } = options;
254
+ let disposed = false;
255
+ let inPaste = false;
256
+ let pending: Promise<void> | undefined;
257
+ let stopping = false;
258
+ // Undefined follows output; message identity keeps retained history stable after eviction.
259
+ let historyTop: number | undefined;
260
+ let historyAnchor: SettingsChatAnchor | undefined;
261
+ let historyRows = 0;
262
+ let historyMaximum = 0;
263
+ const scrollHistory = (delta: number) => {
264
+ const next = Math.max(0, Math.min(historyMaximum, (historyTop ?? historyMaximum) + delta));
265
+ historyTop = next === historyMaximum ? undefined : next;
266
+ historyAnchor = historyTop === undefined ? undefined : transcript.anchorAt(historyTop);
267
+ render();
268
+ };
269
+ const queued: Array<{ kind: "steer" | "followUp"; message: UserMessage; text: string }> = [];
270
+ const editor = new SettingsChatEditor(
271
+ tui,
272
+ theme,
273
+ () => {
274
+ const status =
275
+ state.error || agent.state.errorMessage
276
+ ? "Agent error"
277
+ : !draft.candidate
278
+ ? "Invalid"
279
+ : draft.diagnostics
280
+ ? "Warnings"
281
+ : "Valid";
282
+ const saveKey = !pending && !inPaste && draft.candidate ? settingsChatSaveShortcut(keybindings) : undefined;
283
+ // Match Pi core: sentence-case states and lowercase key + "to" action hints.
284
+ const working = !inPaste && settingsChatStopInput("\x1b", keybindings) ? "Working · esc to interrupt" : "Working";
285
+ return {
286
+ top: queued.length > 0 ? `pi-starship · ${queued.length} queued` : "pi-starship",
287
+ bottom: `${status} · unsaved · ${pending ? working : saveKey ? `${saveKey} to save profile` : "Idle"} · ctrl+c to discard`,
288
+ };
289
+ },
290
+ keybindings,
291
+ );
292
+ editor.onTranscriptPage = (direction) => scrollHistory(direction * Math.max(1, historyRows));
293
+ editor.setText(state.input);
294
+ const render = () => {
295
+ if (!disposed && !signal.aborted) tui.requestRender();
296
+ };
297
+ // Update transcript identities before this listener requests the next frame.
298
+ const transcript = createSettingsChatTranscript(agent, tui, draft.directory);
299
+ const unsubscribe = agent.subscribe((event) => {
300
+ if (event.type === "message_start") {
301
+ const index = queued.findIndex((item) => item.message === event.message);
302
+ if (index >= 0) queued.splice(index, 1);
303
+ }
304
+ render();
305
+ });
306
+ const clearQueue = () => {
307
+ queued.length = 0;
308
+ agent.clearAllQueues();
309
+ };
310
+ const restoreQueue = () => {
311
+ const messages = [
312
+ ...queued.filter((item) => item.kind === "steer"),
313
+ ...queued.filter((item) => item.kind === "followUp"),
314
+ ].map((item) => item.text);
315
+ clearQueue();
316
+ if (messages.length > 0) editor.setText([...messages, editor.getExpandedText()].filter(Boolean).join("\n\n"));
317
+ };
318
+ const abort = () => {
319
+ stopping = true;
320
+ clearQueue();
321
+ agent.abort();
322
+ };
323
+ signal.addEventListener("abort", abort, { once: true });
324
+ const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
325
+ const failed = () => {
326
+ const last = agent.state.messages.at(-1);
327
+ return last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted");
328
+ };
329
+ const submit = (input: string, kind: "steer" | "followUp") => {
330
+ if (signal.aborted || disposed) return;
331
+ if (!input.trim()) return;
332
+ // Native submission clears the editor first. Retain input typed while an abort settles.
333
+ if (pending && stopping) {
334
+ editor.setText(input);
335
+ return;
336
+ }
337
+ editor.addToHistory(input);
338
+ editor.setText("");
339
+ state.error = "";
340
+ if (pending) {
341
+ const message: UserMessage = { role: "user", content: [{ type: "text", text: input }], timestamp: Date.now() };
342
+ queued.push({ kind, message, text: input });
343
+ if (kind === "steer") agent.steer(message);
344
+ else agent.followUp(message);
345
+ } else {
346
+ stopping = false;
347
+ pending = (async () => {
348
+ try {
349
+ await agent.prompt(input);
350
+ // agent_end listeners can enqueue after the loop's final poll. Wait for actual
351
+ // idle settlement before continuing; never resume cancelled or failed runs.
352
+ while (!disposed && !signal.aborted && !stopping && !failed() && agent.hasQueuedMessages()) {
353
+ await agent.continue();
354
+ }
355
+ } catch (error) {
356
+ if (!disposed && !signal.aborted) state.error = error instanceof Error ? error.message : String(error);
357
+ } finally {
358
+ pending = undefined;
359
+ if (!disposed && !signal.aborted) restoreQueue();
360
+ else clearQueue();
361
+ render();
362
+ }
363
+ })();
364
+ }
365
+ render();
366
+ };
367
+ // Native Editor expands paste markers and clears itself before calling onSubmit.
368
+ editor.onSubmit = (input) => submit(input, "steer");
369
+ editor.onAction("app.message.followUp", () => submit(editor.getExpandedText().trim(), "followUp"));
370
+ editor.onAction("app.message.dequeue", restoreQueue);
371
+ editor.onAction("app.tools.expand", () => transcript.toggleTools());
372
+ return {
373
+ get focused() {
374
+ return editor.focused;
375
+ },
376
+ set focused(value: boolean) {
377
+ editor.focused = value;
378
+ },
379
+ render(width: number): string[] {
380
+ historyRows = 0;
381
+ if (disposed || signal.aborted || width <= 0) return [];
382
+ const rows = Math.max(0, Math.floor(Number.isFinite(tui.terminal.rows) ? tui.terminal.rows : 24));
383
+ if (rows === 0) return [];
384
+ const input = editor.render(width);
385
+ const cursor = Math.max(
386
+ 0,
387
+ input.findIndex((line) => line.includes(CURSOR_MARKER)),
388
+ );
389
+ const preview = options.preview(width);
390
+ const diagnostics = sanitizeTerminalDocument(state.error || agent.state.errorMessage || draft.diagnostics)
391
+ .split("\n")
392
+ .filter(Boolean)
393
+ .slice(0, 3);
394
+ // Match Pi's transcript -> editor -> footer hierarchy. The fullscreen overlay
395
+ // covers the parent footer, so the real draft preview is part of this dock.
396
+ const details = diagnostics.map((line) => theme.fg("muted", line));
397
+ // Render the footer without extra rules, matching its saved position at the terminal bottom.
398
+ if (input.length + preview.length > rows) {
399
+ return renderBoundedFrame({
400
+ width,
401
+ maxRows: rows,
402
+ rule: rule.render(width)[0] ?? "",
403
+ title: [],
404
+ content: [...input, theme.fg("muted", "Footer preview hidden — enlarge the terminal"), ...details],
405
+ focusedRow: cursor,
406
+ priorityRows: [cursor, input.length],
407
+ });
408
+ }
409
+ const detailLines = details.slice(0, rows - input.length - preview.length);
410
+ const queueLines = [
411
+ ...queued.filter((item) => item.kind === "steer"),
412
+ ...queued.filter((item) => item.kind === "followUp"),
413
+ ]
414
+ .slice(0, Math.min(3, rows - input.length - preview.length - detailLines.length))
415
+ .map((item) =>
416
+ theme.fg(
417
+ "dim",
418
+ `${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument(item.text).replace(/\n/gu, " ")}`,
419
+ ),
420
+ );
421
+ const content = [...queueLines, ...input, ...detailLines, ...preview];
422
+ const available = rows - content.length;
423
+ historyRows = available;
424
+ // Keep the anchor while the dock temporarily leaves no room for history.
425
+ if (available === 0) return content.map((line) => truncateToWidth(line, width, ""));
426
+ const lines = transcript.render(width);
427
+ historyMaximum = Math.max(0, lines.length - available);
428
+ if (historyTop !== undefined) {
429
+ historyTop = Math.min(historyAnchor ? transcript.rowAt(historyAnchor) : historyTop, historyMaximum);
430
+ if (historyTop === historyMaximum) historyTop = undefined;
431
+ }
432
+ const top = historyTop ?? historyMaximum;
433
+ historyAnchor = historyTop === undefined ? undefined : transcript.anchorAt(top);
434
+ const history = lines.slice(top, top + available);
435
+ return [...history, ...Array.from({ length: available - history.length }, () => ""), ...content].map((line) =>
436
+ truncateToWidth(line, width, ""),
437
+ );
438
+ },
439
+ invalidate() {
440
+ editor.invalidate();
441
+ transcript.invalidate();
442
+ },
443
+ handleInput(data: string) {
444
+ if (disposed || signal.aborted || isKeyRelease(data)) return;
445
+ const saveKey = !pending && draft.candidate ? settingsChatSaveShortcut(keybindings) : undefined;
446
+ // Forward entire paste packets and fragments without interpreting embedded shortcuts.
447
+ if (inPaste || data.includes("\x1b[200~")) {
448
+ inPaste = !data.includes("\x1b[201~");
449
+ editor.handlePasteInput(data);
450
+ } else if (matchesKey(data, Key.ctrl("c"))) {
451
+ abort();
452
+ options.complete("discard");
453
+ } else if (saveKey && matchesKey(data, saveKey) && !saveKeyReserved(data, keybindings)) {
454
+ state.input = editor.getExpandedText();
455
+ options.complete("save");
456
+ } else if (settingsChatStopInput(data, keybindings)) {
457
+ if (pending) {
458
+ stopping = true;
459
+ restoreQueue();
460
+ agent.abort();
461
+ }
462
+ } else editor.handleInput(data);
463
+ render();
464
+ },
465
+ handleMouse(event: TuiMouseEvent) {
466
+ if (disposed || signal.aborted || inPaste || historyRows === 0 || event.type !== "wheel" || !event.wheelDelta)
467
+ return undefined;
468
+ scrollHistory(event.wheelDelta < 0 ? -3 : 3);
469
+ return { handled: true, render: true };
470
+ },
471
+ dispose() {
472
+ if (disposed) return;
473
+ disposed = true;
474
+ state.input = editor.getExpandedText();
475
+ signal.removeEventListener("abort", abort);
476
+ unsubscribe();
477
+ transcript.dispose();
478
+ abort();
479
+ },
480
+ async waitForPending() {
481
+ await pending;
482
+ await agent.waitForIdle();
483
+ },
484
+ };
485
+ }
486
+
487
+ export async function showSettingsChat(
488
+ ctx: ExtensionCommandContext,
489
+ agent: Agent,
490
+ draft: SettingsDraft,
491
+ state: ChatViewState,
492
+ owner: WorkflowOwner,
493
+ preview: (width: number) => string[],
494
+ ): Promise<SettingsChatAction> {
495
+ // Keep Kit's cancellation/disposal runner, but mount through Pi's public overlay API.
496
+ // No second TUI, terminal handoff, or manipulation of unrelated overlay handles is needed.
497
+ const fullscreenContext: ExtensionCommandContext = {
498
+ ...ctx,
499
+ ui: {
500
+ ...ctx.ui,
501
+ custom: (factory) =>
502
+ ctx.ui.custom(factory, {
503
+ overlay: true,
504
+ overlayOptions: { width: "100%", maxHeight: "100%", anchor: "top-left", margin: 0 },
505
+ }),
506
+ },
507
+ };
508
+ const result = await runCustomInteraction<SettingsChatAction>(fullscreenContext, {
509
+ signal: owner.signal,
510
+ isCurrent: owner.isCurrent,
511
+ create: ({ tui, theme, keybindings, signal, complete }) =>
512
+ createSettingsChatComponent({
513
+ agent,
514
+ draft,
515
+ state,
516
+ tui,
517
+ theme,
518
+ keybindings,
519
+ signal,
520
+ preview,
521
+ complete,
522
+ }),
523
+ });
524
+ if (result.kind === "error") throw result.error;
525
+ return result.kind === "completed" ? result.value : "discard";
526
+ }