Files
thinkrail/scripts/check-binary-seams.ts
Rinat S 672d3a5a76 chore(deps): upgrade pi to 1.5.2 and expose cache warming in Settings (#1301)
* chore(deps): upgrade pi to 1.5.1 and port the Anthropic SSE framing patch

* fix(server): follow pi 1.5.1's moved provider default models

* refactor(server): drop the image-only queued-message workaround pi 1.5.1 fixes natively

* fix(server): wait for pending pi credential writes before the host exits

* fix(server): wait for pending pi credential writes before the host exits

* feat(settings): keep cache warming at streaming and expose pi's mode in Settings → Models

* fix(server): read pi settings for cache warming through createPiSettings and register the default override

* docs(pi-compatibility): record the pi 1.5.1 re-check and the cache-warming and credential-write adaptations

* docs(pi-compatibility): keep a removal gate for the queued-message image copy

* fix(server): keep the image override through pi's save() and reconcile cache warming for chats registering mid-write

* chore(deps): upgrade pi to 1.5.2

* refactor(server): trim cache-warming and credential-settle notes to one line

* fix(server): read the cache-warming mode from pi's settings file at every decision so delegated children follow it

* docs(server): record the accepted gaps of opted-in idle cache warming
2026-11-10 18:37:39 +01:00

157 lines
6.1 KiB
TypeScript

#!/usr/bin/env bun
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, resolve, sep } from "node:path";
import { parseSync, Visitor } from "oxc-parser";
const ALLOWLIST: Record<string, { reason: string; imports: string[] }> = {
"pi-ai/dist/auth/oauth/load.js": {
reason: "handled — registerBunOAuthFlows() registered in registerBundledRuntime",
imports: ["__rewriteRelativeImportExtension(new URL(runtimeSpecifier, import.meta.url).href)"],
},
"pi-ai/dist/api/bedrock-converse-stream.lazy.js": {
reason: "handled — setBedrockProviderModule() registered in registerBundledRuntime",
imports: ["__rewriteRelativeImportExtension(new URL(runtimeSpecifier, import.meta.url).href)"],
},
"pi-ai/dist/auth/context.js": {
reason:
"safe — the importNodeModule wrapper only ever receives node: builtin specifiers " +
"(a compiled binary resolves those at runtime)",
imports: ["__rewriteRelativeImportExtension(specifier)"],
},
"pi-ai/dist/env-api-keys.js": {
reason:
"safe — the dynamicImport wrapper only ever receives node: builtin specifiers " +
"(a compiled binary resolves those at runtime)",
imports: ["__rewriteRelativeImportExtension(specifier)"],
},
};
const SKIPPED_DIST_DIRS: Record<string, string> = {
"pi-coding-agent/dist/bundle":
"CLI/RPC-only bundled runtime (reachable only via pi's bin and the ./rpc-entry export) — " +
"the in-process library import ('.' → dist/index.js) never loads it, so its opaque imports " +
"(content-hashed chunk duplicates of the allowlisted modular seams) never run in the compiled binary",
};
function packageRoot(name: string, entry: string): string {
const marker = `${sep}@earendil-works${sep}${name}${sep}`;
const at = entry.lastIndexOf(marker);
if (at < 0) throw new Error(`cannot locate package root for ${name} from ${entry}`);
return entry.slice(0, at + marker.length - 1);
}
function listJsFiles(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
if (statSync(full).isDirectory()) out.push(...listJsFiles(full));
else if (full.endsWith(".js")) out.push(full);
}
return out;
}
function opaqueImportsIn(fileName: string, source: string): string[] {
const { program, errors } = parseSync(fileName, source, { lang: "jsx" });
if (errors.length > 0) {
throw new Error(`cannot parse ${fileName}: ${errors.map((error) => error.message).join("; ")}`);
}
const found: string[] = [];
new Visitor({
ImportExpression({ source: specifier }) {
const isConstant =
(specifier.type === "Literal" && typeof specifier.value === "string") ||
(specifier.type === "TemplateLiteral" && specifier.expressions.length === 0);
if (!isConstant) {
found.push(source.slice(specifier.start, specifier.end).replace(/\s+/g, " ").trim());
}
},
}).visit(program);
return found.sort();
}
const repoRoot = resolve(import.meta.dir, "..");
const roots = new Map<string, string>();
const queue: { name: string; root: string }[] = [];
const enqueue = (name: string, resolveFrom: string): void => {
if (roots.has(name)) return;
const root = packageRoot(name, Bun.resolveSync(`@earendil-works/${name}`, resolveFrom));
roots.set(name, root);
queue.push({ name, root });
};
enqueue("pi-coding-agent", join(repoRoot, "packages", "server"));
for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
const { root } = next;
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as {
dependencies?: Record<string, string>;
};
for (const dep of Object.keys(pkg.dependencies ?? {})) {
if (dep.startsWith("@earendil-works/")) enqueue(dep.slice("@earendil-works/".length), root);
}
}
const found = new Map<string, string[]>();
const usedSkips = new Set<string>();
for (const [name, root] of roots) {
for (const file of listJsFiles(join(root, "dist"))) {
const id = `${name}/${file
.slice(root.length + 1)
.split(sep)
.join("/")}`;
const skipped = Object.keys(SKIPPED_DIST_DIRS).find((dir) => id.startsWith(`${dir}/`));
if (skipped !== undefined) {
usedSkips.add(skipped);
continue;
}
const source = readFileSync(file, "utf8");
if (!/\bimport\s*\(/.test(source)) continue;
const imports = opaqueImportsIn(id, source);
if (imports.length === 0) continue;
found.set(id, imports);
}
}
const unexpected: string[] = [];
const stale: string[] = [];
for (const id of new Set([...found.keys(), ...Object.keys(ALLOWLIST)])) {
const actual = [...(found.get(id) ?? [])];
const expected = [...(ALLOWLIST[id]?.imports ?? [])].sort();
for (const imp of expected) {
const at = actual.indexOf(imp);
if (at >= 0) actual.splice(at, 1);
else stale.push(`${id}: import(${imp}) (${ALLOWLIST[id]?.reason})`);
}
unexpected.push(...actual.map((imp) => `${id}: import(${imp})`));
}
for (const [dir, reason] of Object.entries(SKIPPED_DIST_DIRS)) {
if (!usedSkips.has(dir)) stale.push(`${dir}: skipped dist dir no longer present (${reason})`);
}
if (unexpected.length > 0) {
console.error(
"check-binary-seams: NEW bundler-opaque dynamic import(s) in pi — the compiled binary cannot resolve these at runtime:",
);
for (const line of unexpected.sort()) console.error(` - ${line}`);
console.error(
"\nVerify each one: register a static seam in registerBundledRuntime (packages/server/src/agent/extensions.ts),",
);
console.error(
"or confirm it only receives node: builtins — then allowlist the occurrence in scripts/check-binary-seams.ts with that justification.",
);
}
if (stale.length > 0) {
console.error(
"check-binary-seams: stale allowlist occurrence(s) — pi moved, removed, or reshaped these imports:",
);
for (const line of stale.sort()) console.error(` - ${line}`);
console.error(
"\nRe-verify the seam still covers the replacement, then update the allowlist in scripts/check-binary-seams.ts.",
);
}
if (unexpected.length > 0 || stale.length > 0) process.exit(1);
const occurrences = [...found.values()].reduce((n, imports) => n + imports.length, 0);
console.log(
`check-binary-seams: OK (${occurrences} known opaque import occurrences in ${found.size} files across ${roots.size} pi packages, all handled or safe)`,
);