@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,40 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ const launchctl = args => execFileSync("launchctl", args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
4
+ /**
5
+ * The 2026-10-21 fleet upgrade registered a one-shot nymph restart with
6
+ * `launchctl submit`, which launchd keeps alive: the job re-ran forever and
7
+ * restarted nymph every ~15s. Remove only jobs that match it exactly — a
8
+ * submitted `ai.dreamlake.refresh.*` job running this user's
9
+ * `fleet-upgrades/<id>/restart.py` — and never touch anything else.
10
+ */
11
+ export function removeLeftoverRestartJobs(run = launchctl, home = homedir(), platform = process.platform, uid = process.getuid?.()) {
12
+ if (platform !== "darwin" || uid === undefined)
13
+ return [];
14
+ const script = new RegExp(`^\\s*${escape(home)}/\\.local/share/dreamlake/fleet-upgrades/[A-Za-z0-9._-]+/restart\\.py$`, "m");
15
+ const removed = [];
16
+ let listing;
17
+ try {
18
+ listing = run(["list"]);
19
+ }
20
+ catch {
21
+ return removed;
22
+ }
23
+ for (const line of listing.split("\n")) {
24
+ const label = line.trim().split(/\s+/)[2];
25
+ if (!label || !/^ai\.dreamlake\.refresh\.[A-Za-z0-9]+$/.test(label))
26
+ continue;
27
+ try {
28
+ const detail = run(["print", `gui/${uid}/${label}`]);
29
+ if (!/^\s*type = Submitted$/m.test(detail) || !script.test(detail))
30
+ continue;
31
+ run(["remove", label]);
32
+ removed.push(label);
33
+ }
34
+ catch { /* best effort: leave anything we cannot inspect or remove */ }
35
+ }
36
+ return removed;
37
+ }
38
+ function escape(value) {
39
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
40
+ }
@@ -3,6 +3,8 @@ import { Duplex } from 'node:stream';
3
3
  import WebSocket from 'ws';
4
4
  import type { Command } from 'commander';
5
5
  import { hostRequest } from './api.js';
6
+ /** Wait the server's Retry-After (capped at 5s) or exponential backoff, whichever is longer. */
7
+ export declare function busyRetryDelay(attempt: number, retryAt?: string, now?: number): number;
6
8
  export interface SshTarget {
7
9
  hostId: string;
8
10
  enrollmentId: string;
@@ -43,7 +45,10 @@ export interface SshIO {
43
45
  fetch: typeof fetch;
44
46
  socket: (url: string, ticket: string) => WebSocket;
45
47
  spawn: (args: string[]) => ChildProcess;
48
+ chooseTarget?: (targets: SshTarget[]) => Promise<string>;
46
49
  }
50
+ export declare const defaultSshIO: SshIO;
51
+ export declare function chooseSshTarget(targets: SshTarget[], selector: string, opts: SshOptions, argv: string[] | undefined, choose?: SshIO['chooseTarget']): Promise<SshTarget>;
47
52
  export declare function sshPublicKey(value: string): string;
48
53
  export declare function validateSshTarget(t: SshTarget, hostId: string, namespace: string): void;
49
54
  export declare function validateSshSession(s: SshSession, t: SshTarget, previous?: string): string;
@@ -8,16 +8,50 @@ import { Duplex } from 'node:stream';
8
8
  import { promisify } from 'node:util';
9
9
  import { setTimeout as delay } from 'node:timers/promises';
10
10
  import WebSocket from 'ws';
11
- import { hostApiPath, hostRequest } from './api.js';
11
+ import { select } from '@inquirer/prompts';
12
+ import { HostApiError, hostApiPath, hostRequest } from './api.js';
12
13
  import { hostStatus } from './enroll.js';
13
14
  import { resolveHostNamespace } from './inventory.js';
14
15
  const ID = /^[a-f0-9]{24}$/;
15
- const defaults = {
16
+ // Same budget as the browser relay: 4 delegation attempts within 25s.
17
+ const BUSY_MAX_ATTEMPTS = 4, BUSY_RETRY_BUDGET_MS = 25000;
18
+ /** Wait the server's Retry-After (capped at 5s) or exponential backoff, whichever is longer. */
19
+ export function busyRetryDelay(attempt, retryAt, now = Date.now()) {
20
+ const hinted = retryAt ? Math.min(Math.max(Date.parse(retryAt) - now, 0), 5000) : 0;
21
+ return Math.max(Number.isFinite(hinted) ? hinted : 0, 1000 * 2 ** (attempt - 1));
22
+ }
23
+ export const defaultSshIO = {
16
24
  request: hostRequest, fetch: (...args) => fetch(...args),
17
25
  socket: (url, ticket) => new WebSocket(url, 'nymph-ssh.v1', { headers: { Authorization: `Bearer ${ticket}` },
18
26
  perMessageDeflate: false, maxPayload: 65537, handshakeTimeout: 10000, followRedirects: false }),
19
27
  spawn: args => spawn('ssh', args, { stdio: 'inherit' }),
20
28
  };
29
+ export async function chooseSshTarget(targets, selector, opts, argv, choose) {
30
+ if (targets.length === 0)
31
+ throw new Error('No ready SSH enrollment for this host');
32
+ if (targets.length === 1)
33
+ return targets[0];
34
+ const label = (t) => `${t.username} (UID ${t.unixUid}) — ready — enrollment ${t.enrollmentId}`;
35
+ if (!choose && process.stdin.isTTY && process.stderr.isTTY) {
36
+ choose = choices => select({ message: `Choose an SSH user on ${selector}`, choices: choices.map(t => ({ name: label(t), value: t.enrollmentId })) }, { output: process.stderr });
37
+ }
38
+ if (!choose) {
39
+ const quote = (value) => /^[A-Za-z0-9_./:@=-]+$/.test(value) ? value : "'" + value.replace(/'/g, "'\\''") + "'";
40
+ const options = [opts.namespace ? ['--namespace', opts.namespace] : [],
41
+ opts.duration ? ['--duration', opts.duration] : [], opts.timeout ? ['--timeout', opts.timeout] : []].flat();
42
+ const rows = targets.map(t => {
43
+ const command = ['dreamlake', argv === undefined ? 'ssh' : 'exec', selector, ...options,
44
+ '--enrollment', t.enrollmentId, ...(argv === undefined ? [] : ['--', ...argv])];
45
+ return ` ${label(t)}\n ${command.map(quote).join(' ')}`;
46
+ });
47
+ throw new Error(`Multiple SSH enrollments; choose one with --enrollment:\n${rows.join('\n')}`);
48
+ }
49
+ const enrollment = await choose(targets);
50
+ const selected = targets.filter(t => t.enrollmentId === enrollment);
51
+ if (selected.length !== 1)
52
+ throw new Error('No unique SSH enrollment selected');
53
+ return selected[0];
54
+ }
21
55
  export function sshPublicKey(value) {
22
56
  if (typeof value !== 'string')
23
57
  throw new Error('Invalid SSH host key');
@@ -98,7 +132,7 @@ export class SshRelay extends Duplex {
98
132
  _final(done) { this.ws.send(Buffer.from([1]), { binary: true }, error => done(error ? new Error('SSH relay FIN failed') : undefined)); }
99
133
  _destroy(error, done) { this.ws.terminate(); done(error); }
100
134
  }
101
- export async function runHostSsh(selector, opts, argv, io = defaults) {
135
+ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
102
136
  if (process.platform === 'win32')
103
137
  throw new Error('Host SSH currently requires Linux or macOS and OpenSSH');
104
138
  if (selector.includes('*'))
@@ -122,12 +156,14 @@ export async function runHostSsh(selector, opts, argv, io = defaults) {
122
156
  if (!Array.isArray(catalog?.targets))
123
157
  throw new Error('Invalid SSH target catalog');
124
158
  const matches = catalog.targets.filter((t) => t.hostId === detail.host.id && (!opts.enrollment || t.enrollmentId === opts.enrollment));
125
- if (matches.length !== 1)
126
- throw new Error(matches.length ? 'Multiple SSH enrollments; select --enrollment' : 'No ready SSH enrollment for this host');
127
- const target = matches[0];
128
- validateSshTarget(target, detail.host.id, namespace);
129
- if (!detail.enrollments.some((e) => e.id === target.enrollmentId && e.machineId === target.machineId && e.unixUser === target.username))
130
- throw new Error('SSH enrollment identity changed');
159
+ // Validate every displayed identity before prompting, and preserve the same
160
+ // host/enrollment binding and host-key checks after the selection.
161
+ for (const target of matches) {
162
+ validateSshTarget(target, detail.host.id, namespace);
163
+ if (!detail.enrollments.some((e) => e.id === target.enrollmentId && e.machineId === target.machineId && e.unixUser === target.username))
164
+ throw new Error('SSH enrollment identity changed');
165
+ }
166
+ const target = await chooseSshTarget(matches, selector, opts, argv, io.chooseTarget);
131
167
  const dir = await mkdtemp(join(tmpdir(), 'dreamlake-ssh-'));
132
168
  let sessionId, credential;
133
169
  let child, relay, socket, ws;
@@ -152,10 +188,25 @@ export async function runHostSsh(selector, opts, argv, io = defaults) {
152
188
  const key = join(dir, 'identity');
153
189
  await promisify(execFile)('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', key], { timeout: 10000 });
154
190
  abort.signal.throwIfAborted();
155
- // One submission only: an ambiguous failure must not create a second session.
156
- const delegated = await io.request(`${base}/terminal-targets/${target.enrollmentId}/session`, 'POST', {
157
- clientPublicKey: sshPublicKey(await readFile(key + '.pub', 'utf8')), durationSeconds: duration,
158
- });
191
+ // An ambiguous failure must not create a second session. Only a definite
192
+ // controlplane_busy refusal (nothing was created) is resubmitted, within a bounded budget.
193
+ const clientPublicKey = sshPublicKey(await readFile(key + '.pub', 'utf8'));
194
+ const busyDeadline = Date.now() + BUSY_RETRY_BUDGET_MS;
195
+ let delegated;
196
+ for (let attempt = 1;; attempt++) {
197
+ try {
198
+ delegated = await io.request(`${base}/terminal-targets/${target.enrollmentId}/session`, 'POST', { clientPublicKey, durationSeconds: duration });
199
+ break;
200
+ }
201
+ catch (error) {
202
+ if (!(error instanceof HostApiError) || error.code !== 'controlplane_busy' || attempt >= BUSY_MAX_ATTEMPTS)
203
+ throw error;
204
+ const wait = busyRetryDelay(attempt, error.retryAt);
205
+ if (Date.now() + wait >= busyDeadline)
206
+ throw error;
207
+ await delay(wait, undefined, { signal: abort.signal });
208
+ }
209
+ }
159
210
  credential = delegated?.credential;
160
211
  if (typeof credential !== 'string' || !credential || credential.length > 8192 || /\s/.test(credential))
161
212
  throw new Error('Invalid SSH session credential');
@@ -0,0 +1,122 @@
1
+ import type { Command } from "commander";
2
+ import { hostStatus } from "./enroll.js";
3
+ import { listHosts, resolveHostNamespace } from "./inventory.js";
4
+ /**
5
+ * Host-side upgrade, verification and rollback run the enrollment bootstrap
6
+ * (bootstrap.py) over `dreamlake exec`. The program and its JSON payload travel
7
+ * on stdin, so the remote command stays a short fixed loader.
8
+ */
9
+ export declare const BOOTSTRAP_LOADER: string;
10
+ export declare function bootstrapInput(payload: Record<string, unknown>): Buffer;
11
+ /** The bootstrap prints exactly one JSON object; tolerate shell noise before it. */
12
+ export declare function parseBootstrapOutput(text: string): Record<string, any> | undefined;
13
+ export interface ExecTarget {
14
+ selector: string;
15
+ namespace?: string;
16
+ enrollment?: string;
17
+ }
18
+ export interface ExecReply {
19
+ exitCode: number;
20
+ result?: Record<string, any>;
21
+ }
22
+ export type HostExec = (target: ExecTarget, payload: Record<string, unknown>, timeoutSeconds: number) => Promise<ExecReply>;
23
+ /** Runs one bootstrap action through the nymph SSH relay (the `dreamlake exec` path). */
24
+ export declare const execOverNymph: HostExec;
25
+ export type FleetAction = "upgrade" | "rollback";
26
+ export interface FleetOptions {
27
+ action: FleetAction;
28
+ nymphVersion?: string;
29
+ upgradeId?: string;
30
+ namespace?: string;
31
+ enrollment?: string;
32
+ all?: boolean;
33
+ dryRun?: boolean;
34
+ concurrency?: string | number;
35
+ maxFailures?: string | number;
36
+ restartDelay?: string | number;
37
+ stableSeconds?: string | number;
38
+ verifyTimeout?: string | number;
39
+ record?: string;
40
+ json?: boolean;
41
+ }
42
+ export interface FleetPlan {
43
+ action: FleetAction;
44
+ version?: string;
45
+ upgradeId?: string;
46
+ dryRun: boolean;
47
+ namespace?: string;
48
+ enrollment?: string;
49
+ concurrency: number;
50
+ maxFailures: number;
51
+ restartDelay: number;
52
+ stableSeconds: number;
53
+ verifyTimeout: number;
54
+ }
55
+ export interface FleetHost {
56
+ id: string;
57
+ name: string;
58
+ namespace: string;
59
+ online: boolean;
60
+ }
61
+ export type HostOutcomeStatus = "upgraded" | "rolled_back" | "current" | "planned" | "failed" | "skipped" | "not_started";
62
+ export interface HostOutcome {
63
+ host: string;
64
+ hostId: string;
65
+ status: HostOutcomeStatus;
66
+ upgradeId?: string;
67
+ version?: string | null;
68
+ previousVersion?: string | null;
69
+ pid?: {
70
+ before?: number | null;
71
+ after?: number | null;
72
+ };
73
+ restarts?: number;
74
+ restart?: Record<string, unknown>;
75
+ leftoverJobsRemoved?: string[];
76
+ failures?: string[];
77
+ code?: string;
78
+ error?: string;
79
+ plan?: Record<string, unknown>;
80
+ startedAt?: string;
81
+ finishedAt?: string;
82
+ earlierRestart?: {
83
+ upgradeId: string;
84
+ status: "verified";
85
+ };
86
+ }
87
+ export interface FleetDeps {
88
+ exec: HostExec;
89
+ sleep: (ms: number) => Promise<void>;
90
+ now: () => number;
91
+ record: (entry: Record<string, unknown>) => void;
92
+ }
93
+ export declare function resolveFleetPlan(opts: FleetOptions): FleetPlan;
94
+ export interface ResolveDeps {
95
+ status: typeof hostStatus;
96
+ list: typeof listHosts;
97
+ namespace: typeof resolveHostNamespace;
98
+ }
99
+ /** Expands selectors into distinct hosts, in order. A host appears at most once. */
100
+ export declare function resolveFleetHosts(selectors: string[], opts: {
101
+ all?: boolean;
102
+ namespace?: string;
103
+ }, deps?: ResolveDeps): Promise<FleetHost[]>;
104
+ /** One host: apply, wait out the delayed restart, then verify it happened exactly once. */
105
+ export declare function processFleetHost(host: FleetHost, plan: FleetPlan, deps: FleetDeps): Promise<HostOutcome>;
106
+ export interface FleetReport {
107
+ action: FleetAction;
108
+ version?: string;
109
+ dryRun: boolean;
110
+ stoppedEarly: boolean;
111
+ counts: Partial<Record<HostOutcomeStatus, number>>;
112
+ hosts: HostOutcome[];
113
+ record?: string;
114
+ }
115
+ /** Bounded concurrency; stops starting hosts after maxFailures; one worker per host at a time. */
116
+ export declare function runFleet(hosts: FleetHost[], plan: FleetPlan, deps: FleetDeps): Promise<FleetReport>;
117
+ export declare function fleetSucceeded(report: FleetReport): boolean;
118
+ export declare function formatFleetReport(report: FleetReport): string;
119
+ export declare function runHostsUpgrade(selectors: string[], opts: FleetOptions, overrides?: Partial<FleetDeps> & {
120
+ resolve?: ResolveDeps;
121
+ }): Promise<number>;
122
+ export declare function registerHostUpgradeCommands(group: Command): void;