Agent 1.0.0: polls the Hub for signed jobs, runs crosscode, sends reports and stats
apps/agent (docs/AGENT-1.0-PLAN.md §3-4, §10): listens on nothing; checks every job (pinned Hub key, server, time window, replays for 90 days, type per mode, strict arguments) before running crosscode with an argument array; opens the sealed config into a root-only file only for the job; redacts log lines; keeps unsent reports in an outbox; encrypts exports before upload; check-ports on the central server (read-only); self-update with automatic revert. One bundled dist/cli.js, a systemd unit and the install script that joins a server with a one-time token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* update-agent (AGENT-1.0-PLAN §3): the newest agent@x.y.z is checked out and built next to the
|
||||
* running copy, `current` is switched to it and the agent exits, so systemd starts the new one.
|
||||
* A one-shot systemd timer switches back to `previous` unless the new agent clears
|
||||
* update-pending.json by polling the Hub within 150 seconds.
|
||||
*
|
||||
* /opt/crosscode/agent/releases/<version>/ checkouts of the monorepo at agent@<version>
|
||||
* /opt/crosscode/agent/current, previous symlinks to releases
|
||||
* /opt/crosscode/agent/revert.sh written by the install script
|
||||
*/
|
||||
|
||||
const REPO = process.env.CROSSCODE_REPO || "https://c-git.crosscode.co.za/joshua/crosscode-platform.git";
|
||||
const CONFIRM_SECONDS = 150;
|
||||
|
||||
const pendingFile = () => path.join(paths.stateDir, "update-pending.json");
|
||||
|
||||
function exec(cmd: string, args: string[], cwd?: string, timeoutMs = 15 * 60_000): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 20_000_000, env: { ...process.env, NODE_ENV: "development" } }, (err, stdout, stderr) => {
|
||||
if (err) reject(new Error(`${cmd} ${args.join(" ")}: ${String(stderr).trim().split("\n").slice(-3).join(" ") || err.message}`));
|
||||
else resolve(String(stdout));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface UpdateOutcome {
|
||||
status: agent.JobStatus;
|
||||
message: string;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
/** Exit after reporting, so systemd starts the new version. */
|
||||
restart: boolean;
|
||||
}
|
||||
|
||||
export async function updateAgent(tag: string, currentVersion: string): Promise<UpdateOutcome> {
|
||||
const version = tag.replace(/^agent@/, "");
|
||||
const steps: agent.ReportStep[] = [];
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const s: agent.ReportStep = { name, startedAt: new Date().toISOString(), finishedAt: null, outcome: "ok" };
|
||||
steps.push(s);
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
s.outcome = "failed";
|
||||
s.detail = (e as Error).message.slice(0, 2000);
|
||||
throw e;
|
||||
} finally {
|
||||
s.finishedAt = new Date().toISOString();
|
||||
}
|
||||
};
|
||||
if (version === currentVersion) return { status: "succeeded", message: `Already on ${tag}.`, steps, result: { version }, restart: false };
|
||||
|
||||
const root = paths.agentRoot;
|
||||
const dir = path.join(root, "releases", version);
|
||||
try {
|
||||
await step(`Checking out ${tag}`, async () => {
|
||||
if (!fs.existsSync(path.join(dir, ".git"))) {
|
||||
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
||||
await exec("git", ["clone", "--quiet", "--depth", "1", "--branch", tag, REPO, dir]);
|
||||
}
|
||||
});
|
||||
await step("Installing and building", async () => {
|
||||
await exec("npm", ["ci", "--no-audit", "--no-fund", "--include=dev", "-w", "packages/contracts", "-w", "apps/agent"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "packages/contracts"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "apps/agent"], dir);
|
||||
});
|
||||
await step("Checking the new build", async () => {
|
||||
const out = await exec(process.execPath, [path.join(dir, "apps/agent/dist/cli.js"), "version"], dir, 30_000);
|
||||
if (out.trim() !== version) throw new Error(`The new build says it's ${out.trim()}, not ${version}.`);
|
||||
});
|
||||
await step("Switching over", async () => {
|
||||
const current = path.join(root, "current");
|
||||
const previous = path.join(root, "previous");
|
||||
const old = fs.readlinkSync(current);
|
||||
fs.writeFileSync(pendingFile(), JSON.stringify({ from: currentVersion, to: version, at: new Date().toISOString() }), { mode: 0o600 });
|
||||
replaceLink(previous, old);
|
||||
replaceLink(current, dir);
|
||||
// If the new agent doesn't poll within CONFIRM_SECONDS, revert.sh puts `previous` back.
|
||||
await exec("systemd-run", [`--on-active=${CONFIRM_SECONDS}`, `--unit=crosscode-agent-revert-${Date.now()}`, path.join(root, "revert.sh")]);
|
||||
});
|
||||
} catch (e) {
|
||||
return { status: "failed", message: `The agent wasn't updated: ${(e as Error).message}`, steps, result: { from: currentVersion, to: version }, restart: false };
|
||||
}
|
||||
return { status: "succeeded", message: `Switching to ${tag}; it confirms by polling within ${CONFIRM_SECONDS} seconds.`, steps, result: { from: currentVersion, to: version }, restart: true };
|
||||
}
|
||||
|
||||
function replaceLink(link: string, target: string): void {
|
||||
const tmp = `${link}.tmp-${process.pid}`;
|
||||
fs.rmSync(tmp, { force: true });
|
||||
fs.symlinkSync(target, tmp);
|
||||
fs.renameSync(tmp, link);
|
||||
}
|
||||
|
||||
/** Called after the first successful poll: this version works, so it stays. */
|
||||
export function confirmUpdate(): void {
|
||||
fs.rmSync(pendingFile(), { force: true });
|
||||
}
|
||||
Reference in New Issue
Block a user