Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,16 @@ disabled, and writes the wrappers into `~/.crosshead/bin`.
(the default), checking for a new release about once an hour and retrying failed checks after 30 minutes. Before installing, Crosshead verifies GitHub's signed
build attestation for the exact archive digest and this repository's release
workflow. If verification or download fails, the host still launches and the
update is retried later. `crosshead update --manual` disables automatic
update is retried later. If another install still holds the update lock and
the launch check times out, launch is deferred; retry after the install
finishes. `crosshead update --manual` disables automatic
updates. `crosshead update --policy` shows the current setting. The older
`--pin` option remains an alias for `--manual`.

For a manual install, obtain the digest from an independent release channel
and run `crosshead update --sha256 <digest>`.
and run `crosshead update --sha256 <digest>`. Operator updates and rollbacks
refuse to change runtime files while a host is running. Close host sessions
first, or use `--force` at the end of the command to update during a session.

To check that a release matches this source, compare the installer's
`RELEASE_SHA256` with `SHA256SUMS` on the matching GitHub release. Public
Expand Down
6 changes: 5 additions & 1 deletion docs/SECURITY-REVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ from it is in scope.
workflow and tag before installing. In `manual` mode, the operator supplies
a trusted SHA-256 from an independent channel. Both paths validate archive
entries and run `npm ci --omit=dev --ignore-scripts` with install scripts
disabled. A failed update check does not prevent the host from launching.
disabled. Remote verification and download failures do not prevent host
launch; a failure to establish the update lock and host lease defers it.
Operator updates and rollbacks check live host leases and native processes
under the update lock. Staged release installs recheck immediately before
applying. `--force` explicitly bypasses the active-host guard.
See `src/runtime/release-attestation.ts`, `runtime-auto-update.ts`, and
`validateRuntimeReleaseArchive`.
2. **Local daemon HTTP API.** It binds `127.0.0.1` on a configurable port
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@crosshead/runtime",
"version": "0.5.0-alpha.14",
"version": "0.5.0-alpha.15",
"description": "Crosshead local runtime: persistent memory for Claude Code, Codex, Pi, Hermes and OpenCode. CLI, daemon, host adapters and hooks.",
"license": "Apache-2.0",
"private": true,
Expand Down
9 changes: 7 additions & 2 deletions src/runtime/claude-code-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,8 +474,13 @@ export ONLYBOTS_HOME=${shellQuote(config.runtimeHome)}
export CROSSHEAD_HOME="$ONLYBOTS_HOME"
export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)}

if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then
${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2
if [[ ! -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then
printf 'Crosshead update check is unavailable; retry host launch after repairing the runtime.\n' >&2
exit 1
fi
if ! ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then
printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2
exit 1
fi
exec ${shellQuote(config.claudeBinary)} "$@"
`;
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,10 @@ export const runOnlyBotsCtlCli = async (
"crosshead billing invoice (--invoice-id <id>|--payment-hash <hash>) [--home <path>] [--profile <name>] [--json]",
"crosshead check-updates [--home <path>] [--channel stable|beta|canary] [--json]",
"crosshead apply [--home <path>] [--manifest <path>]",
"crosshead update --sha256 <trusted-release-digest> [--home <path>] [--no-restart]",
"crosshead update --sha256 <trusted-release-digest> [--home <path>] [--no-restart] [--force]",
"crosshead update --manual|--auto|--policy [--home <path>]",
"crosshead update [adapter] [--home <path>] [--channel stable|beta|canary] [--version <version>]",
"crosshead rollback [adapter] --to <version> [--home <path>]",
"crosshead update [adapter] [--home <path>] [--channel stable|beta|canary] [--version <version>] [--force]",
"crosshead rollback [adapter] --to <version> [--home <path>] [--force]",
"crosshead doctor [--home <path>] [--workspace-root <path>] [--json]",
"crosshead workspace add --workspace-root <path> --adapter codex|claude-code|both --profile <name> [--source-excerpts on|off] [--replace-user-hooks] [--dry-run] [--json]",
"crosshead workspace remove --workspace-root <path> [--adapter codex|claude-code|both] [--dry-run] [--json]",
Expand Down
22 changes: 16 additions & 6 deletions src/runtime/cli/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { OnlyBotsLocalRuntimeDaemon, RuntimeAdapterName, RuntimeChannel, Runtime
import path from "path";
import { RUNTIME_ADAPTER_NAMES, ensureRuntimeHomeLayout, loadAdapterRecord, loadRuntimeConfig, resolveRuntimeHome } from "../runtime-persistence";
import { billingFromCli } from "./billing";
import { maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, withRuntimeUpdateLock } from "../runtime-auto-update";
import { assertNoLiveRuntimeHosts, maintainRuntimeBeforeLaunch, runtimeUpdatePolicy, withRuntimeUpdateLock } from "../runtime-auto-update";
import { DEFAULT_CHECKOUT_CREDIT_UNITS } from "../billing-remediation";
import { inspectHostHookRegistrations } from "../host-hook-doctor";
import { inspectWorkspaceHooks, workspaceBindingStatus } from "../workspace-hooks";
Expand Down Expand Up @@ -64,12 +64,16 @@ export const updateFromCli = async (argv: string[]): Promise<string> => {
const channel = typeof flags.channel === "string" ? (flags.channel as RuntimeChannel) : config.channel;
const versionOverride = typeof flags.version === "string" ? flags.version : undefined;
const target = positionals[0];
const mutate = <T>(action: () => Promise<T>): Promise<T> => withRuntimeUpdateLock(paths.home, () => {
assertNoLiveRuntimeHosts(paths.home, flags.force === true);
return action();
});

if (target && RUNTIME_ADAPTER_NAMES.includes(target as RuntimeAdapterName)) {
const adapterName = target as RuntimeAdapterName;
const adapter = loadAdapterRecord(paths, adapterName);
const targetVersion = resolveAdapterTargetVersion(adapterName, channel, versionOverride);
await updateRuntimeAdapterVersion(paths.home, adapterName, targetVersion);
await mutate(() => updateRuntimeAdapterVersion(paths.home, adapterName, targetVersion));
return [
`Updated ${adapterName}`,
`channel: ${channel}`,
Expand All @@ -78,19 +82,20 @@ export const updateFromCli = async (argv: string[]): Promise<string> => {
}

if (typeof flags["base-url"] === "string" || typeof flags.baseUrl === "string" || (!versionOverride && typeof flags.channel !== "string")) {
const result = await withRuntimeUpdateLock(paths.home, async () => {
const result = await mutate(async () => {
const updated = await updateManagedRuntimeRelease(paths.home, {
baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : typeof flags.baseUrl === "string" ? flags.baseUrl : undefined,
trustedSha256: typeof flags.sha256 === "string" ? flags.sha256 : undefined,
restart: !flags["no-restart"],
beforeApply: () => assertNoLiveRuntimeHosts(paths.home, flags.force === true),
});
if (runtimeUpdatePolicy(paths.home).mode === "manual") runtimeUpdatePolicy(paths.home, "manual");
return updated;
});
return formatRuntimeReleaseUpdate(result);
}

const updated = await updateRuntimeCatalogInstall(paths.home, channel, versionOverride);
const updated = await mutate(() => updateRuntimeCatalogInstall(paths.home, channel, versionOverride));
return [
"Updated runtime install metadata",
`channel: ${channel}`,
Expand All @@ -109,11 +114,16 @@ export const rollbackFromCli = async (argv: string[]): Promise<string> => {
throw new Error("rollback requires --to <version>");
}
const target = positionals[0];
const runtimeHome = resolveRuntimeHome(home);
const mutate = <T>(action: () => Promise<T>): Promise<T> => withRuntimeUpdateLock(runtimeHome, () => {
assertNoLiveRuntimeHosts(runtimeHome, flags.force === true);
return action();
});
if (target && RUNTIME_ADAPTER_NAMES.includes(target as RuntimeAdapterName)) {
await rollbackRuntimeAdapterVersion(resolveRuntimeHome(home), target as RuntimeAdapterName, targetVersion);
await mutate(() => rollbackRuntimeAdapterVersion(runtimeHome, target as RuntimeAdapterName, targetVersion));
return `Rolled back ${target} to ${targetVersion}`;
}
await rollbackRuntimeCoreVersion(resolveRuntimeHome(home), targetVersion);
await mutate(() => rollbackRuntimeCoreVersion(runtimeHome, targetVersion));
return `Rolled back runtime core to ${targetVersion}`;
};

Expand Down
9 changes: 7 additions & 2 deletions src/runtime/codex-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,8 +467,13 @@ export ONLYBOTS_HOME=${shellQuote(config.runtimeHome)}
export CROSSHEAD_HOME="$ONLYBOTS_HOME"
export ONLYBOTS_RUNTIME_HOME=${shellQuote(config.runtimeHome)}

if [[ -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then
${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2 || printf 'Crosshead update check failed; continuing host launch.\n' >&2
if [[ ! -x ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} ]]; then
printf 'Crosshead update check is unavailable; retry host launch after repairing the runtime.\n' >&2
exit 1
fi
if ! ${shellQuote(path.join(config.runtimeHome, "bin", "onlybotsctl"))} update --check-on-launch --host-pid "$$" >&2; then
printf 'Crosshead could not safely check for updates; retry host launch after the update finishes.\n' >&2
exit 1
fi
exec ${shellQuote(config.codexBinary)} --enable hooks "$@"
`;
Expand Down
8 changes: 6 additions & 2 deletions src/runtime/local-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1630,7 +1630,8 @@ const downloadRuntimeRelease = async (
explicitBaseUrl?: string,
trustedSha256?: string,
timeoutMs = 120_000,
expectedReleaseId?: string
expectedReleaseId?: string,
beforeApply?: () => void
): Promise<DownloadedRuntimeRelease> => {
const baseUrl = resolveReleaseUpdateBaseUrl(paths, explicitBaseUrl);
if (!trustedSha256 || !/^[a-f0-9]{64}$/.test(trustedSha256)) {
Expand Down Expand Up @@ -1702,6 +1703,7 @@ const downloadRuntimeRelease = async (
const npmExecutable = path.join(path.dirname(process.execPath), process.platform === "win32" ? "npm.cmd" : "npm");
if (!existsSync(npmExecutable)) throw new Error(`Runtime update cannot find npm beside ${process.execPath}`);
await runRuntimeInstallCommand(npmExecutable, ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-timeout=15000", "--fetch-retries=1"], stageRoot, timeoutMs);
beforeApply?.();
rmSync(releaseRoot, { recursive: true, force: true });
renameSync(stageRoot, releaseRoot);
} finally {
Expand Down Expand Up @@ -1888,13 +1890,14 @@ export const updateManagedRuntimeRelease = async (
restart?: boolean;
timeoutMs?: number;
expectedReleaseId?: string;
beforeApply?: () => void;
} = {}
): Promise<RuntimeReleaseUpdateResult> => {
readWorkspaceHookPolicy(resolveRuntimePaths(home));
const paths = ensureRuntimeHomeLayout(home);
const previousRelease = inspectInstalledRuntimeRelease(paths);
const specs = await collectManagedAdapterReinstallSpecs(paths);
const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256, options.timeoutMs, options.expectedReleaseId);
const release = await downloadRuntimeRelease(paths, options.baseUrl, options.trustedSha256, options.timeoutMs, options.expectedReleaseId, options.beforeApply);
// A release must not leave launchers pointing at a half-applied installation.
// Keep credentials, memory and queued writes outside this file-level rollback.
const protectedFiles = new Set([
Expand All @@ -1920,6 +1923,7 @@ export const updateManagedRuntimeRelease = async (
const priorDaemon = loadDaemonState(paths);
let restartAttempted = false;
try {
options.beforeApply?.();
const reapplied = await reapplyManagedRuntimeRelease(paths, release, specs);
restartAttempted = options.restart !== false && priorDaemon.status === "running";
const daemon = await restartRuntimeDaemonIfNeeded(paths, release, options.restart !== false);
Expand Down
29 changes: 28 additions & 1 deletion src/runtime/runtime-auto-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,28 @@ export const runtimeHasActiveWork = (home: string, hostRunning = () => true): bo
return false;
};

/** Call while holding the update lock, before changing files used by a host. */
export const assertNoLiveRuntimeHosts = (
home: string,
force = false,
ownerAlive = alive,
nativeHostsRunning = () => nativeHostProcessesRunning(process.pid)
): void => {
if (force) return;
const leases = path.join(ensureRuntimeHomeLayout(home).state, "host-processes");
for (const file of existsSync(leases) ? readdirSync(leases) : []) {
if (!/^\d+\.json$/.test(file)) continue;
const pid = Number(file.slice(0, -5));
if (ownerAlive(pid)) {
throw new Error("A managed host is running; close it before updating, or use --force to update during its session");
}
rmSync(path.join(leases, file));
}
if (nativeHostsRunning()) {
throw new Error("A Codex or Claude host is running; close it before updating, or use --force to update during its session");
}
};

/** Serializes all release installs and update-policy writes across CLI processes. */
export const withRuntimeUpdateLock = async <T>(home: string | undefined, action: () => Promise<T> | T, ownerAlive = alive): Promise<T> => {
const paths = ensureRuntimeHomeLayout(home);
Expand Down Expand Up @@ -141,7 +163,12 @@ export const maintainRuntimeBeforeLaunch = async (home: string | undefined, host
if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead update available; deferred while another host is active.";
await deps.verify(candidate[1], release.sha256);
if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) return "Crosshead verified update available; deferred while another host is active.";
const updated = await deps.update(paths.home, { trustedSha256: release.sha256, timeoutMs: 45_000, expectedReleaseId: release.available });
const updated = await deps.update(paths.home, {
trustedSha256: release.sha256, timeoutMs: 45_000, expectedReleaseId: release.available,
beforeApply: () => {
if (deps.nativeHostsRunning(hostPid) || hasActiveWork()) throw new Error("A host became active during the update; retry after it exits");
},
});
if (updated.releaseId !== release.available) throw new Error("Installed release did not match the verified release");
writeJsonFile(stateFile, { checkedAtMs: deps.now(), installed: release.available, available: release.available, status: "updated" });
return `Crosshead automatically updated to ${candidate[1]} (signed release verified).`;
Expand Down
30 changes: 26 additions & 4 deletions tests/runtime/adapter-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync,
import os from "node:os";
import path from "node:path";
import { runInNewContext } from "node:vm";
import { execFileSync } from "node:child_process";
import { execFileSync, spawnSync } from "node:child_process";

import {
buildWrapperScript,
Expand Down Expand Up @@ -196,7 +196,7 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" "
},
);

it.each(["codex", "claude"])("launches %s when the update check fails", host => {
it.each(["codex", "claude"])("defers %s when the update check fails", host => {
const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-failed-update-check-"));
try {
const runtimeHome = path.join(fixture, "runtime");
Expand All @@ -210,8 +210,30 @@ printf '%s\\n' "\${CODEX_HOME:-\${CLAUDE_CONFIG_DIR:-\${CLAUDE_CODE_HOME:-}}}" "
writeFileSync(wrapper, host === "codex"
? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" })
: renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture }));
const output = execFileSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } });
expect(output).toContain("host launched");
const result = spawnSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } });
expect(result.status).toBe(1);
expect(result.stdout).not.toContain("host launched");
expect(result.stderr).toContain("retry host launch");
} finally { rmSync(fixture, { recursive: true, force: true }); }
});

it.each(["codex", "claude"])("defers %s launch when the update check is missing", host => {
const fixture = mkdtempSync(path.join(os.tmpdir(), "crosshead-locked-launch-"));
try {
const runtimeHome = path.join(fixture, "runtime");
const hostBinary = path.join(fixture, "host-stub");
const wrapper = path.join(fixture, "launcher");
mkdirSync(path.join(runtimeHome, "bin"), { recursive: true });
writeFileSync(hostBinary, "#!/bin/sh\nprintf 'host launched\\n'\n", { mode: 0o755 });
const common = { marker: "test", adapterVersion: "test", runtimeHome, hostHome: path.join(fixture, "host"),
profileName: "default", installedAt: "now", updatedAt: "now" };
writeFileSync(wrapper, host === "codex"
? renderCodexLaunchWrapper({ ...common, adapterName: "codex", codexBinary: hostBinary, skillName: "test" })
: renderClaudeLaunchWrapper({ ...common, adapterName: "claude-code", claudeBinary: hostBinary, workspaceRoot: fixture }));
const result = spawnSync("bash", [wrapper], { encoding: "utf8", env: { PATH: process.env.PATH } });
expect(result.status).toBe(1);
expect(result.stdout).not.toContain("host launched");
expect(result.stderr).toContain("update check is unavailable");
} finally { rmSync(fixture, { recursive: true, force: true }); }
});

Expand Down
Loading
Loading