mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-10 12:07:09 +02:00
## Thinking Path > - Paperclip manages agents that must write work and report task outcomes through its API. > - Local adapters select an execution engine and its permission settings. > - A higher ACP Node requirement can make an unchanged installation lose access to its default engine. > - The adapter then silently selects CLI, which can change permissions and block API access. > - This pull request keeps the engine choice fixed and reports missing prerequisites before work starts. > - It also gives explicit Codex CLI runs usable defaults and keeps managed services on a supported Node runtime. ## Linked Issues or Issue Description Refs #12215. Related changes: #11792 raised the Node requirement; #13094 addressed separate runner networking behavior. This change fixes the engine-selection and managed-launcher paths. **What happened?** An unchanged agent could switch from ACP to CLI after an upgrade. Codex CLI then used read-only permissions with networking disabled. The run could finish without updating its task. Repeated recovery attempts used the same unavailable setup. Managed updates also skipped the Node check and did not refresh old launchers. **Expected behavior** An unavailable engine must fail with a clear setup error. It must not silently select another engine. Explicit CLI runs must be able to write workspace files and call the API unless the operator configures stricter settings. Managed updates must validate Node and keep child tools on that runtime. **Steps to reproduce** 1. Run an ACP-default agent under Node 22 after the ACP minimum rises to 24.11. 2. Leave the engine unset and disable the approval/sandbox bypass. 3. Observe the old adapter select CLI and fail to write task disposition through the API. 4. Start a managed service with an old launcher and a supervisor PATH that selects a different Node for child tools. ## What Changed - Remove automatic engine fallback for Codex, Claude, Gemini, and Kimi. Check prerequisites for default and explicit ACP selections. - Return a configuration error with proof that provider work did not start. Stop automatic continuation retries for this error. - Enable Codex ACP workspace networking at the actual turn boundary. Upstream mode presets otherwise force it off even when config.toml enables it. Preserve explicit network denial and read-only mode. - Set workspace-write and network access defaults for explicit Codex CLI runs. Preserve explicit sandbox modes, profiles, and network restrictions. - Pin the validated Node directory in managed launcher PATH. Refresh legacy launchers during installs and npm/Git updates. - Reject updates on unsupported Node. Keep update checks, dry runs, and rollback available. - Synchronize the qualified Codex ACP executable identity across server, TypeScript runner, Rust runner, and provider-pack launch paths. - Add regression tests and update engine and installation documentation. ## Verification - [Full CI passed on the final head](https://github.com/paperclipai/paperclip/actions/runs/34387099695): typecheck, build/native runner verification, all general and serialized test shards, all browser shards, release registry, canary dry run, and policy checks. - Greptile: 5/5 on `2c1d6e2815830a5cd39e36c8a082cc0c4441b6c0`, with no unresolved review findings. Security gates are green. - Full workspace typecheck and build also passed locally. The final deployed Linux build passed. - Full Codex, Claude, Gemini, and Kimi source test suites: 804 passed, 2 skipped. Installer, updater, and launcher tests: 47 passed. Installed ACP turn-boundary tests: 3 passed. ACP packaging tests: 14 passed. Focused recovery classification tests also passed. - Real Linux Codex CLI runs, both fresh and resumed, wrote a workspace file and reached the control-plane health API with the new defaults. - Explicit read-only and network-disabled control probes retained those restrictions. - A real ACP run on the final deployed Linux build wrote a file and reached the control-plane API with HTTP 200, without engine fallback. The same probe failed DNS before the turn-policy patch. - Executable-identity and installed-policy contracts: 12 passed. Affected native server tests: 197 passed. Runner factory tests: 21 passed. Rust qualification and native provider integration tests: 11 passed. - Deployed the production changes to a Linux service on Node 24.20 after a verified database backup. Health, bootstrap readiness, static UI, executable/cwd identity, and guarded restart checks passed. The restart lost no runs. - Corrected stale Kimi skill-default and Gemini remote-archive fixtures; both suites pass. ## Risks - Default or legacy auto engine settings now fail when ACP is unavailable. Operators who intend to use CLI must select it explicitly. - Codex CLI now permits workspace writes and networking by default, and ACP workspace-write turns permit networking by default. Explicit operator sandbox settings remain authoritative. - Old managed launchers keep their pinned Node until they are reinstalled under a supported runtime. An old updater cannot repair itself; the documentation gives the current installer command. - Custom service wrappers and global/source installations must configure their runtime PATH. No database migration is required. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository inspection, shell execution, and test tools. The exact serving model identifier and context-window size are not exposed in this session. ## 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>
274 lines
19 KiB
TypeScript
274 lines
19 KiB
TypeScript
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { execFile } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import * as p from "@clack/prompts";
|
|
import pc from "picocolors";
|
|
import { assertManagedShimWritable, writeManagedShim, buildNextManifest, flipCurrentAtomic, isManagedExecutable, pruneInstallPayloads, readInstallManifest, resolveInstallStorePaths, withInstallStoreLock, writeInstallManifestAtomic, type InstallChannel, type InstallManifest, type InstallRecord, type InstallStorePaths } from "../install-store.js";
|
|
import { dbBackupCommand } from "./db-backup.js";
|
|
import { assertSupportedNodeVersion, installGitPayload, installNpmPayload, PUBLIC_NPM_REGISTRY, resolveGitHubRef, resolvePublishedVersion, type CommandRunner } from "./install.js";
|
|
import { resolvePaperclipInstanceId, resolvePaperclipInstanceRoot } from "../config/home.js";
|
|
import { resolveConfigPath } from "../config/store.js";
|
|
import { detectServiceManager } from "../services/service-manager.js";
|
|
import { restartManagedService } from "./service.js";
|
|
import { packageVersion } from "../version.js";
|
|
|
|
const execFileAsync = promisify(execFile);
|
|
export type InstallMode = "managed" | "global-npm" | "npx" | "source" | "unknown";
|
|
export type UpdateOptions = { canary?: boolean; latest?: boolean; version?: string; rollback?: boolean; check?: boolean; dryRun?: boolean; json?: boolean; yes?: boolean; backup?: boolean };
|
|
type Dependencies = { executablePath: string; runCommand: CommandRunner; backup: () => Promise<void>; confirm: (message: string) => Promise<boolean>; now: () => Date; paths: InstallStorePaths; restartActiveService: (expectedVersion: string) => Promise<boolean>; hasInstanceData: () => boolean };
|
|
|
|
const DATABASE_UNREACHABLE_CODES = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT"]);
|
|
|
|
function hasPaperclipInstanceData(): boolean {
|
|
return Boolean(process.env.DATABASE_URL?.trim())
|
|
|| fs.existsSync(resolveConfigPath())
|
|
|| fs.existsSync(resolvePaperclipInstanceRoot());
|
|
}
|
|
|
|
function isDatabaseUnreachableError(error: unknown): boolean {
|
|
const pending = [error];
|
|
const seen = new Set<unknown>();
|
|
while (pending.length > 0) {
|
|
const current = pending.pop();
|
|
if (current === null || current === undefined || seen.has(current)) continue;
|
|
seen.add(current);
|
|
if (typeof current === "string") {
|
|
if (/\b(?:ECONNREFUSED|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT)\b|connection refused/i.test(current)) return true;
|
|
continue;
|
|
}
|
|
if (typeof current !== "object") continue;
|
|
const record = current as Record<string, unknown>;
|
|
if (typeof record.code === "string" && DATABASE_UNREACHABLE_CODES.has(record.code)) return true;
|
|
if (typeof record.message === "string" && /\b(?:ECONNREFUSED|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT)\b|connection refused/i.test(record.message)) return true;
|
|
if (record.cause !== undefined) pending.push(record.cause);
|
|
if (Array.isArray(record.errors)) pending.push(...record.errors);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
async function runPreUpdateBackup(options: UpdateOptions, backup: () => Promise<void>, hasInstanceData = hasPaperclipInstanceData): Promise<void> {
|
|
if (!hasInstanceData()) {
|
|
const message = "Skipping the pre-update backup because this Paperclip instance has not been onboarded and has no data to back up.";
|
|
if (options.json) console.error(message); else console.log(pc.yellow(message));
|
|
return;
|
|
}
|
|
try {
|
|
await backup();
|
|
} catch (error) {
|
|
if (isDatabaseUnreachableError(error)) {
|
|
throw new Error(
|
|
"The Paperclip database is not running or reachable, so the pre-update backup cannot be taken. Start the service with `paperclipai service start` and retry, or skip the backup with `paperclipai update --no-backup`.",
|
|
{ cause: error },
|
|
);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function restartActiveManagedService(expectedVersion: string): Promise<boolean> {
|
|
const instanceId = resolvePaperclipInstanceId();
|
|
const detection = await detectServiceManager({ instanceId });
|
|
if (!detection.supported || !(await detection.manager.status()).active) return false;
|
|
await restartManagedService({ instanceId, expectedVersion });
|
|
return true;
|
|
}
|
|
|
|
export function detectInstallMode(executablePath = process.argv[1] ?? "", paths = resolveInstallStorePaths()): InstallMode {
|
|
const resolved = path.resolve(executablePath || ".");
|
|
const manifest = readInstallManifest(paths);
|
|
if (manifest && isManagedExecutable(resolved, manifest, paths)) return "managed";
|
|
const normalized = resolved.split(path.sep).join("/");
|
|
if (normalized.includes("/.npm/_npx/") || normalized.includes("/node_modules/.cache/npx/")) return "npx";
|
|
if (normalized.includes("/node_modules/paperclipai/")) return "global-npm";
|
|
let cursor = path.dirname(resolved);
|
|
while (cursor !== path.dirname(cursor)) {
|
|
if (fs.existsSync(path.join(cursor, ".git"))) return "source";
|
|
cursor = path.dirname(cursor);
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
export function compareVersions(left: string, right: string): number {
|
|
const parse = (value: string) => { const [core, prerelease = ""] = value.replace(/^v/, "").split("-", 2); return { numbers: core.split(".").map((part) => Number(part) || 0), prerelease }; };
|
|
const a = parse(left); const b = parse(right);
|
|
for (let index = 0; index < Math.max(a.numbers.length, b.numbers.length); index += 1) { const delta = (a.numbers[index] ?? 0) - (b.numbers[index] ?? 0); if (delta !== 0) return Math.sign(delta); }
|
|
if (a.prerelease === b.prerelease) return 0;
|
|
if (!a.prerelease) return 1;
|
|
if (!b.prerelease) return -1;
|
|
const aParts = a.prerelease.split(".");
|
|
const bParts = b.prerelease.split(".");
|
|
for (let index = 0; index < Math.max(aParts.length, bParts.length); index += 1) {
|
|
const leftPart = aParts[index];
|
|
const rightPart = bParts[index];
|
|
if (leftPart === undefined) return -1;
|
|
if (rightPart === undefined) return 1;
|
|
if (leftPart === rightPart) continue;
|
|
const leftNumeric = /^\d+$/.test(leftPart);
|
|
const rightNumeric = /^\d+$/.test(rightPart);
|
|
if (leftNumeric && rightNumeric) return Math.sign(Number(leftPart) - Number(rightPart));
|
|
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
|
|
return leftPart < rightPart ? -1 : 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
export function resolveUpdateRequest(manifest: InstallManifest | null, options: Pick<UpdateOptions, "canary" | "latest" | "version">): { spec: string; channel: InstallChannel; explicit: boolean } {
|
|
const selected = Number(Boolean(options.canary)) + Number(Boolean(options.latest)) + Number(Boolean(options.version));
|
|
if (selected > 1) throw new Error("Choose only one of --latest, --canary, or --version.");
|
|
if (options.version) return { spec: options.version.trim(), channel: "pinned", explicit: true };
|
|
if (options.canary) return { spec: "canary", channel: "canary", explicit: true };
|
|
if (options.latest) return { spec: "latest", channel: "latest", explicit: true };
|
|
if (manifest?.channel === "pinned") return { spec: manifest.version, channel: "pinned", explicit: false };
|
|
const channel = manifest?.channel === "canary" ? "canary" : "latest";
|
|
return { spec: channel, channel, explicit: false };
|
|
}
|
|
|
|
export function rollbackManagedInstall(paths = resolveInstallStorePaths()): InstallManifest {
|
|
const manifest = readInstallManifest(paths);
|
|
if (!manifest) throw new Error("No managed install was found to roll back.");
|
|
const target = manifest.previous[0];
|
|
if (!target) throw new Error("No previous managed payload is available for rollback.");
|
|
if (!fs.existsSync(target.payloadPath)) throw new Error(`Previous payload is missing: ${target.payloadPath}`);
|
|
const current: InstallRecord = { source: manifest.source, version: manifest.version, channel: manifest.channel, payloadPath: manifest.payloadPath, repo: manifest.repo, ref: manifest.ref, sha: manifest.sha, installedAt: manifest.installedAt };
|
|
const next: InstallManifest = { schemaVersion: manifest.schemaVersion, ...target, previous: [current, ...manifest.previous.slice(1)].slice(0, 2) };
|
|
const oldTarget = fs.readlinkSync(paths.currentPath);
|
|
flipCurrentAtomic(target.payloadPath, paths);
|
|
try { writeInstallManifestAtomic(next, paths); } catch (error) { flipCurrentAtomic(path.resolve(paths.cliRoot, oldTarget), paths); throw error; }
|
|
return next;
|
|
}
|
|
|
|
async function defaultConfirm(message: string): Promise<boolean> {
|
|
if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
|
|
const answer = await p.confirm({ message, initialValue: false });
|
|
return !p.isCancel(answer) && answer === true;
|
|
}
|
|
function emit(options: UpdateOptions, value: Record<string, unknown>, message: string): void { if (options.json) console.log(JSON.stringify(value, null, 2)); else console.log(message); }
|
|
|
|
async function rollbackAfterServiceValidationFailure(
|
|
paths: InstallStorePaths,
|
|
restartActiveService: (expectedVersion: string) => Promise<boolean>,
|
|
validationError: unknown,
|
|
payloadLabel: string,
|
|
): Promise<never> {
|
|
const rolledBack = await withInstallStoreLock(async () => rollbackManagedInstall(paths), paths);
|
|
try {
|
|
await restartActiveService(rolledBack.version);
|
|
} catch (restartError) {
|
|
throw new Error(
|
|
`${payloadLabel} failed service validation and was rolled back to ${rolledBack.version}, but the rolled-back service also failed to restart.`,
|
|
{ cause: new AggregateError([validationError, restartError]) },
|
|
);
|
|
}
|
|
throw new Error(`${payloadLabel} failed service validation and was rolled back to ${rolledBack.version}.`, { cause: validationError });
|
|
}
|
|
|
|
export async function updateCommand(options: UpdateOptions, overrides: Partial<Dependencies> = {}): Promise<void> {
|
|
const paths = overrides.paths ?? resolveInstallStorePaths();
|
|
const executablePath = overrides.executablePath ?? process.argv[1] ?? "";
|
|
const runCommand = overrides.runCommand ?? execFileAsync;
|
|
const mode = detectInstallMode(executablePath, paths);
|
|
const manifest = readInstallManifest(paths);
|
|
if (options.rollback) {
|
|
if (mode !== "managed") throw new Error("--rollback is only available for managed installs.");
|
|
if (options.dryRun) { emit(options, { mode, action: "rollback", dryRun: true, target: manifest?.previous[0]?.version ?? null }, `Would roll back to ${manifest?.previous[0]?.version ?? "the previous payload"}.`); return; }
|
|
const next = await withInstallStoreLock(async () => rollbackManagedInstall(paths), paths);
|
|
const restarted = await (overrides.restartActiveService ?? restartActiveManagedService)(next.version);
|
|
emit(options, { mode, action: "rollback", version: next.version, restarted }, pc.green(`Rolled back to paperclipai ${next.version}${restarted ? " and restarted the active service" : ""}. Database migrations are not reversed; restore the pre-update backup if needed.`));
|
|
return;
|
|
}
|
|
if (mode === "npx") { emit(options, { mode, action: "install" }, "This is an ephemeral npx install. Run `paperclipai install`, then use `paperclipai update` from the managed shim."); return; }
|
|
if (mode === "source" || mode === "unknown") { emit(options, { mode, action: "manual" }, "This appears to be a source checkout. Update it with `git pull` followed by `pnpm install`; Paperclip will not mutate the repository."); return; }
|
|
if (!options.check && !options.dryRun) assertSupportedNodeVersion();
|
|
const request = resolveUpdateRequest(mode === "managed" ? manifest : null, options);
|
|
if (mode === "managed" && manifest?.source === "git") {
|
|
if (!manifest.repo || !manifest.ref || !manifest.sha) throw new Error("Managed git install metadata is incomplete.");
|
|
if (/^[0-9a-f]{7,40}$/i.test(manifest.ref)) { emit(options, { mode, source: "git", pinned: true, sha: manifest.sha }, `Git install is pinned at ${manifest.sha.slice(0, 12)}.`); return; }
|
|
const targetSha = await resolveGitHubRef(manifest.repo, manifest.ref, runCommand);
|
|
if (targetSha === manifest.sha) { emit(options, { mode, source: "git", changed: false, sha: targetSha, ref: manifest.ref }, `${manifest.repo}@${manifest.ref} is already at ${targetSha.slice(0, 12)}.`); return; }
|
|
if (options.check || options.dryRun) { emit(options, { mode, source: "git", changed: true, currentSha: manifest.sha, targetSha, ref: manifest.ref, dryRun: Boolean(options.dryRun) }, `Git update available: ${manifest.sha.slice(0, 12)} → ${targetSha.slice(0, 12)}.`); if (options.check) process.exitCode = 10; return; }
|
|
if (options.yes !== true) {
|
|
const confirmed = await (overrides.confirm ?? defaultConfirm)(`Update from ${manifest.repo}@${manifest.ref} and execute build scripts from commit ${targetSha.slice(0, 12)}?`);
|
|
if (!confirmed) throw new Error("Git update cancelled. Re-run with --yes to confirm executing build scripts from the updated commit.");
|
|
}
|
|
if (options.backup !== false) await runPreUpdateBackup(options, overrides.backup ?? (() => dbBackupCommand({})), overrides.hasInstanceData);
|
|
const installed = await withInstallStoreLock(async () => {
|
|
assertManagedShimWritable(paths);
|
|
const payload = await installGitPayload(manifest.repo!, targetSha, runCommand, paths);
|
|
writeManagedShim(paths);
|
|
const record: InstallRecord = { source: "git", version: payload.version, channel: "pinned", repo: manifest.repo, ref: manifest.ref, sha: targetSha, payloadPath: payload.payloadPath, installedAt: (overrides.now?.() ?? new Date()).toISOString() };
|
|
const next = buildNextManifest(record, manifest); const oldTarget = fs.readlinkSync(paths.currentPath); flipCurrentAtomic(payload.payloadPath, paths);
|
|
try { writeInstallManifestAtomic(next, paths); } catch (error) { flipCurrentAtomic(path.resolve(paths.cliRoot, oldTarget), paths); throw error; }
|
|
pruneInstallPayloads(next, paths); return payload;
|
|
}, paths);
|
|
let restarted: boolean;
|
|
try {
|
|
restarted = await (overrides.restartActiveService ?? restartActiveManagedService)(installed.version);
|
|
} catch (error) {
|
|
return rollbackAfterServiceValidationFailure(
|
|
paths,
|
|
overrides.restartActiveService ?? restartActiveManagedService,
|
|
error,
|
|
"Updated git payload",
|
|
);
|
|
}
|
|
emit(options, { mode, source: "git", changed: true, currentSha: manifest.sha, targetSha, reused: installed.reused, restarted }, pc.yellow(`Updated unreleased git payload ${manifest.sha.slice(0, 12)} → ${targetSha.slice(0, 12)} from ${manifest.repo}@${manifest.ref}${restarted ? " and restarted the active service" : ""}.`));
|
|
return;
|
|
}
|
|
const targetVersion = await resolvePublishedVersion(request.spec, runCommand);
|
|
const currentVersion = manifest?.version ?? (mode === "global-npm" ? packageVersion : undefined);
|
|
const comparison = currentVersion ? compareVersions(targetVersion, currentVersion) : 1;
|
|
if (options.check) { emit(options, { mode, currentVersion: currentVersion ?? null, targetVersion, updateAvailable: comparison > 0, downgrade: comparison < 0, channel: request.channel }, comparison > 0 ? `Update available: ${targetVersion}` : comparison < 0 ? `Target ${targetVersion} is older than ${currentVersion}.` : `paperclipai ${targetVersion} is current.`); if (comparison > 0) process.exitCode = 10; return; }
|
|
if (mode === "global-npm") {
|
|
if (comparison < 0 && options.yes !== true) { const confirmed = await (overrides.confirm ?? defaultConfirm)(`Downgrade paperclipai from ${currentVersion} to ${targetVersion}?`); if (!confirmed) throw new Error("Downgrade cancelled. Re-run with --yes to confirm explicitly."); }
|
|
const args = ["install", "-g", `paperclipai@${targetVersion}`, `--registry=${PUBLIC_NPM_REGISTRY}`, `--@paperclipai:registry=${PUBLIC_NPM_REGISTRY}`]; console.log(`Running: npm ${args.join(" ")}`);
|
|
if (!options.dryRun) {
|
|
const npmConfigDir = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-npm-"));
|
|
const npmUserConfigPath = path.join(npmConfigDir, "npmrc");
|
|
try {
|
|
fs.writeFileSync(npmUserConfigPath, `registry=${PUBLIC_NPM_REGISTRY}\n@paperclipai:registry=${PUBLIC_NPM_REGISTRY}\n`, { mode: 0o600 });
|
|
await runCommand("npm", args, {
|
|
env: {
|
|
...process.env,
|
|
npm_config_registry: PUBLIC_NPM_REGISTRY,
|
|
NPM_CONFIG_REGISTRY: PUBLIC_NPM_REGISTRY,
|
|
npm_config_userconfig: npmUserConfigPath,
|
|
NPM_CONFIG_USERCONFIG: npmUserConfigPath,
|
|
},
|
|
maxBuffer: 16 * 1024 * 1024,
|
|
});
|
|
} finally {
|
|
fs.rmSync(npmConfigDir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
emit(options, { mode, action: "update", targetVersion, dryRun: Boolean(options.dryRun), command: ["npm", ...args] }, options.dryRun ? "Dry run complete." : pc.green(`Updated global npm install to ${targetVersion}.`)); return;
|
|
}
|
|
if (!manifest) throw new Error("Managed install metadata is missing.");
|
|
if (comparison === 0) { emit(options, { mode, currentVersion, targetVersion, changed: false }, `paperclipai ${targetVersion} is already active.`); return; }
|
|
if (comparison < 0 && options.yes !== true) { const confirmed = await (overrides.confirm ?? defaultConfirm)(`Downgrade paperclipai from ${currentVersion} to ${targetVersion}?`); if (!confirmed) throw new Error("Downgrade cancelled. Re-run with --yes to confirm explicitly."); }
|
|
if (options.dryRun) { emit(options, { mode, currentVersion, targetVersion, action: comparison < 0 ? "downgrade" : "update", backup: options.backup !== false, dryRun: true }, `Would ${comparison < 0 ? "downgrade" : "update"} paperclipai ${currentVersion} → ${targetVersion}${options.backup === false ? " without a backup" : " after a database backup"}.`); return; }
|
|
if (options.backup !== false) await runPreUpdateBackup(options, overrides.backup ?? (() => dbBackupCommand({})), overrides.hasInstanceData);
|
|
const installed = await withInstallStoreLock(async () => {
|
|
assertManagedShimWritable(paths);
|
|
const payload = await installNpmPayload(targetVersion, runCommand, paths);
|
|
writeManagedShim(paths);
|
|
const record: InstallRecord = { source: "npm", version: targetVersion, channel: request.channel, payloadPath: payload.payloadPath, installedAt: (overrides.now?.() ?? new Date()).toISOString() };
|
|
const next = buildNextManifest(record, manifest); const oldTarget = fs.readlinkSync(paths.currentPath); flipCurrentAtomic(payload.payloadPath, paths);
|
|
try { writeInstallManifestAtomic(next, paths); } catch (error) { flipCurrentAtomic(path.resolve(paths.cliRoot, oldTarget), paths); throw error; }
|
|
pruneInstallPayloads(next, paths); return payload;
|
|
}, paths);
|
|
let restarted: boolean;
|
|
try {
|
|
restarted = await (overrides.restartActiveService ?? restartActiveManagedService)(targetVersion);
|
|
} catch (error) {
|
|
return rollbackAfterServiceValidationFailure(
|
|
paths,
|
|
overrides.restartActiveService ?? restartActiveManagedService,
|
|
error,
|
|
"Updated payload",
|
|
);
|
|
}
|
|
emit(options, { mode, currentVersion, targetVersion, changed: true, reused: installed.reused, restarted }, pc.green(`Updated paperclipai ${currentVersion} → ${targetVersion}${restarted ? " and restarted the active service" : ""}. Run \`paperclipai update --rollback\` for an instant payload rollback.`));
|
|
}
|