@caveman-ai/cli 2.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ // What the CLI reads from Caveman Cloud's plan answer (GET /api/v1/auth/me,
2
+ // tiers spec §4) and from caveman-proxy's route-state.json: the routing row's
3
+ // state and numbers, the once-per-period pause line, and `caveman billing`.
4
+ // Limits never touch a local module. A /me that cannot be read, or lacks a
5
+ // field, is "no answer": nothing fails because of it.
6
+ import { readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { moduleHost } from "./apply.js";
9
+ import { cavemanHome } from "./config-home.js";
10
+ let answer;
11
+ // One /me per command, shared by the module states, the status row and the
12
+ // sign-in lines.
13
+ export function cloudAnswer() {
14
+ answer ??= moduleHost().cloudMe().catch(() => ({ status: 0, me: null }));
15
+ return answer;
16
+ }
17
+ export async function cloudMe() {
18
+ return (await cloudAnswer()).me;
19
+ }
20
+ const LEVELS = ["off", "counts", "usage", "decisions"];
21
+ // What caveman-proxy sends per request, by the same rule: the CLI telemetry
22
+ // opt-out sends nothing; otherwise /me's data.level, counts when /me names
23
+ // none or cannot be read (never more).
24
+ export function runtimeDataLevel(me, telemetryOff) {
25
+ if (telemetryOff)
26
+ return "off";
27
+ const level = me?.data?.level;
28
+ return typeof level === "string" && LEVELS.includes(level) ? level : "counts";
29
+ }
30
+ // What routing sends, with its off switch: said at sign-in, by `caveman on
31
+ // routing` and by setup when already signed in. The long form is SECURITY.md.
32
+ export const ROUTING_ON_LINE = "routing is on · adds Auto to your agent's model picker; each request on Auto sends your latest ask (with what your agent attaches to it), the one before it, the end of the agent's last reply and request facts (tools, effort, agent headers, token counts) to Caveman Cloud to pick the model and effort; on the Free plan Caveman may keep them to improve routing; requests go to your providers on your keys, only ones routed to a Caveman Cloud model pass through it · caveman off routing to stop";
33
+ // The same in three short rows, for the first-run screen: what goes, who may
34
+ // keep it, how to stop it, and where every word is.
35
+ export const ROUTING_ON_SHORT = [
36
+ "On Auto, your last two asks (with what the agent attaches), the end of its",
37
+ "last reply and request facts go to Caveman Cloud; the Free plan may keep them.",
38
+ "Stop: caveman off routing · every word: caveman on routing",
39
+ ];
40
+ export async function printSignInLines() {
41
+ for (const line of await signInLines())
42
+ process.stderr.write(`${line}\n`);
43
+ }
44
+ // After every sign-in: what routing does now and what data leaves the machine,
45
+ // each with the way to stop it. Routing's line first, runtime data's second.
46
+ export async function signInLines() {
47
+ const h = moduleHost();
48
+ const lines = [];
49
+ // The stored switch, as caveman-proxy reads it, not the registry default.
50
+ const modules = h.readConfig().modules;
51
+ const routing = !!modules && typeof modules === "object" && modules.routing === true;
52
+ lines.push(routing ? ROUTING_ON_LINE : "routing is off · caveman on routing to turn it on");
53
+ const telemetryOff = h.telemetryOff();
54
+ const level = runtimeDataLevel(await cloudMe(), telemetryOff);
55
+ lines.push(telemetryOff
56
+ ? "runtime data: nothing sent (telemetry is off) · caveman telemetry on to send counts"
57
+ : level === "off"
58
+ ? "runtime data: nothing sent (your organization's data level is off)"
59
+ : `runtime data: ${level} per request to your Cloud, never prompt text · caveman telemetry off to stop`);
60
+ return lines;
61
+ }
62
+ export function cloudProduct(answer, id) {
63
+ return Array.isArray(answer?.products) ? answer.products.find((product) => product?.id === id) : undefined;
64
+ }
65
+ // "1,204 of 100,000 free decisions this month", or nothing without numbers.
66
+ export function decisionsNote(product) {
67
+ const count = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? n.toLocaleString("en-US") : undefined;
68
+ const used = count(product?.used);
69
+ const allowance = count(product?.free_allowance);
70
+ if (used && allowance)
71
+ return `${used} of ${allowance} free decisions this month`;
72
+ return used ? `${used} decisions this month` : undefined;
73
+ }
74
+ export function routeState(now = new Date()) {
75
+ try {
76
+ const state = JSON.parse(readFileSync(join(cavemanHome(), "route-state.json"), "utf8"));
77
+ return Date.parse(state?.until ?? "") > now.getTime() ? state : undefined;
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ // The routing pause from /me, else from the proxy's record.
84
+ export function routingPause(product) {
85
+ if (product?.state === "limited")
86
+ return product;
87
+ const proxy = routeState();
88
+ if (proxy?.outcome !== "paused")
89
+ return undefined;
90
+ return { state: "limited", ...(proxy.reason ? { reason: proxy.reason } : {}), ...(proxy.notice ? { notice: proxy.notice } : {}),
91
+ ...(proxy.reason === "allowance" && proxy.until ? { period_end: proxy.until } : {}) };
92
+ }
93
+ // The period's end, or the next 1st (UTC) when nobody says.
94
+ function periodEnd(product, now) {
95
+ const end = product.period_end ? new Date(product.period_end) : new Date(NaN);
96
+ return Number.isNaN(end.getTime()) ? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)) : end;
97
+ }
98
+ // Cloud's text reaches a terminal: no control or bidi characters, bounded.
99
+ function printable(text) {
100
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 240);
101
+ }
102
+ // The pause line, once per period (the period it was shown for is kept in the
103
+ // config): Cloud's notice when it sends one, else "Free routing used for
104
+ // October. Back to local until Nov 1 · add a card: caveman billing".
105
+ export function pauseNotice(pause, now = new Date()) {
106
+ if (pause?.reason !== "allowance" && pause?.reason !== "billing_limit")
107
+ return undefined;
108
+ const end = periodEnd(pause, now);
109
+ const key = `${pause.reason}@${end.toISOString()}`;
110
+ const h = moduleHost();
111
+ if (h.readConfig().routingPauseNotice === key)
112
+ return undefined;
113
+ h.mutateConfig((out) => { out.routingPauseNotice = key; });
114
+ if (pause.notice && printable(pause.notice))
115
+ return printable(pause.notice);
116
+ const month = new Date(end.getTime() - 1).toLocaleString("en-US", { month: "long", timeZone: "UTC" });
117
+ const until = end.toLocaleString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
118
+ return pause.reason === "allowance"
119
+ ? `Free routing used for ${month}. Back to local until ${until} · add a card: caveman billing`
120
+ : `Routing reached your billing limit for ${month} · raise it: caveman billing`;
121
+ }
122
+ // The routing row's note and the pause line, for `caveman status`. Asks Cloud
123
+ // only while signed in with routing on.
124
+ export async function routingStatus(on) {
125
+ if (!on || !moduleHost().signedIn())
126
+ return {};
127
+ const product = cloudProduct(await cloudMe(), "routing");
128
+ const note = decisionsNote(product);
129
+ const notice = pauseNotice(routingPause(product));
130
+ return { ...(note ? { note } : {}), ...(notice ? { notice } : {}) };
131
+ }
132
+ // The web app beside a control API: api.<domain> → app.<domain>, the local
133
+ // dev API on :8080 → the dev web on :3000, otherwise the same origin.
134
+ export function appUrl(base) {
135
+ const url = new URL(base || "https://api.caveman.so");
136
+ if (url.hostname.startsWith("api."))
137
+ url.hostname = `app.${url.hostname.slice(4)}`;
138
+ else if ((url.hostname === "localhost" || url.hostname === "127.0.0.1") && url.port === "8080")
139
+ url.port = "3000";
140
+ return url.origin;
141
+ }
142
+ // `caveman billing`: open the signed-in Cloud's billing page; always print it.
143
+ export function billingCommand() {
144
+ const h = moduleHost();
145
+ const base = h.readConfig().baseURL;
146
+ const url = `${appUrl((typeof base === "string" && base) || process.env.CAVE_API_URL || "")}/billing`;
147
+ console.log(url);
148
+ if (h.interactive())
149
+ h.openBrowser(url);
150
+ }
@@ -0,0 +1,73 @@
1
+ // One config home: ~/.caveman (CAVEMAN_HOME). The cloud and capability config
2
+ // used to live in ~/.caveman-cloud/config.json; the first read copies it to
3
+ // ~/.caveman/cloud.json and leaves the old file for older CLIs. Every reader
4
+ // and writer goes through cloudConfigPath().
5
+ import { randomBytes } from "node:crypto";
6
+ import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ export function cavemanHome() {
10
+ return process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman");
11
+ }
12
+ export function legacyCloudDir() {
13
+ return join(homedir(), ".caveman-cloud");
14
+ }
15
+ function legacyConfigPath() {
16
+ return join(legacyCloudDir(), "config.json");
17
+ }
18
+ let migrated = "";
19
+ // The copy lands under a private name and is hard-linked into place, so a
20
+ // racing process sees either no file or the whole 0600 file; EEXIST means
21
+ // another process won. A copy that cannot be made leaves the old file in use
22
+ // and is retried on the next run.
23
+ export function cloudConfigPath() {
24
+ const path = join(cavemanHome(), "cloud.json");
25
+ if (migrated === path)
26
+ return path;
27
+ const legacy = legacyConfigPath();
28
+ if (!existsSync(path) && existsSync(legacy)) {
29
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
30
+ try {
31
+ mkdirSync(cavemanHome(), { recursive: true, mode: 0o700 });
32
+ copyFileSync(legacy, tmp);
33
+ chmodSync(tmp, 0o600);
34
+ try {
35
+ linkSync(tmp, path);
36
+ }
37
+ catch (error) {
38
+ if (error.code !== "EEXIST")
39
+ throw error;
40
+ }
41
+ }
42
+ catch {
43
+ return legacy;
44
+ }
45
+ finally {
46
+ try {
47
+ unlinkSync(tmp);
48
+ }
49
+ catch { /* never created */ }
50
+ }
51
+ }
52
+ migrated = path;
53
+ return path;
54
+ }
55
+ // While the old file exists, an older CLI may still run against it (a
56
+ // rollback). Keys it must keep respecting, the telemetry decision above all,
57
+ // are mirrored there. Best effort: the new file is the authority.
58
+ export function mirrorToLegacy(key, value) {
59
+ const legacy = legacyConfigPath();
60
+ if (!existsSync(legacy) || cloudConfigPath() === legacy)
61
+ return;
62
+ try {
63
+ const parsed = JSON.parse(readFileSync(legacy, "utf8"));
64
+ const out = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
65
+ out[key] = value;
66
+ const tmp = `${legacy}.${process.pid}.tmp`;
67
+ writeFileSync(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
68
+ renameSync(tmp, legacy);
69
+ }
70
+ catch {
71
+ /* an unreadable old file is the older CLI's problem, not this write's */
72
+ }
73
+ }
@@ -0,0 +1,86 @@
1
+ // Bare `caveman doctor`: local checks first (modules, config, binaries, the
2
+ // runtime port, wired agents), one failure per line with its fix. States the
3
+ // user chose print as notes and do not fail. Cloud is checked only when signed
4
+ // in, after the local lines are out, so a Cloud failure never hides them.
5
+ import { currentSelection, moduleHost, moduleStates } from "./apply.js";
6
+ import { findModule, MODULES } from "./registry.js";
7
+ import { moduleChoice, moduleFix } from "./status.js";
8
+ export async function modulesDoctor() {
9
+ const h = moduleHost();
10
+ const failures = [];
11
+ const notes = [];
12
+ const states = await moduleStates();
13
+ for (const state of states) {
14
+ if (!state.on || state.active || state.reason?.includes(" has an invalid value: "))
15
+ continue;
16
+ const fix = moduleFix(state);
17
+ if (moduleChoice(state))
18
+ notes.push(`· ${state.id}: ${state.reason}${fix ? ` · ${fix}` : ""}`);
19
+ else if (findModule(state.id)?.external)
20
+ failures.push(`${state.id}: ${state.reason}${state.reason?.endsWith(" not installed") ? " · fix: install it" : ""}, or caveman off ${state.id}`);
21
+ else
22
+ failures.push(`${state.id}: ${state.reason}${fix ? ` · fix: ${fix}` : ""}`);
23
+ }
24
+ // Invalid values fail whether their module is on or off.
25
+ const selection = currentSelection();
26
+ for (const m of MODULES) {
27
+ for (const effect of m.capabilities) {
28
+ const invalid = h.capability(effect.key).invalid;
29
+ if (invalid !== undefined)
30
+ failures.push(`${effect.key} has an invalid value: ${invalid} · fix: caveman ${selection[m.id] ? "on" : "off"} ${m.id}`);
31
+ }
32
+ }
33
+ const stale = h.staleBinaries();
34
+ if (stale.length)
35
+ failures.push(`${stale.join(", ")} ${stale.length > 1 ? "are" : "is"} out of date · fix: caveman setup --install`);
36
+ for (const runtime of await h.localRuntimes()) {
37
+ if (runtime.foreign)
38
+ failures.push(`${runtime.host}:${runtime.port} is held by another program · fix: stop it, then caveman start`);
39
+ // A runtime keeps the binary it started from until it restarts.
40
+ else if (runtime.stale)
41
+ failures.push(`${runtime.host}:${runtime.port} still runs caveman-proxy ${runtime.stale.running}; ${runtime.stale.installed} is installed · fix: caveman stop, then start your agent again`);
42
+ }
43
+ const down = await h.runtimeDown();
44
+ if (down)
45
+ failures.push(down);
46
+ const wired = h.nativeAgents().filter((agent) => agent.wired);
47
+ for (const agent of wired) {
48
+ const state = h.agentState(agent.id);
49
+ if (state === "degraded")
50
+ failures.push(`${agent.id}: wiring degraded · fix: ${h.agentFix(agent.id)}`);
51
+ else if (state === "unavailable")
52
+ failures.push(`${agent.id}: wired but not runnable · fix: reinstall ${agent.id}, or caveman disable ${agent.id}`);
53
+ const ask = h.agentAsk(agent.id);
54
+ if (ask)
55
+ notes.push(`· ${agent.id}: ${ask}`);
56
+ }
57
+ const traffic = h.agentTraffic();
58
+ if (traffic.fix)
59
+ notes.push(`· ${traffic.line} · ${traffic.fix}`);
60
+ for (const failure of failures)
61
+ console.log(`✗ ${failure}`);
62
+ for (const note of notes)
63
+ console.log(note);
64
+ let cloudFailed = false;
65
+ if (h.signedIn()) {
66
+ try {
67
+ await h.cloudCheck();
68
+ }
69
+ catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ const status = error.status;
72
+ // Down, slow or erroring (no answer, 5xx): signing in again fixes none of it.
73
+ if (status === 0 || (typeof status === "number" && status >= 500))
74
+ console.log(`· cloud: ${message} · try again later`);
75
+ else {
76
+ cloudFailed = true;
77
+ console.log(`✗ cloud: ${message} · fix: caveman login`);
78
+ }
79
+ }
80
+ }
81
+ if (failures.length || cloudFailed) {
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ console.log(`✓ healthy · ${states.filter((state) => state.on).length} modules on · ${wired.length} agents wired`);
86
+ }
@@ -0,0 +1,157 @@
1
+ // The signed module index and the module lockfile.
2
+ //
3
+ // modules.json (scripts/gen-modules-index.mjs) lists, per module, the binaries
4
+ // it needs and each platform build's sha256. It is signed through the
5
+ // release's checksums.txt: its sha256 is a line of that manifest, which the
6
+ // pinned release key signs (checksums.txt.keysig) and which names its release.
7
+ // Same key, same verifier as `caveman setup --install`.
8
+ //
9
+ // ~/.caveman/modules.lock.json records, per module, the release asked for, the
10
+ // release installed and the sha256 of each binary on disk.
11
+ import { createHash, randomBytes } from "node:crypto";
12
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { BINARY_RELEASE, BINARY_RELEASE_BASE_DEFAULT } from "../binaries.generated.js";
15
+ import { binaryInstallFilename, cavemanHome, cleanupPartial, downloadReleaseBinary, ensureCavemanHome, fetchReleaseAsset, parseSignedChecksums, removeAsideBinaries, replaceBinary, setupPlatform, setupTimeoutSeconds, sha256File, verifyChecksumSignature, } from "../index.js";
16
+ import { trimTrailingSlashes } from "../provider-routing.js";
17
+ function releaseBase() {
18
+ return `${trimTrailingSlashes(process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT)}/${BINARY_RELEASE}`;
19
+ }
20
+ // A name only this process owns, so concurrent installs (or setup --install,
21
+ // which uses `<target>.part`) never write, hash or publish each other's file.
22
+ function uniquePath(path, suffix) {
23
+ return `${path}.${process.pid}.${randomBytes(6).toString("hex")}.${suffix}`;
24
+ }
25
+ async function fetchBytes(url, timeoutSeconds) {
26
+ try {
27
+ return Buffer.from(await (await fetchReleaseAsset(url, timeoutSeconds)).arrayBuffer());
28
+ }
29
+ catch (error) {
30
+ throw new Error(`could not download the module index (${url}: ${error.message}) — check the network and try again`);
31
+ }
32
+ }
33
+ // Fetches modules.json of the pinned release and refuses it unless the signed
34
+ // checksums.txt lists its exact bytes.
35
+ // The pinned release was cut before modules.json existed. Its checksums.txt is
36
+ // signed and simply does not list one, so callers may fall back to the full
37
+ // signed install; every other failure here is a refusal.
38
+ export class NoModuleIndexError extends Error {
39
+ }
40
+ export async function loadModuleIndex() {
41
+ const base = releaseBase();
42
+ const timeout = setupTimeoutSeconds();
43
+ const [checksumsRaw, signature] = (await Promise.all([
44
+ fetchBytes(`${base}/checksums.txt`, timeout),
45
+ fetchBytes(`${base}/checksums.txt.keysig`, timeout),
46
+ ])).map((bytes) => bytes.toString("utf8"));
47
+ if (!verifyChecksumSignature(checksumsRaw, signature)) {
48
+ throw new Error(`signature check failed for checksums.txt of ${BINARY_RELEASE} — refusing modules.json`);
49
+ }
50
+ let expected;
51
+ try {
52
+ expected = parseSignedChecksums(checksumsRaw).get("modules.json");
53
+ }
54
+ catch (error) {
55
+ throw new Error(`signature check failed for checksums.txt (${error.message}) — refusing modules.json`);
56
+ }
57
+ if (!expected)
58
+ throw new NoModuleIndexError(`${BINARY_RELEASE} has no signed modules.json — refusing to read modules`);
59
+ const raw = await fetchBytes(`${base}/modules.json`, timeout);
60
+ if (createHash("sha256").update(raw).digest("hex") !== expected) {
61
+ throw new Error(`signature check failed for modules.json of ${BINARY_RELEASE} — refusing it`);
62
+ }
63
+ const index = JSON.parse(raw.toString("utf8"));
64
+ if (index.schema !== "caveman.modules.v1" || index.release !== BINARY_RELEASE || !Array.isArray(index.modules)) {
65
+ throw new Error(`modules.json of ${BINARY_RELEASE} is not a caveman.modules.v1 index for that release`);
66
+ }
67
+ return index;
68
+ }
69
+ function lockPath() {
70
+ return join(cavemanHome(), "modules.lock.json");
71
+ }
72
+ // A missing or unreadable lockfile is an empty one: every binary it would name
73
+ // is re-checked against its signed digest before use anyway.
74
+ export function readLock() {
75
+ try {
76
+ const parsed = JSON.parse(readFileSync(lockPath(), "utf8"));
77
+ if (parsed.schema === "caveman.modules.lock.v1" && parsed.modules && typeof parsed.modules === "object")
78
+ return parsed;
79
+ }
80
+ catch {
81
+ // fall through
82
+ }
83
+ return { schema: "caveman.modules.lock.v1", modules: {} };
84
+ }
85
+ export function writeLock(lock) {
86
+ ensureCavemanHome();
87
+ const path = lockPath();
88
+ const temp = uniquePath(path, "tmp");
89
+ writeFileSync(temp, `${JSON.stringify(lock, null, 2)}\n`, { mode: 0o600 });
90
+ chmodSync(temp, 0o600);
91
+ renameSync(temp, path);
92
+ }
93
+ // Downloads the binaries the named modules need into ~/.caveman/bin, each
94
+ // checked against the signed index, and records each module in the lockfile
95
+ // as soon as its binaries are in place. A signature or network failure throws;
96
+ // a module with no build for this platform is skipped and named in
97
+ // `problems`, so the others still install.
98
+ export async function ensureModuleBinaries(ids, downloading) {
99
+ const platform = setupPlatform();
100
+ const index = await loadModuleIndex();
101
+ const timeout = setupTimeoutSeconds();
102
+ const binDir = join(ensureCavemanHome(), "bin");
103
+ mkdirSync(binDir, { recursive: true, mode: 0o700 });
104
+ removeAsideBinaries(binDir);
105
+ const lock = readLock();
106
+ const problems = [];
107
+ for (const id of ids) {
108
+ const entry = index.modules.find((module) => module.id === id);
109
+ if (!entry) {
110
+ problems.push(`${id}: not in modules.json of ${index.release}`);
111
+ continue;
112
+ }
113
+ const picked = Object.entries(entry.binaries).map(([binary, builds]) => {
114
+ if (!/^[a-z0-9-]+$/.test(binary))
115
+ throw new Error(`modules.json of ${index.release} names an invalid binary ${JSON.stringify(binary)}`);
116
+ return [binary, builds.find((build) => build.os === platform.os && build.arch === platform.arch)];
117
+ });
118
+ const missing = picked.filter(([, build]) => !build).map(([binary]) => binary);
119
+ if (missing.length > 0) {
120
+ problems.push(`${id}: ${missing.join(", ")} has no ${platform.os}/${platform.arch} build in ${index.release}`);
121
+ continue;
122
+ }
123
+ const digests = {};
124
+ for (const [binary, build] of picked) {
125
+ const { name, sha256 } = build;
126
+ if (name !== `${binary}_${platform.os}_${platform.arch}` || !/^[a-f0-9]{64}$/.test(sha256)) {
127
+ throw new Error(`modules.json of ${index.release} has an invalid ${binary} build entry`);
128
+ }
129
+ const target = join(binDir, binaryInstallFilename(binary, platform.os));
130
+ digests[binary] = sha256;
131
+ if (sha256File(target) === sha256)
132
+ continue;
133
+ const part = uniquePath(target, "part");
134
+ downloading?.(binary);
135
+ try {
136
+ let got;
137
+ try {
138
+ got = (await downloadReleaseBinary(`${releaseBase()}/${name}`, part, timeout)).sha256;
139
+ }
140
+ catch (error) {
141
+ throw new Error(`the ${id} module could not download ${name} (${error.message}) — check the network, then retry with \`caveman on ${id}\``);
142
+ }
143
+ if (got !== sha256)
144
+ throw new Error(`signature check failed for ${name} — refusing to install the ${id} module; partial download deleted`);
145
+ chmodSync(part, 0o755);
146
+ replaceBinary(part, target);
147
+ }
148
+ catch (error) {
149
+ cleanupPartial(part);
150
+ throw error;
151
+ }
152
+ }
153
+ lock.modules[id] = { asked: BINARY_RELEASE, installed: index.release, binaries: digests };
154
+ writeLock(lock);
155
+ }
156
+ return { lock, problems };
157
+ }