@andares/pi-toolkits 0.12.4 → 0.14.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/CHANGELOG.md +43 -0
- package/README.md +134 -17
- package/README.zh-CN.md +115 -16
- package/package.json +24 -11
- package/src/features/ask/index.ts +6 -0
- package/src/features/init/apply.ts +32 -12
- package/src/features/init/audit-uat.test.ts +103 -0
- package/src/features/init/audit.ts +148 -0
- package/src/features/init/detect.ts +4 -0
- package/src/features/init/index.ts +47 -2
- package/src/features/init/plan.ts +11 -0
- package/src/features/init/refresh.test.ts +208 -0
- package/src/features/init/refresh.ts +255 -0
- package/src/features/init/spec.ts +20 -0
- package/src/features/init/templates/agents-skeleton.md +2 -0
- package/src/features/init/templates/uat-readme.md +53 -0
- package/src/features/init/templates/workflow-block.md +21 -0
- package/src/features/init/templates.test.ts +3 -1
- package/src/features/init/templates.ts +2 -0
- package/src/features/init/types.ts +12 -1
- package/src/features/permission/index.ts +32 -0
- package/src/features/permission/policy.test.ts +10 -0
- package/src/features/permission/units.test.ts +157 -0
- package/src/features/permission/units.ts +317 -15
- package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
- package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
- package/src/features/plan/assets/index.html +14 -0
- package/src/features/plan/assets.test.ts +64 -0
- package/src/features/plan/blocks.test.ts +77 -0
- package/src/features/plan/blocks.ts +153 -0
- package/src/features/plan/diff.test.ts +144 -0
- package/src/features/plan/diff.ts +193 -0
- package/src/features/plan/feedback.test.ts +233 -0
- package/src/features/plan/feedback.ts +182 -0
- package/src/features/plan/index.test.ts +385 -0
- package/src/features/plan/index.ts +433 -0
- package/src/features/plan/prompt.test.ts +91 -0
- package/src/features/plan/prompt.ts +110 -0
- package/src/features/plan/render.test.ts +94 -0
- package/src/features/plan/render.ts +131 -0
- package/src/features/plan/server.test.ts +374 -0
- package/src/features/plan/server.ts +272 -0
- package/src/features/plan/store.test.ts +145 -0
- package/src/features/plan/store.ts +244 -0
- package/src/features/review/index.ts +54 -28
- package/src/features/review/review.test.ts +46 -1
- package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
- package/src/features/uat/assets/index-DCBQCsli.js +1 -0
- package/src/features/uat/assets/index.html +14 -0
- package/src/features/uat/constants.ts +23 -0
- package/src/features/uat/index.test.ts +404 -0
- package/src/features/uat/index.ts +329 -0
- package/src/features/uat/item-tool.ts +280 -0
- package/src/features/uat/ledger.test.ts +249 -0
- package/src/features/uat/ledger.ts +504 -0
- package/src/features/uat/prompt.ts +78 -0
- package/src/features/uat/record-tool.ts +167 -0
- package/src/features/uat/records.test.ts +145 -0
- package/src/features/uat/records.ts +268 -0
- package/src/features/uat/server.ts +181 -0
- package/src/features/uat/state.test.ts +41 -0
- package/src/features/uat/state.ts +67 -0
- package/src/features/whats-new/changelog.ts +104 -0
- package/src/features/whats-new/constants.ts +35 -0
- package/src/features/whats-new/index.ts +146 -0
- package/src/features/whats-new/notice.ts +68 -0
- package/src/features/whats-new/paths.ts +29 -0
- package/src/features/whats-new/store.ts +114 -0
- package/src/features/whats-new/version.ts +43 -0
- package/src/features/whats-new/whats-new.test.ts +460 -0
- package/src/index.ts +13 -1
- package/src/lib/ask-control.ts +25 -0
- package/src/lib/opener.test.ts +72 -0
- package/src/lib/opener.ts +121 -0
- package/src/lib/permission-control.ts +39 -0
- package/src/lib/startup.test.ts +1 -1
- package/src/lib/web-review.ts +341 -0
|
@@ -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
|
+
}
|
package/src/lib/startup.test.ts
CHANGED
|
@@ -14,7 +14,7 @@ describe("startup handoff", () => {
|
|
|
14
14
|
|
|
15
15
|
it("ignores other commands", () => {
|
|
16
16
|
markStartupCommand("ask-perm");
|
|
17
|
-
expect(consumeStartupCommand("
|
|
17
|
+
expect(consumeStartupCommand("ask-review")).toBe(false);
|
|
18
18
|
expect(consumeStartupCommand("ask-perm")).toBe(true);
|
|
19
19
|
});
|
|
20
20
|
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared web-review server — the HTTP shell used by `/ask-plan` and `/ask-uat`.
|
|
3
|
+
*
|
|
4
|
+
* Both features do the same thing: serve a small Vite page from inside the pi
|
|
5
|
+
* process, hand it a token, and let it read/write state over HTTP + SSE. The
|
|
6
|
+
* shell is what makes that safe and boring:
|
|
7
|
+
*
|
|
8
|
+
* - a per-run token in the URL, echoed back as a header on API calls;
|
|
9
|
+
* - a Host allowlist and a cross-origin refusal on writes, because WSL forces
|
|
10
|
+
* `0.0.0.0` binding (see lib/opener.ts) and a loopback-only assumption would
|
|
11
|
+
* be wrong there;
|
|
12
|
+
* - a port walk so two features (or two sessions) never fight over a port;
|
|
13
|
+
* - SSR-less static file serving with real-path containment;
|
|
14
|
+
* - SSE listeners with a heartbeat, so a closed tab cannot hold the process
|
|
15
|
+
* open (listeners are removed on `close`, the server is `unref`ed).
|
|
16
|
+
*
|
|
17
|
+
* Feature code only supplies routes and renders its own payload; it never
|
|
18
|
+
* touches sockets, tokens or MIME types.
|
|
19
|
+
*/
|
|
20
|
+
import { randomBytes } from "node:crypto";
|
|
21
|
+
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
22
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
23
|
+
import { extname, isAbsolute, resolve } from "node:path";
|
|
24
|
+
import { relative as pathRelative } from "node:path";
|
|
25
|
+
|
|
26
|
+
const MIME: Record<string, string> = {
|
|
27
|
+
".html": "text/html; charset=utf-8",
|
|
28
|
+
".js": "text/javascript; charset=utf-8",
|
|
29
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
30
|
+
".css": "text/css; charset=utf-8",
|
|
31
|
+
".json": "application/json; charset=utf-8",
|
|
32
|
+
".svg": "image/svg+xml",
|
|
33
|
+
".png": "image/png",
|
|
34
|
+
".woff2": "font/woff2",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export interface WebRequestContext {
|
|
38
|
+
url: URL;
|
|
39
|
+
req: IncomingMessage;
|
|
40
|
+
res: ServerResponse;
|
|
41
|
+
port: number;
|
|
42
|
+
token: string;
|
|
43
|
+
json(body: unknown, status?: number): void;
|
|
44
|
+
text(body: string, status?: number, type?: string): void;
|
|
45
|
+
readBody(limit?: number): Promise<unknown>;
|
|
46
|
+
/** Start an SSE stream on this response (handled by the shell). */
|
|
47
|
+
sse(): void;
|
|
48
|
+
broadcast(event: string, data: unknown): void;
|
|
49
|
+
/** Set when the feature decided the server is closing (refuse new writes). */
|
|
50
|
+
closing: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface WebServerOptions {
|
|
54
|
+
assetsDir: string;
|
|
55
|
+
/** Called for authenticated `/api/*` requests; return true when handled. */
|
|
56
|
+
routes: (ctx: WebRequestContext) => boolean | Promise<boolean>;
|
|
57
|
+
portStart?: number;
|
|
58
|
+
portAttempts?: number;
|
|
59
|
+
/** Header the page echoes the token in. Default `x-plan-token`. */
|
|
60
|
+
tokenHeader?: string;
|
|
61
|
+
bindHost?: string;
|
|
62
|
+
urlHost?: string;
|
|
63
|
+
missingUiHtml?: string;
|
|
64
|
+
heartbeatMs?: number;
|
|
65
|
+
onClose?: () => void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface WebServerHandle {
|
|
69
|
+
url: string;
|
|
70
|
+
port: number;
|
|
71
|
+
token: string;
|
|
72
|
+
close(): Promise<void>;
|
|
73
|
+
broadcast(event: string, data: unknown): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function json(res: ServerResponse, body: unknown, status = 200): void {
|
|
77
|
+
const text = JSON.stringify(body);
|
|
78
|
+
res.writeHead(status, {
|
|
79
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
80
|
+
"Content-Length": Buffer.byteLength(text),
|
|
81
|
+
"Cache-Control": "no-store",
|
|
82
|
+
});
|
|
83
|
+
res.end(text);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function text(
|
|
87
|
+
res: ServerResponse,
|
|
88
|
+
body: string,
|
|
89
|
+
status = 200,
|
|
90
|
+
type = "text/plain; charset=utf-8",
|
|
91
|
+
): void {
|
|
92
|
+
res.writeHead(status, { "Content-Type": type, "Content-Length": Buffer.byteLength(body) });
|
|
93
|
+
res.end(body);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function readBody(req: IncomingMessage, limit = 1024 * 1024): Promise<unknown> {
|
|
97
|
+
return new Promise((resolveBody, reject) => {
|
|
98
|
+
const chunks: Buffer[] = [];
|
|
99
|
+
let size = 0;
|
|
100
|
+
req.on("data", (chunk: Buffer) => {
|
|
101
|
+
size += chunk.length;
|
|
102
|
+
if (size > limit) {
|
|
103
|
+
reject(new Error("body too large"));
|
|
104
|
+
req.destroy();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
chunks.push(chunk);
|
|
108
|
+
});
|
|
109
|
+
req.on("end", () => {
|
|
110
|
+
try {
|
|
111
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
112
|
+
resolveBody(raw === "" ? {} : JSON.parse(raw));
|
|
113
|
+
} catch (error) {
|
|
114
|
+
reject(error);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
req.on("error", reject);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Host:port pairs the page may be served under. */
|
|
122
|
+
export function allowedHosts(port: number, extra: string): string[] {
|
|
123
|
+
return ["127.0.0.1", "localhost", "[::1]", "::1", extra]
|
|
124
|
+
.filter((host) => host !== "")
|
|
125
|
+
.map((host) => `${host}:${port}`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parseHost(value: string | undefined): string {
|
|
129
|
+
return (value ?? "").toLowerCase();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function startWebServer(options: WebServerOptions): Promise<WebServerHandle> {
|
|
133
|
+
const token = randomBytes(12).toString("hex");
|
|
134
|
+
const tokenHeader = options.tokenHeader ?? "x-plan-token";
|
|
135
|
+
const portStart = options.portStart ?? 3401;
|
|
136
|
+
const attempts = options.portAttempts ?? 20;
|
|
137
|
+
const host = options.bindHost ?? "127.0.0.1";
|
|
138
|
+
const displayHost = options.urlHost ?? "127.0.0.1";
|
|
139
|
+
const assetsRoot = resolve(options.assetsDir);
|
|
140
|
+
const heartbeatMs = options.heartbeatMs ?? 25_000;
|
|
141
|
+
|
|
142
|
+
const listeners = new Set<ServerResponse>();
|
|
143
|
+
let heartbeat: NodeJS.Timeout | undefined;
|
|
144
|
+
|
|
145
|
+
const broadcast = (event: string, data: unknown): void => {
|
|
146
|
+
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
147
|
+
for (const listener of listeners) listener.write(payload);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const authenticate = (url: URL, req: IncomingMessage): boolean => {
|
|
151
|
+
if (url.searchParams.get("t") === token) return true;
|
|
152
|
+
return req.headers[tokenHeader] === token;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const sameOrigin = (req: IncomingMessage, port: number): boolean => {
|
|
156
|
+
const site = req.headers["sec-fetch-site"];
|
|
157
|
+
if (site === "same-origin" || site === "none") return true;
|
|
158
|
+
const origin = req.headers.origin;
|
|
159
|
+
// curl and same-process callers carry neither header. If the browser did
|
|
160
|
+
// tell us this is a cross-/same-site request but omitted Origin, fail
|
|
161
|
+
// closed rather than treating the missing header as proof of safety.
|
|
162
|
+
if (typeof origin !== "string") return site === undefined;
|
|
163
|
+
try {
|
|
164
|
+
const parsed = new URL(origin);
|
|
165
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
|
166
|
+
// An Origin without an explicit port means the protocol's default,
|
|
167
|
+
// never the port of the server receiving the request. Substituting the
|
|
168
|
+
// latter would let a page on localhost:80 impersonate this review.
|
|
169
|
+
const originPort = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
|
170
|
+
return allowedHosts(port, displayHost).includes(
|
|
171
|
+
parseHost(`${parsed.hostname}:${originPort}`),
|
|
172
|
+
);
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const handler = async (
|
|
179
|
+
req: IncomingMessage,
|
|
180
|
+
res: ServerResponse,
|
|
181
|
+
port: number,
|
|
182
|
+
state: { closing: boolean },
|
|
183
|
+
): Promise<void> => {
|
|
184
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
185
|
+
const allowed = allowedHosts(port, displayHost);
|
|
186
|
+
if (!allowed.includes(parseHost(req.headers.host))) {
|
|
187
|
+
text(res, "host not allowed", 400);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const writes = req.method === "POST" || req.method === "PUT" || req.method === "DELETE";
|
|
192
|
+
if (writes && !sameOrigin(req, port)) {
|
|
193
|
+
text(res, "cross-origin write refused", 403);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (url.pathname === "/" || url.pathname === "/index.html") {
|
|
198
|
+
if (!authenticate(url, req)) {
|
|
199
|
+
text(res, "missing or invalid token", 401);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const indexPath = resolve(assetsRoot, "index.html");
|
|
203
|
+
if (existsSync(indexPath)) {
|
|
204
|
+
text(res, readFileSync(indexPath, "utf8"), 200, MIME[".html"]);
|
|
205
|
+
} else {
|
|
206
|
+
text(res, options.missingUiHtml ?? MISSING_UI_HTML, 200, MIME[".html"]);
|
|
207
|
+
}
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (url.pathname === "/favicon.ico") {
|
|
212
|
+
res.writeHead(204).end();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (!url.pathname.startsWith("/api/")) {
|
|
217
|
+
// Vite emits the bundle at the root of `outDir` (assetsDir: "."), so the
|
|
218
|
+
// page asks for `/index-<hash>.js`, not `/assets/index-<hash>.js` —
|
|
219
|
+
// resolving any path inside assetsDir covers both layouts.
|
|
220
|
+
const requested = pathRelative(
|
|
221
|
+
assetsRoot,
|
|
222
|
+
resolve(assetsRoot, `.${decodeURIComponent(url.pathname)}`),
|
|
223
|
+
);
|
|
224
|
+
const path = resolve(assetsRoot, requested);
|
|
225
|
+
const insideAssets =
|
|
226
|
+
requested !== "" && !requested.startsWith("..") && !isAbsolute(requested);
|
|
227
|
+
if (!insideAssets || !existsSync(path) || !statSync(path).isFile()) {
|
|
228
|
+
text(res, "not found", 404);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const body = readFileSync(path);
|
|
232
|
+
res.writeHead(200, {
|
|
233
|
+
"Content-Type": MIME[extname(path)] ?? "application/octet-stream",
|
|
234
|
+
"Content-Length": body.length,
|
|
235
|
+
});
|
|
236
|
+
res.end(body);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (!authenticate(url, req)) {
|
|
241
|
+
text(res, "missing or invalid token", 401);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (url.pathname === "/api/events" && req.method === "GET") {
|
|
246
|
+
res.writeHead(200, {
|
|
247
|
+
"Content-Type": "text/event-stream",
|
|
248
|
+
"Cache-Control": "no-store",
|
|
249
|
+
Connection: "keep-alive",
|
|
250
|
+
});
|
|
251
|
+
res.write(": connected\n\n");
|
|
252
|
+
listeners.add(res);
|
|
253
|
+
req.on("close", () => listeners.delete(res));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const handled = await options.routes({
|
|
258
|
+
url,
|
|
259
|
+
req,
|
|
260
|
+
res,
|
|
261
|
+
port,
|
|
262
|
+
token,
|
|
263
|
+
json: (body, status) => json(res, body, status),
|
|
264
|
+
text: (body, status, type) => text(res, body, status, type),
|
|
265
|
+
readBody: (limit) => readBody(req, limit),
|
|
266
|
+
sse: () => {
|
|
267
|
+
res.writeHead(200, {
|
|
268
|
+
"Content-Type": "text/event-stream",
|
|
269
|
+
"Cache-Control": "no-store",
|
|
270
|
+
Connection: "keep-alive",
|
|
271
|
+
});
|
|
272
|
+
res.write(": connected\n\n");
|
|
273
|
+
listeners.add(res);
|
|
274
|
+
req.on("close", () => listeners.delete(res));
|
|
275
|
+
},
|
|
276
|
+
broadcast,
|
|
277
|
+
closing: state.closing,
|
|
278
|
+
});
|
|
279
|
+
if (!handled) {
|
|
280
|
+
text(res, "not found", 404);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const state = { closing: false };
|
|
286
|
+
let currentPort = 0;
|
|
287
|
+
let server: ReturnType<typeof createServer> | undefined;
|
|
288
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
289
|
+
const port = portStart + attempt;
|
|
290
|
+
const candidate = createServer((req, res) => {
|
|
291
|
+
void handler(req, res, port, state).catch((error: unknown) => {
|
|
292
|
+
text(res, `internal error: ${error instanceof Error ? error.message : String(error)}`, 500);
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
const started = await new Promise<boolean>((resolveStarted) => {
|
|
296
|
+
candidate.once("error", () => resolveStarted(false));
|
|
297
|
+
candidate.listen(port, host, () => resolveStarted(true));
|
|
298
|
+
});
|
|
299
|
+
if (started) {
|
|
300
|
+
server = candidate;
|
|
301
|
+
currentPort = port;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
candidate.close();
|
|
305
|
+
}
|
|
306
|
+
if (!server) {
|
|
307
|
+
throw new Error(`cannot bind a review server on ports ${portStart}–${portStart + attempts - 1}`);
|
|
308
|
+
}
|
|
309
|
+
server.unref();
|
|
310
|
+
heartbeat = setInterval(() => {
|
|
311
|
+
for (const listener of listeners) listener.write(": ping\n\n");
|
|
312
|
+
}, heartbeatMs);
|
|
313
|
+
heartbeat.unref();
|
|
314
|
+
|
|
315
|
+
const close = async (): Promise<void> => {
|
|
316
|
+
state.closing = true;
|
|
317
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
318
|
+
for (const listener of listeners) listener.end();
|
|
319
|
+
listeners.clear();
|
|
320
|
+
await new Promise<void>((resolveClosed) => server?.close(() => resolveClosed()) ?? resolveClosed());
|
|
321
|
+
options.onClose?.();
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
return {
|
|
325
|
+
url: `http://${displayHost}:${currentPort}/?t=${token}`,
|
|
326
|
+
port: currentPort,
|
|
327
|
+
token,
|
|
328
|
+
close,
|
|
329
|
+
broadcast,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const MISSING_UI_HTML = `<!doctype html>
|
|
334
|
+
<html lang="en"><head><meta charset="utf-8"><title>pi-toolkits</title>
|
|
335
|
+
<style>body{font:14px/1.6 system-ui,sans-serif;margin:3rem;max-width:42rem;color:#d8dee9;background:#1e222a}
|
|
336
|
+
code{background:#2b313c;padding:.1rem .35rem;border-radius:4px}</style></head>
|
|
337
|
+
<body><h1>The review UI is not built</h1>
|
|
338
|
+
<p>The feature's <code>assets/</code> directory is empty. Build it with <code>pnpm ui:build</code>
|
|
339
|
+
from the repository root, then reload this page.</p>
|
|
340
|
+
<p>The API works without the UI: <code>GET /api/state?t=<token></code>.</p>
|
|
341
|
+
</body></html>`;
|