@andares/pi-toolkits 0.12.4 → 0.13.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 (65) hide show
  1. package/README.md +100 -15
  2. package/README.zh-CN.md +94 -14
  3. package/package.json +19 -10
  4. package/src/features/ask/index.ts +6 -0
  5. package/src/features/init/apply.ts +32 -12
  6. package/src/features/init/audit-uat.test.ts +103 -0
  7. package/src/features/init/audit.ts +148 -0
  8. package/src/features/init/detect.ts +4 -0
  9. package/src/features/init/index.ts +47 -2
  10. package/src/features/init/plan.ts +11 -0
  11. package/src/features/init/refresh.test.ts +208 -0
  12. package/src/features/init/refresh.ts +255 -0
  13. package/src/features/init/spec.ts +20 -0
  14. package/src/features/init/templates/agents-skeleton.md +2 -0
  15. package/src/features/init/templates/uat-readme.md +53 -0
  16. package/src/features/init/templates/workflow-block.md +21 -0
  17. package/src/features/init/templates.test.ts +3 -1
  18. package/src/features/init/templates.ts +2 -0
  19. package/src/features/init/types.ts +12 -1
  20. package/src/features/permission/index.ts +32 -0
  21. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  22. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  23. package/src/features/plan/assets/index.html +14 -0
  24. package/src/features/plan/assets.test.ts +64 -0
  25. package/src/features/plan/blocks.test.ts +77 -0
  26. package/src/features/plan/blocks.ts +153 -0
  27. package/src/features/plan/diff.test.ts +144 -0
  28. package/src/features/plan/diff.ts +193 -0
  29. package/src/features/plan/feedback.test.ts +233 -0
  30. package/src/features/plan/feedback.ts +182 -0
  31. package/src/features/plan/index.test.ts +385 -0
  32. package/src/features/plan/index.ts +433 -0
  33. package/src/features/plan/prompt.test.ts +91 -0
  34. package/src/features/plan/prompt.ts +110 -0
  35. package/src/features/plan/render.test.ts +94 -0
  36. package/src/features/plan/render.ts +131 -0
  37. package/src/features/plan/server.test.ts +374 -0
  38. package/src/features/plan/server.ts +272 -0
  39. package/src/features/plan/store.test.ts +145 -0
  40. package/src/features/plan/store.ts +244 -0
  41. package/src/features/review/index.ts +54 -28
  42. package/src/features/review/review.test.ts +46 -1
  43. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  44. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  45. package/src/features/uat/assets/index.html +14 -0
  46. package/src/features/uat/constants.ts +23 -0
  47. package/src/features/uat/index.test.ts +404 -0
  48. package/src/features/uat/index.ts +329 -0
  49. package/src/features/uat/item-tool.ts +280 -0
  50. package/src/features/uat/ledger.test.ts +249 -0
  51. package/src/features/uat/ledger.ts +504 -0
  52. package/src/features/uat/prompt.ts +78 -0
  53. package/src/features/uat/record-tool.ts +167 -0
  54. package/src/features/uat/records.test.ts +145 -0
  55. package/src/features/uat/records.ts +268 -0
  56. package/src/features/uat/server.ts +181 -0
  57. package/src/features/uat/state.test.ts +41 -0
  58. package/src/features/uat/state.ts +67 -0
  59. package/src/index.ts +10 -1
  60. package/src/lib/ask-control.ts +25 -0
  61. package/src/lib/opener.test.ts +72 -0
  62. package/src/lib/opener.ts +121 -0
  63. package/src/lib/permission-control.ts +39 -0
  64. package/src/lib/startup.test.ts +1 -1
  65. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,181 @@
1
+ /**
2
+ * UAT server — the acceptance page, served from inside the pi process.
3
+ *
4
+ * Routes (all behind the shared token/Host/Origin shell):
5
+ * GET /api/state → derived acceptance state (items, pending records, counts)
6
+ * POST /api/toggle → {item, checked}: append a check/uncheck event
7
+ * GET /api/report → raw text of one change record (evidence in a drawer)
8
+ * GET /api/events → SSE; any change (from this process or another) arrives
9
+ * as a `state` event
10
+ *
11
+ * There is no submit endpoint on purpose: a checkbox writes its event
12
+ * immediately, so closing the page cannot lose a decision. The watcher exists
13
+ * because the ledger is a file: another pi session may append to it while this
14
+ * page is open, and the page must converge without a reload.
15
+ */
16
+ import { statSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { UAT_WATCH_MS } from "./constants.js";
20
+ import {
21
+ appendEvent,
22
+ ledgerPath,
23
+ newEventId,
24
+ type UatState,
25
+ } from "./ledger.js";
26
+ import { readRecordText } from "./records.js";
27
+ import { loadSnapshot } from "./state.js";
28
+ import { bindHost, isWsl, urlHost } from "../../lib/opener.js";
29
+ import { startWebServer, type WebServerHandle } from "../../lib/web-review.js";
30
+
31
+ export interface UatPayload extends UatState {
32
+ root: string;
33
+ /** Malformed ledger lines (a corrupt stream must not look like an empty one). */
34
+ skipped: number;
35
+ /** Minimal record index for the evidence drawer. */
36
+ records: Array<{ id: string; title: string; at?: string }>;
37
+ }
38
+
39
+ export function buildUatPayload(root: string): UatPayload {
40
+ const snapshot = loadSnapshot(root);
41
+ return {
42
+ ...snapshot.state,
43
+ root,
44
+ skipped: snapshot.skipped,
45
+ records: snapshot.records.map((record) => ({
46
+ id: record.id,
47
+ title: record.title,
48
+ at: record.at,
49
+ })),
50
+ };
51
+ }
52
+
53
+ export interface StartUatServerOptions {
54
+ root: string;
55
+ assetsDir?: string;
56
+ portStart?: number;
57
+ portAttempts?: number;
58
+ bindHost?: string;
59
+ urlHost?: string;
60
+ /** Clock injection (tests). */
61
+ now?: () => Date;
62
+ /** Called on every request, for the idle timeout. */
63
+ onActivity?: () => void;
64
+ watchMs?: number;
65
+ }
66
+
67
+ export interface UatServerHandle {
68
+ url: string;
69
+ port: number;
70
+ token: string;
71
+ close: () => Promise<void>;
72
+ broadcast: (event: string, data: unknown) => void;
73
+ }
74
+
75
+ export async function startUatServer(options: StartUatServerOptions): Promise<UatServerHandle> {
76
+ const assetsDir = options.assetsDir ?? fileURLToPath(new URL("./assets/", import.meta.url));
77
+ const now = options.now ?? (() => new Date());
78
+ const watchMs = options.watchMs ?? UAT_WATCH_MS;
79
+ const touch = options.onActivity ?? (() => {});
80
+
81
+ const signature = (): string => {
82
+ const parts: string[] = [];
83
+ try {
84
+ const stat = statSync(ledgerPath(options.root));
85
+ parts.push(`l:${stat.size}:${stat.mtimeMs}`);
86
+ } catch {
87
+ parts.push("l:none");
88
+ }
89
+ try {
90
+ const stat = statSync(join(options.root, ".agents/implementations"));
91
+ parts.push(`r:${stat.mtimeMs}`);
92
+ } catch {
93
+ parts.push("r:none");
94
+ }
95
+ return parts.join("|");
96
+ };
97
+
98
+ let handle: WebServerHandle | undefined;
99
+ let lastSignature = signature();
100
+
101
+ const server = await startWebServer({
102
+ assetsDir,
103
+ portStart: options.portStart,
104
+ portAttempts: options.portAttempts,
105
+ bindHost: options.bindHost ?? bindHost(isWsl()),
106
+ urlHost: options.urlHost ?? urlHost(isWsl()),
107
+ routes: async (ctx) => {
108
+ touch();
109
+ if (ctx.url.pathname === "/api/state" && ctx.req.method === "GET") {
110
+ ctx.json(buildUatPayload(options.root));
111
+ return true;
112
+ }
113
+
114
+ if (ctx.url.pathname === "/api/toggle" && ctx.req.method === "POST") {
115
+ const body = (await ctx.readBody()) as { item?: unknown; checked?: unknown };
116
+ const item = typeof body.item === "string" ? body.item : "";
117
+ if (typeof body.checked !== "boolean") {
118
+ ctx.json({ error: "checked must be a boolean" }, 400);
119
+ return true;
120
+ }
121
+ const checked = body.checked;
122
+ const snapshot = loadSnapshot(options.root);
123
+ const known = snapshot.state.items.some((entry) => entry.id === item);
124
+ if (!known) {
125
+ ctx.json({ error: "unknown item" }, 404);
126
+ return true;
127
+ }
128
+ const at = now();
129
+ appendEvent(ledgerPath(options.root), {
130
+ v: 1,
131
+ id: newEventId(at),
132
+ ts: at.toISOString(),
133
+ type: checked ? "check" : "uncheck",
134
+ item,
135
+ });
136
+ const payload = buildUatPayload(options.root);
137
+ lastSignature = signature();
138
+ ctx.broadcast("state", { reason: "toggle" });
139
+ ctx.json({ ok: true, state: payload });
140
+ return true;
141
+ }
142
+
143
+ if (ctx.url.pathname === "/api/report" && ctx.req.method === "GET") {
144
+ const id = ctx.url.searchParams.get("id") ?? "";
145
+ const text = readRecordText(options.root, id);
146
+ if (text === undefined) {
147
+ ctx.json({ error: "unknown record" }, 404);
148
+ return true;
149
+ }
150
+ ctx.json({ id, text });
151
+ return true;
152
+ }
153
+
154
+ return false;
155
+ },
156
+ });
157
+ handle = server;
158
+
159
+ // Another process may append to the ledger (or add a record) while the page
160
+ // is open; converge without asking the operator to reload.
161
+ const watcher = setInterval(() => {
162
+ const next = signature();
163
+ if (next === lastSignature) return;
164
+ lastSignature = next;
165
+ handle?.broadcast("state", { reason: "external" });
166
+ }, watchMs);
167
+ watcher.unref();
168
+
169
+ const close = async (): Promise<void> => {
170
+ clearInterval(watcher);
171
+ await handle?.close();
172
+ };
173
+
174
+ return {
175
+ url: server.url,
176
+ port: server.port,
177
+ token: server.token,
178
+ close,
179
+ broadcast: server.broadcast,
180
+ };
181
+ }
@@ -0,0 +1,41 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterEach, describe, expect, it } from "vitest";
6
+ import { resetProjectRootCache, resolveProjectRoot } from "./state.js";
7
+
8
+ const roots: string[] = [];
9
+
10
+ afterEach(() => {
11
+ resetProjectRootCache();
12
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
13
+ });
14
+
15
+ function git(cwd: string, args: string[]): void {
16
+ execFileSync("git", ["-C", cwd, ...args], { stdio: "ignore" });
17
+ }
18
+
19
+ describe("resolveProjectRoot", () => {
20
+ it("uses the cwd itself outside git", () => {
21
+ const root = mkdtempSync(join(tmpdir(), "uat-nongit-"));
22
+ roots.push(root);
23
+ expect(resolveProjectRoot(root)).toBe(root);
24
+ });
25
+
26
+ it("resolves a linked worktree to the main checkout", () => {
27
+ const main = mkdtempSync(join(tmpdir(), "uat-main-"));
28
+ const parent = mkdtempSync(join(tmpdir(), "uat-worktrees-"));
29
+ const linked = join(parent, "linked");
30
+ roots.push(main, parent);
31
+ git(main, ["init", "-q"]);
32
+ writeFileSync(join(main, "file.txt"), "one\n", "utf8");
33
+ git(main, ["add", "file.txt"]);
34
+ git(main, ["-c", "user.email=test@example.com", "-c", "user.name=test", "commit", "-qm", "init"]);
35
+ git(main, ["worktree", "add", "-qb", "uat-review", linked]);
36
+
37
+ resetProjectRootCache();
38
+ expect(resolveProjectRoot(linked)).toBe(main);
39
+ expect(resolveProjectRoot(main)).toBe(main);
40
+ });
41
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * UAT feature — where the project lives and what the ledger currently says.
3
+ *
4
+ * **The ledger belongs to the main checkout.** A linked git worktree has its
5
+ * own working tree, and writing acceptance history into it would split the
6
+ * record the moment a second agent session uses `git worktree add`. So the root
7
+ * is resolved through `git worktree list` (first entry = the main worktree) and
8
+ * every read/write of `.agents/uat/` and `.agents/implementations/` uses it.
9
+ *
10
+ * Resolution is cached per cwd: the page polls, `/ask-uat` reads, and nothing
11
+ * changed in between. The cache is the reason a UI refresh does not spawn git.
12
+ */
13
+ import { execFileSync } from "node:child_process";
14
+ import { existsSync } from "node:fs";
15
+ import { join, resolve } from "node:path";
16
+ import { STATE_FILE } from "../init/spec.js";
17
+ import { deriveState, ledgerPath, readEvents, type UatState } from "./ledger.js";
18
+ import { listRecords, type RecordEntry } from "./records.js";
19
+
20
+ const rootCache = new Map<string, string>();
21
+
22
+ /** The main worktree of the repository containing `cwd` (or `cwd` itself). */
23
+ export function resolveProjectRoot(cwd: string): string {
24
+ const start = resolve(cwd);
25
+ const cached = rootCache.get(start);
26
+ if (cached) return cached;
27
+
28
+ let root = start;
29
+ try {
30
+ const output = execFileSync("git", ["-C", start, "worktree", "list", "--porcelain"], {
31
+ encoding: "utf8",
32
+ timeout: 3000,
33
+ stdio: ["ignore", "pipe", "ignore"],
34
+ });
35
+ const line = output.split("\n").find((entry) => entry.startsWith("worktree "));
36
+ const first = line?.slice("worktree ".length).trim();
37
+ if (first) root = resolve(first);
38
+ } catch {
39
+ // Not a git checkout (or git is missing): the cwd is the project.
40
+ }
41
+ rootCache.set(start, root);
42
+ return root;
43
+ }
44
+
45
+ /** Test seam: forget the memoized roots. */
46
+ export function resetProjectRootCache(): void {
47
+ rootCache.clear();
48
+ }
49
+
50
+ /** The UAT flow only exists in a project that installed the framework. */
51
+ export function frameworkInstalled(root: string): boolean {
52
+ return existsSync(join(root, STATE_FILE));
53
+ }
54
+
55
+ export interface UatSnapshot {
56
+ root: string;
57
+ records: RecordEntry[];
58
+ state: UatState;
59
+ /** Malformed ledger lines; surfaced so a corrupt file is not silently "empty". */
60
+ skipped: number;
61
+ }
62
+
63
+ export function loadSnapshot(root: string): UatSnapshot {
64
+ const records = listRecords(root);
65
+ const { events, skipped } = readEvents(ledgerPath(root));
66
+ return { root, records, state: deriveState(records, events), skipped };
67
+ }
package/src/index.ts CHANGED
@@ -8,11 +8,12 @@
8
8
  * - ask — read-only Q&A mode (/ask)
9
9
  * - favorites — model favorites (ctrl+A/ctrl+J in /model, favorites-only cycling)
10
10
  * - stash — prompt stash (ctrl+alt+y swap / double-press stash-and-clear)
11
- * - review — third-party code review with a configured review model (third-review)
11
+ * - review — third-party code review with a configured review model (/ask-review, alias /third-review)
12
12
  * - compact — dedicated compact model for /compact + auto-compact summaries
13
13
  * - autostart — replay project-declared slash commands at session start (/add-dir persistence)
14
14
  * - permission — session-scoped boundary permission checks (/ask-perm)
15
15
  * - init — agent memory framework install / adoption (/ask-init)
16
+ * - uat — acceptance ledger and browser page (/ask-uat, record_change)
16
17
  * - quit-guard — quit watchdog: force-exit when pi's shutdown hangs (/quit-guard)
17
18
  *
18
19
  * `ask` and `permission` are independent gates on one bus: each answers its own
@@ -28,9 +29,11 @@ import { registerCompact } from "./features/compact/index.js";
28
29
  import { registerFavorites } from "./features/favorites/index.js";
29
30
  import { registerInit } from "./features/init/index.js";
30
31
  import { registerPermission } from "./features/permission/index.js";
32
+ import { registerPlan } from "./features/plan/index.js";
31
33
  import { registerQuitGuard } from "./features/quit-guard/index.js";
32
34
  import { registerReview } from "./features/review/index.js";
33
35
  import { registerStash } from "./features/stash/index.js";
36
+ import { registerUat } from "./features/uat/index.js";
34
37
 
35
38
  export default function piToolkits(pi: ExtensionAPI): void {
36
39
  // One rolling audit sink for every gate. Creation is lazy and side-effect
@@ -42,6 +45,9 @@ export default function piToolkits(pi: ExtensionAPI): void {
42
45
  // Permission registers its session_start reset before autostart, so a
43
46
  // project-declared `/ask-perm ...` runs against a freshly reset mode.
44
47
  registerPermission(pi, gates, { audit });
48
+ // Plan mode drives the permission control that `registerPermission` just
49
+ // published (it turns checks on while planning and restores them after).
50
+ registerPlan(pi, gates);
45
51
  registerAutostart(pi);
46
52
  registerCompact(pi);
47
53
  registerFavorites(pi);
@@ -49,6 +55,9 @@ export default function piToolkits(pi: ExtensionAPI): void {
49
55
  registerQuitGuard(pi);
50
56
  registerReview(pi);
51
57
  registerStash(pi);
58
+ // UAT registers after plan so its `before_agent_start` re-assertion runs last
59
+ // and can add `record_change` to whatever tool set plan installed.
60
+ registerUat(pi);
52
61
 
53
62
  gates.install(pi);
54
63
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * ask control — lets `/ask-plan` leave consult mode before opening its broader
3
+ * planning phase.
4
+ *
5
+ * `/ask` owns its state and its tool-set snapshot, so another feature must not
6
+ * imitate the exit by manipulating tools itself. This small handle is the same
7
+ * registry pattern as `permission-control.ts`: the owner publishes enter/exit
8
+ * semantics, the caller only asks for a transition.
9
+ */
10
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+
12
+ export interface AskControl {
13
+ isActive(): boolean;
14
+ exit(ctx: ExtensionContext): void;
15
+ }
16
+
17
+ let current: AskControl | undefined;
18
+
19
+ export function setAskControl(control: AskControl | undefined): void {
20
+ current = control;
21
+ }
22
+
23
+ export function getAskControl(): AskControl | undefined {
24
+ return current;
25
+ }
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { bindHost, isWsl, pickOpener, urlHost } from "./opener.js";
3
+
4
+ const URL_UNDER_TEST = "http://172.24.47.146:3401/?t=abc";
5
+
6
+ describe("isWsl", () => {
7
+ it("detects WSL from the environment", () => {
8
+ expect(isWsl({ WSL_DISTRO_NAME: "Ubuntu-24.04" } as NodeJS.ProcessEnv, "")).toBe(true);
9
+ expect(isWsl({ WSL_INTEROP: "/run/WSL/1_interop" } as NodeJS.ProcessEnv, "")).toBe(true);
10
+ });
11
+
12
+ it("detects WSL from the kernel string", () => {
13
+ expect(isWsl({} as NodeJS.ProcessEnv, "Linux version 6.18.33.2-microsoft-standard-WSL2")).toBe(true);
14
+ expect(isWsl({} as NodeJS.ProcessEnv, "Linux version 6.8.0-generic")).toBe(false);
15
+ });
16
+ });
17
+
18
+ describe("bindHost / urlHost", () => {
19
+ it("binds everything on WSL, because Windows cannot reach 127.0.0.1 there", () => {
20
+ expect(bindHost(true)).toBe("0.0.0.0");
21
+ expect(bindHost(false)).toBe("127.0.0.1");
22
+ });
23
+
24
+ it("never puts 0.0.0.0 in the URL", () => {
25
+ expect(urlHost(false)).toBe("127.0.0.1");
26
+ expect(urlHost(true)).not.toBe("0.0.0.0");
27
+ });
28
+ });
29
+
30
+ describe("pickOpener", () => {
31
+ const has = (...commands: string[]) => (command: string) => commands.includes(command);
32
+
33
+ it("prefers wslview on WSL", () => {
34
+ expect(pickOpener(URL_UNDER_TEST, { wsl: true, has: has("wslview", "cmd.exe") })).toEqual({
35
+ command: "wslview",
36
+ args: [URL_UNDER_TEST],
37
+ });
38
+ });
39
+
40
+ it("falls back to cmd.exe start with an empty window title and a Windows cwd", () => {
41
+ const plan = pickOpener(URL_UNDER_TEST, { wsl: true, has: has("cmd.exe", "xdg-open") });
42
+ expect(plan).toEqual({
43
+ command: "cmd.exe",
44
+ args: ["/c", "start", "", URL_UNDER_TEST],
45
+ cwd: "/mnt/c",
46
+ });
47
+ });
48
+
49
+ it("falls back to powershell Start-Process and escapes single quotes", () => {
50
+ const plan = pickOpener("http://x/?t=it's", { wsl: true, has: has("powershell.exe") });
51
+ expect(plan?.command).toBe("powershell.exe");
52
+ expect(plan?.args.join(" ")).toContain("Start-Process 'http://x/?t=it''s'");
53
+ });
54
+
55
+ it("never prefers xdg-open on WSL — it would launch the WSL-internal chrome", () => {
56
+ const plan = pickOpener(URL_UNDER_TEST, { wsl: true, has: has("xdg-open") });
57
+ expect(plan).toEqual({ command: "xdg-open", args: [URL_UNDER_TEST] });
58
+ // …only as the last resort, after every Windows-side opener is missing.
59
+ expect(pickOpener(URL_UNDER_TEST, { wsl: true, has: has("cmd.exe", "xdg-open") })?.command).toBe("cmd.exe");
60
+ });
61
+
62
+ it("uses open on macOS and xdg-open elsewhere", () => {
63
+ expect(pickOpener(URL_UNDER_TEST, { wsl: false, has: has(), platform: "darwin" })?.command).toBe("open");
64
+ expect(pickOpener(URL_UNDER_TEST, { wsl: false, has: has("xdg-open"), platform: "linux" })?.command).toBe(
65
+ "xdg-open",
66
+ );
67
+ });
68
+
69
+ it("returns undefined when nothing can open it", () => {
70
+ expect(pickOpener(URL_UNDER_TEST, { wsl: false, has: has(), platform: "linux" })).toBeUndefined();
71
+ });
72
+ });
@@ -0,0 +1,121 @@
1
+ /**
2
+ * plan opener — get the review into the operator's *Windows* browser.
3
+ *
4
+ * Measured on this machine (WSL2, NAT, no `localhostForwarding`):
5
+ * - Windows cannot reach a server bound to 127.0.0.1 inside WSL, and cannot
6
+ * reach `localhost:<port>` either — only `<wsl-ip>:<port>` works;
7
+ * - `xdg-open` resolves to `/usr/bin/google-chrome`, i.e. a browser *inside*
8
+ * WSL, which is exactly the failure this module exists to avoid.
9
+ *
10
+ * So: on WSL bind 0.0.0.0 and print the eth0 address, then hand the URL to a
11
+ * Windows-side opener (`wslview`, `cmd.exe /c start`, `powershell Start-Process`)
12
+ * before ever considering `xdg-open`.
13
+ */
14
+ import { spawn, spawnSync } from "node:child_process";
15
+ import { readFileSync } from "node:fs";
16
+ import { networkInterfaces } from "node:os";
17
+
18
+ export interface OpenerPlan {
19
+ command: string;
20
+ args: string[];
21
+ /** cwd for the child — cmd.exe warns when it starts in a UNC (\\wsl.localhost) path. */
22
+ cwd?: string;
23
+ }
24
+
25
+ export interface OpenerOptions {
26
+ /** Whether we are inside WSL. */
27
+ wsl: boolean;
28
+ /** Which helpers exist on PATH. */
29
+ has: (command: string) => boolean;
30
+ platform?: NodeJS.Platform;
31
+ }
32
+
33
+ export function isWsl(env: NodeJS.ProcessEnv = process.env, procVersion?: string): boolean {
34
+ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
35
+ const version =
36
+ procVersion ??
37
+ (() => {
38
+ try {
39
+ return readFileSync("/proc/version", "utf8");
40
+ } catch {
41
+ return "";
42
+ }
43
+ })();
44
+ return /microsoft/i.test(version);
45
+ }
46
+
47
+ /** First non-internal IPv4 address — the address Windows must use under NAT. */
48
+ export function primaryIPv4(): string | undefined {
49
+ for (const addresses of Object.values(networkInterfaces())) {
50
+ for (const address of addresses ?? []) {
51
+ if (address.family === "IPv4" && !address.internal) return address.address;
52
+ }
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ /** Address the review server binds to. */
58
+ export function bindHost(wsl: boolean): string {
59
+ return wsl ? "0.0.0.0" : "127.0.0.1";
60
+ }
61
+
62
+ /** Host to put in the printed URL (what the browser will connect to). */
63
+ export function urlHost(wsl: boolean): string {
64
+ if (!wsl) return "127.0.0.1";
65
+ return primaryIPv4() ?? "127.0.0.1";
66
+ }
67
+
68
+ /**
69
+ * Pick the command that opens `url`, preferring the Windows side on WSL.
70
+ * Returns undefined when nothing suitable exists (the caller just prints the URL).
71
+ */
72
+ export function pickOpener(url: string, options: OpenerOptions): OpenerPlan | undefined {
73
+ const { wsl, has } = options;
74
+ if (wsl) {
75
+ if (has("wslview")) return { command: "wslview", args: [url] };
76
+ if (has("cmd.exe")) {
77
+ // `start "" <url>`: the empty title is mandatory, otherwise the URL
78
+ // itself is taken for the window title. cwd must be a Windows path.
79
+ return { command: "cmd.exe", args: ["/c", "start", "", url], cwd: "/mnt/c" };
80
+ }
81
+ if (has("powershell.exe")) {
82
+ return {
83
+ command: "powershell.exe",
84
+ args: ["-NoProfile", "-Command", `Start-Process '${url.replace(/'/g, "''")}'`],
85
+ };
86
+ }
87
+ }
88
+ if (options.platform === "darwin") return { command: "open", args: [url] };
89
+ if (has("xdg-open")) return { command: "xdg-open", args: [url] };
90
+ return undefined;
91
+ }
92
+
93
+ /** Whether a command is on PATH (no shell, no side effects). */
94
+ export function commandExists(command: string): boolean {
95
+ const probe = process.platform === "win32" ? ["where", command] : ["sh", "-c", `command -v ${command}`];
96
+ const result = spawnSync(probe[0], probe.slice(1), { stdio: "ignore" });
97
+ return result.status === 0;
98
+ }
99
+
100
+ /** Open the URL. Returns the plan used, or undefined when the caller must print it. */
101
+ export function openInBrowser(url: string): OpenerPlan | undefined {
102
+ const wsl = isWsl();
103
+ const plan = pickOpener(url, { wsl, has: commandExists });
104
+ if (!plan) return undefined;
105
+ try {
106
+ const child = spawn(plan.command, plan.args, {
107
+ cwd: plan.cwd,
108
+ detached: true,
109
+ stdio: "ignore",
110
+ });
111
+ // commandExists() is only a probe: the executable can still disappear or
112
+ // fail before spawn. Without a listener that asynchronous `error` event is
113
+ // unhandled and can take down the pi process; the printed URL is the
114
+ // recovery path either way.
115
+ child.once("error", () => {});
116
+ child.unref();
117
+ return plan;
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * permission control — the handle `/ask-plan` uses to turn the boundary checks
3
+ * on for the planning phase and put them back afterwards.
4
+ *
5
+ * Why a registry instead of an import: `/ask-perm` keeps its state in a closure
6
+ * inside `registerPermission()`, so there is no module-level setter to call.
7
+ * A tiny registry (same pattern as `src/lib/startup.ts` for the autostart
8
+ * handoff) lets the permission feature publish a control handle at registration
9
+ * time and the plan feature look it up — without either feature importing the
10
+ * other's internals, and without the plan feature knowing anything about modes.
11
+ */
12
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
+ import type { PermissionModes } from "../features/permission/constants.js";
14
+
15
+ export interface PermissionSnapshot {
16
+ enabled: boolean;
17
+ modes: PermissionModes;
18
+ }
19
+
20
+ export interface PermissionControl {
21
+ /** Current state, for `restore` later. */
22
+ snapshot(): PermissionSnapshot;
23
+ /** Turn checks on with the default modes — a no-op when already enabled. */
24
+ enableDefaults(ctx: ExtensionContext): void;
25
+ /** Put back exactly what `snapshot()` returned. */
26
+ restore(ctx: ExtensionContext, snapshot: PermissionSnapshot): void;
27
+ /** Turn checks off (used when there was nothing to restore). */
28
+ disable(ctx: ExtensionContext): void;
29
+ }
30
+
31
+ let current: PermissionControl | undefined;
32
+
33
+ export function setPermissionControl(control: PermissionControl | undefined): void {
34
+ current = control;
35
+ }
36
+
37
+ export function getPermissionControl(): PermissionControl | undefined {
38
+ return current;
39
+ }
@@ -14,7 +14,7 @@ describe("startup handoff", () => {
14
14
 
15
15
  it("ignores other commands", () => {
16
16
  markStartupCommand("ask-perm");
17
- expect(consumeStartupCommand("third-review")).toBe(false);
17
+ expect(consumeStartupCommand("ask-review")).toBe(false);
18
18
  expect(consumeStartupCommand("ask-perm")).toBe(true);
19
19
  });
20
20