mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
## Thinking Path > - Paperclip coordinates agents across local, SSH, and sandbox environments. > - Native Runner must launch artifacts for the execution host. > - A Linux controller currently selects Linux OpenCode assets for a macOS SSH host. > - Remote launch-file validation also accepts only ELF executables. > - The standard Core image must carry a verified Mac runtime for this host pair. > - This pull request adds that runtime and selects it for Apple Silicon SSH hosts. > - Self-hosted and hosted controllers can use the same generic implementation. ## Linked Issues or Issue Description **What happened?** A native OpenCode run on an Apple Silicon SSH host receives Linux controller artifacts. Its private launch-file verifier also rejects Mach-O files. A working legacy CLI agent does not exercise this path. **Expected behavior** The controller must select and verify the target's native daemon, Node, OpenCode executable, and proxy. Existing Linux targets and legacy agents must keep their current behavior. **Steps to reproduce** 1. Run a standard Linux Core image. 2. Select an SSH environment on an Apple Silicon Mac. 3. Start a native OpenCode agent with a compatible model connection. 4. Observe the incompatible runtime selection before useful agent work. **Paperclip version or commit** Base: `324ec1f537a9ba1e84239faa81bcef326a5dd1b7`. **Deployment mode** Docker or another Linux controller, with macOS ARM64 execution over SSH. Related work: #21662 covers local OpenCode confinement. #22236 covers SSH process cleanup. This change does not depend on either PR. No duplicate macOS OpenCode runtime PR was found. ## What Changed - Select a verified `darwin-arm64` runtime for OpenCode SSH targets. Preserve the Linux image default and explicit operator overrides. - Verify Mach-O launch files against the admitted architecture, file digests, and remote account. Keep existing Linux receipt and recovery behavior. - Build the Mac runtime on an Apple Silicon CI host with standalone Node 24.21.0. Keep OpenCode pinned to 1.18.34. - Package the sealed OpenCode runtime artifacts and required package metadata. Omit other harness distributions and their optional qualification inventories. - Verify archive provenance and safe extraction on Linux. Include the runtime in standard and merge-queue Core images. Avoid storing the transport archive in an image layer. - Reuse artifacts only from successful protected master image builds with identical runtime inputs. Test cache trust boundaries and register the script tests in CI. - Document runtime delivery, manual image inputs, and the initial Apple Silicon scope. No Cloud source, schema, or agent configuration changes. ## Verification - `pnpm -r typecheck` — passed. - `pnpm build` — passed. - Focused OpenCode artifact selection and private staging tests — 21 passed. - Focused native executor tests for OpenCode, SSH, and provider packs — 60 passed. - Real Rust daemon transport tests with the OpenCode protocol fixture — 4 passed. - Installed OpenCode 1.18.34 server qualification with a local provider fixture — 3 passed. - Runtime packaging, cache trust, workflow, image-contract, and merge-queue tests — 26 passed. - The CI release-workflow test group, including canary reuse and provenance — 218 passed. - Docker workflow and build-stamp guards — 29 passed after adding the Mac digest expectation, updating the excluded-source COPY expectation, and removing the redundant production commit ARG. - The source SDK registry, public-type, and evidence checks — 59 passed after updating only the root package metadata hash. Lock, compiler, parser, and model pins did not change. - Fresh-host provider-pack upload harness — 7 passed. The new regression first failed with `package_version:acpx`, then passed after the required metadata was preserved. - Node version policy — passed against a clean tracked-file snapshot. Generated local provider assets make the direct workspace scan fail; they are absent from the CI checkout. - Built, packaged, installed, and verified the actual Mac runtime. Both the controller verifier and the remote startup verifier accept its pins, target, sealed files, manifest, and package metadata. The pre-change private launch verifier rejects the real Mach-O files; the candidate accepts those same files. The dedicated archive is about 101 MB. - Live native smoke: real Mac daemon, private staged Mach-O files, OpenCode 1.18.34, and a local GLM-5.3 backend. The model read two files, edited the implementation, ran three tests, completed the semantic finish call, and summarized the three passes. An independent test run passed. The test file stayed unchanged. This used the existing `allow` mode and a scratch account-home fixture on a Mac. It does not prove hosted SSH dispatch. - The full CI workflow passed on `ae74808631f1933edec89aa1e80db7f2b756aca3`: server test shards, Runner Rust and native server tests, type checking, builds, browser suites, image checks, the native Mac producer, and Linux runtime installation. Greptile is 5/5 with no unresolved threads. - Local `pnpm test:run` used a disposable PostgreSQL 18 fixture after embedded Postgres failed to start because its macOS package lacks dynamic libraries. All six chat shards passed (1,971 tests). The redundant unsharded local run was interrupted during the general-server group after all current-head CI test jobs passed. The later local workspace and serialized groups did not run. The owned PostgreSQL fixture is stopped. This is not a local full-suite pass. Retained review failures: the first PR revision omitted package metadata and did not ignore downloaded image inputs. The fresh-host upload regression reproduced the metadata failure before its fix. Generated inputs are now ignored. CI also exposed a missing Node policy exception for the pinned Mac producer; the exception is limited to that producer job. A later policy attempt exposed an old exact-dependency assertion in canary reuse tests. The assertion now covers the added runtime and evaluates the publication gate for success, failure, cancellation, and skip outcomes. The Runner support suite then found that the new test registration changed a pinned root package input; the standard source registry generator updated that one hash, and all 59 affected tests passed. The server matrix then found four outdated image guard expectations and a duplicate production commit ARG. The focused image guards now pass after updating those expectations and keeping one commit ARG before Mac verification. Retained failures: the first producer attempt used Homebrew Node, which failed the relocation check. The successful producer used standalone Node 24.21.0. Live smoke attempts also encountered a stopped tunnel, an upstream model failure, and the existing Rust restriction on OpenCode permission requests in `ask` mode. The successful tool trace used the existing `allow` mode. Its initial reporter looked for tool names in generic item events; verification of the retained canonical tool events and an independent rerun confirmed the result. The upstream model failure is not explained by a later pass. Not run locally: a full Docker image build, because the existing Docker daemon does not respond. The PR adds native producer qualification and Linux installation verification to CI. Hosted deployment, remote service-account dispatch, and hosted continuation remain acceptance steps after deployment. ## Risks - A cold Mac runtime build adds CI time when Runner or producer inputs change. Reuse is bounded and accepts only a successful protected master producer. The artifact digest and runtime input identity remain verified. - Standard images gain a dedicated Mac runtime payload. Manual image builds can omit it; Mac OpenCode SSH runs then fail with a named missing-runtime error. Linux behavior remains available. - This release covers Apple Silicon SSH distribution. It does not qualify Intel Mac distribution or expand other harness support. - The OpenCode permission bridge keeps its existing behavior. This PR does not add `ask` approval support. - No saved run/session schema or provider pin changes. Existing Linux receipts retain their interpretation. A surviving admitted Runner bypasses new artifact discovery. Legacy agents are not converted. Existing account-change and old-receipt restoration tests remain in coverage. - No migration, cluster change, new sandbox image requirement, or Cloud control-plane change. A staging application rebuild and deployment are separate from this PR. ## Model Used OpenAI GPT-6, through Codex, with repository tools, code execution, tests, and SSH inspection. The session does not expose a more specific model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
150 lines
9.6 KiB
JavaScript
150 lines
9.6 KiB
JavaScript
import { createHash } from "node:crypto";
|
|
import { execFileSync } from "node:child_process";
|
|
import { chmodSync, closeSync, copyFileSync, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { runnerBinaryFileTarget } from "../packages/paperclip-runner/src/live/runner-binary.ts";
|
|
|
|
const schema = "paperclip.runner.remote-runtime.v1";
|
|
const target = "darwin-arm64";
|
|
const sha = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join(",")}]`
|
|
: value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value);
|
|
|
|
function shaFile(path, limit = 2 * 1024 ** 3) {
|
|
const metadata = lstatSync(path);
|
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > limit) throw Error("Invalid remote runtime file");
|
|
const fd = openSync(path, "r"), hash = createHash("sha256"), buffer = Buffer.alloc(1024 * 1024);
|
|
let total = 0;
|
|
try {
|
|
let bytes;
|
|
while ((bytes = readSync(fd, buffer, 0, buffer.length, null))) {
|
|
total += bytes;
|
|
if (total > metadata.size) throw Error("Remote runtime file changed");
|
|
hash.update(buffer.subarray(0, bytes));
|
|
}
|
|
const after = fstatSync(fd);
|
|
if (total !== metadata.size || after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs) throw Error("Remote runtime file changed");
|
|
return `sha256:${hash.digest("hex")}`;
|
|
} finally { closeSync(fd); }
|
|
}
|
|
|
|
export function createOpenCodeRuntimePack(source, destination) {
|
|
const sourceRoot = realpathSync(source);
|
|
const manifest = JSON.parse(readFileSync(join(sourceRoot, "provider-pack.json"), "utf8"));
|
|
if (manifest.digest !== sha(canonical(manifest.payload))) throw Error("Invalid source provider pack digest");
|
|
mkdirSync(destination, { recursive: true });
|
|
cpSync(join(sourceRoot, "dist"), join(destination, "dist"), { recursive: true, verbatimSymlinks: true });
|
|
for (const artifact of Object.values(manifest.payload.artifacts)) {
|
|
const path = artifact.path;
|
|
if (typeof path !== "string" || isAbsolute(path) || path.includes("\\") || path.split("/").some(part => !part || part === "." || part === "..")) throw Error("Invalid runtime artifact path");
|
|
const file = realpathSync(join(sourceRoot, path));
|
|
if (relative(sourceRoot, file).startsWith("..") || shaFile(file) !== artifact.sha256) throw Error("Invalid runtime artifact identity");
|
|
const target = join(destination, path);
|
|
mkdirSync(dirname(target), { recursive: true });
|
|
copyFileSync(file, target);
|
|
chmodSync(target, lstatSync(file).mode & 0o777);
|
|
}
|
|
for (const [name, pin] of Object.entries({ acpx: "acpx", "@agentclientprotocol/claude-agent-acp": "claudeAcp",
|
|
"@agentclientprotocol/codex-acp": "codexAcp", "opencode-ai": "opencode" })) {
|
|
const path = join("node_modules", name, "package.json"), file = realpathSync(join(sourceRoot, path));
|
|
if (relative(sourceRoot, file).startsWith("..") || JSON.parse(readFileSync(file, "utf8")).version !== manifest.payload.pins[pin]) {
|
|
throw Error(`Invalid runtime package metadata: ${name}`);
|
|
}
|
|
mkdirSync(dirname(join(destination, path)), { recursive: true });
|
|
copyFileSync(file, join(destination, path));
|
|
}
|
|
delete manifest.payload.providers;
|
|
delete manifest.payload.candidateProviders;
|
|
manifest.digest = sha(canonical(manifest.payload));
|
|
writeFileSync(join(destination, "provider-pack.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
return manifest;
|
|
}
|
|
|
|
export function verifyMacRuntime(directory, sourceRevision, inputsDigest) {
|
|
const root = resolve(directory);
|
|
if (realpathSync(root) !== root) throw Error("Remote runtime must be a canonical directory");
|
|
const metadata = JSON.parse(readFileSync(join(root, "runtime.json"), "utf8"));
|
|
const pack = JSON.parse(readFileSync(join(root, "provider-pack/provider-pack.json"), "utf8"));
|
|
const binary = join(root, "bin/paperclip-runnerd"), runner = lstatSync(binary);
|
|
if (metadata.schema !== schema || metadata.target !== target || !/^[a-f0-9]{40}$/.test(sourceRevision ?? "")
|
|
|| metadata.sourceRevision !== sourceRevision || pack.payload?.runnerSourceRevision !== sourceRevision
|
|
|| (inputsDigest !== undefined && metadata.runtimeInputsDigest !== inputsDigest)
|
|
|| pack.schema !== "paperclip-runner/remote-provider-pack/v1"
|
|
|| pack.payload?.target?.platform !== "darwin" || pack.payload?.target?.architecture !== "arm64"
|
|
|| pack.payload?.pins?.opencode !== "1.18.34"
|
|
|| metadata.providerPackDigest !== pack.digest || pack.digest !== sha(canonical(pack.payload))
|
|
|| !runner.isFile() || runner.isSymbolicLink() || (runner.mode & 0o111) === 0
|
|
|| runnerBinaryFileTarget(binary) !== target || metadata.runnerSha256 !== shaFile(binary)) {
|
|
throw Error("Remote macOS runtime source, target, pin or digest mismatch");
|
|
}
|
|
return metadata;
|
|
}
|
|
|
|
export function packageMacRuntime({ providerPack, runnerBinary, sourceRevision, output, inputsDigest }) {
|
|
if (inputsDigest !== undefined && !/^sha256:[a-f0-9]{64}$/.test(inputsDigest)) throw Error("Invalid runtime inputs digest");
|
|
if (`${process.platform}-${process.arch}` !== target) throw Error("Build the macOS runtime on a native Apple Silicon host");
|
|
if (existsSync(output)) throw Error("Remote runtime output already exists");
|
|
const root = join(resolve(output), target);
|
|
mkdirSync(join(root, "bin"), { recursive: true });
|
|
try {
|
|
createOpenCodeRuntimePack(providerPack, join(root, "provider-pack"));
|
|
copyFileSync(runnerBinary, join(root, "bin/paperclip-runnerd"));
|
|
chmodSync(join(root, "bin/paperclip-runnerd"), 0o755);
|
|
const pack = JSON.parse(readFileSync(join(root, "provider-pack/provider-pack.json"), "utf8"));
|
|
writeFileSync(join(root, "runtime.json"), JSON.stringify({ schema, sourceRevision, target, ...(inputsDigest ? { runtimeInputsDigest: inputsDigest } : {}),
|
|
providerPackDigest: pack.digest, runnerSha256: shaFile(join(root, "bin/paperclip-runnerd")) }, null, 2) + "\n");
|
|
const metadata = verifyMacRuntime(root, sourceRevision);
|
|
const archive = join(resolve(output), `${target}.tar.gz`);
|
|
execFileSync("tar", ["-czf", archive, "-C", resolve(output), target], { env: { ...process.env, COPYFILE_DISABLE: "1" } });
|
|
writeFileSync(join(resolve(output), `${target}.json`), JSON.stringify({ ...metadata, archiveSha256: shaFile(archive) }, null, 2) + "\n");
|
|
rmSync(root, { recursive: true });
|
|
return metadata;
|
|
} catch (error) {
|
|
rmSync(output, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function installMacRuntime({ input, output, sourceRevision, inputsDigest }) {
|
|
if (inputsDigest !== undefined && !/^sha256:[a-f0-9]{64}$/.test(inputsDigest)) throw Error("Invalid runtime inputs digest");
|
|
const names = readdirSync(input).filter(name => name !== ".gitkeep").sort();
|
|
if (names.length === 0) return false;
|
|
if (names.join() !== `${target}.json,${target}.tar.gz`) throw Error("Unexpected remote runtime input files");
|
|
const metadata = JSON.parse(readFileSync(join(input, `${target}.json`), "utf8"));
|
|
const archive = join(input, `${target}.tar.gz`);
|
|
if ((metadata.sourceRevision !== sourceRevision && (!inputsDigest || metadata.runtimeInputsDigest !== inputsDigest))
|
|
|| (inputsDigest && metadata.runtimeInputsDigest !== inputsDigest)
|
|
|| metadata.archiveSha256 !== shaFile(archive)) throw Error("Remote runtime archive source or digest mismatch");
|
|
if (existsSync(join(output, target))) throw Error("Remote runtime destination already exists");
|
|
mkdirSync(output, { recursive: true });
|
|
if (realpathSync(output) !== resolve(output)) throw Error("Remote runtime output must be canonical");
|
|
execFileSync("python3", ["-c", `import pathlib,sys,tarfile
|
|
archive,destination,target=sys.argv[1:]
|
|
with tarfile.open(archive,'r:gz') as bundle:
|
|
entries=bundle.getmembers()
|
|
if len(entries)>100000 or sum(e.size for e in entries)>8*1024**3: raise RuntimeError('Runtime archive exceeds bounds')
|
|
names=set()
|
|
for entry in entries:
|
|
path=pathlib.PurePosixPath(entry.name)
|
|
if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=target or entry.name in names: raise RuntimeError('Unsafe runtime archive path')
|
|
if not(entry.isfile() or entry.isdir() or entry.issym() or entry.islnk()): raise RuntimeError('Unsafe runtime archive entry')
|
|
names.add(entry.name)
|
|
bundle.extractall(destination,filter='data')
|
|
`, archive, output, target], { stdio: "pipe", timeout: 300_000 });
|
|
const { archiveSha256, ...expected } = metadata;
|
|
if (canonical(verifyMacRuntime(join(output, target), metadata.sourceRevision, inputsDigest)) !== canonical(expected)) throw Error("Remote runtime archive metadata mismatch");
|
|
return true;
|
|
}
|
|
|
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const [command, ...args] = process.argv.slice(2);
|
|
if (command === "package" && [4, 5].includes(args.length)) {
|
|
const [providerPack, runnerBinary, sourceRevision, output, inputsDigest] = args;
|
|
console.log(JSON.stringify(packageMacRuntime({ providerPack, runnerBinary, sourceRevision, output, inputsDigest })));
|
|
} else if (command === "install" && [3, 4].includes(args.length)) {
|
|
const [input, output, sourceRevision, inputsDigest] = args;
|
|
console.log(JSON.stringify({ installed: installMacRuntime({ input, output, sourceRevision, inputsDigest: inputsDigest || undefined }) }));
|
|
} else throw Error(`Usage: ${basename(process.argv[1])} package PACK RUNNER SOURCE OUTPUT | install INPUT OUTPUT SOURCE`);
|
|
}
|