pi-better-show 0.5.2 → 0.6.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.
package/README.md CHANGED
@@ -49,7 +49,7 @@ If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr
49
49
  - `view: "page"` opens the file in your default browser.
50
50
  Markdown renders with its blocks; `.html`, `.tsx`, and `.jsx` run in a sandboxed frame; images show as they are.
51
51
  - `view: "edit"` (the default) opens the file in your editor.
52
- Each save reaches the agent as a diff, without starting a turn.
52
+ Your saves reach the agent as one net diff per file, without starting a turn.
53
53
  - Select any passage on a page to comment on it.
54
54
  The feedback panel sends your comments and an overall note in one message.
55
55
  - Open pages reload when the agent edits the file.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.5.2",
3
+ "version": "0.6.1",
4
4
  "description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,9 +27,18 @@ import {
27
27
  type PublishedDocument,
28
28
  parseAnswer,
29
29
  } from "./contract.ts";
30
- import { createEditSession, defaultLaunch, defaultRun, EDITOR_ENV, type EditDeps, WATCH_MS } from "./edit.ts";
30
+ import {
31
+ createEditSession,
32
+ defaultLaunch,
33
+ defaultRun,
34
+ EDITOR_ENV,
35
+ type EditDeps,
36
+ SETTLE_MS,
37
+ WATCH_MS,
38
+ } from "./edit.ts";
31
39
  import { createAllowList, HTML_FILE, IMAGE_FILE, MARKDOWN_FILE, REACT_FILE } from "./files.ts";
32
40
  import type { PageServer, PageServerOptions } from "./server.ts";
41
+ import { onPath, urlOpener } from "./system.ts";
33
42
 
34
43
  export const MESSAGE_TYPE = "better-show";
35
44
  export const MINI_SDD_FILE = /(^|\/)docs\/specs\/[^/]+\/(decision|spec|design|verification)\.md$/;
@@ -41,8 +50,8 @@ export const MAX_DOCUMENTS = 32;
41
50
  export const MAX_REMEMBERED_ANSWERS = 256;
42
51
  /** How long a page just sent to the browser counts as open before its tab connects. */
43
52
  export const PAGE_OPEN_WAIT_MS = 15_000;
44
- /** The command that opens a URL in the default browser. */
45
- export const OPENER = process.platform === "darwin" ? "open" : "xdg-open";
53
+ /** The command that opens a URL in the default browser (system.ts: `rundll32` on Windows, by absolute path). */
54
+ export const OPENER = urlOpener(process.platform)[0];
46
55
 
47
56
  export type View = "page" | "edit";
48
57
 
@@ -58,6 +67,8 @@ export interface Deps extends EditDeps {
58
67
  realpath: (path: string) => string;
59
68
  newId: () => string;
60
69
  now: () => number;
70
+ /** Runs `run` after `ms`; the returned function cancels it. */
71
+ schedule: (run: () => void, ms: number) => () => void;
61
72
  }
62
73
 
63
74
  /**
@@ -69,7 +80,14 @@ export const createPageServer = async (options: PageServerOptions): Promise<Page
69
80
 
70
81
  export const defaultDeps = (): Deps => ({
71
82
  editor: process.env[EDITOR_ENV],
72
- onPath: (command) => spawnSync("sh", ["-c", 'command -v "$1"', "sh", command], { stdio: "ignore" }).status === 0,
83
+ onPath: (command) =>
84
+ onPath(
85
+ command,
86
+ process.platform,
87
+ process.env,
88
+ undefined,
89
+ (name) => spawnSync("sh", ["-c", 'command -v "$1"', "sh", name], { stdio: "ignore" }).status === 0,
90
+ ),
73
91
  launch: defaultLaunch,
74
92
  run: defaultRun,
75
93
  platform: process.platform,
@@ -90,12 +108,18 @@ export const defaultDeps = (): Deps => ({
90
108
  },
91
109
  servePages: createPageServer,
92
110
  openUrl: (url) => {
93
- const opened = defaultRun(OPENER, [url]);
94
- if (opened.status !== 0) throw new Error(`${OPENER} failed: ${(opened.stderr || opened.stdout).trim()}`);
111
+ const [opener, args] = urlOpener(process.platform);
112
+ const opened = defaultRun(opener, args(url));
113
+ if (opened.status !== 0) throw new Error(`${opener} failed: ${(opened.stderr || opened.stdout).trim()}`);
95
114
  },
96
115
  realpath: (path) => (existsSync(path) ? realpathSync(path) : path),
97
116
  newId: randomUUID,
98
117
  now: Date.now,
118
+ schedule: (run, ms) => {
119
+ const timer = setTimeout(run, ms);
120
+ timer.unref?.();
121
+ return () => clearTimeout(timer);
122
+ },
99
123
  });
100
124
 
101
125
  interface DocEntry {
@@ -143,7 +167,48 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
143
167
  if (ctx?.hasUI) ctx.ui.notify(`${notice} go to the agent with your next message.`, "info");
144
168
  };
145
169
 
146
- const edits = createEditSession(deps, (message, display) => deliver(message, `Your edits to ${display}`));
170
+ // The user's saves are held, not sent one by one: when idle, their net change joins the next run as it starts;
171
+ // while the agent works, it is steered in once the saves stop for SETTLE_MS.
172
+ let cancelSettle: (() => void) | undefined;
173
+ /** The file of the last change waiting to be reported, while one waits. */
174
+ let waiting: string | undefined;
175
+ /** The user was told their edits wait for their next message. */
176
+ let told = false;
177
+ const busy = (): boolean => ctx !== undefined && !ctx.isIdle();
178
+ const editMessage = (text: string) => ({ customType: MESSAGE_TYPE, content: text, display: true });
179
+ const stopSettle = (): void => {
180
+ cancelSettle?.();
181
+ cancelSettle = undefined;
182
+ };
183
+ /** Takes every unreported change; the user's next change starts a new report. */
184
+ const takeEdits = (): string | undefined => {
185
+ stopSettle();
186
+ waiting = undefined;
187
+ told = false;
188
+ return edits.take();
189
+ };
190
+ const tellHeld = (display: string): void => {
191
+ if (told || !ctx?.hasUI) return;
192
+ told = true;
193
+ ctx.ui.notify(`Your edits to ${display} go to the agent with your next message.`, "info");
194
+ };
195
+ const settleLater = (display: string): void => {
196
+ stopSettle();
197
+ cancelSettle = deps.schedule(() => {
198
+ cancelSettle = undefined;
199
+ if (!busy()) return tellHeld(display);
200
+ const text = takeEdits();
201
+ if (text) pi.sendMessage(editMessage(text), { deliverAs: "steer" });
202
+ }, SETTLE_MS);
203
+ };
204
+ const edits = createEditSession(deps, {
205
+ changed: (display) => {
206
+ waiting = display;
207
+ if (busy()) settleLater(display);
208
+ else tellHeld(display);
209
+ },
210
+ urgent: (text) => deliver(text, "Your edits"),
211
+ });
147
212
 
148
213
  const listed = (): PublishedDocument[] =>
149
214
  [...docs.values()].map((entry) => ({
@@ -462,8 +527,20 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
462
527
  /** A turn or run ended: tool calls that never ended no longer hold back the user's saves. */
463
528
  const agentSettled = (): void => edits.settle();
464
529
 
530
+ /** A run starts: the user's edits since the agent last saw each file join it as one message, or nothing when none changed. */
531
+ const agentStarting = (): { customType: string; content: string; display: boolean } | undefined => {
532
+ const text = takeEdits();
533
+ return text ? editMessage(text) : undefined;
534
+ };
535
+
536
+ /** A run started without a prompt (a queued message or a retry): edits still waiting go in once the saves settle. */
537
+ const agentStarted = (): void => {
538
+ if (waiting !== undefined && !cancelSettle) settleLater(waiting);
539
+ };
540
+
465
541
  const shutdown = (): void => {
466
542
  closed = true;
543
+ stopSettle();
467
544
  docs.clear();
468
545
  answers.clear();
469
546
  edits.close();
@@ -484,6 +561,8 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
484
561
  agentWrote,
485
562
  agentWillWrite,
486
563
  agentSettled,
564
+ agentStarting,
565
+ agentStarted,
487
566
  shutdown,
488
567
  setContext: (next: ExtensionContext) => {
489
568
  ctx = next;
@@ -1,10 +1,15 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { join } from "node:path";
3
+ import { gitDiffHunks, windowsTextEditor } from "./system.ts";
3
4
 
4
5
  /** Edit mode (D7): the user's own editor, no terminal pane. Saves are noticed by watching the file. */
5
6
 
6
7
  export const EDITOR_ENV = "PI_BETTER_SHOW_EDITOR";
7
8
  export const MAX_DIFF_CHARS = 20_000;
9
+ /** A reported diff keeps at most this many lines. */
10
+ export const MAX_DIFF_LINES = 200;
11
+ /** While the agent works, edits are reported once the user stopped saving for this long. */
12
+ export const SETTLE_MS = 3000;
8
13
  export const WATCH_MS = 500;
9
14
 
10
15
  export interface RunResult {
@@ -44,8 +49,11 @@ export const defaultLaunch = (command: string, args: string[]): Promise<void> =>
44
49
  });
45
50
  });
46
51
 
47
- /** Splits a command line into words, honouring single and double quotes and backslash escapes; no expansion happens. */
48
- export function shellWords(line: string): string[] {
52
+ /**
53
+ * Splits a command line into words, honouring single and double quotes and backslash escapes; no expansion happens. With `windows`, a
54
+ * backslash is an ordinary character, so `"C:\\Program Files\\Editor\\editor.exe" -w` keeps its path.
55
+ */
56
+ export function shellWords(line: string, windows = false): string[] {
49
57
  const words: string[] = [];
50
58
  let word = "";
51
59
  let quote: string | undefined;
@@ -54,12 +62,12 @@ export function shellWords(line: string): string[] {
54
62
  const char = line[index] as string;
55
63
  if (quote) {
56
64
  if (char === quote) quote = undefined;
57
- else if (char === "\\" && quote === '"' && index + 1 < line.length) word += line[++index];
65
+ else if (!windows && char === "\\" && quote === '"' && index + 1 < line.length) word += line[++index];
58
66
  else word += char;
59
67
  } else if (char === "'" || char === '"') {
60
68
  quote = char;
61
69
  started = true;
62
- } else if (char === "\\" && index + 1 < line.length) {
70
+ } else if (!windows && char === "\\" && index + 1 < line.length) {
63
71
  word += line[++index];
64
72
  started = true;
65
73
  } else if (/\s/.test(char)) {
@@ -76,24 +84,27 @@ export function shellWords(line: string): string[] {
76
84
  return words;
77
85
  }
78
86
 
79
- /** The user's edits as zero-context hunks: the `@@` headers carry the line numbers. */
87
+ /** The user's edits as zero-context hunks: the `@@` headers carry the line numbers. A long diff keeps its first lines and says how many it left out. */
80
88
  export function feedbackMessage(display: string, diff: string, duringShell = false): string {
81
- const hunks = diff
82
- .split("\n")
83
- .filter((line) => !line.startsWith("--- ") && !line.startsWith("+++ "))
84
- .join("\n");
85
- const body =
86
- hunks.length > MAX_DIFF_CHARS ? `${hunks.slice(0, MAX_DIFF_CHARS)}\n… (truncated; read ${display})\n` : hunks;
89
+ const lines = diff.split("\n").filter((line) => !line.startsWith("--- ") && !line.startsWith("+++ "));
90
+ if (lines.at(-1) === "") lines.pop();
91
+ const kept = lines.slice(0, MAX_DIFF_LINES).join("\n");
92
+ const body = kept.slice(0, MAX_DIFF_CHARS);
93
+ const left = lines.length - Math.min(lines.length, MAX_DIFF_LINES);
94
+ const more = left > 0 ? `: ${left} more diff line${left === 1 ? "" : "s"}` : "";
95
+ const cut = left > 0 || body.length < kept.length ? `\n… (truncated${more}; read ${display})` : "";
87
96
  const head = duringShell
88
97
  ? `${display} changed while a shell command ran; this may include the command's own changes, not only the user's edits:`
89
98
  : `User edited ${display}:`;
90
- return `${head}\n\`\`\`diff\n${body}\`\`\``;
99
+ return `${head}\n\`\`\`diff\n${body}${cut}\n\`\`\``;
91
100
  }
92
101
 
93
102
  interface Watched {
94
103
  display: string;
95
- /** The content the agent last saw. */
104
+ /** The content the agent last saw: the baseline of the next report. */
96
105
  snapshot: string;
106
+ /** Part of the change not yet reported came while a shell command ran. */
107
+ duringShell: boolean;
97
108
  stop: () => void;
98
109
  onError: (error: Error) => void;
99
110
  }
@@ -104,7 +115,19 @@ interface Active {
104
115
  before: Map<string, string>;
105
116
  }
106
117
 
107
- export function createEditSession(deps: EditDeps, onEdit: (message: string, display: string) => void) {
118
+ export interface EditEvents {
119
+ /** A shown file changed in a way the agent has not seen; it waits for `take`. Called on every such change. */
120
+ changed: (display: string) => void;
121
+ /** The agent is about to write a file whose unreported change it must see first: deliver this at once. */
122
+ urgent: (message: string) => void;
123
+ }
124
+
125
+ /**
126
+ * Watches the documents opened in the user's editor and keeps what changed since the agent last saw each one.
127
+ * Saves are not reported one by one: `take` reports the net change of every file since the last report, once,
128
+ * so intermediate states never reach the agent and a change undone before the report sends nothing.
129
+ */
130
+ export function createEditSession(deps: EditDeps, events: EditEvents) {
108
131
  const watched = new Map<string, Watched>();
109
132
  /**
110
133
  * Tool calls running now, by tool call id: a change seen meanwhile is the agent's. They are keyed by id so a call
@@ -116,7 +139,7 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
116
139
  /** Opens the paths in the user's editor: the chosen command, else VS Code, else the system's text editor. */
117
140
  async function open(paths: string[]): Promise<string> {
118
141
  if (deps.editor) {
119
- const [command, ...args] = shellWords(deps.editor);
142
+ const [command, ...args] = shellWords(deps.editor, deps.platform === "win32");
120
143
  if (!command) throw new Error(`${EDITOR_ENV} is empty`);
121
144
  if (!deps.onPath(command)) throw new Error(`${EDITOR_ENV}=${deps.editor}, but ${command} is not on PATH`);
122
145
  await deps.launch(command, [...args, ...paths]);
@@ -126,6 +149,12 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
126
149
  await deps.launch("code", paths);
127
150
  return "VS Code";
128
151
  }
152
+ if (deps.platform === "win32") {
153
+ // Notepad, by absolute path, is on every Windows machine; it opens one file per window.
154
+ const notepad = windowsTextEditor();
155
+ for (const path of paths) await deps.launch(notepad, [path]);
156
+ return "Notepad";
157
+ }
129
158
  const [command, args] =
130
159
  deps.platform === "darwin" ? (["open", ["-t", ...paths]] as const) : (["xdg-open", paths] as const);
131
160
  if (!deps.onPath(command)) throw new Error(`edit mode needs ${EDITOR_ENV}, VS Code (code), or ${command} on PATH`);
@@ -141,18 +170,72 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
141
170
  return "the system text editor";
142
171
  }
143
172
 
173
+ /**
174
+ * Zero-context hunks from `before` to `after`. `diff` when it is on PATH; on Windows without it (Git for Windows keeps `diff` out of the
175
+ * PATH it adds), `git diff --no-index`, whose header lines are taken out. Both exit 1 when the files differ.
176
+ */
177
+ function diffOf(before: string, after: string, display: string): string {
178
+ if (deps.platform === "win32" && !deps.onPath("diff")) {
179
+ const git = deps.run("git", [
180
+ "-c",
181
+ "core.autocrlf=false",
182
+ "-c",
183
+ "core.safecrlf=false",
184
+ "diff",
185
+ "--no-index",
186
+ "--no-color",
187
+ "--no-ext-diff",
188
+ "-U0",
189
+ "--",
190
+ before,
191
+ after,
192
+ ]);
193
+ if (git.status !== 0 && git.status !== 1)
194
+ throw new Error(`git diff failed: ${(git.stderr || git.stdout).trim()}`);
195
+ return gitDiffHunks(git.stdout);
196
+ }
197
+ const diff = deps.run("diff", ["-U0", "--label", `a/${display}`, "--label", `b/${display}`, before, after]);
198
+ if (diff.status !== 0 && diff.status !== 1) throw new Error(`diff failed: ${diff.stderr.trim()}`);
199
+ return diff.stdout;
200
+ }
201
+
144
202
  const paused = (path: string): boolean =>
145
203
  [...active.values()].some((call) => call.path === undefined || call.path === path);
146
204
 
147
- /** Reports how `path` went from `from` to `content`, and makes `content` the version the agent saw. */
148
- function report(path: string, doc: Watched, from: string, content: string, duringShell: boolean): void {
205
+ /** The diff of a file from what the agent saw to `content`, as a message section; the agent has now seen `content`. */
206
+ function report(doc: Watched, content: string): string {
149
207
  scratch ??= deps.makeDir();
150
208
  const before = join(scratch, "before");
151
- deps.writeFile(before, from);
152
- const diff = deps.run("diff", ["-U0", "--label", `a/${doc.display}`, "--label", `b/${doc.display}`, before, path]);
153
- if (diff.status !== 0 && diff.status !== 1) throw new Error(`diff failed: ${diff.stderr.trim()}`);
209
+ const after = join(scratch, "after");
210
+ deps.writeFile(before, doc.snapshot);
211
+ // The content read, not the file: a save landing between the read and the diff waits for the next report.
212
+ deps.writeFile(after, content);
213
+ const section = feedbackMessage(doc.display, diffOf(before, after, doc.display), doc.duringShell);
154
214
  doc.snapshot = content;
155
- onEdit(feedbackMessage(doc.display, diff.stdout, duringShell), doc.display);
215
+ doc.duringShell = false;
216
+ return section;
217
+ }
218
+
219
+ /** The net change of each file (of `only`, when given) since the agent last saw it, in one message; undefined when nothing changed. */
220
+ function take(only?: string): string | undefined {
221
+ const sections: string[] = [];
222
+ for (const [path, doc] of watched) {
223
+ if ((only !== undefined && path !== only) || paused(path)) continue;
224
+ const content = deps.readFile(path);
225
+ if (content === undefined) continue;
226
+ if (content === doc.snapshot) {
227
+ doc.duringShell = false;
228
+ continue;
229
+ }
230
+ try {
231
+ sections.push(report(doc, content));
232
+ } catch (error) {
233
+ doc.snapshot = content;
234
+ doc.duringShell = false;
235
+ doc.onError(error as Error);
236
+ }
237
+ }
238
+ return sections.length > 0 ? sections.join("\n\n") : undefined;
156
239
  }
157
240
 
158
241
  function onChange(path: string): void {
@@ -160,10 +243,10 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
160
243
  if (!doc || paused(path)) return;
161
244
  const content = deps.readFile(path);
162
245
  if (content === undefined || content === doc.snapshot) return;
163
- report(path, doc, doc.snapshot, content, false);
246
+ events.changed(doc.display);
164
247
  }
165
248
 
166
- /** A call ended: the version the agent saw is what is on disk now, except that a shell command's window reports what changed in it. */
249
+ /** A call ended: a write or edit's result is the version the agent saw; a shell command's window joins what waits to be reported. */
167
250
  function release(id: string): void {
168
251
  const call = active.get(id);
169
252
  if (!call) return;
@@ -172,23 +255,24 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
172
255
  if (call.path !== undefined && call.path !== path) continue;
173
256
  const content = deps.readFile(path);
174
257
  if (content === undefined) continue;
258
+ if (call.path !== undefined) {
259
+ doc.snapshot = content;
260
+ doc.duringShell = false;
261
+ continue;
262
+ }
175
263
  // Measured against what the agent last saw, so a save the watcher had not seen yet still counts, and a
176
- // second shell command ending on the same change reports nothing again. The label says whether the change
177
- // came while the command ran.
264
+ // second shell command ending on the same change adds nothing. The label says whether the change came while
265
+ // the command ran.
266
+ if (content === doc.snapshot) continue;
178
267
  const began = call.before.get(path);
179
- if (call.path === undefined && content !== doc.snapshot) {
180
- try {
181
- report(path, doc, doc.snapshot, content, began === undefined || content !== began);
182
- } catch (error) {
183
- doc.snapshot = content;
184
- doc.onError(error as Error);
185
- }
186
- } else doc.snapshot = content;
268
+ if (began === undefined || content !== began) doc.duringShell = true;
269
+ events.changed(doc.display);
187
270
  }
188
271
  }
189
272
 
190
273
  return {
191
274
  open,
275
+ take,
192
276
  /** Starts watching a document; a document already watched keeps the version the agent saw. */
193
277
  watch(path: string, display: string, content: string, onError: (error: Error) => void): void {
194
278
  const known = watched.get(path);
@@ -203,10 +287,13 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
203
287
  onError(error as Error);
204
288
  }
205
289
  });
206
- watched.set(path, { display, snapshot: content, stop, onError });
290
+ watched.set(path, { display, snapshot: content, duringShell: false, stop, onError });
207
291
  },
208
292
  has: (path: string): boolean => watched.has(path),
209
- /** The tool call `id` is about to write `path` (or run a shell command, when `path` is undefined). */
293
+ /**
294
+ * The tool call `id` is about to write `path` (or run a shell command, when `path` is undefined). Before a write
295
+ * or edit replaces the version the agent saw, the user's unreported change to that file goes out at once.
296
+ */
210
297
  willWrite(id: string, path: string | undefined): void {
211
298
  const before = new Map<string, string>();
212
299
  if (path === undefined) {
@@ -214,6 +301,9 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
214
301
  const content = deps.readFile(watchedPath);
215
302
  if (content !== undefined) before.set(watchedPath, content);
216
303
  }
304
+ } else if (watched.has(path)) {
305
+ const message = take(path);
306
+ if (message) events.urgent(message);
217
307
  }
218
308
  active.set(id, { path, before });
219
309
  },
@@ -46,6 +46,13 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
46
46
  }
47
47
  });
48
48
  pi.on("turn_end", () => show.agentSettled());
49
+ // The user's saves reach the agent as one net diff per file when a run starts, instead of one message per save.
50
+ pi.on("before_agent_start", (_event, ctx) => {
51
+ show.setContext(ctx);
52
+ const message = show.agentStarting();
53
+ return message ? { message } : undefined;
54
+ });
55
+ pi.on("agent_start", () => show.agentStarted());
49
56
  pi.on("agent_end", () => show.agentSettled());
50
57
 
51
58
  pi.on("tool_result", async (event, ctx) => {
@@ -0,0 +1,78 @@
1
+ import { statSync } from "node:fs";
2
+ import { win32 } from "node:path";
3
+
4
+ /** Platform details the extension needs from the operating system: the browser opener, the PATH lookup, the fallback text editor. */
5
+
6
+ type Env = Record<string, string | undefined>;
7
+
8
+ /** A Windows program under `%SystemRoot%`, by absolute path, so that a `rundll32` or `notepad` earlier on PATH (Git for Windows puts its own tools there) is never the one run. */
9
+ export const systemProgram = (env: Env, ...parts: string[]): string =>
10
+ win32.join(env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows", ...parts);
11
+
12
+ /**
13
+ * The command that opens a URL in the default browser. On Windows it is `rundll32 url.dll,FileProtocolHandler`, which takes the URL as one
14
+ * argument with no shell in between, so `&` and `%` in a query reach the browser as written (`cmd /c start` would parse them), and exits 0.
15
+ */
16
+ export function urlOpener(
17
+ platform: string,
18
+ env: Env = process.env,
19
+ ): [command: string, args: (url: string) => string[]] {
20
+ if (platform === "darwin") return ["open", (url) => [url]];
21
+ if (platform === "win32")
22
+ return [systemProgram(env, "System32", "rundll32.exe"), (url) => ["url.dll,FileProtocolHandler", url]];
23
+ return ["xdg-open", (url) => [url]];
24
+ }
25
+
26
+ const isFile = (path: string): boolean => {
27
+ try {
28
+ return statSync(path).isFile();
29
+ } catch {
30
+ return false;
31
+ }
32
+ };
33
+
34
+ /**
35
+ * Whether `command` names a program on PATH that can be started without a shell. On Windows the PATH is scanned, with no shell (a desk
36
+ * machine need not have `sh`), for `.exe` and `.com` only: Node spawns nothing else without `shell: true`, so a `code.cmd` shim counts as
37
+ * absent and the caller falls back instead of failing at launch. Elsewhere `sh -c 'command -v'` answers, as it did before.
38
+ */
39
+ export function onPath(
40
+ command: string,
41
+ platform: string,
42
+ env: Env = process.env,
43
+ exists: (path: string) => boolean = isFile,
44
+ shell: (command: string) => boolean = () => false,
45
+ ): boolean {
46
+ if (platform !== "win32") return shell(command);
47
+ const ext = /\.([^\\/.]+)$/.exec(command)?.[1]?.toLowerCase();
48
+ if (ext === "exe" || ext === "com") return checkNames([command], command, env, exists);
49
+ return checkNames([`${command}.exe`, `${command}.com`], command, env, exists);
50
+ }
51
+
52
+ function checkNames(names: string[], command: string, env: Env, exists: (path: string) => boolean): boolean {
53
+ const path = env.PATH ?? env.Path ?? "";
54
+ if (/[\\/]/.test(command)) return names.some((name) => exists(name));
55
+ const dirs = path
56
+ .split(";")
57
+ .map((dir) => dir.replace(/^"(.*)"$/, "$1"))
58
+ .filter((dir) => dir !== "");
59
+ return dirs.some((dir) => names.some((name) => exists(win32.join(dir, name))));
60
+ }
61
+
62
+ /** The text editor a Windows machine always has, for edit mode when neither PI_BETTER_SHOW_EDITOR nor VS Code is there; it opens one file per window. */
63
+ export const windowsTextEditor = (env: Env = process.env): string => systemProgram(env, "notepad.exe");
64
+
65
+ /**
66
+ * `git diff --no-index` output with git's own header lines taken out, so that what is left reads like `diff -U0` without `--label`: the
67
+ * `@@` hunks and their lines. The `---` and `+++` lines go too; the caller names the file itself. Git writes the line before a hunk after its
68
+ * header (`@@ -2 +2 @@ one`); that context is dropped, as `diff` has none. A binary change keeps git's `Binary files … differ` line.
69
+ */
70
+ export function gitDiffHunks(stdout: string): string {
71
+ const lines = stdout.split("\n");
72
+ const first = lines.findIndex((line) => line.startsWith("@@"));
73
+ if (first === -1) return lines.find((line) => line.startsWith("Binary files ")) ?? "";
74
+ return lines
75
+ .slice(first)
76
+ .map((line) => (line.startsWith("@@") ? line.replace(/^(@@ [^@]* @@).*$/, "$1") : line))
77
+ .join("\n");
78
+ }