@dreamlake/dreamlake-cli 0.94.0 → 0.96.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,366 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFileSync, mkdirSync } from "node:fs";
3
+ import { randomBytes } from "node:crypto";
4
+ import { homedir } from "node:os";
5
+ import path from "node:path";
6
+ import { BOOTSTRAP_PYTHON } from "./bootstrap-source.js";
7
+ import { hostStatus } from "./enroll.js";
8
+ import { hostConnection, listHosts, resolveHostNamespace } from "./inventory.js";
9
+ import { defaultSshIO, runHostSsh } from "./ssh.js";
10
+ /**
11
+ * Host-side upgrade, verification and rollback run the enrollment bootstrap
12
+ * (bootstrap.py) over `dreamlake exec`. The program and its JSON payload travel
13
+ * on stdin, so the remote command stays a short fixed loader.
14
+ */
15
+ export const BOOTSTRAP_LOADER = [
16
+ "import io,sys",
17
+ "d=sys.stdin.buffer.read()",
18
+ "n,_,r=d.partition(b'\\n')",
19
+ "n=int(n)",
20
+ "sys.stdin=io.TextIOWrapper(io.BytesIO(r[n:]),encoding='utf-8')",
21
+ "exec(compile(r[:n].decode('utf-8'),'dreamlake-host-bootstrap','exec'),{'__name__':'__main__'})",
22
+ ].join("\n");
23
+ export function bootstrapInput(payload) {
24
+ const source = Buffer.from(BOOTSTRAP_PYTHON, "utf8");
25
+ return Buffer.concat([Buffer.from(`${source.length}\n`), source, Buffer.from(JSON.stringify(payload))]);
26
+ }
27
+ /** The bootstrap prints exactly one JSON object; tolerate shell noise before it. */
28
+ export function parseBootstrapOutput(text) {
29
+ for (const line of text.trim().split("\n").reverse()) {
30
+ try {
31
+ const value = JSON.parse(line);
32
+ if (value && typeof value === "object" && !Array.isArray(value))
33
+ return value;
34
+ }
35
+ catch { }
36
+ }
37
+ return undefined;
38
+ }
39
+ /** Runs one bootstrap action through the nymph SSH relay (the `dreamlake exec` path). */
40
+ export const execOverNymph = async (target, payload, timeoutSeconds) => {
41
+ const chunks = [];
42
+ let bytes = 0;
43
+ const io = { ...defaultSshIO, spawn: args => {
44
+ const child = spawn("ssh", args, { stdio: ["pipe", "pipe", "ignore"] });
45
+ child.stdout.on("data", (b) => { bytes += b.length; if (bytes <= 64_000)
46
+ chunks.push(b); });
47
+ child.stdin.on("error", () => { });
48
+ child.stdin.end(bootstrapInput(payload));
49
+ return child;
50
+ } };
51
+ const exitCode = await runHostSsh(target.selector, { namespace: target.namespace, enrollment: target.enrollment,
52
+ duration: "1800", timeout: String(timeoutSeconds) }, ["python3", "-c", BOOTSTRAP_LOADER], io);
53
+ return { exitCode, result: parseBootstrapOutput(Buffer.concat(chunks).toString("utf8")) };
54
+ };
55
+ const VERSION = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
56
+ const UPGRADE_ID = /^\d{8}-\d{3}$/;
57
+ const ENROLLMENT = /^[a-f0-9]{24}$/;
58
+ // Host-side verification waits up to this long after the scheduled restart.
59
+ const RESTART_GRACE = 90;
60
+ function integer(value, fallback, low, high, flag) {
61
+ const n = value === undefined ? fallback : Number(value);
62
+ if (!Number.isInteger(n) || n < low || n > high)
63
+ throw new Error(`${flag} must be an integer from ${low} to ${high}`);
64
+ return n;
65
+ }
66
+ export function resolveFleetPlan(opts) {
67
+ let version;
68
+ if (opts.action === "upgrade") {
69
+ if (typeof opts.nymphVersion !== "string" || !VERSION.test(opts.nymphVersion)) {
70
+ throw new Error("--nymph-version must be an exact release such as 0.1.32; fleet upgrades never use latest");
71
+ }
72
+ version = opts.nymphVersion.replace(/^v/, "");
73
+ }
74
+ else if (opts.nymphVersion !== undefined)
75
+ throw new Error("rollback restores the kept previous binary; omit --nymph-version");
76
+ if (opts.upgradeId !== undefined && (opts.action !== "rollback" || !UPGRADE_ID.test(opts.upgradeId))) {
77
+ throw new Error("--upgrade-id applies to rollback and must look like YYYYMMDD-NNN");
78
+ }
79
+ if (opts.enrollment !== undefined && !ENROLLMENT.test(opts.enrollment))
80
+ throw new Error("--enrollment must be an exact enrollment ID");
81
+ const restartDelay = integer(opts.restartDelay, 15, 5, 300, "--restart-delay");
82
+ const stableSeconds = integer(opts.stableSeconds, 15, 5, 300, "--stable-seconds");
83
+ return {
84
+ action: opts.action, version, upgradeId: opts.upgradeId, dryRun: opts.dryRun === true, namespace: opts.namespace, enrollment: opts.enrollment,
85
+ concurrency: integer(opts.concurrency, 1, 1, 16, "--concurrency"),
86
+ maxFailures: integer(opts.maxFailures, 1, 1, 10_000, "--max-failures"),
87
+ restartDelay, stableSeconds,
88
+ verifyTimeout: integer(opts.verifyTimeout, 300, restartDelay + stableSeconds + 30, 3600, "--verify-timeout"),
89
+ };
90
+ }
91
+ const resolveDefaults = { status: hostStatus, list: listHosts, namespace: resolveHostNamespace };
92
+ /** Expands selectors into distinct hosts, in order. A host appears at most once. */
93
+ export async function resolveFleetHosts(selectors, opts, deps = resolveDefaults) {
94
+ if (opts.all ? selectors.length > 0 : selectors.length === 0)
95
+ throw new Error("Select hosts by ID, namespace/group/host or namespace/group/*, or use --all (not both)");
96
+ const hosts = [];
97
+ const seen = new Set();
98
+ const add = (host, namespace, enrollments = host.enrollments) => {
99
+ if (!host || typeof host.id !== "string" || !/^[a-f0-9]{24}$/i.test(host.id) || typeof host.name !== "string")
100
+ throw new Error("Host API returned an invalid host");
101
+ const id = host.id.toLowerCase();
102
+ if (seen.has(id))
103
+ return;
104
+ seen.add(id);
105
+ hosts.push({ id, name: host.name, namespace, online: hostConnection(enrollments) === "online" });
106
+ };
107
+ if (opts.all) {
108
+ const namespace = await deps.namespace(opts.namespace);
109
+ for (const host of (await deps.list({ namespace, all: true })).hosts)
110
+ add(host, namespace);
111
+ return hosts;
112
+ }
113
+ for (const selector of selectors) {
114
+ const parts = selector.split("/");
115
+ if (parts.length === 3 && parts[2] === "*") {
116
+ if (opts.namespace !== undefined && opts.namespace !== parts[0])
117
+ throw new Error("--namespace conflicts with the host selector");
118
+ for (const host of (await deps.list({ namespace: parts[0], group: parts[1], all: true })).hosts)
119
+ add(host, parts[0]);
120
+ continue;
121
+ }
122
+ if (selector.includes("*"))
123
+ throw new Error("Wildcards select a whole group: namespace/group/*");
124
+ if (parts.length === 3 && opts.namespace !== undefined && opts.namespace !== parts[0])
125
+ throw new Error("--namespace conflicts with the host selector");
126
+ const namespace = parts.length === 3 ? parts[0] : await deps.namespace(opts.namespace);
127
+ const detail = await deps.status(selector, { namespace: parts.length === 3 ? undefined : namespace });
128
+ add(detail?.host, namespace, detail?.enrollments);
129
+ }
130
+ return hosts;
131
+ }
132
+ const nowIso = (deps) => new Date(deps.now()).toISOString();
133
+ function failure(base, code, error, extra = {}) {
134
+ return { ...base, ...extra, status: "failed", code, error };
135
+ }
136
+ const HOST_ERRORS = {
137
+ service_not_installed: "no nymph service from `dreamlake hosts enroll` was found for this host name",
138
+ nymph_binary_unmanaged: "the service binary is not a user-owned regular file in a writable directory (package-managed or root-owned); upgrade it with its installer",
139
+ nymph_binary_missing: "the service binary is missing",
140
+ upgrade_in_progress: "another upgrade, verification or rollback holds this host's lock",
141
+ restart_pending: "another restart became due on the host during this run; rerun to apply",
142
+ restart_schedule_failed: "the delayed restart could not be scheduled; the previous binary was restored",
143
+ installer_failed: "the nymph installer did not produce a binary",
144
+ installer_version_mismatch: "the installed binary reports a different version than requested",
145
+ rollback_receipt_mismatch: "the installed binary is not the one the selected upgrade installed; nothing was changed",
146
+ rollback_binary_corrupt: "the kept previous binary no longer matches its recorded checksum; nothing was changed",
147
+ receipt_not_found: "no upgrade receipt from this tool matches the installed binary",
148
+ systemd_run_required: "Linux upgrade needs systemd-run for the one-shot restart timer",
149
+ invalid_version: "invalid nymph version",
150
+ upgrade_failed: "host-side upgrade failed",
151
+ };
152
+ function hostError(reply) {
153
+ const code = typeof reply.result?.code === "string" ? reply.result.code : "no_result";
154
+ return { code, error: HOST_ERRORS[code] ?? (code === "no_result" ? `the host returned no result (exit ${reply.exitCode})` : `host-side check failed: ${code}`) };
155
+ }
156
+ /** One host: apply, wait out the delayed restart, then verify it happened exactly once. */
157
+ export async function processFleetHost(host, plan, deps) {
158
+ const base = { host: host.name, hostId: host.id, status: "failed", startedAt: nowIso(deps) };
159
+ const done = (outcome) => ({ ...outcome, finishedAt: nowIso(deps) });
160
+ if (!host.online)
161
+ return done({ ...base, status: "skipped", code: "offline", error: "no verified online enrollment; not contacted" });
162
+ const target = { selector: host.id, namespace: host.namespace, enrollment: plan.enrollment };
163
+ if (plan.dryRun) {
164
+ let reply;
165
+ try {
166
+ reply = await deps.exec(target, { action: "inspect", name: host.name, ...(plan.version ? { version: plan.version } : {}) }, 120);
167
+ }
168
+ catch (error) {
169
+ return done(failure(base, "transport", error instanceof Error ? error.message : "exec failed"));
170
+ }
171
+ if (reply.result?.status !== "inspected")
172
+ return done(failure(base, hostError(reply).code, hostError(reply).error));
173
+ const { status: _status, ...inspected } = reply.result;
174
+ return done({ ...base, status: "planned", version: inspected.version, plan: inspected });
175
+ }
176
+ const payload = { action: plan.action, name: host.name, restartDelaySeconds: plan.restartDelay,
177
+ ...(plan.version ? { version: plan.version } : {}), ...(plan.upgradeId ? { upgradeId: plan.upgradeId } : {}) };
178
+ let earlier;
179
+ // At most two rounds: a restart still due from an earlier run is verified first (never
180
+ // stacked), then the requested action is applied once.
181
+ for (let round = 0; round < 2; round++) {
182
+ let reply;
183
+ try {
184
+ reply = await deps.exec(target, payload, 600);
185
+ }
186
+ catch (error) {
187
+ return done(failure(base, "transport", error instanceof Error ? error.message : "exec failed"));
188
+ }
189
+ const applied = reply.result;
190
+ const extra = earlier ? { earlierRestart: earlier } : {};
191
+ if (applied?.status === "current") {
192
+ return done({ ...base, ...extra, status: "current", version: applied.version, pid: { before: applied.pid, after: applied.pid }, restarts: 0, leftoverJobsRemoved: applied.leftoverJobsRemoved });
193
+ }
194
+ if (applied?.code === "restart_pending" && UPGRADE_ID.test(applied.upgradeId) && round === 0) {
195
+ const previous = await verifyRestart(host, target, applied.upgradeId, plan, deps, { ...base, upgradeId: applied.upgradeId });
196
+ if (previous.status !== "verified") {
197
+ return done(failure(previous.outcome, "earlier_restart_unverified", `an earlier restart (${applied.upgradeId}) was still due and did not verify: ${previous.outcome.error}`));
198
+ }
199
+ earlier = { upgradeId: applied.upgradeId, status: "verified" };
200
+ continue;
201
+ }
202
+ if (applied?.status !== "restart_scheduled" || !UPGRADE_ID.test(applied.upgradeId)) {
203
+ const { code, error } = hostError(reply);
204
+ return done(failure({ ...base, ...extra }, code, error));
205
+ }
206
+ const pending = { ...base, ...extra, upgradeId: applied.upgradeId, version: applied.version, previousVersion: applied.previousVersion,
207
+ restart: applied.restart, leftoverJobsRemoved: applied.leftoverJobsRemoved };
208
+ deps.record({ type: "scheduled", ...pending });
209
+ const result = await verifyRestart(host, target, applied.upgradeId, plan, deps, pending);
210
+ return done(result.status === "verified" ? { ...result.outcome, status: plan.action === "rollback" ? "rolled_back" : "upgraded" } : result.outcome);
211
+ }
212
+ return done(failure(base, "restart_pending", "a restart is still pending on the host"));
213
+ }
214
+ /** Waits out the delayed restart, then verifies it, retrying while the relay reconnects. */
215
+ async function verifyRestart(host, target, upgradeId, plan, deps, pending) {
216
+ // The restart ends the session that scheduled it; reconnect only after it is due.
217
+ await deps.sleep((plan.restartDelay + 3) * 1000);
218
+ const deadline = deps.now() + plan.verifyTimeout * 1000;
219
+ let last = "verification did not run";
220
+ while (true) {
221
+ try {
222
+ const check = await deps.exec(target, { action: "verify", name: host.name, upgradeId, stableSeconds: plan.stableSeconds }, plan.stableSeconds + RESTART_GRACE + 60);
223
+ const result = check.result;
224
+ const observed = result?.status === "verified" || result?.status === "failed" ? {
225
+ version: result.version, pid: result.pid, restarts: result.restarts, failures: result.failures,
226
+ } : undefined;
227
+ if (result?.status === "verified")
228
+ return { status: "verified", outcome: { ...pending, ...observed } };
229
+ if (result?.status === "failed") {
230
+ return { status: "failed", outcome: failure(pending, "verification_failed", `restart verification failed: ${(result.failures ?? []).join(", ")}`, observed) };
231
+ }
232
+ // A missing result means the relay dropped (often nymph restarting); a busy lock clears.
233
+ if (result?.code && result.code !== "upgrade_in_progress") {
234
+ const e = hostError(check);
235
+ return { status: "failed", outcome: failure(pending, e.code, e.error) };
236
+ }
237
+ last = result?.code ? HOST_ERRORS[result.code] : `verification session ended without a result (exit ${check.exitCode})`;
238
+ }
239
+ catch (error) {
240
+ last = error instanceof Error ? error.message : "exec failed";
241
+ }
242
+ if (deps.now() >= deadline)
243
+ return { status: "failed", outcome: failure(pending, "verification_timeout", `${last}; rerun upgrade or inspect with --dry-run`) };
244
+ await deps.sleep(5000);
245
+ }
246
+ }
247
+ /** Bounded concurrency; stops starting hosts after maxFailures; one worker per host at a time. */
248
+ export async function runFleet(hosts, plan, deps) {
249
+ const ids = new Set(hosts.map(h => h.id));
250
+ if (ids.size !== hosts.length)
251
+ throw new Error("A host was selected twice");
252
+ const outcomes = new Array(hosts.length);
253
+ const active = new Set();
254
+ let next = 0, failures = 0;
255
+ const worker = async () => {
256
+ while (next < hosts.length && failures < plan.maxFailures) {
257
+ const index = next++;
258
+ const host = hosts[index];
259
+ if (active.has(host.id))
260
+ throw new Error("A host was scheduled twice concurrently");
261
+ active.add(host.id);
262
+ let outcome;
263
+ try {
264
+ outcome = await processFleetHost(host, plan, deps);
265
+ }
266
+ catch (error) {
267
+ outcome = { host: host.name, hostId: host.id, status: "failed", code: "internal", error: error instanceof Error ? error.message : String(error) };
268
+ }
269
+ finally {
270
+ active.delete(host.id);
271
+ }
272
+ if (outcome.status === "failed")
273
+ failures++;
274
+ outcomes[index] = outcome;
275
+ deps.record({ type: "host", ...outcome });
276
+ }
277
+ };
278
+ await Promise.all(Array.from({ length: Math.min(plan.concurrency, hosts.length) }, worker));
279
+ // Array.from, not map: map skips the holes left by hosts that were never started.
280
+ const final = Array.from(hosts, (h, i) => outcomes[i] ?? { host: h.name, hostId: h.id, status: "not_started" });
281
+ const counts = {};
282
+ for (const outcome of final)
283
+ counts[outcome.status] = (counts[outcome.status] ?? 0) + 1;
284
+ return { action: plan.action, ...(plan.version ? { version: plan.version } : {}), dryRun: plan.dryRun,
285
+ stoppedEarly: final.some(o => o.status === "not_started"), counts, hosts: final };
286
+ }
287
+ export function fleetSucceeded(report) {
288
+ return report.hosts.every(h => ["upgraded", "rolled_back", "current", "planned"].includes(h.status));
289
+ }
290
+ function cell(value) {
291
+ return value === undefined || value === null || value === "" ? "-" : String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
292
+ }
293
+ export function formatFleetReport(report) {
294
+ const rows = [["HOST", "STATUS", "VERSION", "PID", "RESTARTS", "NOTE"], ...report.hosts.map(h => [
295
+ cell(h.host), h.status, h.plan ? `${cell(h.version)} (plan: ${cell(h.plan.plan)})` : h.previousVersion && h.version ? `${h.previousVersion} -> ${h.version}` : cell(h.version),
296
+ h.pid ? `${cell(h.pid.before)} -> ${cell(h.pid.after)}` : "-", cell(h.restarts),
297
+ cell([h.error, h.leftoverJobsRemoved?.length ? `removed leftover job ${h.leftoverJobsRemoved.join(", ")}` : "",
298
+ h.plan && Array.isArray(h.plan.leftoverJobs) && h.plan.leftoverJobs.length ? `would remove leftover job ${h.plan.leftoverJobs.join(", ")}` : ""].filter(Boolean).join("; ")),
299
+ ])];
300
+ const widths = rows[0].map((_, i) => Math.max(...rows.map(r => r[i].length)));
301
+ const lines = rows.map(r => r.map((v, i) => i === r.length - 1 ? v : v.padEnd(widths[i])).join(" "));
302
+ lines.push(Object.entries(report.counts).map(([k, v]) => `${v} ${k}`).join(", ") + ".");
303
+ if (report.stoppedEarly)
304
+ lines.push("Stopped after reaching --max-failures; not_started hosts were not contacted.");
305
+ if (report.dryRun)
306
+ lines.push("Dry run: hosts were inspected read-only; nothing was changed.");
307
+ if (report.record)
308
+ lines.push(`Outcome record: ${report.record}`);
309
+ return lines.join("\n");
310
+ }
311
+ function recordFile(file) {
312
+ const target = file ?? path.join(homedir(), ".dreamlake/hosts-upgrades", `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}.jsonl`);
313
+ mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
314
+ return { path: target, write: entry => appendFileSync(target, JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n", { mode: 0o600 }) };
315
+ }
316
+ export async function runHostsUpgrade(selectors, opts, overrides = {}) {
317
+ let record;
318
+ try {
319
+ const plan = resolveFleetPlan(opts);
320
+ const hosts = await resolveFleetHosts(selectors, { all: opts.all, namespace: opts.namespace }, overrides.resolve);
321
+ if (plan.enrollment && hosts.length !== 1)
322
+ throw new Error("--enrollment applies to exactly one host");
323
+ if (plan.upgradeId && hosts.length !== 1)
324
+ throw new Error("--upgrade-id applies to exactly one host; upgrade IDs are per host");
325
+ record = recordFile(opts.record);
326
+ const deps = { exec: overrides.exec ?? execOverNymph, sleep: overrides.sleep ?? (ms => new Promise(r => setTimeout(r, ms))),
327
+ now: overrides.now ?? Date.now, record: overrides.record ?? record.write };
328
+ deps.record({ type: "run", action: plan.action, version: plan.version, dryRun: plan.dryRun, concurrency: plan.concurrency,
329
+ maxFailures: plan.maxFailures, hosts: hosts.map(h => ({ host: h.name, hostId: h.id, online: h.online })) });
330
+ const report = { ...await runFleet(hosts, plan, deps), record: record.path };
331
+ deps.record({ type: "summary", counts: report.counts, stoppedEarly: report.stoppedEarly });
332
+ console.log(opts.json ? JSON.stringify(report, null, 2) : formatFleetReport(report));
333
+ return fleetSucceeded(report) ? 0 : 1;
334
+ }
335
+ catch (error) {
336
+ const message = error instanceof Error ? error.message : String(error);
337
+ if (opts.json)
338
+ console.log(JSON.stringify({ status: "error", error: message, ...(record ? { record: record.path } : {}) }));
339
+ else
340
+ console.error(`Host ${opts.action}: ${message}`);
341
+ return 1;
342
+ }
343
+ }
344
+ export function registerHostUpgradeCommands(group) {
345
+ const common = (command) => command
346
+ .argument("[selectors...]", "host IDs, namespace/group/host, or quoted namespace/group/*")
347
+ .option("--all", "every host in --namespace (offline hosts are reported as skipped)")
348
+ .option("--namespace <namespace>", "namespace for --all and host IDs (default: signed-in personal namespace)")
349
+ .option("--enrollment <id>", "exact SSH enrollment when one host has several")
350
+ .option("--dry-run", "inspect each host read-only (version, pending restart, leftover jobs); change nothing")
351
+ .option("--concurrency <n>", "hosts processed at once, 1–16 (default 1)")
352
+ .option("--max-failures <n>", "stop starting new hosts after this many failures (default 1)")
353
+ .option("--restart-delay <seconds>", "delay before the one-shot nymph restart, 5–300 (default 15)")
354
+ .option("--stable-seconds <seconds>", "new nymph PID must stay unchanged this long, 5–300 (default 15)")
355
+ .option("--verify-timeout <seconds>", "time allowed to reconnect and verify after the restart (default 300)")
356
+ .option("--record <path>", "JSON Lines outcome record (default ~/.dreamlake/hosts-upgrades/<run>.jsonl)")
357
+ .option("--json", "emit the fleet report as JSON");
358
+ common(group.command("upgrade")
359
+ .description("upgrade nymph on enrolled hosts over the nymph relay with one verified delayed restart"))
360
+ .option("--nymph-version <version>", "exact nymph release to install, such as 0.1.32 (required)")
361
+ .action(async (selectors, opts) => { process.exitCode = await runHostsUpgrade(selectors, { ...opts, action: "upgrade" }); });
362
+ common(group.command("rollback")
363
+ .description("restore the nymph binary kept by the last upgrade and verify one delayed restart"))
364
+ .option("--upgrade-id <id>", "roll back this YYYYMMDD-NNN host receipt instead of the latest (one host only)")
365
+ .action(async (selectors, opts) => { process.exitCode = await runHostsUpgrade(selectors, { ...opts, action: "rollback" }); });
366
+ }
@@ -13,6 +13,7 @@ import { compareVersions, resolveChannel } from "./releases.js";
13
13
  import { activeChannel, autoUpdaterDisabled, pinnedVersion, updatesDisabled } from "./settings.js";
14
14
  import { installWarnings, performInstall } from "./install.js";
15
15
  import { remindAfterInstall } from "../skill/reminders.js";
16
+ import { removeLeftoverRestartJobs } from "../hosts/leftover-jobs.js";
16
17
  import { VERSION } from "../version.js";
17
18
  /** How long to wait between unattended checks. */
18
19
  const CHECK_INTERVAL_MS = 4 * 60 * 60 * 1000;
@@ -53,6 +54,9 @@ export async function runUpdate(opts = {}) {
53
54
  if (!quiet)
54
55
  process.stdout.write(`${msg}\n`);
55
56
  };
57
+ // Runs on every update check, so auto-updating Macs clear the job without anyone logging in.
58
+ for (const label of removeLeftoverRestartJobs())
59
+ say(`Removed leftover fleet-upgrade restart job ${label}.`);
56
60
  if (updatesDisabled()) {
57
61
  say("Updates are disabled (DREAMLAKE_DISABLE_UPDATES).");
58
62
  return 0;
@@ -2,6 +2,14 @@ import type { Command } from "commander";
2
2
  export declare function entryName(name: string, prefix?: string): string;
3
3
  export declare function revisionNumber(value?: string): number | undefined;
4
4
  export declare function expiryValue(value: string | undefined, clear?: boolean): string | null | undefined;
5
+ /** Convert a relative duration such as `90d`, `12h` or `1w3d` into a UTC RFC3339 expiry measured from `now`. */
6
+ export declare function expiryDuration(value: string, now?: Date): string;
7
+ /** Resolve the mutually exclusive `--expires-at`, `--expires-in` and `--no-expiry` options into one request value. */
8
+ export declare function resolveExpiry(options: {
9
+ expiresAt?: string;
10
+ expiresIn?: string;
11
+ clear?: boolean;
12
+ }, now?: Date): string | null | undefined;
5
13
  export declare function secretValue(raw: string, json?: boolean): string | Record<string, string>;
6
14
  export declare function writeRequestId(value: unknown): string;
7
15
  export declare function writeReceipt(result: any, id: string): Record<string, unknown>;
@@ -29,6 +29,36 @@ export function expiryValue(value, clear = false) {
29
29
  throw new Error("Invalid expiry; use UTC RFC3339");
30
30
  return date.toISOString();
31
31
  }
32
+ const DURATION_UNIT_SECONDS = { s: 1, m: 60, h: 3600, d: 86400, w: 604800 };
33
+ /** Convert a relative duration such as `90d`, `12h` or `1w3d` into a UTC RFC3339 expiry measured from `now`. */
34
+ export function expiryDuration(value, now = new Date()) {
35
+ const invalid = () => new Error("Invalid expiry duration; use whole units such as 90d, 12h, 30m or 1w3d");
36
+ if (!/^(?:\d+[smhdw])+$/.test(value))
37
+ throw invalid();
38
+ let seconds = 0;
39
+ const seen = new Set();
40
+ for (const [, count, unit] of value.matchAll(/(\d+)([smhdw])/g)) {
41
+ if (seen.has(unit))
42
+ throw invalid();
43
+ seen.add(unit);
44
+ seconds += Number(count) * DURATION_UNIT_SECONDS[unit];
45
+ }
46
+ if (!Number.isSafeInteger(seconds) || seconds <= 0)
47
+ throw invalid();
48
+ const date = new Date(now.getTime() + seconds * 1000);
49
+ if (!Number.isFinite(date.getTime()))
50
+ throw invalid();
51
+ return date.toISOString();
52
+ }
53
+ /** Resolve the mutually exclusive `--expires-at`, `--expires-in` and `--no-expiry` options into one request value. */
54
+ export function resolveExpiry(options, now = new Date()) {
55
+ const chosen = [options.expiresAt !== undefined, options.expiresIn !== undefined, options.clear === true].filter(Boolean).length;
56
+ if (chosen > 1)
57
+ throw new Error("Choose only one of --expires-at, --expires-in or --no-expiry");
58
+ if (options.expiresIn !== undefined)
59
+ return expiryDuration(options.expiresIn, now);
60
+ return expiryValue(options.expiresAt, options.clear === true);
61
+ }
32
62
  export function secretValue(raw, json = false) {
33
63
  let value = raw;
34
64
  if (json) {
@@ -104,6 +134,7 @@ export function registerVaultMutations(vault) {
104
134
  .option("--stdin", "read exact string value from stdin")
105
135
  .option("--stdin-json", "read string or field map JSON from stdin")
106
136
  .option("--expires-at <timestamp>", "UTC expiry for vault retrieval; omitted preserves current expiry")
137
+ .option("--expires-in <duration>", "relative expiry from now, such as 90d, 12h or 1w3d; converted to UTC before upload")
107
138
  .option("--no-expiry", "explicitly clear vault retrieval expiry")
108
139
  .option("--env <name>", "saved environment variable name")
109
140
  .option("--key-name <name>", "saved composed JSON key")
@@ -121,7 +152,7 @@ export function registerVaultMutations(vault) {
121
152
  throw new Error("Choose --stdin or --stdin-json");
122
153
  if (!options.stdin && !options.stdinJson && !process.stdin.isTTY)
123
154
  throw new Error("Noninteractive add requires --stdin or --stdin-json");
124
- const expiresAt = expiryValue(options.expiresAt, options.expiry === false);
155
+ const expiresAt = resolveExpiry({ expiresAt: options.expiresAt, expiresIn: options.expiresIn, clear: options.expiry === false });
125
156
  const raw = options.stdin || options.stdinJson ? await stdinValue() : await password({ message: "Secret value", mask: "*" }, { output: process.stderr });
126
157
  const value = secretValue(raw, options.stdinJson);
127
158
  console.error(`Write request ID: ${writeId}`);
@@ -1 +1 @@
1
- export declare const VERSION = "0.94.0";
1
+ export declare const VERSION = "0.96.0";
@@ -6,4 +6,4 @@
6
6
  // value means a binary that re-installs the same version forever.
7
7
  //
8
8
  // Editing this by hand does nothing for a release; bump package.json.
9
- export const VERSION = "0.94.0";
9
+ export const VERSION = "0.96.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamlake/dreamlake-cli",
3
- "version": "0.94.0",
3
+ "version": "0.96.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
@@ -35,13 +35,13 @@
35
35
  "node": ">=18"
36
36
  },
37
37
  "optionalDependencies": {
38
- "@dreamlake/dreamlake-cli-darwin-arm64": "0.94.0",
39
- "@dreamlake/dreamlake-cli-darwin-x64": "0.94.0",
40
- "@dreamlake/dreamlake-cli-linux-x64": "0.94.0",
41
- "@dreamlake/dreamlake-cli-linux-arm64": "0.94.0",
42
- "@dreamlake/dreamlake-cli-linux-x64-musl": "0.94.0",
43
- "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.94.0",
44
- "@dreamlake/dreamlake-cli-win32-x64": "0.94.0",
45
- "@dreamlake/dreamlake-cli-win32-arm64": "0.94.0"
38
+ "@dreamlake/dreamlake-cli-darwin-arm64": "0.96.0",
39
+ "@dreamlake/dreamlake-cli-darwin-x64": "0.96.0",
40
+ "@dreamlake/dreamlake-cli-linux-x64": "0.96.0",
41
+ "@dreamlake/dreamlake-cli-linux-arm64": "0.96.0",
42
+ "@dreamlake/dreamlake-cli-linux-x64-musl": "0.96.0",
43
+ "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.96.0",
44
+ "@dreamlake/dreamlake-cli-win32-x64": "0.96.0",
45
+ "@dreamlake/dreamlake-cli-win32-arm64": "0.96.0"
46
46
  }
47
47
  }