Files
openbot/scripts/pin-opencode-runtime.ts
Aleksander DygońandClaude Opus 5.5 03c2ff34c2 Remove code comments and add the no-comments rule (#12604)
* Remove code comments and add the no-comments rule

Remove the comments from first-party code and configuration files:
TS/JS, JSX, CSS, SQL migrations, Swift, Kotlin, Gradle, shell,
Docker, systemd, Nix, YAML, TOML, JSONC and GritQL.

Keep only what a tool reads: license headers, shebangs, compiler
and lint directives, JSDoc types in plain .js files, generated file
headers, GritQL scope lines, the install-server.sh help text and the
openbot-boat-pre-stop marker. Vendored code, fixtures and released
schemas keep their comments.

Add the rule to AGENTS.md, and change the docs that asked for
comments. Add two i18n keys that only comments named to
RELEASED_SOURCE_KEYS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep comments that are data in strings

The benchmark task files in opencode-free-models-bench.ts tell the
model what each function must do. The sample file and HTML page in
the two stories are display content. Put their comments back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep released migrations and mobile native inputs unchanged

check:migrations compares each released migration with v0.73.0 byte
for byte, so restore src/backend/migrations. A change to a native
build input of apps/mobile makes a new runtime version, so restore
those files and the extra fingerprint sources.

List these files and the comment markers that a tool reads in
AGENTS.md. Remove the last requests for comments in
src/renderer/AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:19:28 +01:00

246 lines
10 KiB
TypeScript

import { execFileSync } from "node:child_process";
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { z } from "zod";
import { type AgentRuntimeLock, loadAgentRuntimeLock } from "./agent-runtime-lock";
import { sha256, sha256File } from "./remote-desktop-runtime-release";
export type OpencodeRuntimeTarget = "darwin-arm64" | "darwin-x64" | "linux-x64" | "linux-arm64" | "win32-x64";
const TARGETS = {
"darwin-arm64": { package: "@opencode/cli-darwin-arm64", executable: "opencode", platformDirectory: "mac" },
"darwin-x64": { package: "@opencode/cli-darwin-x64", executable: "opencode", platformDirectory: "mac" },
"linux-x64": { package: "@opencode/cli-linux-x64", executable: "opencode", platformDirectory: "linux" },
"linux-arm64": { package: "@opencode/cli-linux-arm64", executable: "opencode", platformDirectory: "linux" },
"win32-x64": { package: "@opencode/cli-windows-x64", executable: "opencode.exe", platformDirectory: "win" },
} as const satisfies Record<OpencodeRuntimeTarget, { package: string; executable: string; platformDirectory: string }>;
const TARGET_IDS: readonly OpencodeRuntimeTarget[] = [
"darwin-arm64",
"darwin-x64",
"linux-x64",
"linux-arm64",
"win32-x64",
];
const REGISTRY = "https://registry.npmjs.org";
const CLI_PACKAGE = "@opencode/cli";
const LICENSE_PACKAGE = "opencode-ai";
const REPOSITORY = "https://github.com/anomalyco/opencode";
const DISK_HEADROOM = 1.05;
const DISK_GRANULARITY = 10_000_000;
const umbrellaSchema = z.object({
version: z.string().regex(/^\d+\.\d+\.\d+$/u),
optionalDependencies: z.record(z.string(), z.string()),
});
const platformSchema = z.object({
name: z.string(),
version: z.string(),
dist: z.object({
tarball: z.string().url(),
unpackedSize: z.number().int().positive(),
}),
});
const packageManifestSchema = z.object({ name: z.string(), version: z.string() });
export interface OpencodeRuntimePin {
registry: string;
repository: string;
version: string;
license: "MIT";
licensePackage: { name: typeof LICENSE_PACKAGE; version: string };
licenseSha256: string;
artifacts: Record<OpencodeRuntimeTarget, OpencodeArtifactPin>;
}
interface OpencodeArtifactPin {
package: string;
asset: string;
assetSha256: string;
binarySha256: string;
downloadBytes: number;
installedBytes: number;
executable: string;
platformDirectory: string;
}
export async function pinOpencodeRuntime(
input: {
version?: string | undefined;
licenseVersion?: string | undefined;
fetchImpl?: typeof fetch;
runBinary?: boolean;
} = {},
): Promise<OpencodeRuntimePin> {
const fetchImpl = input.fetchImpl ?? fetch;
const umbrella = await fetchParsed(
fetchImpl,
`${REGISTRY}/${CLI_PACKAGE}/${input.version ?? "latest"}`,
umbrellaSchema,
);
const version = umbrella.version;
const pinTarget = (target: OpencodeRuntimeTarget) =>
pinArtifact(fetchImpl, target, version, umbrella.optionalDependencies, input.runBinary);
const artifacts: Record<OpencodeRuntimeTarget, OpencodeArtifactPin> = {
"darwin-arm64": await pinTarget("darwin-arm64"),
"darwin-x64": await pinTarget("darwin-x64"),
"linux-x64": await pinTarget("linux-x64"),
"linux-arm64": await pinTarget("linux-arm64"),
"win32-x64": await pinTarget("win32-x64"),
};
const licenseVersion =
input.licenseVersion ??
(await fetchParsed(fetchImpl, `${REGISTRY}/${LICENSE_PACKAGE}/latest`, packageManifestSchema)).version;
const license = await packageLicense(fetchImpl, licenseVersion);
return {
registry: REGISTRY,
repository: REPOSITORY,
version,
license: "MIT",
licensePackage: { name: LICENSE_PACKAGE, version: licenseVersion },
licenseSha256: sha256(license),
artifacts,
};
}
async function pinArtifact(
fetchImpl: typeof fetch,
target: OpencodeRuntimeTarget,
version: string,
optionalDependencies: Record<string, string>,
runBinary = true,
): Promise<OpencodeArtifactPin> {
const descriptor = TARGETS[target];
if (optionalDependencies[descriptor.package] !== version) {
throw new Error(`${CLI_PACKAGE} ${version} does not list ${descriptor.package} at the same version.`);
}
const platform = await fetchParsed(fetchImpl, `${REGISTRY}/${descriptor.package}/${version}`, platformSchema);
if (platform.name !== descriptor.package || platform.version !== version) {
throw new Error(`The registry served the wrong package for ${target}.`);
}
const asset = `${descriptor.package.slice(descriptor.package.indexOf("/") + 1)}-${version}.tgz`;
if (platform.dist.tarball !== `${REGISTRY}/${descriptor.package}/-/${asset}`) {
throw new Error(`Unexpected tarball URL for ${target}: ${platform.dist.tarball}`);
}
const archiveBytes = await fetchBytes(fetchImpl, platform.dist.tarball);
const temporaryRoot = await mkdtemp(join(tmpdir(), "openbot-opencode-pin-"));
try {
const archive = join(temporaryRoot, asset);
const extracted = join(temporaryRoot, "extracted");
await writeFile(archive, archiveBytes, { mode: 0o600 });
validateOpencodeArchive(archive, descriptor.executable);
await mkdir(extracted, { recursive: true });
execFileSync("tar", ["-xzf", archive, "-C", extracted, "--no-same-owner"], { stdio: "inherit" });
const packageRoot = join(extracted, "package");
const manifest = packageManifestSchema.parse(JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")));
if (manifest.name !== descriptor.package || manifest.version !== version) {
throw new Error(`The ${target} package manifest does not match the registry metadata.`);
}
const binary = join(packageRoot, "bin", descriptor.executable);
if (runBinary && target === `${process.platform}-${process.arch}`) {
await chmod(binary, 0o755);
const printed = execFileSync(binary, ["--version"], { encoding: "utf8", windowsHide: true }).trim();
if (printed.replace(/^(?:opencode\s+)?v?/iu, "") !== version) {
throw new Error(`The ${target} binary prints "${printed}" and not "${version}".`);
}
}
return {
package: descriptor.package,
asset,
assetSha256: sha256(archiveBytes),
binarySha256: await sha256File(binary),
downloadBytes: archiveBytes.byteLength,
installedBytes: Math.ceil((platform.dist.unpackedSize * DISK_HEADROOM) / DISK_GRANULARITY) * DISK_GRANULARITY,
executable: descriptor.executable,
platformDirectory: descriptor.platformDirectory,
};
} finally {
await rm(temporaryRoot, { recursive: true, force: true });
}
}
async function packageLicense(fetchImpl: typeof fetch, version: string): Promise<Buffer> {
const asset = `${LICENSE_PACKAGE}-${version}.tgz`;
const archiveBytes = await fetchBytes(fetchImpl, `${REGISTRY}/${LICENSE_PACKAGE}/-/${asset}`);
const temporaryRoot = await mkdtemp(join(tmpdir(), "openbot-opencode-pin-"));
try {
const archive = join(temporaryRoot, asset);
await writeFile(archive, archiveBytes, { mode: 0o600 });
execFileSync(
"tar",
["-xzf", archive, "-C", temporaryRoot, "--no-same-owner", "package/package.json", "package/LICENSE"],
{ stdio: "inherit" },
);
const manifest = packageManifestSchema.parse(
JSON.parse(await readFile(join(temporaryRoot, "package", "package.json"), "utf8")),
);
if (manifest.name !== LICENSE_PACKAGE || manifest.version !== version) {
throw new Error(`The ${LICENSE_PACKAGE} ${version} package manifest does not match the registry metadata.`);
}
return await readFile(join(temporaryRoot, "package", "LICENSE"));
} finally {
await rm(temporaryRoot, { recursive: true, force: true });
}
}
export function validateOpencodeArchive(archive: string, executable: string): string[] {
const names = execFileSync("tar", ["-tzf", archive], { encoding: "utf8" }).split(/\r?\n/u).filter(Boolean);
const details = execFileSync("tar", ["-tvzf", archive], { encoding: "utf8" }).split(/\r?\n/u).filter(Boolean);
if (details.some((line) => !["-", "d"].includes(line.trimStart().charAt(0)))) {
throw new Error("The OpenCode runtime archive contains a link or a special file.");
}
for (const name of names) {
if (name.includes("\0") || name.includes("\\")) throw new Error(`Unsafe OpenCode archive path: ${name}`);
const parts = name.replace(/\/+$/u, "").split("/");
if (parts[0] !== "package" || parts.some((part) => !part || part === "." || part === "..")) {
throw new Error(`Unsafe OpenCode archive path: ${name}`);
}
}
for (const required of ["package/package.json", `package/bin/${executable}`]) {
if (!names.includes(required)) throw new Error(`The OpenCode runtime archive is missing ${required}.`);
}
return names;
}
async function fetchParsed<Schema extends z.ZodType>(
fetchImpl: typeof fetch,
url: string,
schema: Schema,
): Promise<z.output<Schema>> {
return schema.parse(JSON.parse(Buffer.from(await fetchBytes(fetchImpl, url)).toString("utf8")));
}
async function fetchBytes(fetchImpl: typeof fetch, url: string): Promise<Buffer> {
const response = await fetchImpl(url, {
headers: { "User-Agent": "OpenBot-runtime-pin" },
redirect: "follow",
});
if (!response.ok) throw new Error(`${url} answered HTTP ${response.status}.`);
return Buffer.from(await response.arrayBuffer());
}
export function isPinnedAlready(pin: OpencodeRuntimePin, lock: AgentRuntimeLock): boolean {
return JSON.stringify(pin) === JSON.stringify(lock.opencode);
}
if (import.meta.main) {
const pin = await pinOpencodeRuntime({ version: process.argv[2], licenseVersion: process.argv[3] });
const lock = await loadAgentRuntimeLock().catch(() => null);
process.stdout.write(`${JSON.stringify({ opencode: pin }, null, 2)}\n`);
for (const target of TARGET_IDS) {
if (target !== `${process.platform}-${process.arch}`) {
process.stdout.write(`This host cannot run the ${target} binary, so its version is not asserted.\n`);
}
}
if (lock && isPinnedAlready(pin, lock)) {
process.stdout.write(`native-runtime.lock.json already pins OpenCode ${pin.version}.\n`);
} else {
process.stdout.write(`Copy the "opencode" block above into native-runtime.lock.json.\n`);
}
}