proper-base 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { type Dirent, mkdirSync, writeFileSync } from "node:fs";
3
+ import { readdir, unlink } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+
6
+ export type UpdateKind = "pi" | "user" | "project";
7
+ const LAUNCH = Symbol.for("proper-updater.launch.v1");
8
+
9
+ function launchId(): string {
10
+ let id = Reflect.get(process, LAUNCH) as string | undefined;
11
+ if (!id) {
12
+ id = randomUUID();
13
+ Reflect.set(process, LAUNCH, id);
14
+ }
15
+ return id;
16
+ }
17
+
18
+ function scope(kind: UpdateKind, cwd: string): string {
19
+ return kind === "project"
20
+ ? `project-${createHash("sha256").update(resolve(cwd)).digest("hex")}`
21
+ : kind;
22
+ }
23
+
24
+ // @lat: [[auto-updates#Next-launch readiness]]
25
+ export function rememberUpdate(
26
+ agentDir: string,
27
+ kind: UpdateKind,
28
+ cwd: string,
29
+ ): void {
30
+ const directory = join(agentDir, "proper-updater-ready");
31
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
32
+ // Tiny synchronous markers survive an immediate quit after a native notice.
33
+ // Empty, exclusively created files need no partial-content recovery protocol.
34
+ try {
35
+ writeFileSync(join(directory, `${scope(kind, cwd)}-${launchId()}`), "", {
36
+ flag: "wx",
37
+ mode: 0o600,
38
+ });
39
+ } catch (error) {
40
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
41
+ }
42
+ }
43
+
44
+ export async function pendingUpdates(
45
+ agentDir: string,
46
+ cwd: string,
47
+ trusted: boolean,
48
+ ) {
49
+ const directory = join(agentDir, "proper-updater-ready");
50
+ const ready = {
51
+ pi: false,
52
+ packages: false,
53
+ project: false,
54
+ files: [] as string[],
55
+ };
56
+ let entries: Dirent[];
57
+ try {
58
+ entries = await readdir(directory, { withFileTypes: true });
59
+ } catch (error) {
60
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
61
+ return ready;
62
+ }
63
+ const kinds: UpdateKind[] = trusted
64
+ ? ["pi", "user", "project"]
65
+ : ["pi", "user"];
66
+ for (const entry of entries) {
67
+ if (!entry.isFile() || entry.name.endsWith(`-${launchId()}`)) continue;
68
+ for (const kind of kinds) {
69
+ const prefix = `${scope(kind, cwd)}-`;
70
+ if (
71
+ !entry.name.startsWith(prefix) ||
72
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(
73
+ entry.name.slice(prefix.length),
74
+ )
75
+ )
76
+ continue;
77
+ ready.files.push(join(directory, entry.name));
78
+ if (kind === "pi") ready.pi = true;
79
+ else ready.packages = true;
80
+ if (kind === "project") ready.project = true;
81
+ }
82
+ }
83
+ return ready;
84
+ }
85
+
86
+ export async function clearUpdates(files: string[]): Promise<void> {
87
+ for (const file of files) {
88
+ try {
89
+ await unlink(file);
90
+ } catch (error) {
91
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,268 @@
1
+ import { spawn } from "node:child_process";
2
+ import { type FileHandle, mkdir, open, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import type { Args } from "@earendil-works/pi-coding-agent";
6
+
7
+ export const RESTART_MARKER = "PROPER_UPDATER_RESTART";
8
+ export const TIMEOUT_MS = 180_000;
9
+ export type Snapshot = Record<string, { name: string; revision: string }>;
10
+ export type CommandResult = { code: number; stdout: string; stopped: boolean };
11
+
12
+ export function enabled(value: string | undefined): boolean {
13
+ return /^(1|true|yes)$/i.test(value ?? "");
14
+ }
15
+
16
+ export function consumeRestartMarker(
17
+ env: NodeJS.ProcessEnv,
18
+ pid: number,
19
+ ): boolean {
20
+ const restarted = env[RESTART_MARKER] === String(pid);
21
+ delete env[RESTART_MARKER];
22
+ return restarted;
23
+ }
24
+
25
+ // @lat: [[auto-updates#Restart contract]]
26
+ export function restartArgs(
27
+ raw: string[],
28
+ parsed: Args,
29
+ sessionFile?: string,
30
+ ): string[] | undefined {
31
+ if (
32
+ parsed.messages.length ||
33
+ parsed.fileArgs.length ||
34
+ parsed.unknownFlags.size ||
35
+ parsed.diagnostics.length ||
36
+ parsed.fork ||
37
+ parsed.resume ||
38
+ parsed.sessionId
39
+ )
40
+ return undefined;
41
+ const valuedFlags = new Set([
42
+ "--provider",
43
+ "--model",
44
+ "--api-key",
45
+ "--system-prompt",
46
+ "--append-system-prompt",
47
+ "--name",
48
+ "-n",
49
+ "--session-dir",
50
+ "--models",
51
+ "--tools",
52
+ "-t",
53
+ "--exclude-tools",
54
+ "-xt",
55
+ "--thinking",
56
+ "--extension",
57
+ "-e",
58
+ "--skill",
59
+ "--prompt-template",
60
+ "--theme",
61
+ "--use-theme",
62
+ "--tui-mode",
63
+ "--mode",
64
+ ]);
65
+ const args: string[] = [];
66
+ for (let i = 0; i < raw.length; i++) {
67
+ const arg = raw[i];
68
+ if (arg === "--") break;
69
+ if (arg === "-c" || arg === "--continue") continue;
70
+ if (arg === "--session") {
71
+ i++;
72
+ continue;
73
+ }
74
+ if (arg !== undefined) {
75
+ args.push(arg);
76
+ if (valuedFlags.has(arg)) {
77
+ const value = raw[++i];
78
+ if (value === undefined) return undefined;
79
+ args.push(value);
80
+ }
81
+ }
82
+ }
83
+ // Never resume a not-yet-persisted session or reinterpret --continue later.
84
+ if ((parsed.continue || parsed.session) && !sessionFile) return undefined;
85
+ if (sessionFile && !parsed.noSession) args.push("--session", sessionFile);
86
+ return args;
87
+ }
88
+
89
+ export function parseSnapshot(text: string): Snapshot {
90
+ const value: unknown = JSON.parse(text);
91
+ if (!value || typeof value !== "object" || Array.isArray(value))
92
+ throw new TypeError("Invalid update inventory");
93
+ for (const entry of Object.values(value)) {
94
+ if (
95
+ !entry ||
96
+ typeof entry !== "object" ||
97
+ typeof entry.name !== "string" ||
98
+ typeof entry.revision !== "string"
99
+ ) {
100
+ throw new TypeError("Invalid update inventory entry");
101
+ }
102
+ }
103
+ return value as Snapshot;
104
+ }
105
+
106
+ function display(text: string): string {
107
+ return stripVTControlCharacters(text)
108
+ .replace(/[\r\n\t]/g, " ")
109
+ .slice(0, 100);
110
+ }
111
+
112
+ export function changes(before: Snapshot, after: Snapshot): string[] {
113
+ return [...new Set([...Object.keys(before), ...Object.keys(after)])].flatMap(
114
+ (key) => {
115
+ const old = before[key];
116
+ const next = after[key];
117
+ if (old?.revision === next?.revision) return [];
118
+ return [
119
+ `${display(next?.name ?? old?.name ?? key)} ${display(old?.revision ?? "missing")} → ${display(next?.revision ?? "missing")}`,
120
+ ];
121
+ },
122
+ );
123
+ }
124
+
125
+ export function summary(items: string[]): string {
126
+ return `${items.slice(0, 4).join("; ")}${items.length > 4 ? `; +${items.length - 4} more` : ""}`;
127
+ }
128
+
129
+ // Only recognized native Pi progress becomes UI text. Never echo installer logs,
130
+ // command arguments, registry credentials, or private repository URLs.
131
+ export function updateStatus(line: string): string | undefined {
132
+ const text = stripVTControlCharacters(line).trim();
133
+ if (text === "Updated packages") return "Checking Pi version…";
134
+ if (text === "Updating user npm packages...")
135
+ return "Updating global packages…";
136
+ if (text === "Updating project npm packages...")
137
+ return "Updating project packages…";
138
+ const npm =
139
+ /^Updating npm:((?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*)(?:@[^\s]+)?\.\.\.$/.exec(
140
+ text,
141
+ );
142
+ if (npm) return `Updating ${npm[1]?.slice(0, 100)}…`;
143
+ if (/^Updating (?:git:|https?:\/\/|ssh:\/\/)/.test(text))
144
+ return "Updating git package…";
145
+ if (
146
+ text.startsWith("Updating pi with ") ||
147
+ text === "Updating managed pi installation..."
148
+ )
149
+ return "Updating Pi…";
150
+ if (/^pi is already up to date \(v[^()]+\)$/.test(text))
151
+ return "Pi is up to date";
152
+ if (/^Updated pi from \S+ to \S+$/.test(text)) return "Pi updated";
153
+ return undefined;
154
+ }
155
+
156
+ // @lat: [[auto-updates#Update isolation]]
157
+ export async function acquireLock(
158
+ agentDir: string,
159
+ ): Promise<(() => Promise<void>) | undefined> {
160
+ await mkdir(agentDir, { recursive: true });
161
+ const path = join(agentDir, "proper-updater.lock");
162
+ let file: FileHandle;
163
+ try {
164
+ file = await open(path, "wx", 0o600);
165
+ } catch (error) {
166
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return undefined;
167
+ throw error;
168
+ }
169
+ try {
170
+ await file.writeFile(`${process.pid}\n`);
171
+ } catch (error) {
172
+ await unlink(path);
173
+ throw error;
174
+ } finally {
175
+ await file.close();
176
+ }
177
+ return () => unlink(path);
178
+ }
179
+
180
+ // Keep npm/git and their descendants inside one process group. Never kill only
181
+ // the CLI parent and release the lock while an installer still mutates files.
182
+ export function run(
183
+ command: string,
184
+ args: string[],
185
+ options: {
186
+ cwd: string;
187
+ env: NodeJS.ProcessEnv;
188
+ signal: AbortSignal;
189
+ timeout?: number;
190
+ onLine?: (line: string) => void;
191
+ },
192
+ ): Promise<CommandResult> {
193
+ return new Promise((resolve, reject) => {
194
+ if (options.signal.aborted) {
195
+ resolve({ code: 1, stdout: "", stopped: true });
196
+ return;
197
+ }
198
+ const child = spawn(command, args, {
199
+ cwd: options.cwd,
200
+ env: options.env,
201
+ detached: true,
202
+ stdio: ["ignore", "pipe", "pipe"],
203
+ });
204
+ let stdout = "";
205
+ let lineBuffer = "";
206
+ let oversizedLine = false;
207
+ const emitLine = () => {
208
+ if (!oversizedLine && lineBuffer.length <= 4096)
209
+ options.onLine?.(lineBuffer);
210
+ lineBuffer = "";
211
+ oversizedLine = false;
212
+ };
213
+ let stopped = false;
214
+ let overflow = false;
215
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
216
+ const kill = (signal: NodeJS.Signals) => {
217
+ if (!child.pid) return;
218
+ try {
219
+ process.kill(-child.pid, signal);
220
+ } catch (error) {
221
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
222
+ }
223
+ };
224
+ const stop = () => {
225
+ if (stopped) return;
226
+ stopped = true;
227
+ kill("SIGTERM");
228
+ killTimer = setTimeout(() => kill("SIGKILL"), 1000);
229
+ };
230
+ const timer = setTimeout(stop, options.timeout ?? TIMEOUT_MS);
231
+ options.signal.addEventListener("abort", stop, { once: true });
232
+ child.stdout.setEncoding("utf8");
233
+ child.stdout.on("data", (chunk: string) => {
234
+ if (options.onLine) {
235
+ const lines = chunk.split(/[\r\n]/);
236
+ for (const [index, line] of lines.entries()) {
237
+ if (index > 0) emitLine();
238
+ if (!oversizedLine) lineBuffer += line;
239
+ if (lineBuffer.length > 4096) {
240
+ lineBuffer = "";
241
+ oversizedLine = true;
242
+ }
243
+ }
244
+ }
245
+ stdout += chunk;
246
+ if (stdout.length > 1_048_576) {
247
+ stdout = stdout.slice(-1_048_576);
248
+ overflow = true;
249
+ }
250
+ });
251
+ // Do not leak registry credentials or private repository URLs into the UI.
252
+ child.stderr.resume();
253
+ let spawnError: Error | undefined;
254
+ child.on("error", (error) => {
255
+ spawnError = error;
256
+ });
257
+ child.on("close", (code) => {
258
+ if (lineBuffer) emitLine();
259
+ clearTimeout(timer);
260
+ clearTimeout(killTimer);
261
+ options.signal.removeEventListener("abort", stop);
262
+ // Descendants may have closed their pipes but still be alive.
263
+ if (stopped) kill("SIGKILL");
264
+ if (spawnError) reject(spawnError);
265
+ else resolve({ code: overflow ? 1 : (code ?? 1), stdout, stopped });
266
+ });
267
+ });
268
+ }
@@ -0,0 +1,146 @@
1
+ import { lstatSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ type ExtensionContext,
5
+ InteractiveMode,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { installWrapper } from "../host-interop.ts";
8
+
9
+ const ID = "proper-updater-enabled";
10
+ const disabledPath = (agentDir: string) =>
11
+ join(agentDir, "proper-updater.disabled");
12
+
13
+ export function readEnabled(agentDir: string): boolean {
14
+ try {
15
+ lstatSync(disabledPath(agentDir));
16
+ return false;
17
+ } catch (error) {
18
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
19
+ return true;
20
+ }
21
+ }
22
+
23
+ function saveEnabled(agentDir: string, enabled: boolean): void {
24
+ try {
25
+ if (enabled) unlinkSync(disabledPath(agentDir));
26
+ else {
27
+ mkdirSync(agentDir, { recursive: true, mode: 0o700 });
28
+ writeFileSync(disabledPath(agentDir), "", { flag: "wx", mode: 0o600 });
29
+ }
30
+ } catch (error) {
31
+ if (
32
+ (error as NodeJS.ErrnoException).code !== (enabled ? "ENOENT" : "EEXIST")
33
+ )
34
+ throw error;
35
+ }
36
+ }
37
+
38
+ type Item = {
39
+ id: string;
40
+ label: string;
41
+ description?: string;
42
+ currentValue: string;
43
+ values: string[];
44
+ };
45
+ type List = { items: Item[]; onChange(id: string, value: string): void };
46
+
47
+ // @lat: [[auto-updates#Settings toggle]]
48
+ export function installSettings(
49
+ agentDir: string,
50
+ ctx: ExtensionContext,
51
+ onChange: (enabled: boolean) => void,
52
+ ) {
53
+ let enabled = false;
54
+ const warn = (error: unknown) => {
55
+ if (typeof (error as NodeJS.ErrnoException).code !== "string") throw error;
56
+ ctx.ui.notify(
57
+ "proper-base updates: Could not read or save the auto-update preference. Automatic updates keep their previous setting (disabled if unreadable).",
58
+ "warning",
59
+ );
60
+ };
61
+ try {
62
+ enabled = readEnabled(agentDir);
63
+ } catch (error) {
64
+ warn(error);
65
+ }
66
+ let active = true;
67
+ let clearItem: (() => void) | undefined;
68
+ const target = InteractiveMode.prototype;
69
+ const native = Reflect.get(target, "showSettingsSelector");
70
+ let remove: (() => void) | undefined;
71
+ if (typeof native === "function") {
72
+ remove = installWrapper(
73
+ target,
74
+ "showSettingsSelector",
75
+ function (this: InteractiveMode, ...args: unknown[]) {
76
+ const result = Reflect.apply(native, this, args);
77
+ if (
78
+ !active ||
79
+ Reflect.get(this, "sessionManager") !== ctx.sessionManager
80
+ )
81
+ return result;
82
+ clearItem?.();
83
+ clearItem = undefined;
84
+ const container = Reflect.get(this, "editorContainer") as
85
+ | { children?: { settingsList?: List }[] }
86
+ | undefined;
87
+ const list = container?.children?.find(
88
+ (child) => child.constructor?.name === "SettingsSelectorComponent",
89
+ )?.settingsList;
90
+ if (
91
+ !list ||
92
+ !Array.isArray(list.items) ||
93
+ typeof list.onChange !== "function" ||
94
+ list.items.some((item) => item.id === ID)
95
+ )
96
+ return result;
97
+ const item: Item = {
98
+ id: ID,
99
+ label: "Automatic updates",
100
+ description:
101
+ "proper-base: install detected updates on the next launch. Startup flags override this preference; running installs are not interrupted.",
102
+ currentValue: String(enabled),
103
+ values: ["true", "false"],
104
+ };
105
+ list.items.push(item);
106
+ const nativeChange = list.onChange;
107
+ const restoreChange = installWrapper(
108
+ list,
109
+ "onChange",
110
+ function (this: List, id: string, value: string) {
111
+ if (id !== ID || !active)
112
+ return Reflect.apply(nativeChange, this, [id, value]);
113
+ if (value !== "true" && value !== "false") return;
114
+ try {
115
+ saveEnabled(agentDir, value === "true");
116
+ enabled = value === "true";
117
+ } catch (error) {
118
+ warn(error);
119
+ }
120
+ item.currentValue = String(enabled);
121
+ onChange(enabled);
122
+ },
123
+ );
124
+ clearItem = () => {
125
+ restoreChange();
126
+ const index = list.items.indexOf(item);
127
+ if (index !== -1) list.items.splice(index, 1);
128
+ };
129
+ return result;
130
+ },
131
+ );
132
+ } else
133
+ ctx.ui.notify(
134
+ "proper-base updates: This Pi version cannot show the Automatic updates setting. Use --no-auto-update instead.",
135
+ "warning",
136
+ );
137
+ return {
138
+ enabled: () => enabled,
139
+ dispose() {
140
+ active = false;
141
+ clearItem?.();
142
+ clearItem = undefined;
143
+ remove?.();
144
+ },
145
+ };
146
+ }
@@ -0,0 +1,114 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ type EditorFactory = NonNullable<
4
+ ReturnType<ExtensionContext["ui"]["getEditorComponent"]>
5
+ >;
6
+ type EditorKeybindings = Parameters<EditorFactory>[2];
7
+ type BindingValue = ReturnType<EditorKeybindings["getUserBindings"]>[string];
8
+
9
+ const INSTALLED = Symbol.for("pi-proper-base.fullscreen-keybindings");
10
+ const LEGACY_INSTALLED = Symbol.for("pi-proper-customs.fullscreen-keybindings");
11
+ const FULLSCREEN_KEYS = {
12
+ "tui.altScreen.pageUp": "ctrl+shift+pageUp",
13
+ "tui.altScreen.pageDown": "ctrl+shift+pageDown",
14
+ "tui.altScreen.top": "ctrl+shift+home",
15
+ "tui.altScreen.bottom": "ctrl+shift+end",
16
+ } as const;
17
+ const OWNED_ACTIONS = [
18
+ ...Object.keys(FULLSCREEN_KEYS),
19
+ "app.clipboard.pasteImage",
20
+ "tui.input.newLine",
21
+ "app.message.followUp",
22
+ ] as const;
23
+
24
+ type Controller = { apply(capture?: boolean): void; restore?(): void };
25
+ type PatchedKeybindings = EditorKeybindings & {
26
+ [INSTALLED]?: true | Controller;
27
+ [LEGACY_INSTALLED]?: true | Controller;
28
+ };
29
+
30
+ function sameBinding(a: BindingValue, b: BindingValue): boolean {
31
+ return JSON.stringify(a) === JSON.stringify(b);
32
+ }
33
+
34
+ /** Install proper-base bindings and return an ownership-checked restoration. */
35
+ export function installBaseKeybindings(
36
+ keybindings: EditorKeybindings,
37
+ ): () => void {
38
+ const patched = keybindings as PatchedKeybindings;
39
+ const previous = patched[INSTALLED] ?? patched[LEGACY_INSTALLED];
40
+ if (previous && previous !== true) {
41
+ if (previous.restore) previous.restore();
42
+ else previous.apply = () => {};
43
+ }
44
+
45
+ const originalReload = keybindings.reload;
46
+ let installed = true;
47
+ let baseline: Record<string, BindingValue> = {};
48
+ let applied: Record<string, BindingValue> = {};
49
+ const captureBaseline = () => {
50
+ const current = keybindings.getUserBindings();
51
+ baseline = Object.fromEntries(
52
+ OWNED_ACTIONS.filter((action) => action in current).map((action) => [
53
+ action,
54
+ current[action],
55
+ ]),
56
+ );
57
+ };
58
+ const controller: Controller = {
59
+ apply(capture = false) {
60
+ if (!installed) return;
61
+ if (capture) captureBaseline();
62
+ const imagePasteKeys = [
63
+ ...new Set([
64
+ ...keybindings.getKeys("app.clipboard.pasteImage"),
65
+ "ctrl+v" as const,
66
+ "ctrl+shift+v" as const,
67
+ ]),
68
+ ];
69
+ const newLineKeys = [
70
+ ...new Set([
71
+ ...keybindings.getKeys("tui.input.newLine"),
72
+ "alt+enter" as const,
73
+ ]),
74
+ ];
75
+ const followUpKeys = keybindings
76
+ .getKeys("app.message.followUp")
77
+ .filter((key) => key !== "alt+enter");
78
+ const next: Record<string, BindingValue> = {
79
+ ...keybindings.getUserBindings(),
80
+ ...FULLSCREEN_KEYS,
81
+ "app.clipboard.pasteImage": imagePasteKeys,
82
+ "tui.input.newLine": newLineKeys,
83
+ "app.message.followUp": followUpKeys,
84
+ };
85
+ keybindings.setUserBindings(next);
86
+ applied = Object.fromEntries(
87
+ OWNED_ACTIONS.map((action) => [action, next[action]]),
88
+ );
89
+ },
90
+ restore() {
91
+ installed = false;
92
+ if (patched[INSTALLED] !== controller) return;
93
+ if (keybindings.reload === reload) keybindings.reload = originalReload;
94
+ const current = keybindings.getUserBindings();
95
+ const next = { ...current };
96
+ for (const action of OWNED_ACTIONS) {
97
+ if (!sameBinding(current[action], applied[action])) continue;
98
+ if (action in baseline) next[action] = baseline[action];
99
+ else delete next[action];
100
+ }
101
+ keybindings.setUserBindings(next);
102
+ delete patched[INSTALLED];
103
+ },
104
+ };
105
+ function reload(): void {
106
+ originalReload.call(keybindings);
107
+ controller.apply(true);
108
+ }
109
+ keybindings.reload = reload;
110
+ patched[INSTALLED] = controller;
111
+ delete patched[LEGACY_INSTALLED];
112
+ controller.apply(true);
113
+ return () => controller.restore?.();
114
+ }