@narumitw/pi-starship 0.60.1 → 0.62.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.
- package/README.md +63 -6
- package/dist/chunks/chunk-43VIENBN.ts +1586 -0
- package/dist/chunks/chunk-43VIENBN.ts.map +7 -0
- package/dist/chunks/chunk-HPZTMIZS.ts +646 -0
- package/dist/chunks/chunk-HPZTMIZS.ts.map +7 -0
- package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
- package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
- package/dist/chunks/chunk-KP33I6BR.ts +579 -0
- package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
- package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-PWTSHSP3.ts} +853 -1001
- package/dist/chunks/chunk-PWTSHSP3.ts.map +7 -0
- package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
- package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
- package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
- package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
- package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
- package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
- package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
- package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
- package/dist/chunks/command-configuration-menu-S2LXCOJG.ts +147 -0
- package/dist/chunks/command-configuration-menu-S2LXCOJG.ts.map +7 -0
- package/dist/chunks/command-settings-chat-O34BEU4X.ts +1041 -0
- package/dist/chunks/command-settings-chat-O34BEU4X.ts.map +7 -0
- package/dist/chunks/commands-ZYIJVIEJ.ts +1022 -0
- package/dist/chunks/commands-ZYIJVIEJ.ts.map +7 -0
- package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
- package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
- package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
- package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
- package/dist/chunks/directory-OX6BWJZA.ts +31 -0
- package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
- package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
- package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
- package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
- package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
- package/dist/chunks/languages-CBQNNYXM.ts +262 -0
- package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
- package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
- package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
- package/dist/chunks/system-574MHB4R.ts +165 -0
- package/dist/chunks/system-574MHB4R.ts.map +7 -0
- package/dist/index.ts +558 -150
- package/dist/index.ts.map +4 -4
- package/package.json +5 -1
- package/skills/configure-pi-starship/SKILL.md +14 -0
- package/skills/configure-pi-starship/references/configuration.md +109 -24
- package/skills/configure-pi-starship/references/module-catalog.md +278 -25
- package/skills/configure-pi-starship/references/modules.md +213 -36
- package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
- package/src/command-configuration-menu.ts +155 -0
- package/src/command-configuration.ts +9 -84
- package/src/command-preview.ts +3 -3
- package/src/command-settings-chat.ts +210 -0
- package/src/commands.ts +54 -98
- package/src/config/module-options.ts +112 -0
- package/src/config.ts +17 -53
- package/src/effective-config.ts +5 -4
- package/src/format/bounded-regex.ts +66 -0
- package/src/format/version.ts +24 -0
- package/src/modules/catalog.ts +10 -0
- package/src/modules/cloud.ts +1 -0
- package/src/modules/deployment.ts +8 -0
- package/src/modules/development.ts +20 -2
- package/src/modules/directory.ts +171 -51
- package/src/modules/execution.ts +2 -0
- package/src/modules/git/branch.ts +19 -4
- package/src/modules/git/commit.ts +9 -2
- package/src/modules/git/metrics.ts +9 -4
- package/src/modules/git/runtime.ts +122 -33
- package/src/modules/git/state.ts +23 -2
- package/src/modules/git/status-templates.ts +58 -0
- package/src/modules/git/status.ts +96 -30
- package/src/modules/jujutsu.ts +225 -0
- package/src/modules/languages.ts +26 -2
- package/src/modules/package.ts +1 -0
- package/src/modules/render.ts +42 -16
- package/src/modules/system.ts +54 -0
- package/src/modules/time-format.ts +188 -0
- package/src/modules/time.ts +11 -5
- package/src/modules/types.ts +42 -4
- package/src/pi-starship.ts +56 -12
- package/src/profile-store.ts +5 -0
- package/src/runtime/cloud.ts +3 -0
- package/src/runtime/command.ts +1 -1
- package/src/runtime/deployment.ts +120 -4
- package/src/runtime/development.ts +86 -13
- package/src/runtime/directory.ts +33 -0
- package/src/runtime/execution.ts +12 -2
- package/src/runtime/helpers.ts +57 -8
- package/src/runtime/jujutsu.ts +225 -0
- package/src/runtime/languages.ts +106 -19
- package/src/runtime/package.ts +3 -0
- package/src/runtime/system.ts +202 -0
- package/src/runtime/types.ts +3 -0
- package/src/runtime/version-requirements.ts +30 -0
- package/src/runtime/workspace.ts +12 -1
- package/src/settings-agent.ts +80 -0
- package/src/settings-chat-transcript.ts +140 -0
- package/src/settings-chat-ui.ts +426 -0
- package/src/settings-draft.ts +260 -0
- package/src/settings-snapshots.ts +41 -0
- package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
- package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
- package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
- package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
- package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
- package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
- package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
- package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
- package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
- package/dist/chunks/languages-JO6R2PHL.ts +0 -168
- package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
- package/dist/chunks/package-H24VJEX3.ts.map +0 -7
- package/src/command-inspector.ts +0 -41
|
@@ -0,0 +1,426 @@
|
|
|
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
|
+
Editor,
|
|
12
|
+
getKeybindings,
|
|
13
|
+
isKeyRelease,
|
|
14
|
+
Key,
|
|
15
|
+
matchesKey,
|
|
16
|
+
parseKey,
|
|
17
|
+
type TUI,
|
|
18
|
+
TUI_KEYBINDINGS,
|
|
19
|
+
truncateToWidth,
|
|
20
|
+
} from "@earendil-works/pi-tui";
|
|
21
|
+
import { HorizontalRule, renderBoundedFrame, runCustomInteraction } from "@narumitw/pi-tui-kit";
|
|
22
|
+
import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
|
|
23
|
+
import type { WorkflowOwner } from "./command-configuration.js";
|
|
24
|
+
import { createSettingsChatTranscript } from "./settings-chat-transcript.js";
|
|
25
|
+
import type { SettingsDraft } from "./settings-draft.js";
|
|
26
|
+
|
|
27
|
+
export type SettingsChatAction = "review" | "save" | "discard";
|
|
28
|
+
|
|
29
|
+
const SAVE_SHORTCUTS = [
|
|
30
|
+
{ key: "ctrl+s", inputs: ["\x13", "\x1b[115;5u", "\x1b[27;5;115~"] },
|
|
31
|
+
{ key: "f2", inputs: ["\x1bOQ", "\x1b[12~", "\x1b[[B"] },
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
/** Never replace native editing, cancellation, or registered message actions. */
|
|
35
|
+
function saveKeyReserved(data: string, keybindings: Pick<KeybindingsManager, "matches">): boolean {
|
|
36
|
+
const editorKeys = getKeybindings();
|
|
37
|
+
return (
|
|
38
|
+
(Object.keys(TUI_KEYBINDINGS) as Array<keyof typeof TUI_KEYBINDINGS>).some(
|
|
39
|
+
(action) => editorKeys.matches(data, action) || keybindings.matches(data, action),
|
|
40
|
+
) ||
|
|
41
|
+
(
|
|
42
|
+
["app.clipboard.pasteImage", "app.interrupt", "app.exit", "app.message.followUp", "app.message.dequeue"] as const
|
|
43
|
+
).some((action) => keybindings.matches(data, action))
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Check supported input encodings through Pi's matcher before displaying a save hint. */
|
|
48
|
+
export function settingsChatSaveShortcut(
|
|
49
|
+
keybindings: Pick<KeybindingsManager, "matches">,
|
|
50
|
+
): "ctrl+s" | "f2" | undefined {
|
|
51
|
+
return SAVE_SHORTCUTS.find(({ key, inputs }) => {
|
|
52
|
+
const matching = inputs.filter((data) => matchesKey(data, key));
|
|
53
|
+
return matching.length > 0 && matching.every((data) => !saveKeyReserved(data, keybindings));
|
|
54
|
+
})?.key;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ChatViewState {
|
|
58
|
+
input: string;
|
|
59
|
+
error: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Frame the review menu's footer preview without changing its render width. */
|
|
63
|
+
export function renderSettingsChatPreview(
|
|
64
|
+
width: number,
|
|
65
|
+
preview: readonly string[],
|
|
66
|
+
theme: Pick<Theme, "fg">,
|
|
67
|
+
): string[] {
|
|
68
|
+
if (width <= 0) return [];
|
|
69
|
+
const ruleStyle = (text: string) => theme.fg("border", text);
|
|
70
|
+
const top = new HorizontalRule({
|
|
71
|
+
label: "Preview",
|
|
72
|
+
labelAlignment: "left",
|
|
73
|
+
ruleStyle,
|
|
74
|
+
labelStyle: (text) => theme.fg("dim", text),
|
|
75
|
+
});
|
|
76
|
+
const bottom = new HorizontalRule({ ruleStyle });
|
|
77
|
+
return [top.render(width)[0] ?? "", ...preview, bottom.render(width)[0] ?? ""];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Add labels only to the public Editor border hooks; native scroll indicators keep priority. */
|
|
81
|
+
export class SettingsChatEditor extends CustomEditor {
|
|
82
|
+
constructor(
|
|
83
|
+
tui: TUI,
|
|
84
|
+
private readonly chromeTheme: Theme,
|
|
85
|
+
private readonly labels: () => { top: string; bottom: string },
|
|
86
|
+
keybindings: KeybindingsManager,
|
|
87
|
+
) {
|
|
88
|
+
super(
|
|
89
|
+
tui,
|
|
90
|
+
{
|
|
91
|
+
borderColor: (text) => chromeTheme.fg("borderMuted", text),
|
|
92
|
+
selectList: {
|
|
93
|
+
selectedPrefix: (text) => chromeTheme.fg("accent", text),
|
|
94
|
+
selectedText: (text) => chromeTheme.fg("accent", text),
|
|
95
|
+
description: (text) => chromeTheme.fg("muted", text),
|
|
96
|
+
scrollInfo: (text) => chromeTheme.fg("dim", text),
|
|
97
|
+
noMatch: (text) => chromeTheme.fg("warning", text),
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
keybindings,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
/** Bypass app shortcuts while the native Editor owns a bracketed paste. */
|
|
104
|
+
handlePasteInput(data: string): void {
|
|
105
|
+
Editor.prototype.handleInput.call(this, data);
|
|
106
|
+
}
|
|
107
|
+
protected renderTopBorder(width: number, hiddenLineCount: number): string {
|
|
108
|
+
return hiddenLineCount > 0
|
|
109
|
+
? super.renderTopBorder(width, hiddenLineCount)
|
|
110
|
+
: this.labeledBorder(width, this.labels().top);
|
|
111
|
+
}
|
|
112
|
+
protected renderBottomBorder(width: number, hiddenLineCount: number): string {
|
|
113
|
+
return hiddenLineCount > 0
|
|
114
|
+
? super.renderBottomBorder(width, hiddenLineCount)
|
|
115
|
+
: this.labeledBorder(width, this.labels().bottom);
|
|
116
|
+
}
|
|
117
|
+
private labeledBorder(width: number, label: string): string {
|
|
118
|
+
return (
|
|
119
|
+
new HorizontalRule({
|
|
120
|
+
label,
|
|
121
|
+
labelAlignment: "left",
|
|
122
|
+
ruleStyle: this.borderColor,
|
|
123
|
+
labelStyle: (text) => this.chromeTheme.fg("dim", text),
|
|
124
|
+
}).render(width)[0] ?? ""
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Editor actions win collisions. Escape remains a review fallback for unusable cancel settings. */
|
|
130
|
+
export function settingsChatReviewInput(data: string, keybindings: Pick<KeybindingsManager, "matches">): boolean {
|
|
131
|
+
const editorKeys = getKeybindings();
|
|
132
|
+
const parsed = parseKey(data);
|
|
133
|
+
const textKey = parsed?.startsWith("shift+") ? parsed.slice(6) : parsed;
|
|
134
|
+
const printable =
|
|
135
|
+
data.charCodeAt(0) >= 32 || (textKey !== undefined && (Array.from(textKey).length === 1 || textKey === "space"));
|
|
136
|
+
// These native Editor branches remain active even when their configurable actions are remapped.
|
|
137
|
+
const nativeEditing =
|
|
138
|
+
printable ||
|
|
139
|
+
matchesKey(data, "shift+backspace") ||
|
|
140
|
+
matchesKey(data, "shift+delete") ||
|
|
141
|
+
data.charCodeAt(0) === 10 ||
|
|
142
|
+
data === "\x1b\r" ||
|
|
143
|
+
data === "\x1b[13;2~" ||
|
|
144
|
+
(data.includes("\x1b") && data.includes("\r"));
|
|
145
|
+
const editing =
|
|
146
|
+
nativeEditing ||
|
|
147
|
+
(Object.keys(TUI_KEYBINDINGS) as Array<keyof typeof TUI_KEYBINDINGS>)
|
|
148
|
+
.filter((key) => key.startsWith("tui.editor.") || key.startsWith("tui.input."))
|
|
149
|
+
.some((key) => editorKeys.matches(data, key));
|
|
150
|
+
return !editing && (keybindings.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function settingsChatTranscript(agent: Agent): string[] {
|
|
154
|
+
return [...agent.state.messages, ...(agent.state.streamingMessage ? [agent.state.streamingMessage] : [])]
|
|
155
|
+
.filter((message) => message.role !== "system")
|
|
156
|
+
.flatMap((message) => {
|
|
157
|
+
if (!("content" in message) || !Array.isArray(message.content)) return [];
|
|
158
|
+
const label = message.role === "user" ? "You" : message.role === "assistant" ? "Agent" : "Tool";
|
|
159
|
+
const text = message.content
|
|
160
|
+
.map((part) => {
|
|
161
|
+
if (part.type === "text") return part.text;
|
|
162
|
+
if (part.type === "toolCall") return `Using ${part.name}…`;
|
|
163
|
+
return "";
|
|
164
|
+
})
|
|
165
|
+
.filter(Boolean)
|
|
166
|
+
.join("\n");
|
|
167
|
+
const error = message.role === "assistant" ? message.errorMessage : undefined;
|
|
168
|
+
const output = [text, error].filter(Boolean).join("\n");
|
|
169
|
+
return output ? [`${label}: ${sanitizeTerminalDocument(output)}`] : [];
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function createSettingsChatComponent(options: {
|
|
174
|
+
agent: Agent;
|
|
175
|
+
draft: SettingsDraft;
|
|
176
|
+
state: ChatViewState;
|
|
177
|
+
tui: TUI;
|
|
178
|
+
theme: Theme;
|
|
179
|
+
keybindings: KeybindingsManager;
|
|
180
|
+
signal: AbortSignal;
|
|
181
|
+
preview(width: number): string[];
|
|
182
|
+
complete(value: SettingsChatAction): void;
|
|
183
|
+
}) {
|
|
184
|
+
const { agent, draft, state, tui, theme, keybindings, signal } = options;
|
|
185
|
+
let disposed = false;
|
|
186
|
+
let inPaste = false;
|
|
187
|
+
let pending: Promise<void> | undefined;
|
|
188
|
+
let stopping = false;
|
|
189
|
+
const queued: Array<{ kind: "steer" | "followUp"; message: UserMessage; text: string }> = [];
|
|
190
|
+
const editor = new SettingsChatEditor(
|
|
191
|
+
tui,
|
|
192
|
+
theme,
|
|
193
|
+
() => {
|
|
194
|
+
const status =
|
|
195
|
+
state.error || agent.state.errorMessage
|
|
196
|
+
? "Agent error"
|
|
197
|
+
: !draft.candidate
|
|
198
|
+
? "Invalid"
|
|
199
|
+
: draft.diagnostics
|
|
200
|
+
? "Warnings"
|
|
201
|
+
: "Valid";
|
|
202
|
+
const saveKey = !pending && !inPaste && draft.candidate ? settingsChatSaveShortcut(keybindings) : undefined;
|
|
203
|
+
return {
|
|
204
|
+
top: queued.length > 0 ? `pi-starship · ${queued.length} queued` : "pi-starship",
|
|
205
|
+
bottom: `${status} · unsaved · ${pending ? "Working · Cancel stop" : saveKey ? `${saveKey} save profile` : "Cancel review"} · Ctrl+C discard`,
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
keybindings,
|
|
209
|
+
);
|
|
210
|
+
editor.setText(state.input);
|
|
211
|
+
const render = () => {
|
|
212
|
+
if (!disposed && !signal.aborted) tui.requestRender();
|
|
213
|
+
};
|
|
214
|
+
const unsubscribe = agent.subscribe((event) => {
|
|
215
|
+
if (event.type === "message_start") {
|
|
216
|
+
const index = queued.findIndex((item) => item.message === event.message);
|
|
217
|
+
if (index >= 0) queued.splice(index, 1);
|
|
218
|
+
}
|
|
219
|
+
render();
|
|
220
|
+
});
|
|
221
|
+
const clearQueue = () => {
|
|
222
|
+
queued.length = 0;
|
|
223
|
+
agent.clearAllQueues();
|
|
224
|
+
};
|
|
225
|
+
const restoreQueue = () => {
|
|
226
|
+
const messages = [
|
|
227
|
+
...queued.filter((item) => item.kind === "steer"),
|
|
228
|
+
...queued.filter((item) => item.kind === "followUp"),
|
|
229
|
+
].map((item) => item.text);
|
|
230
|
+
clearQueue();
|
|
231
|
+
if (messages.length > 0) editor.setText([...messages, editor.getExpandedText()].filter(Boolean).join("\n\n"));
|
|
232
|
+
};
|
|
233
|
+
const abort = () => {
|
|
234
|
+
stopping = true;
|
|
235
|
+
clearQueue();
|
|
236
|
+
agent.abort();
|
|
237
|
+
};
|
|
238
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
239
|
+
const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
|
|
240
|
+
const transcript = createSettingsChatTranscript(agent, tui, draft.directory);
|
|
241
|
+
const failed = () => {
|
|
242
|
+
const last = agent.state.messages.at(-1);
|
|
243
|
+
return last?.role === "assistant" && (last.stopReason === "error" || last.stopReason === "aborted");
|
|
244
|
+
};
|
|
245
|
+
const submit = (input: string, kind: "steer" | "followUp") => {
|
|
246
|
+
if (signal.aborted || disposed) return;
|
|
247
|
+
if (!input.trim()) return;
|
|
248
|
+
// Native submission clears the editor first. Retain input typed while an abort settles.
|
|
249
|
+
if (pending && stopping) {
|
|
250
|
+
editor.setText(input);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
editor.addToHistory(input);
|
|
254
|
+
editor.setText("");
|
|
255
|
+
state.error = "";
|
|
256
|
+
if (pending) {
|
|
257
|
+
const message: UserMessage = { role: "user", content: [{ type: "text", text: input }], timestamp: Date.now() };
|
|
258
|
+
queued.push({ kind, message, text: input });
|
|
259
|
+
if (kind === "steer") agent.steer(message);
|
|
260
|
+
else agent.followUp(message);
|
|
261
|
+
} else {
|
|
262
|
+
stopping = false;
|
|
263
|
+
pending = (async () => {
|
|
264
|
+
try {
|
|
265
|
+
await agent.prompt(input);
|
|
266
|
+
// agent_end listeners can enqueue after the loop's final poll. Wait for actual
|
|
267
|
+
// idle settlement before continuing; never resume cancelled or failed runs.
|
|
268
|
+
while (!disposed && !signal.aborted && !stopping && !failed() && agent.hasQueuedMessages()) {
|
|
269
|
+
await agent.continue();
|
|
270
|
+
}
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (!disposed && !signal.aborted) state.error = error instanceof Error ? error.message : String(error);
|
|
273
|
+
} finally {
|
|
274
|
+
pending = undefined;
|
|
275
|
+
if (!disposed && !signal.aborted) restoreQueue();
|
|
276
|
+
else clearQueue();
|
|
277
|
+
render();
|
|
278
|
+
}
|
|
279
|
+
})();
|
|
280
|
+
}
|
|
281
|
+
render();
|
|
282
|
+
};
|
|
283
|
+
// Native Editor expands paste markers and clears itself before calling onSubmit.
|
|
284
|
+
editor.onSubmit = (input) => submit(input, "steer");
|
|
285
|
+
editor.onAction("app.message.followUp", () => submit(editor.getExpandedText().trim(), "followUp"));
|
|
286
|
+
editor.onAction("app.message.dequeue", restoreQueue);
|
|
287
|
+
return {
|
|
288
|
+
get focused() {
|
|
289
|
+
return editor.focused;
|
|
290
|
+
},
|
|
291
|
+
set focused(value: boolean) {
|
|
292
|
+
editor.focused = value;
|
|
293
|
+
},
|
|
294
|
+
render(width: number): string[] {
|
|
295
|
+
if (disposed || signal.aborted || width <= 0) return [];
|
|
296
|
+
const rows = Math.max(0, Math.floor(Number.isFinite(tui.terminal.rows) ? tui.terminal.rows : 24));
|
|
297
|
+
if (rows === 0) return [];
|
|
298
|
+
const input = editor.render(width);
|
|
299
|
+
const cursor = Math.max(
|
|
300
|
+
0,
|
|
301
|
+
input.findIndex((line) => line.includes(CURSOR_MARKER)),
|
|
302
|
+
);
|
|
303
|
+
const preview = options.preview(width);
|
|
304
|
+
const diagnostics = sanitizeTerminalDocument(state.error || agent.state.errorMessage || draft.diagnostics)
|
|
305
|
+
.split("\n")
|
|
306
|
+
.filter(Boolean)
|
|
307
|
+
.slice(0, 3);
|
|
308
|
+
// Match Pi's transcript -> editor -> footer hierarchy. The fullscreen overlay
|
|
309
|
+
// covers the parent footer, so the real draft preview is part of this dock.
|
|
310
|
+
const details = diagnostics.map((line) => theme.fg("muted", line));
|
|
311
|
+
// Render the footer without extra rules, matching its saved position at the terminal bottom.
|
|
312
|
+
if (input.length + preview.length > rows) {
|
|
313
|
+
return renderBoundedFrame({
|
|
314
|
+
width,
|
|
315
|
+
maxRows: rows,
|
|
316
|
+
rule: rule.render(width)[0] ?? "",
|
|
317
|
+
title: [],
|
|
318
|
+
content: [...input, theme.fg("muted", "Footer preview hidden — enlarge the terminal"), ...details],
|
|
319
|
+
focusedRow: cursor,
|
|
320
|
+
priorityRows: [cursor, input.length],
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
const detailLines = details.slice(0, rows - input.length - preview.length);
|
|
324
|
+
const queueLines = [
|
|
325
|
+
...queued.filter((item) => item.kind === "steer"),
|
|
326
|
+
...queued.filter((item) => item.kind === "followUp"),
|
|
327
|
+
]
|
|
328
|
+
.slice(0, Math.min(3, rows - input.length - preview.length - detailLines.length))
|
|
329
|
+
.map((item) =>
|
|
330
|
+
theme.fg(
|
|
331
|
+
"dim",
|
|
332
|
+
`${item.kind === "steer" ? "Steering" : "Follow-up"}: ${sanitizeTerminalDocument(item.text).replace(/\n/gu, " ")}`,
|
|
333
|
+
),
|
|
334
|
+
);
|
|
335
|
+
const content = [...queueLines, ...input, ...detailLines, ...preview];
|
|
336
|
+
const available = rows - content.length;
|
|
337
|
+
const history = available > 0 ? transcript.render(width).slice(-available) : [];
|
|
338
|
+
return [...history, ...Array.from({ length: available - history.length }, () => ""), ...content].map((line) =>
|
|
339
|
+
truncateToWidth(line, width, ""),
|
|
340
|
+
);
|
|
341
|
+
},
|
|
342
|
+
invalidate() {
|
|
343
|
+
editor.invalidate();
|
|
344
|
+
transcript.invalidate();
|
|
345
|
+
},
|
|
346
|
+
handleInput(data: string) {
|
|
347
|
+
if (disposed || signal.aborted || isKeyRelease(data)) return;
|
|
348
|
+
const saveKey = !pending && draft.candidate ? settingsChatSaveShortcut(keybindings) : undefined;
|
|
349
|
+
// Forward entire paste packets and fragments without interpreting embedded shortcuts.
|
|
350
|
+
if (inPaste || data.includes("\x1b[200~")) {
|
|
351
|
+
inPaste = !data.includes("\x1b[201~");
|
|
352
|
+
editor.handlePasteInput(data);
|
|
353
|
+
} else if (matchesKey(data, Key.ctrl("c"))) {
|
|
354
|
+
abort();
|
|
355
|
+
options.complete("discard");
|
|
356
|
+
} else if (saveKey && matchesKey(data, saveKey) && !saveKeyReserved(data, keybindings)) {
|
|
357
|
+
state.input = editor.getExpandedText();
|
|
358
|
+
options.complete("save");
|
|
359
|
+
} else if (settingsChatReviewInput(data, keybindings)) {
|
|
360
|
+
if (pending) {
|
|
361
|
+
stopping = true;
|
|
362
|
+
restoreQueue();
|
|
363
|
+
agent.abort();
|
|
364
|
+
} else {
|
|
365
|
+
state.input = editor.getExpandedText();
|
|
366
|
+
options.complete("review");
|
|
367
|
+
}
|
|
368
|
+
} else editor.handleInput(data);
|
|
369
|
+
render();
|
|
370
|
+
},
|
|
371
|
+
dispose() {
|
|
372
|
+
if (disposed) return;
|
|
373
|
+
disposed = true;
|
|
374
|
+
state.input = editor.getExpandedText();
|
|
375
|
+
signal.removeEventListener("abort", abort);
|
|
376
|
+
unsubscribe();
|
|
377
|
+
transcript.dispose();
|
|
378
|
+
abort();
|
|
379
|
+
},
|
|
380
|
+
async waitForPending() {
|
|
381
|
+
await pending;
|
|
382
|
+
await agent.waitForIdle();
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export async function showSettingsChat(
|
|
388
|
+
ctx: ExtensionCommandContext,
|
|
389
|
+
agent: Agent,
|
|
390
|
+
draft: SettingsDraft,
|
|
391
|
+
state: ChatViewState,
|
|
392
|
+
owner: WorkflowOwner,
|
|
393
|
+
preview: (width: number) => string[],
|
|
394
|
+
): Promise<SettingsChatAction> {
|
|
395
|
+
// Keep Kit's cancellation/disposal runner, but mount through Pi's public overlay API.
|
|
396
|
+
// No second TUI, terminal handoff, or manipulation of unrelated overlay handles is needed.
|
|
397
|
+
const fullscreenContext: ExtensionCommandContext = {
|
|
398
|
+
...ctx,
|
|
399
|
+
ui: {
|
|
400
|
+
...ctx.ui,
|
|
401
|
+
custom: (factory) =>
|
|
402
|
+
ctx.ui.custom(factory, {
|
|
403
|
+
overlay: true,
|
|
404
|
+
overlayOptions: { width: "100%", maxHeight: "100%", anchor: "top-left", margin: 0 },
|
|
405
|
+
}),
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
const result = await runCustomInteraction<SettingsChatAction>(fullscreenContext, {
|
|
409
|
+
signal: owner.signal,
|
|
410
|
+
isCurrent: owner.isCurrent,
|
|
411
|
+
create: ({ tui, theme, keybindings, signal, complete }) =>
|
|
412
|
+
createSettingsChatComponent({
|
|
413
|
+
agent,
|
|
414
|
+
draft,
|
|
415
|
+
state,
|
|
416
|
+
tui,
|
|
417
|
+
theme,
|
|
418
|
+
keybindings,
|
|
419
|
+
signal,
|
|
420
|
+
preview,
|
|
421
|
+
complete,
|
|
422
|
+
}),
|
|
423
|
+
});
|
|
424
|
+
if (result.kind === "error") throw result.error;
|
|
425
|
+
return result.kind === "completed" ? result.value : "discard";
|
|
426
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeSync,
|
|
3
|
+
constants,
|
|
4
|
+
fstatSync,
|
|
5
|
+
ftruncateSync,
|
|
6
|
+
mkdtempSync,
|
|
7
|
+
openSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
realpathSync,
|
|
10
|
+
rmSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
15
|
+
import {
|
|
16
|
+
createEditTool,
|
|
17
|
+
createReadTool,
|
|
18
|
+
createWriteTool,
|
|
19
|
+
truncateHead,
|
|
20
|
+
withFileMutationQueue,
|
|
21
|
+
} from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { BUILT_IN_EXAMPLE, type LoadedStarshipConfig, validateConfigDocument } from "./config.js";
|
|
23
|
+
import type { settingsSnapshots } from "./settings-snapshots.js";
|
|
24
|
+
|
|
25
|
+
const MAX_DRAFT_BYTES = 64 * 1024;
|
|
26
|
+
|
|
27
|
+
export interface SettingsDraftOptions {
|
|
28
|
+
settingsPath: string;
|
|
29
|
+
baseline: Buffer | undefined;
|
|
30
|
+
packageRoot: string;
|
|
31
|
+
snapshots?: ReturnType<typeof settingsSnapshots>;
|
|
32
|
+
isCurrent(): boolean;
|
|
33
|
+
onPreview(loaded: LoadedStarshipConfig): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Private file tools; the active settings path is only an immutable read snapshot. */
|
|
37
|
+
export function createSettingsDraft(options: SettingsDraftOptions) {
|
|
38
|
+
if (options.baseline && options.baseline.length > MAX_DRAFT_BYTES)
|
|
39
|
+
throw new Error("The settings draft exceeds 64 KiB");
|
|
40
|
+
const roots = ["skills/configure-pi-starship", "src"].map((part) => realpathSync(join(options.packageRoot, part)));
|
|
41
|
+
const directory = realpathSync(mkdtempSync(join(tmpdir(), "pi-starship-draft-")));
|
|
42
|
+
const path = join(directory, "pi-starship.toml");
|
|
43
|
+
const baseline = options.baseline && Buffer.from(options.baseline);
|
|
44
|
+
const snapshots = new Map(
|
|
45
|
+
Object.entries(options.snapshots ?? {}).map(([name, content]) => [join(directory, name), content]),
|
|
46
|
+
);
|
|
47
|
+
const snapshotPaths = [...snapshots.keys()];
|
|
48
|
+
let disposed = false;
|
|
49
|
+
let removed = false;
|
|
50
|
+
let revision = 0;
|
|
51
|
+
let valid: LoadedStarshipConfig | undefined;
|
|
52
|
+
let diagnostics = "";
|
|
53
|
+
const assertCurrent = () => {
|
|
54
|
+
if (disposed || !options.isCurrent()) throw new Error("The settings draft owner is no longer active");
|
|
55
|
+
};
|
|
56
|
+
const assertDraft = (target: string) => {
|
|
57
|
+
assertCurrent();
|
|
58
|
+
if (resolve(target) !== path || realpathSync(directory) !== directory || realpathSync(path) !== path) {
|
|
59
|
+
throw new Error("Only the owned settings draft can be changed");
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const readDraft = () => {
|
|
63
|
+
assertDraft(path);
|
|
64
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
65
|
+
try {
|
|
66
|
+
const stat = fstatSync(fd);
|
|
67
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_DRAFT_BYTES)
|
|
68
|
+
throw new Error("The owned draft is not a private regular file up to 64 KiB");
|
|
69
|
+
return readFileSync(fd);
|
|
70
|
+
} finally {
|
|
71
|
+
closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const validate = (publish = true) => {
|
|
75
|
+
valid = undefined;
|
|
76
|
+
let candidate: LoadedStarshipConfig;
|
|
77
|
+
try {
|
|
78
|
+
candidate = validateConfigDocument(options.settingsPath, readDraft().toString("utf8"));
|
|
79
|
+
} catch (error) {
|
|
80
|
+
diagnostics = error instanceof Error ? error.message : String(error);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
diagnostics = candidate.diagnostics.map((item) => `${item.severity}: ${item.path}: ${item.message}`).join("\n");
|
|
84
|
+
if (publish) options.onPreview(candidate);
|
|
85
|
+
valid = candidate;
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
writeFileSync(path, baseline ?? BUILT_IN_EXAMPLE, { mode: 0o600, flag: "wx" });
|
|
89
|
+
validate(false);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
try {
|
|
92
|
+
rmSync(directory, { recursive: true, force: true });
|
|
93
|
+
} catch (cleanupError) {
|
|
94
|
+
throw new AggregateError(
|
|
95
|
+
[error, cleanupError],
|
|
96
|
+
`Settings draft initialization and cleanup failed at ${directory}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
const readAllowed = (target: string): Buffer => {
|
|
102
|
+
assertCurrent();
|
|
103
|
+
if (resolve(target) === resolve(options.settingsPath)) {
|
|
104
|
+
if (!baseline) throw new Error("The active settings file was missing when this preview started");
|
|
105
|
+
return Buffer.from(baseline);
|
|
106
|
+
}
|
|
107
|
+
if (resolve(target) === path) return readDraft();
|
|
108
|
+
if (snapshots.has(resolve(target))) {
|
|
109
|
+
const content = snapshots.get(resolve(target));
|
|
110
|
+
if (content === undefined)
|
|
111
|
+
throw new Error(
|
|
112
|
+
"No exact loaded settings document is available; read active-state.json for its source and diagnostics",
|
|
113
|
+
);
|
|
114
|
+
return Buffer.from(content);
|
|
115
|
+
}
|
|
116
|
+
const canonical = realpathSync(target);
|
|
117
|
+
if (
|
|
118
|
+
!roots.some((root) => {
|
|
119
|
+
const child = relative(root, canonical);
|
|
120
|
+
return (
|
|
121
|
+
child !== "" &&
|
|
122
|
+
child !== ".." &&
|
|
123
|
+
!child.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) &&
|
|
124
|
+
!isAbsolute(child)
|
|
125
|
+
);
|
|
126
|
+
})
|
|
127
|
+
)
|
|
128
|
+
throw new Error("Read access is limited to the settings snapshot, draft, and bundled configuration documents");
|
|
129
|
+
const fd = openSync(canonical, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
130
|
+
try {
|
|
131
|
+
const stat = fstatSync(fd);
|
|
132
|
+
if (!stat.isFile() || stat.size > 1024 * 1024)
|
|
133
|
+
throw new Error("Only bundled text documents up to 1 MiB can be read");
|
|
134
|
+
return readFileSync(fd);
|
|
135
|
+
} finally {
|
|
136
|
+
closeSync(fd);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const writeDraft = async (target: string, text: string) => {
|
|
140
|
+
assertDraft(target);
|
|
141
|
+
if (Buffer.byteLength(text) > MAX_DRAFT_BYTES) throw new Error("The settings draft exceeds 64 KiB");
|
|
142
|
+
const fd = openSync(path, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
143
|
+
try {
|
|
144
|
+
const stat = fstatSync(fd);
|
|
145
|
+
if (!stat.isFile() || stat.nlink !== 1) throw new Error("The owned draft is not a private regular file");
|
|
146
|
+
// Keep validation and preview in the core tool's mutation queue, without an await boundary.
|
|
147
|
+
valid = undefined;
|
|
148
|
+
ftruncateSync(fd, 0);
|
|
149
|
+
writeFileSync(fd, text);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
diagnostics = error instanceof Error ? error.message : String(error);
|
|
152
|
+
throw error;
|
|
153
|
+
} finally {
|
|
154
|
+
closeSync(fd);
|
|
155
|
+
}
|
|
156
|
+
revision += 1;
|
|
157
|
+
validate();
|
|
158
|
+
if (!valid)
|
|
159
|
+
throw new Error(
|
|
160
|
+
`Draft saved but preview rejected; repair the draft. ${truncateHead(diagnostics, { maxBytes: 48 * 1024, maxLines: 1900 }).content}`,
|
|
161
|
+
);
|
|
162
|
+
};
|
|
163
|
+
const read = createReadTool(directory, {
|
|
164
|
+
operations: {
|
|
165
|
+
access: async (target) => {
|
|
166
|
+
readAllowed(target);
|
|
167
|
+
},
|
|
168
|
+
readFile: async (target) => readAllowed(target),
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
const write = createWriteTool(directory, {
|
|
172
|
+
operations: {
|
|
173
|
+
mkdir: async (target) => {
|
|
174
|
+
assertCurrent();
|
|
175
|
+
if (target !== directory) throw new Error("Only the draft directory is writable");
|
|
176
|
+
},
|
|
177
|
+
writeFile: writeDraft,
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
const edit = createEditTool(directory, {
|
|
181
|
+
operations: {
|
|
182
|
+
access: async (target) => assertDraft(target),
|
|
183
|
+
readFile: async (target) => {
|
|
184
|
+
assertDraft(target);
|
|
185
|
+
return readDraft();
|
|
186
|
+
},
|
|
187
|
+
writeFile: writeDraft,
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
read.description =
|
|
191
|
+
"Read text from immutable disk/active configuration and module snapshots, the owned draft, or bundled configuration skill/source documents. Output is limited to 50 KiB or 2,000 lines; use offset and limit to continue.";
|
|
192
|
+
write.description =
|
|
193
|
+
"Replace only the owned pi-starship TOML draft, up to 64 KiB. The host validates and previews it. Invalid text stays in the draft and returns an error for repair. Never writes the active settings file.";
|
|
194
|
+
edit.description +=
|
|
195
|
+
" Only the owned pi-starship TOML draft is editable. The host validates and previews the result; invalid text stays in the draft for repair. Never changes active settings.";
|
|
196
|
+
// The outer queue includes reads and result diagnostics. Core mutators retain their
|
|
197
|
+
// own file-path queue; a distinct directory key avoids recursive queue admission.
|
|
198
|
+
const ordered = <T>(operation: () => Promise<T>) =>
|
|
199
|
+
withFileMutationQueue(directory, async () => {
|
|
200
|
+
assertCurrent();
|
|
201
|
+
const result = await operation();
|
|
202
|
+
assertCurrent();
|
|
203
|
+
return result;
|
|
204
|
+
});
|
|
205
|
+
const readExecute = read.execute.bind(read);
|
|
206
|
+
read.execute = (...args) => ordered(() => readExecute(...args));
|
|
207
|
+
const warningResult = async <T extends { content: Awaited<ReturnType<typeof read.execute>>["content"] }>(
|
|
208
|
+
operation: Promise<T>,
|
|
209
|
+
): Promise<T> => {
|
|
210
|
+
const result = await operation;
|
|
211
|
+
assertCurrent();
|
|
212
|
+
return {
|
|
213
|
+
...result,
|
|
214
|
+
content: [
|
|
215
|
+
...result.content,
|
|
216
|
+
{
|
|
217
|
+
type: "text" as const,
|
|
218
|
+
text: truncateHead(`Draft validated. Preview updated; active settings unchanged.\n${diagnostics}`, {
|
|
219
|
+
maxBytes: 48 * 1024,
|
|
220
|
+
maxLines: 1900,
|
|
221
|
+
}).content,
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
const writeExecute = write.execute.bind(write);
|
|
227
|
+
write.execute = (...args) => ordered(() => warningResult(writeExecute(...args)));
|
|
228
|
+
const editExecute = edit.execute.bind(edit);
|
|
229
|
+
edit.execute = (...args) => ordered(() => warningResult(editExecute(...args)));
|
|
230
|
+
return {
|
|
231
|
+
directory,
|
|
232
|
+
path,
|
|
233
|
+
snapshotPaths,
|
|
234
|
+
tools: [read, write, edit] as [typeof read, typeof write, typeof edit],
|
|
235
|
+
get revision() {
|
|
236
|
+
return revision;
|
|
237
|
+
},
|
|
238
|
+
get candidate() {
|
|
239
|
+
return valid;
|
|
240
|
+
},
|
|
241
|
+
get rawDocument() {
|
|
242
|
+
return readDraft().toString("utf8");
|
|
243
|
+
},
|
|
244
|
+
get diagnostics() {
|
|
245
|
+
return diagnostics;
|
|
246
|
+
},
|
|
247
|
+
assertRevision(expected: number) {
|
|
248
|
+
assertCurrent();
|
|
249
|
+
if (revision !== expected || !valid || valid.rawDocument !== readDraft().toString("utf8"))
|
|
250
|
+
throw new Error("The settings draft changed after review");
|
|
251
|
+
},
|
|
252
|
+
dispose() {
|
|
253
|
+
disposed = true;
|
|
254
|
+
if (removed) return;
|
|
255
|
+
rmSync(directory, { recursive: true, force: true });
|
|
256
|
+
removed = true;
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
export type SettingsDraft = ReturnType<typeof createSettingsDraft>;
|