@andares/pi-toolkits 0.12.3 → 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.
- package/README.md +100 -15
- package/README.zh-CN.md +94 -14
- package/package.json +19 -10
- 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/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/index.ts +10 -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,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>`;
|