my-durable 0.0.41 → 0.0.43

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/awake.ts +136 -0
  2. package/apps/dpi-backend/src/backup-cli.ts +220 -0
  3. package/apps/dpi-backend/src/backup.ts +523 -0
  4. package/apps/dpi-backend/src/diagnostics-cli.ts +134 -0
  5. package/apps/dpi-backend/src/diagnostics.ts +326 -0
  6. package/apps/dpi-backend/src/env-vars.ts +234 -0
  7. package/apps/dpi-backend/src/main.ts +1 -0
  8. package/apps/dpi-backend/src/projects.ts +33 -1
  9. package/apps/dpi-backend/src/routes.ts +21 -1
  10. package/apps/dpi-backend/src/store.ts +85 -3
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BgKiQEMm.js +81 -0
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-EulngMVY.css +1 -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/HostPanel.vue +11 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +4 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +37 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +41 -1
  19. package/apps/dpi-sdk/src/api.ts +29 -2
  20. package/apps/dpi-sdk/src/client.ts +12 -0
  21. package/apps/dpi-sdk/src/protocol/rest-routes.ts +3 -0
  22. package/bin/dpi.mjs +16 -0
  23. package/docs/host-project-checklist.md +8 -8
  24. package/package.json +1 -1
  25. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D6ClJqd8.css +0 -1
  26. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMb-n4O-.js +0 -81
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Keep-awake (Wave 3 SHOULD of docs/host-project-checklist.md): while any
3
+ * session on this device is busy, hold the OS awake so runs finish instead of
4
+ * pausing mid-turn. Modelled on orca's `agent-awake-service.ts:53-97`
5
+ * (powerSaveBlocker + per-OS assertions), minus Electron.
6
+ *
7
+ * What each platform actually gets — verified live, not assumed:
8
+ * - Linux + systemd: `systemd-inhibit --what=idle --mode=block` — an
9
+ * unprivileged user MAY hold an idle block, but sleep:block answers
10
+ * "Access denied" (root/polkit). So this keeps idle-suspend away while
11
+ * agents run; a lid close or an explicit `systemctl suspend` still sleeps,
12
+ * and that is deliberate — the operator always outranks the agent.
13
+ * - macOS: `caffeinate -i -s` held until the inhibitor is killed.
14
+ * - anything else: no-op (`mode: "none"`), reported through deviceInfo.
15
+ *
16
+ * Failure discipline: a spawn that errors or a child that dies does not throw
17
+ * into a turn — after two failed attempts the inhibitor disables itself for
18
+ * the rest of the process, because a keep-awake helper must never become a
19
+ * crash source (the sessions are durable either way).
20
+ */
21
+ import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";
22
+
23
+ /** What this build can do on this machine. */
24
+ export type AwakeMode = "inhibit" | "caffeinate" | "none";
25
+
26
+ export interface AwakeChild {
27
+ kill(): void;
28
+ }
29
+
30
+ export interface AwakeIo {
31
+ platform(): NodeJS.Platform;
32
+ /** Spawn a long-running holder process; `undefined` = the spawn itself failed. */
33
+ spawn(cmd: string, args: readonly string[]): AwakeChild | undefined;
34
+ }
35
+
36
+ export const defaultAwakeIo = (): AwakeIo => ({
37
+ platform: () => process.platform,
38
+ spawn: (cmd, args) => {
39
+ // ESM-safe: a static import, not `require` (caught live: `require` in an
40
+ // ESM module context throws ReferenceError outside any try/catch).
41
+ try {
42
+ const child: ChildProcess = nodeSpawn(cmd, args as string[], {
43
+ stdio: "ignore",
44
+ detached: false,
45
+ });
46
+ child.unref();
47
+ return { kill: () => void child.kill("SIGTERM") };
48
+ } catch {
49
+ return undefined;
50
+ }
51
+ },
52
+ });
53
+
54
+ /** Give up after this many failed spawns — a helper must never spin. */
55
+ const MAX_FAILURES = 2;
56
+
57
+ export class KeepAwake {
58
+ private readonly io: AwakeIo;
59
+ private child?: AwakeChild;
60
+ private failures = 0;
61
+ private disabled = false;
62
+ private lastBusy = -1;
63
+
64
+ constructor(io: AwakeIo = defaultAwakeIo()) {
65
+ this.io = io;
66
+ }
67
+
68
+ /** The platform mode, computed without spawning anything. */
69
+ get mode(): AwakeMode {
70
+ const platform = this.io.platform();
71
+ if (platform === "linux") return "inhibit";
72
+ if (platform === "darwin") return "caffeinate";
73
+ return "none";
74
+ }
75
+
76
+ /** True while an inhibitor process is being held. */
77
+ get held(): boolean {
78
+ return this.child !== undefined;
79
+ }
80
+
81
+ /**
82
+ * Idempotent: `sync(n)` with the count of busy sessions. Spawn on 0→n,
83
+ * kill on n→0, nothing in between — the WHY text names the current count
84
+ * only at spawn time, which is fine: it is a hint, not a metric.
85
+ */
86
+ sync(busy: number): void {
87
+ if (this.disabled || this.mode === "none") return;
88
+ const shouldHold = busy > 0;
89
+ if (shouldHold === (this.child !== undefined)) {
90
+ this.lastBusy = busy;
91
+ return;
92
+ }
93
+ if (!shouldHold) {
94
+ this.stop();
95
+ this.lastBusy = busy;
96
+ return;
97
+ }
98
+ const reason = `${busy} session${busy === 1 ? "" : "s"} busy on a dpi device`;
99
+ const child =
100
+ this.mode === "inhibit"
101
+ ? this.io.spawn("systemd-inhibit", [
102
+ "--what=idle",
103
+ "--mode=block",
104
+ "--who",
105
+ "dpi device",
106
+ "--why",
107
+ reason,
108
+ // systemd-inhibit runs a command under the lock; hold it forever.
109
+ "sleep",
110
+ "infinity",
111
+ ])
112
+ : this.io.spawn("caffeinate", ["-i", "-s"]);
113
+ if (!child) {
114
+ this.fail();
115
+ return;
116
+ }
117
+ this.child = child;
118
+ this.lastBusy = busy;
119
+ }
120
+
121
+ /** Release the inhibitor if held. Never throws. */
122
+ stop(): void {
123
+ if (!this.child) return;
124
+ try {
125
+ this.child.kill();
126
+ } catch {
127
+ /* already dead */
128
+ }
129
+ this.child = undefined;
130
+ }
131
+
132
+ private fail(): void {
133
+ this.failures += 1;
134
+ if (this.failures >= MAX_FAILURES) this.disabled = true;
135
+ }
136
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * `dpi backup` — device-home backup/restore, "Backup/restore of session data"
3
+ * (SHOULD) in Wave 2 of docs/host-project-checklist.md.
4
+ *
5
+ * Piggery's rule, borrowed from `dpi gc`: a destructive op asks once. `restore`
6
+ * prints the plan (file count, target home, where the old home goes) and exits
7
+ * 0 without touching anything unless `--yes` is passed — and it refuses to run
8
+ * at all, plan included, while the device daemon answers on its port (the same
9
+ * DPI_HOST/DPI_PORT rule `dpi doctor` uses; healthz needs no auth).
10
+ *
11
+ * The CLI io extends the module's `BackupIo` with print/printErr/env/homedir,
12
+ * so one object is faked in tests. Exit codes: 0 ok, 1 backup error, 2 usage
13
+ * error; nothing is ever thrown out of `backupCli`. `argv` is what follows the
14
+ * `backup` word (`backupCli({ argv: ["create", "--home", dir] })`).
15
+ */
16
+ import { homedir } from "node:os";
17
+ import { basename, dirname, join, resolve } from "node:path";
18
+ import {
19
+ createBackup,
20
+ defaultBackupIo,
21
+ deviceIsRunning,
22
+ listBackups,
23
+ readBackupEntries,
24
+ restoreBackup,
25
+ type BackupIo,
26
+ } from "./backup.js";
27
+ import { expand, readEnvFile } from "./doctor.js";
28
+ import { humanBytes } from "./gc.js";
29
+
30
+ export interface BackupCliArgs {
31
+ argv: readonly string[];
32
+ }
33
+
34
+ /** The CLI adds output, env and home to the module's io — one object, so a test fakes exactly what it needs. */
35
+ export interface BackupCliIo extends BackupIo {
36
+ print: (line: string) => void;
37
+ printErr: (line: string) => void;
38
+ env: Record<string, string | undefined>;
39
+ homedir: () => string;
40
+ }
41
+
42
+ export const defaultBackupCliIo = (): BackupCliIo => ({
43
+ ...defaultBackupIo(),
44
+ print: (line) => process.stdout.write(`${line}\n`),
45
+ printErr: (line) => process.stderr.write(`${line}\n`),
46
+ env: process.env as Record<string, string | undefined>,
47
+ homedir,
48
+ });
49
+
50
+ const HELP = `dpi backup — device home backup/restore (checklist Wave 2)
51
+
52
+ dpi backup create [--out FILE] [--home DIR]
53
+ dpi backup list [--home DIR] [--dir DIR]
54
+ dpi backup restore FILE [--home DIR] [--yes]
55
+
56
+ create zip the whole device home (registries, backend/catalog.sqlite,
57
+ sessions, logs) into one 0600 file; nothing is deleted and nothing
58
+ leaves the machine
59
+ list the backups in the default dir (or --dir DIR), newest first
60
+ restore unpack a backup into the home dir; the current home is renamed to
61
+ <home>.bak-<timestamp>, never deleted
62
+
63
+ --home DIR device home (default: $DPI_HOME, else ~/.dpi)
64
+ --out FILE where create writes (default: <home>-backups/dpi-backup-<YYYYMMDD-HHMMSS>.zip,
65
+ a sibling of home, so a backup never sits inside what it backs up)
66
+ --dir DIR where list looks (default: the create dir for that home)
67
+ --yes actually restore — without it, restore only prints the plan
68
+
69
+ Restore refuses to run while the device daemon answers on its port (DPI_HOST /
70
+ DPI_PORT, default 127.0.0.1:4780) — stop it first with \`dpi device stop\`.
71
+ Exit codes: 0 ok, 1 backup error, 2 usage error.`;
72
+
73
+ const flagValue = (argv: readonly string[], name: string): string | undefined => {
74
+ const i = argv.indexOf(name);
75
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
76
+ };
77
+
78
+ /** env wins over the env file, like doctor.ts's `deviceEndpoint`. */
79
+ async function envValues(io: BackupCliIo): Promise<(key: string) => string | undefined> {
80
+ const envFile = io.env.DPI_ENV_FILE;
81
+ let fileEnv: Record<string, string> = {};
82
+ if (envFile) {
83
+ try {
84
+ fileEnv = readEnvFile(Buffer.from(await io.readFile(resolve(expand(envFile, io.homedir())))).toString("utf8"));
85
+ } catch {
86
+ /* unreadable env file: fall back to process env, like doctor.ts */
87
+ }
88
+ }
89
+ return (key) => io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
90
+ }
91
+
92
+ /** `--home` wins, then $DPI_HOME (env file included), then ~/.dpi — the gc-cli rule. */
93
+ async function resolveHome(argv: readonly string[], io: BackupCliIo): Promise<string> {
94
+ const value = await envValues(io);
95
+ const home = flagValue(argv, "--home") ?? value("DPI_HOME") ?? join(io.homedir(), ".dpi");
96
+ return resolve(expand(home, io.homedir()));
97
+ }
98
+
99
+ /** The daemon's healthz, built the way doctor.ts builds its endpoint (0.0.0.0 probed over loopback). */
100
+ async function healthzUrl(io: BackupCliIo): Promise<string> {
101
+ const value = await envValues(io);
102
+ const host = value("DPI_HOST") || "127.0.0.1";
103
+ const probeHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
104
+ const port = Number(value("DPI_PORT") || "4780");
105
+ return `http://${probeHost}:${Number.isInteger(port) && port > 0 ? port : 4780}/healthz`;
106
+ }
107
+
108
+ /** A sibling of home: a backup must never sit inside the directory it backs up. */
109
+ export const defaultBackupDir = (home: string): string => join(dirname(home), `${basename(home)}-backups`);
110
+
111
+ /** `YYYYMMDD-HHMMSS` in local time — the name a human matches against `ls`. */
112
+ const stamp = (now: number): string => {
113
+ const d = new Date(now);
114
+ const p = (n: number) => String(n).padStart(2, "0");
115
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
116
+ };
117
+
118
+ export async function backupCli(args: BackupCliArgs, io: BackupCliIo = defaultBackupCliIo()): Promise<number> {
119
+ try {
120
+ return await run(args, io);
121
+ } catch (error) {
122
+ // The CLI contract is an exit code, never a stack trace (gcCli's rule).
123
+ io.printErr(`dpi backup: ${error instanceof Error ? error.message : String(error)}`);
124
+ return 1;
125
+ }
126
+ }
127
+
128
+ async function run(args: BackupCliArgs, io: BackupCliIo): Promise<number> {
129
+ const argv = args.argv;
130
+ if (argv.includes("--help") || argv.includes("-h")) {
131
+ io.print(HELP);
132
+ return 0;
133
+ }
134
+ const [sub = "", ...rest] = argv;
135
+ const flags: Record<string, Set<string>> = {
136
+ create: new Set(["--home", "--out"]),
137
+ list: new Set(["--home", "--dir"]),
138
+ restore: new Set(["--home", "--yes"]),
139
+ };
140
+ if (!flags[sub]) {
141
+ io.printErr(`dpi backup: unknown subcommand '${sub || "(none)"}' — expected create, list or restore\n\n${HELP}`);
142
+ return 2;
143
+ }
144
+ for (const arg of rest) {
145
+ if (arg.startsWith("-") && !flags[sub].has(arg)) {
146
+ io.printErr(`dpi backup ${sub}: unknown flag '${arg}'\n\n${HELP}`);
147
+ return 2;
148
+ }
149
+ }
150
+ if (sub === "create") return await createCmd(rest, io);
151
+ if (sub === "list") return await listCmd(rest, io);
152
+ return await restoreCmd(rest, io);
153
+ }
154
+
155
+ async function createCmd(rest: readonly string[], io: BackupCliIo): Promise<number> {
156
+ const home = await resolveHome(rest, io);
157
+ const outArg = flagValue(rest, "--out");
158
+ const out = outArg
159
+ ? resolve(expand(outArg, io.homedir()))
160
+ : join(defaultBackupDir(home), `dpi-backup-${stamp(io.now())}.zip`);
161
+ const result = await createBackup(io, { home, out });
162
+ io.print(result.path);
163
+ io.print(`backed up ${result.files} file(s), ${humanBytes(result.bytes)} from ${home}`);
164
+ return 0;
165
+ }
166
+
167
+ async function listCmd(rest: readonly string[], io: BackupCliIo): Promise<number> {
168
+ const home = await resolveHome(rest, io);
169
+ const dirArg = flagValue(rest, "--dir");
170
+ const dir = dirArg ? resolve(expand(dirArg, io.homedir())) : defaultBackupDir(home);
171
+ const backups = await listBackups(io, dir);
172
+ if (!backups.length) {
173
+ io.print(`no backups yet in ${dir}`);
174
+ return 0;
175
+ }
176
+ io.print(`${backups.length} backup(s) in ${dir}, newest first:`);
177
+ for (const b of backups) {
178
+ io.print(` ${new Date(b.mtimeMs).toISOString()} ${humanBytes(b.bytes).padStart(9)} ${b.name}`);
179
+ }
180
+ return 0;
181
+ }
182
+
183
+ async function restoreCmd(rest: readonly string[], io: BackupCliIo): Promise<number> {
184
+ // The positional FILE, skipping flags and the value --home consumes.
185
+ const positional: string[] = [];
186
+ for (let i = 0; i < rest.length; i += 1) {
187
+ if (rest[i] === "--home") i += 1;
188
+ else if (!rest[i].startsWith("-")) positional.push(rest[i]);
189
+ }
190
+ if (positional.length !== 1) {
191
+ io.printErr(`dpi backup restore: expected exactly one FILE (a dpi-backup-*.zip)\n\n${HELP}`);
192
+ return 2;
193
+ }
194
+ const zipPath = resolve(expand(positional[0], io.homedir()));
195
+ const home = await resolveHome(rest, io);
196
+ const url = await healthzUrl(io);
197
+
198
+ if (!rest.includes("--yes")) {
199
+ if (await deviceIsRunning(io, url)) {
200
+ io.printErr("dpi backup restore: the device is running — stop it first (`dpi device stop`)");
201
+ return 1;
202
+ }
203
+ // Read-only: the plan describes the backup, it does not touch the home.
204
+ const entries = await readBackupEntries(io, zipPath);
205
+ const files = entries.filter((e, i) => !(i === 0 && e.name === "manifest.json") && !e.name.endsWith("/")).length;
206
+ io.print(`would restore ${files} file(s) from ${zipPath} into ${home}`);
207
+ io.print(
208
+ (await io.exists(home))
209
+ ? `the current home would be renamed to ${home}.bak-<timestamp> (never deleted)`
210
+ : `${home} does not exist yet — it would be created`,
211
+ );
212
+ io.print("re-run with --yes to restore.");
213
+ return 0;
214
+ }
215
+
216
+ const result = await restoreBackup(io, { zipPath, home, healthzUrl: url });
217
+ io.print(`restored ${result.restored} file(s) from ${zipPath} into ${home}`);
218
+ if (result.backupOfOldHome) io.print(`previous home kept as ${result.backupOfOldHome}`);
219
+ return 0;
220
+ }