my-durable 0.0.40 → 0.0.42

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.
Files changed (26) hide show
  1. package/apps/dpi-backend/src/backup-cli.ts +220 -0
  2. package/apps/dpi-backend/src/backup.ts +523 -0
  3. package/apps/dpi-backend/src/doctor.ts +19 -1
  4. package/apps/dpi-backend/src/env-vars.ts +234 -0
  5. package/apps/dpi-backend/src/main.ts +1 -0
  6. package/apps/dpi-backend/src/notify-cli.ts +211 -0
  7. package/apps/dpi-backend/src/notify-sinks.ts +947 -0
  8. package/apps/dpi-backend/src/projects.ts +18 -1
  9. package/apps/dpi-backend/src/routes.ts +29 -1
  10. package/apps/dpi-backend/src/store.ts +170 -9
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DaurAPEn.css +1 -0
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-o6Rn26ft.js +81 -0
  13. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/EnvPanel.vue +268 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +8 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +37 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NotifyPanel.vue +292 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +41 -1
  19. package/apps/dpi-sdk/src/api.ts +79 -1
  20. package/apps/dpi-sdk/src/client.ts +32 -0
  21. package/apps/dpi-sdk/src/protocol/rest-routes.ts +9 -0
  22. package/bin/dpi.mjs +15 -0
  23. package/docs/host-project-checklist.md +6 -6
  24. package/package.json +1 -1
  25. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMJMesxP.css +0 -1
  26. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jDhVa5sg.js +0 -81
@@ -0,0 +1,523 @@
1
+ /**
2
+ * Device-side backup/restore of the device home — "Backup/restore of session
3
+ * data" (SHOULD), Wave 2 of docs/host-project-checklist.md.
4
+ *
5
+ * Modelled on orca's `rolling-file-backup.ts` (a copy ahead of every risky
6
+ * change) and piggery's CLI ops discipline (every destructive op asks once):
7
+ *
8
+ * - `createBackup` writes exactly one new file and deletes nothing;
9
+ * - `restoreBackup` deletes nothing either — an existing home is renamed to
10
+ * `<home>.bak-<timestamp>` and kept, so the one rollback a restore has is
11
+ * also the only copy it needs;
12
+ * - restore refuses to run while the device daemon answers on its port: a
13
+ * copy taken under a live sqlite handle is not a backup, it is a lie.
14
+ *
15
+ * The zip is built in memory, so the walk is capped (256 MiB by default,
16
+ * `maxBytes`). The writer here emits the same three records as `zip.ts` (local
17
+ * header / central directory / EOCD) but takes bytes, not text — a device home
18
+ * holds `backend/catalog.sqlite`, and `zip.ts`'s `ZipEntry.text` would
19
+ * re-encode it as UTF-8. `crc32` is imported from `zip.ts` so the checksum can
20
+ * never drift between the two writers. `readZipEntries` reads those archives
21
+ * back (methods 0 and 8 only) and refuses anything it does not recognise: this
22
+ * reader exists for OUR backups, not for arbitrary archives.
23
+ *
24
+ * Every fs/clock/network access goes through `BackupIo` (the `gc.ts` /
25
+ * `doctor.ts` pattern), so tests pin the clock and fake the daemon probe
26
+ * instead of trusting a port to happen to be closed. Symlinks are followed by
27
+ * `stat` (a symlinked sessions dir is still the device's data); a walk deeper
28
+ * than 64 levels is refused rather than looped through; empty directories are
29
+ * not preserved (the zip stores files only).
30
+ */
31
+ import { chmod, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
32
+ import { deflateRawSync, inflateRawSync } from "node:zlib";
33
+ import { dirname, join, relative, resolve, sep } from "node:path";
34
+ import { crc32 } from "./zip.js";
35
+ import { humanBytes } from "./gc.js";
36
+ import { PACKAGE_VERSION } from "./store.js";
37
+
38
+ export type BackupErrorCode = "invalid" | "device_running" | "not_found";
39
+
40
+ /** Typed failure, same shape as `ProjectRegistryError`: a CLI picks its exit code from `code`, not from message matching. */
41
+ export class BackupError extends Error {
42
+ readonly code: BackupErrorCode;
43
+
44
+ constructor(code: BackupErrorCode, message: string) {
45
+ super(message);
46
+ this.name = "BackupError";
47
+ this.code = code;
48
+ }
49
+ }
50
+
51
+ const invalid = (message: string) => new BackupError("invalid", message);
52
+ const describeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
53
+
54
+ /** The in-memory zip build is capped so `createBackup` cannot balloon the device's RAM. */
55
+ export const MAX_BACKUP_BYTES = 256 * 1024 * 1024;
56
+ /** `ensurePrivateDir` (dpi-sdk) is synchronous and not injectable; the io carries the same 0700/0600 rule instead. */
57
+ const DIR_MODE = 0o700;
58
+ const FILE_MODE = 0o600;
59
+ /** A deeper tree is a symlink loop, not a device home. */
60
+ const MAX_WALK_DEPTH = 64;
61
+
62
+ export interface BackupStat {
63
+ isFile(): boolean;
64
+ isDirectory(): boolean;
65
+ size: number;
66
+ mode: number;
67
+ mtimeMs: number;
68
+ }
69
+
70
+ export interface BackupIo {
71
+ readFile(path: string): Promise<Uint8Array>;
72
+ /** `mode` applies when the file is created; an explicit `chmod` follows, like projects.ts's persist. */
73
+ writeFile(path: string, data: Uint8Array, mode?: number): Promise<void>;
74
+ rename(from: string, to: string): Promise<void>;
75
+ /** Recursive; `mode` (0700 by default) applies to the directories it creates. */
76
+ mkdir(path: string, mode?: number): Promise<void>;
77
+ stat(path: string): Promise<BackupStat>;
78
+ /** Names only — `stat` decides what each one is (withFileTypes is not injectable-friendly). */
79
+ readdir(path: string): Promise<string[]>;
80
+ chmod(path: string, mode: number): Promise<void>;
81
+ exists(path: string): Promise<boolean>;
82
+ /** Daemon probe for restore. A fetch that THROWS is a refused connection, i.e. "not running". */
83
+ fetch?(url: string, init?: { signal?: AbortSignal }): Promise<{ ok: boolean; status: number }>;
84
+ now(): number;
85
+ }
86
+
87
+ export const defaultBackupIo = (): BackupIo => ({
88
+ readFile: (path) => readFile(path),
89
+ writeFile: (path, data, mode) => writeFile(path, data, { mode }),
90
+ rename: (from, to) => rename(from, to),
91
+ // fs/promises mkdir(recursive) resolves with the first created path — dropped, the io promises void.
92
+ mkdir: async (path, mode) => {
93
+ await mkdir(path, { recursive: true, mode: mode ?? DIR_MODE });
94
+ },
95
+ stat: (path) => stat(path),
96
+ readdir: (path) => readdir(path),
97
+ chmod: (path, mode) => chmod(path, mode),
98
+ exists: async (path) => {
99
+ try {
100
+ await stat(path);
101
+ return true;
102
+ } catch {
103
+ return false;
104
+ }
105
+ },
106
+ fetch: async (url, init) => {
107
+ const res = await fetch(url, init as RequestInit | undefined);
108
+ return { ok: res.ok, status: res.status };
109
+ },
110
+ now: () => Date.now(),
111
+ });
112
+
113
+ // ---------------------------------------------------------------- create
114
+
115
+ /** Entry 0 of every backup zip: what was backed up, by which build. */
116
+ export interface BackupManifest {
117
+ createdAt: string;
118
+ packageVersion: string;
119
+ deviceName?: string;
120
+ files: number;
121
+ bytes: number;
122
+ }
123
+
124
+ export interface CreateBackupOptions {
125
+ home: string;
126
+ out: string;
127
+ deviceName?: string;
128
+ /** Total-bytes guard for the in-memory zip build. Defaults to `MAX_BACKUP_BYTES` (256 MiB). */
129
+ maxBytes?: number;
130
+ }
131
+
132
+ export interface CreateBackupResult {
133
+ path: string;
134
+ files: number;
135
+ bytes: number;
136
+ }
137
+
138
+ interface WalkedFile {
139
+ /** Path relative to home, posix separators — the zip entry name. */
140
+ rel: string;
141
+ abs: string;
142
+ size: number;
143
+ }
144
+
145
+ /**
146
+ * Collect every regular file under `home`, sorted for a deterministic zip:
147
+ * registries, backend/catalog.sqlite, sessions, logs — everything. Skipped:
148
+ * `.lock` files (live handles, not data), non-regular entries (sockets, FIFOs,
149
+ * devices), any `node_modules` segment, and the output file itself (a backup
150
+ * must never swallow a previous backup of itself).
151
+ */
152
+ async function walkHome(io: BackupIo, home: string, out: string, maxBytes: number): Promise<WalkedFile[]> {
153
+ const outAbs = resolve(out);
154
+ const files: WalkedFile[] = [];
155
+ let bytes = 0;
156
+ const visit = async (dir: string, depth: number): Promise<void> => {
157
+ if (depth > MAX_WALK_DEPTH) throw invalid(`${dir} nests deeper than ${MAX_WALK_DEPTH} levels — refusing to walk it`);
158
+ for (const name of (await io.readdir(dir)).sort()) {
159
+ if (name === "node_modules") continue;
160
+ const abs = join(dir, name);
161
+ let entry: BackupStat;
162
+ try {
163
+ entry = await io.stat(abs);
164
+ } catch {
165
+ continue; // broken symlink / vanished entry: not backup-able, not fatal
166
+ }
167
+ if (entry.isDirectory()) {
168
+ await visit(abs, depth + 1);
169
+ continue;
170
+ }
171
+ if (!entry.isFile()) continue; // sockets, FIFOs, devices
172
+ if (name.endsWith(".lock")) continue;
173
+ if (resolve(abs) === outAbs) continue;
174
+ bytes += entry.size;
175
+ if (bytes > maxBytes) {
176
+ throw invalid(
177
+ `${home} is ${bytes} bytes (${humanBytes(bytes)}) after ${files.length + 1} file(s); ` +
178
+ `the in-memory zip build is capped at ${maxBytes} bytes (${humanBytes(maxBytes)})`,
179
+ );
180
+ }
181
+ files.push({ rel: relative(home, abs).split(sep).join("/"), abs, size: entry.size });
182
+ }
183
+ };
184
+ await visit(home, 0);
185
+ return files;
186
+ }
187
+
188
+ /**
189
+ * Zip the whole device home into `opts.out` (0600, parent dirs 0700) and touch
190
+ * nothing else. The timestamped default name is the CLI's decision, not this
191
+ * module's.
192
+ */
193
+ export async function createBackup(io: BackupIo, opts: CreateBackupOptions): Promise<CreateBackupResult> {
194
+ const home = resolve(opts.home);
195
+ const out = resolve(opts.out);
196
+ let homeStat: BackupStat;
197
+ try {
198
+ homeStat = await io.stat(home);
199
+ } catch (error) {
200
+ throw new BackupError("not_found", `home directory not found: ${home} (${describeError(error)})`);
201
+ }
202
+ if (!homeStat.isDirectory()) throw invalid(`home is not a directory: ${home}`);
203
+
204
+ const files = await walkHome(io, home, out, opts.maxBytes ?? MAX_BACKUP_BYTES);
205
+ const bytes = files.reduce((n, f) => n + f.size, 0);
206
+ const manifest: BackupManifest = {
207
+ createdAt: new Date(io.now()).toISOString(),
208
+ packageVersion: PACKAGE_VERSION,
209
+ files: files.length,
210
+ bytes,
211
+ };
212
+ if (opts.deviceName) manifest.deviceName = opts.deviceName;
213
+
214
+ // Entry 0 is the manifest, so restore can always recognise it by position —
215
+ // and a home file that happens to be called manifest.json still round-trips.
216
+ const entries: Array<{ name: string; data: Uint8Array }> = [
217
+ { name: "manifest.json", data: Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, "utf8") },
218
+ ];
219
+ for (const file of files) entries.push({ name: file.rel, data: await io.readFile(file.abs) });
220
+
221
+ const zip = zipBytes(entries, new Date(io.now()));
222
+ await io.mkdir(dirname(out), DIR_MODE);
223
+ await io.writeFile(out, zip, FILE_MODE);
224
+ await io.chmod(out, FILE_MODE);
225
+ return { path: out, files: files.length, bytes };
226
+ }
227
+
228
+ // ---------------------------------------------------------------- zip build
229
+ // The records are the ones zip.ts writes; only the payload differs (bytes, not
230
+ // UTF-8 text). Keep the two byte layouts in sync if zip.ts ever changes.
231
+
232
+ const LOCAL_SIG = 0x04034b50;
233
+ const CENTRAL_SIG = 0x02014b50;
234
+ const EOCD_SIG = 0x06054b50;
235
+ /** Bit 11: file names are UTF-8. */
236
+ const FLAG_UTF8 = 0x0800;
237
+ const VERSION = 20;
238
+
239
+ /** MS-DOS time/date: 2-second resolution, 1980 epoch (zip.ts's rule, verbatim). */
240
+ function dosStamp(date: Date): { time: number; date: number } {
241
+ const year = Math.max(1980, date.getFullYear());
242
+ return {
243
+ time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),
244
+ date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
245
+ };
246
+ }
247
+
248
+ /** Deflate when it helps, store when it does not — the same choice zip.ts makes. */
249
+ function zipBytes(entries: readonly { name: string; data: Uint8Array }[], at: Date): Buffer {
250
+ const stamp = dosStamp(at);
251
+ const locals: Buffer[] = [];
252
+ const centrals: Buffer[] = [];
253
+ let offset = 0;
254
+
255
+ for (const entry of entries) {
256
+ const name = Buffer.from(entry.name, "utf8");
257
+ const raw = Buffer.isBuffer(entry.data)
258
+ ? entry.data
259
+ : Buffer.from(entry.data.buffer, entry.data.byteOffset, entry.data.byteLength);
260
+ const deflated = deflateRawSync(raw);
261
+ const useDeflate = deflated.length < raw.length;
262
+ const body = useDeflate ? deflated : raw;
263
+ const crc = crc32(raw);
264
+
265
+ const local = Buffer.alloc(30);
266
+ local.writeUInt32LE(LOCAL_SIG, 0);
267
+ local.writeUInt16LE(VERSION, 4);
268
+ local.writeUInt16LE(FLAG_UTF8, 6);
269
+ local.writeUInt16LE(useDeflate ? 8 : 0, 8);
270
+ local.writeUInt16LE(stamp.time, 10);
271
+ local.writeUInt16LE(stamp.date, 12);
272
+ local.writeUInt32LE(crc, 14);
273
+ local.writeUInt32LE(body.length, 18);
274
+ local.writeUInt32LE(raw.length, 22);
275
+ local.writeUInt16LE(name.length, 26);
276
+ local.writeUInt16LE(0, 28);
277
+
278
+ const central = Buffer.alloc(46);
279
+ central.writeUInt32LE(CENTRAL_SIG, 0);
280
+ central.writeUInt16LE(VERSION, 4);
281
+ central.writeUInt16LE(VERSION, 6);
282
+ central.writeUInt16LE(FLAG_UTF8, 8);
283
+ central.writeUInt16LE(useDeflate ? 8 : 0, 10);
284
+ central.writeUInt16LE(stamp.time, 12);
285
+ central.writeUInt16LE(stamp.date, 14);
286
+ central.writeUInt32LE(crc, 16);
287
+ central.writeUInt32LE(body.length, 20);
288
+ central.writeUInt32LE(raw.length, 24);
289
+ central.writeUInt16LE(name.length, 28);
290
+ central.writeUInt16LE(0, 30); // extra
291
+ central.writeUInt16LE(0, 32); // comment
292
+ central.writeUInt16LE(0, 34); // disk start
293
+ central.writeUInt16LE(0, 36); // internal attrs
294
+ central.writeUInt32LE(FILE_MODE << 16, 38); // external attrs: rw-------
295
+ central.writeUInt32LE(offset, 42);
296
+
297
+ locals.push(local, name, body);
298
+ centrals.push(central, name);
299
+ offset += local.length + name.length + body.length;
300
+ }
301
+
302
+ const centralBuf = Buffer.concat(centrals);
303
+ const eocd = Buffer.alloc(22);
304
+ eocd.writeUInt32LE(EOCD_SIG, 0);
305
+ eocd.writeUInt16LE(0, 4); // this disk
306
+ eocd.writeUInt16LE(0, 6); // disk with central directory
307
+ eocd.writeUInt16LE(entries.length, 8);
308
+ eocd.writeUInt16LE(entries.length, 10);
309
+ eocd.writeUInt32LE(centralBuf.length, 12);
310
+ eocd.writeUInt32LE(offset, 16);
311
+ eocd.writeUInt16LE(0, 20); // comment length
312
+ return Buffer.concat([...locals, centralBuf, eocd]);
313
+ }
314
+
315
+ // ----------------------------------------------------------------- zip read
316
+
317
+ export interface ZipArchiveEntry {
318
+ name: string;
319
+ data: Uint8Array;
320
+ }
321
+
322
+ /** A name our own writer could have produced: relative, posix, no `..`, no NUL, no backslash. */
323
+ function validateEntryName(name: string): void {
324
+ if (!name) throw invalid("zip entry has an empty name");
325
+ if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name)) {
326
+ throw invalid(`zip entry name is absolute: ${name}`);
327
+ }
328
+ if (name.includes("\\") || name.includes("\0")) {
329
+ throw invalid(`zip entry name is not a posix path: ${JSON.stringify(name)}`);
330
+ }
331
+ for (const segment of name.split("/")) {
332
+ if (segment === "..") throw invalid(`zip entry name escapes the archive: ${name}`);
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Read back a zip this module (or `zip.ts`) wrote: EOCD → central directory →
338
+ * local headers, methods 0 and 8 only, sizes and crc32 verified. This is not a
339
+ * general-purpose unzip: anything unexpected is a `BackupError("invalid")`
340
+ * rather than a best-effort guess.
341
+ */
342
+ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
343
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
344
+ const bad = (why: string): BackupError => invalid(`not a readable backup zip: ${why}`);
345
+
346
+ // The EOCD sits in the last 22 bytes plus (at most) a 64 KiB comment.
347
+ let eocd = -1;
348
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i -= 1) {
349
+ if (buf.readUInt32LE(i) === EOCD_SIG) {
350
+ eocd = i;
351
+ break;
352
+ }
353
+ }
354
+ if (eocd < 0) throw bad("no end-of-central-directory record");
355
+
356
+ const count = buf.readUInt16LE(eocd + 8);
357
+ const centralSize = buf.readUInt32LE(eocd + 12);
358
+ const centralOffset = buf.readUInt32LE(eocd + 16);
359
+ if (centralOffset + centralSize !== eocd) {
360
+ throw bad(`central directory (offset ${centralOffset}, size ${centralSize}) does not end at the EOCD (${eocd})`);
361
+ }
362
+
363
+ const entries: ZipArchiveEntry[] = [];
364
+ let p = centralOffset;
365
+ for (let i = 0; i < count; i += 1) {
366
+ if (p + 46 > eocd) throw bad(`central directory entry ${i} overruns the archive`);
367
+ if (buf.readUInt32LE(p) !== CENTRAL_SIG) throw bad(`central directory entry ${i} is corrupt`);
368
+ const method = buf.readUInt16LE(p + 10);
369
+ const crc = buf.readUInt32LE(p + 16);
370
+ const compressedSize = buf.readUInt32LE(p + 20);
371
+ const uncompressedSize = buf.readUInt32LE(p + 24);
372
+ const nameLength = buf.readUInt16LE(p + 28);
373
+ const extraLength = buf.readUInt16LE(p + 30);
374
+ const commentLength = buf.readUInt16LE(p + 32);
375
+ const localOffset = buf.readUInt32LE(p + 42);
376
+ if (p + 46 + nameLength + extraLength + commentLength > eocd) {
377
+ throw bad(`central directory entry ${i} overruns the archive`);
378
+ }
379
+ const name = buf.toString("utf8", p + 46, p + 46 + nameLength);
380
+ validateEntryName(name);
381
+
382
+ if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== LOCAL_SIG) {
383
+ throw bad(`local header for ${name} is corrupt`);
384
+ }
385
+ const localNameLength = buf.readUInt16LE(localOffset + 26);
386
+ const localExtraLength = buf.readUInt16LE(localOffset + 28);
387
+ const start = localOffset + 30 + localNameLength + localExtraLength;
388
+ if (start + compressedSize > buf.length) throw bad(`data for ${name} overruns the archive`);
389
+
390
+ let out: Buffer;
391
+ if (method === 0) out = buf.subarray(start, start + compressedSize);
392
+ else if (method === 8) {
393
+ try {
394
+ out = inflateRawSync(buf.subarray(start, start + compressedSize));
395
+ } catch (error) {
396
+ throw bad(`cannot inflate ${name} (${describeError(error)})`);
397
+ }
398
+ } else throw bad(`unsupported compression method ${method} for ${name}`);
399
+
400
+ if (out.length !== uncompressedSize) {
401
+ throw bad(`${name} decompressed to ${out.length} bytes, expected ${uncompressedSize}`);
402
+ }
403
+ if (crc32(out) !== crc) throw bad(`checksum mismatch for ${name}`);
404
+
405
+ entries.push({ name, data: out });
406
+ p += 46 + nameLength + extraLength + commentLength;
407
+ }
408
+ if (p - centralOffset !== centralSize) throw bad("central directory size does not match its entries");
409
+ return entries;
410
+ }
411
+
412
+ /** Read + parse a backup file; restore and the CLI's plan share the `not_found` mapping. */
413
+ export async function readBackupEntries(io: BackupIo, zipPath: string): Promise<ZipArchiveEntry[]> {
414
+ let data: Uint8Array;
415
+ try {
416
+ data = await io.readFile(resolve(zipPath));
417
+ } catch (error) {
418
+ throw new BackupError("not_found", `cannot read backup ${zipPath}: ${describeError(error)}`);
419
+ }
420
+ return readZipEntries(data);
421
+ }
422
+
423
+ // ---------------------------------------------------------------- restore
424
+
425
+ export interface RestoreBackupOptions {
426
+ zipPath: string;
427
+ home: string;
428
+ /** When set, restore first refuses if the daemon answers here (healthz needs no auth). */
429
+ healthzUrl?: string;
430
+ }
431
+
432
+ export interface RestoreBackupResult {
433
+ restored: number;
434
+ /** Where the previous home went; absent when there was nothing to move. */
435
+ backupOfOldHome?: string;
436
+ }
437
+
438
+ /**
439
+ * Is the device daemon answering? Any HTTP answer (even 404/500) means yes; a
440
+ * fetch that throws is a refused connection, i.e. no. A missing `io.fetch`
441
+ * cannot probe and reports "not running" — the caller decides whether to trust
442
+ * that.
443
+ */
444
+ export async function deviceIsRunning(io: BackupIo, healthzUrl: string): Promise<boolean> {
445
+ if (!io.fetch) return false;
446
+ try {
447
+ await io.fetch(healthzUrl, { signal: AbortSignal.timeout(2_000) });
448
+ return true;
449
+ } catch {
450
+ return false;
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Unpack a backup into `home`. Nothing is deleted: an existing home is renamed
456
+ * to `<home>.bak-<timestamp>` first (colons and dots flattened to dashes — a
457
+ * Windows filename cannot hold them), then `-2`, `-3`, … if that name is taken.
458
+ * The manifest is the backup's own metadata, so entry 0 named manifest.json is
459
+ * not extracted — a home file of the same name still round-trips, because the
460
+ * manifest always comes first.
461
+ */
462
+ export async function restoreBackup(io: BackupIo, opts: RestoreBackupOptions): Promise<RestoreBackupResult> {
463
+ const home = resolve(opts.home);
464
+ if (opts.healthzUrl && (await deviceIsRunning(io, opts.healthzUrl))) {
465
+ throw new BackupError("device_running", "the device is running — stop it first (`dpi device stop`)");
466
+ }
467
+ const entries = await readBackupEntries(io, opts.zipPath);
468
+
469
+ let backupOfOldHome: string | undefined;
470
+ if (await io.exists(home)) backupOfOldHome = await renameAside(io, home);
471
+
472
+ await io.mkdir(home, DIR_MODE);
473
+ let restored = 0;
474
+ for (let i = 0; i < entries.length; i += 1) {
475
+ const entry = entries[i];
476
+ if (i === 0 && entry.name === "manifest.json") continue;
477
+ if (entry.name.endsWith("/")) {
478
+ await io.mkdir(join(home, entry.name), DIR_MODE); // a directory entry from a foreign zip
479
+ continue;
480
+ }
481
+ const target = join(home, entry.name);
482
+ await io.mkdir(dirname(target), DIR_MODE);
483
+ await io.writeFile(target, entry.data, FILE_MODE);
484
+ await io.chmod(target, FILE_MODE);
485
+ restored += 1;
486
+ }
487
+ return { restored, backupOfOldHome };
488
+ }
489
+
490
+ /** `<home>.bak-<ISO-ish stamp>`, `-2`/`-3` when taken. Never deletes the old home. */
491
+ async function renameAside(io: BackupIo, home: string): Promise<string> {
492
+ const stamp = new Date(io.now()).toISOString().replace(/[:.]/g, "-");
493
+ const base = `${home}.bak-${stamp}`;
494
+ let target = base;
495
+ for (let n = 2; await io.exists(target); n += 1) target = `${base}-${n}`;
496
+ await io.rename(home, target);
497
+ return target;
498
+ }
499
+
500
+ // ------------------------------------------------------------------ list
501
+
502
+ export interface BackupListing {
503
+ name: string;
504
+ bytes: number;
505
+ mtimeMs: number;
506
+ }
507
+
508
+ /** The `dpi-backup-*.zip` files in `dir`, newest first. A missing dir is an empty list, not an error. */
509
+ export async function listBackups(io: BackupIo, dir: string): Promise<BackupListing[]> {
510
+ if (!(await io.exists(dir))) return [];
511
+ const listings: BackupListing[] = [];
512
+ for (const name of await io.readdir(dir)) {
513
+ if (!/^dpi-backup-.*\.zip$/.test(name)) continue;
514
+ try {
515
+ const entry = await io.stat(join(dir, name));
516
+ if (!entry.isFile()) continue;
517
+ listings.push({ name, bytes: entry.size, mtimeMs: entry.mtimeMs });
518
+ } catch {
519
+ /* vanished between readdir and stat: not a backup we can vouch for */
520
+ }
521
+ }
522
+ return listings.sort((a, b) => b.mtimeMs - a.mtimeMs);
523
+ }
@@ -292,7 +292,25 @@ async function probeCheck(io: DoctorIo, cfg: DeviceEndpoint, reachable: boolean)
292
292
  if (!res.ok) return { id, label, status: "warn", detail: `probe-model → ${res.status}` };
293
293
  const detail = typeof body.detail === "string" && body.detail ? body.detail : body.ok === true ? "answered" : "no answer";
294
294
  // A dead provider is a WARN by design: the FE rotates past it, the device is fine.
295
- return { id, label, status: body.ok === true ? "ok" : "warn", detail: detail.slice(0, 160) };
295
+ if (body.ok === true) return { id, label, status: "ok", detail: detail.slice(0, 160) };
296
+ // Say what the failure means when the device classified it: "wait 30s" is a
297
+ // different instruction from "fix the key" or "pick another model".
298
+ const status = typeof body.status === "string" ? body.status : "error";
299
+ const retryMs = typeof body.retryAfterMs === "number" ? body.retryAfterMs : undefined;
300
+ const meaning =
301
+ status === "rate_limited"
302
+ ? `rate limited${retryMs ? ` — retry in ${Math.max(1, Math.round(retryMs / 1000))}s` : " — retry later"}`
303
+ : status === "auth"
304
+ ? "provider key rejected — fix the credential"
305
+ : status === "missing"
306
+ ? "model not in the provider's catalog"
307
+ : "";
308
+ return {
309
+ id,
310
+ label,
311
+ status: "warn",
312
+ detail: `${detail.slice(0, 110)}${meaning ? ` (${meaning})` : ""}`.slice(0, 200),
313
+ };
296
314
  }
297
315
 
298
316
  /** 5. hub — only when this device actually has one. */