my-durable 0.0.42 → 0.0.44

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,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,134 @@
1
+ /**
2
+ * `dpi diagnostics` — the redacted diagnostic bundle CLI (checklist Wave 3).
3
+ *
4
+ * Mirrors `backup-cli.ts`: the CLI io extends the module's `DiagnosticsIo`
5
+ * with print/printErr (env and homedir already live on the module io), so one
6
+ * object is faked in tests. Exit codes: 0 bundle written (failed sections
7
+ * included — the bundle still built), 1 the bundle could not be written,
8
+ * 2 usage error; nothing is ever thrown out of `diagnosticsCli`. `argv` is
9
+ * what follows the `diagnostics` word.
10
+ */
11
+ import { basename, dirname, join, resolve } from "node:path";
12
+ import { collectDiagnostics, defaultDiagnosticsIo, DEVICE_LOG_LINES, type DiagnosticsIo } from "./diagnostics.js";
13
+ import { expand, readEnvFile } from "./doctor.js";
14
+ import { humanBytes } from "./gc.js";
15
+
16
+ export interface DiagnosticsCliArgs {
17
+ argv: readonly string[];
18
+ }
19
+
20
+ /** The CLI adds output to the module's io — one object, so a test fakes exactly what it needs. */
21
+ export interface DiagnosticsCliIo extends DiagnosticsIo {
22
+ print: (line: string) => void;
23
+ printErr: (line: string) => void;
24
+ }
25
+
26
+ export const defaultDiagnosticsCliIo = (): DiagnosticsCliIo => ({
27
+ ...defaultDiagnosticsIo(),
28
+ print: (line) => process.stdout.write(`${line}\n`),
29
+ printErr: (line) => process.stderr.write(`${line}\n`),
30
+ });
31
+
32
+ const HELP = `dpi diagnostics — redacted diagnostic bundle (checklist Wave 3)
33
+
34
+ dpi diagnostics [--out FILE] [--home DIR]
35
+
36
+ Collects everything an operator would paste into a bug report, with secrets
37
+ stripped, into one 0600 zip: manifest, the doctor checks, device/vitals/env,
38
+ session summaries (no transcripts), the project/schedule/notify registries,
39
+ and the last ${DEVICE_LOG_LINES} lines of device.log.
40
+
41
+ --home DIR device home (default: $DPI_HOME, else ~/.dpi)
42
+ --out FILE where the bundle lands (default: <home>-diagnostics/dpi-diagnostics-<YYYYMMDD-HHMMSS>.zip,
43
+ a sibling of home, so a bundle never sits inside what it reads)
44
+
45
+ Every value is redacted before it enters the zip (dpi_ tokens, Bearer headers,
46
+ sk-/pk-/rk- keys, any 32+ char token-shaped run). A section that cannot be
47
+ collected is recorded as {"error": ...} and the bundle still builds — a broken
48
+ device is exactly when diagnostics matter most.
49
+
50
+ Exit codes: 0 bundle written, 1 the bundle could not be written, 2 usage error.`;
51
+
52
+ const flagValue = (argv: readonly string[], name: string): string | undefined => {
53
+ const i = argv.indexOf(name);
54
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
55
+ };
56
+
57
+ /** env wins over the env file, like doctor.ts's `deviceEndpoint`. */
58
+ async function envValues(io: DiagnosticsCliIo): Promise<(key: string) => string | undefined> {
59
+ const envFile = io.env.DPI_ENV_FILE;
60
+ let fileEnv: Record<string, string> = {};
61
+ if (envFile) {
62
+ try {
63
+ fileEnv = readEnvFile(await io.readFile(resolve(expand(envFile, io.homedir()))));
64
+ } catch {
65
+ /* unreadable env file: fall back to process env, like doctor.ts */
66
+ }
67
+ }
68
+ return (key) => io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
69
+ }
70
+
71
+ /** `--home` wins, then $DPI_HOME (env file included), then ~/.dpi — the gc-cli rule. */
72
+ async function resolveHome(argv: readonly string[], io: DiagnosticsCliIo): Promise<string> {
73
+ const value = await envValues(io);
74
+ const home = flagValue(argv, "--home") ?? value("DPI_HOME") ?? join(io.homedir(), ".dpi");
75
+ return resolve(expand(home, io.homedir()));
76
+ }
77
+
78
+ /** A sibling of home: a bundle must never sit inside the directory it reads. */
79
+ export const defaultDiagnosticsDir = (home: string): string => join(dirname(home), `${basename(home)}-diagnostics`);
80
+
81
+ /** `YYYYMMDD-HHMMSS` in local time — the name a human matches against \`ls\`. */
82
+ const stamp = (now: number): string => {
83
+ const d = new Date(now);
84
+ const p = (n: number) => String(n).padStart(2, "0");
85
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
86
+ };
87
+
88
+ export async function diagnosticsCli(args: DiagnosticsCliArgs, io: DiagnosticsCliIo = defaultDiagnosticsCliIo()): Promise<number> {
89
+ try {
90
+ return await run(args, io);
91
+ } catch (error) {
92
+ // The CLI contract is an exit code, never a stack trace (gcCli's rule).
93
+ io.printErr(`dpi diagnostics: ${error instanceof Error ? error.message : String(error)}`);
94
+ return 1;
95
+ }
96
+ }
97
+
98
+ async function run(args: DiagnosticsCliArgs, io: DiagnosticsCliIo): Promise<number> {
99
+ const argv = args.argv;
100
+ if (argv.includes("--help") || argv.includes("-h")) {
101
+ io.print(HELP);
102
+ return 0;
103
+ }
104
+ const allowed = new Set(["--home", "--out"]);
105
+ for (let i = 0; i < argv.length; i += 1) {
106
+ const arg = argv[i];
107
+ if (arg === "--home" || arg === "--out") {
108
+ i += 1; // its value, if any
109
+ continue;
110
+ }
111
+ if (arg.startsWith("-")) {
112
+ io.printErr(`dpi diagnostics: unknown flag '${arg}'\n\n${HELP}`);
113
+ return 2;
114
+ }
115
+ io.printErr(`dpi diagnostics: unexpected argument '${arg}' (no positional arguments)\n\n${HELP}`);
116
+ return 2;
117
+ }
118
+
119
+ const home = await resolveHome(argv, io);
120
+ const outArg = flagValue(argv, "--out");
121
+ const out = outArg
122
+ ? resolve(expand(outArg, io.homedir()))
123
+ : join(defaultDiagnosticsDir(home), `dpi-diagnostics-${stamp(io.now())}.zip`);
124
+
125
+ const result = await collectDiagnostics(io, { home, out });
126
+ for (const section of result.sections) {
127
+ if (section.ok) io.print(`ok ${section.name} ${humanBytes(section.bytes)}`);
128
+ else io.print(`failed ${section.name}: ${section.error}`);
129
+ }
130
+ const failed = result.sections.filter((s) => !s.ok).length;
131
+ io.print(result.path);
132
+ io.print(`diagnostic bundle: ${result.sections.length} section(s), ${humanBytes(result.bytes)} total${failed ? `, ${failed} failed` : ""}`);
133
+ return 0;
134
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * `dpi diagnostics` — a redacted diagnostic bundle as one zip — "Diagnostic
3
+ * bundle" (SHOULD), Wave 3 of docs/host-project-checklist.md.
4
+ *
5
+ * Modelled on orca's PrivacyDiagnosticBundleControls idea: everything an
6
+ * operator would paste into a bug report, with secrets stripped. Every text
7
+ * that enters the bundle passes `redact`/`redactJson` (dpi_ tokens, Bearer
8
+ * headers, sk-/pk-/rk- keys, and any 32+ char token-shaped run); the bundle
9
+ * contains no transcripts by construction, so the raw-long-run rule cannot
10
+ * eat base64 payload it was never meant to see.
11
+ *
12
+ * Each section is INDEPENDENT: one that fails records `{"error": ...}` and the
13
+ * bundle still builds — a broken device is exactly when diagnostics matter
14
+ * most. The API sections talk to the LOCAL device the same way `dpi doctor`
15
+ * does (`deviceEndpoint` + `authHeaders`, `$DPI_HOST|$DPI_PORT`, token from
16
+ * the env file), and `doctor.json` is literally doctor's runner re-run through
17
+ * this module's io — not a reimplementation.
18
+ *
19
+ * Every fs/clock/network access goes through `DiagnosticsIo` (the `backup.ts`
20
+ * pattern: async fs + injectable fetch + clock). doctor.ts's own fs surface is
21
+ * synchronous (`existsSync`/`readFileSync`/`accessSync`), so the io carries
22
+ * that surface too and `diagnosticsDoctorIo` bridges the two worlds — one
23
+ * object to fake in tests, never the real fs or network.
24
+ */
25
+ import { accessSync, existsSync, readFileSync } from "node:fs";
26
+ import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
27
+ import { homedir } from "node:os";
28
+ import { dirname, join, resolve } from "node:path";
29
+ import {
30
+ authHeaders,
31
+ defaultDoctorIo,
32
+ describeError,
33
+ deviceEndpoint,
34
+ expand,
35
+ runDoctor,
36
+ type DoctorIo,
37
+ } from "./doctor.js";
38
+ import { PACKAGE_VERSION } from "./store.js";
39
+ import { zipSync, type ZipEntry } from "./zip.js";
40
+
41
+ export type DiagnosticsErrorCode = "invalid";
42
+
43
+ /** Typed failure, same shape as `BackupError`: a CLI picks its exit code from `code`, not from message matching. */
44
+ export class DiagnosticsError extends Error {
45
+ readonly code: DiagnosticsErrorCode;
46
+
47
+ constructor(code: DiagnosticsErrorCode, message: string) {
48
+ super(message);
49
+ this.name = "DiagnosticsError";
50
+ this.code = code;
51
+ }
52
+ }
53
+
54
+ const invalid = (message: string) => new DiagnosticsError("invalid", message);
55
+
56
+ /** The io carries the same 0700/0600 rule `backup.ts` does (`ensurePrivateDir` is sync and not injectable). */
57
+ const DIR_MODE = 0o700;
58
+ const FILE_MODE = 0o600;
59
+ /** Per-section fetch budget: a hung device must not hang the bundle. */
60
+ const SECTION_TIMEOUT_MS = 10_000;
61
+ /** The device.log tail: the last 400 lines, never the whole file. */
62
+ export const DEVICE_LOG_LINES = 400;
63
+
64
+ /** Narrow fetch surface, `doctor.ts`'s init shape so its checks pass through unchanged. */
65
+ export interface DiagnosticsFetchInit {
66
+ method?: string;
67
+ headers?: Record<string, string>;
68
+ body?: string;
69
+ signal?: AbortSignal;
70
+ }
71
+
72
+ export interface DiagnosticsResponse {
73
+ ok: boolean;
74
+ status: number;
75
+ text(): Promise<string>;
76
+ }
77
+
78
+ export interface DiagnosticsIo {
79
+ readFile(path: string): Promise<string>;
80
+ /** `mode` applies when the file is created; an explicit `chmod` follows, like backup.ts's persist. */
81
+ writeFile(path: string, data: Uint8Array, mode?: number): Promise<void>;
82
+ chmod(path: string, mode: number): Promise<void>;
83
+ /** Recursive; `mode` (0700 by default) applies to the directories it creates. */
84
+ mkdir(path: string, mode?: number): Promise<void>;
85
+ exists(path: string): Promise<boolean>;
86
+ fetch(url: string, init?: DiagnosticsFetchInit): Promise<DiagnosticsResponse>;
87
+ now(): number;
88
+ env: Record<string, string | undefined>;
89
+ homedir: () => string;
90
+ nodeVersion: string;
91
+ /** doctor.ts's fs surface is synchronous; the io carries it so `runDoctor` runs through the same fake. */
92
+ existsSync(path: string): boolean;
93
+ readFileSync(path: string): string;
94
+ accessSync(path: string, mode?: number): void;
95
+ }
96
+
97
+ export const defaultDiagnosticsIo = (): DiagnosticsIo => ({
98
+ readFile: (path) => readFile(path, "utf8"),
99
+ writeFile: (path, data, mode) => writeFile(path, data, { mode }),
100
+ chmod: (path, mode) => chmod(path, mode),
101
+ // fs/promises mkdir(recursive) resolves with the first created path — dropped, the io promises void.
102
+ mkdir: async (path, mode) => {
103
+ await mkdir(path, { recursive: true, mode: mode ?? DIR_MODE });
104
+ },
105
+ exists: async (path) => {
106
+ try {
107
+ await access(path);
108
+ return true;
109
+ } catch {
110
+ return false;
111
+ }
112
+ },
113
+ fetch: (url, init) => fetch(url, init as RequestInit | undefined),
114
+ now: () => Date.now(),
115
+ env: process.env as Record<string, string | undefined>,
116
+ homedir,
117
+ existsSync,
118
+ readFileSync: (path) => readFileSync(path, "utf8"),
119
+ accessSync,
120
+ nodeVersion: process.versions.node,
121
+ });
122
+
123
+ // ---------------------------------------------------------------- redaction
124
+
125
+ /**
126
+ * Mask secret-shaped runs in any text: dpi_ tokens, bearer headers, long
127
+ * key-looking strings. Order matters — the prefixed shapes run first so the
128
+ * raw 32+ catch-all only sees what is left. NEVER the words themselves, only
129
+ * the values.
130
+ */
131
+ export function redact(text: string): string {
132
+ return text
133
+ .replace(/dpi_[A-Za-z0-9_-]{20,}/g, "dpi_••••")
134
+ .replace(/Bearer\s+[A-Za-z0-9._-]{16,}/g, "Bearer ••••")
135
+ .replace(/\b(sk|pk|rk)-[A-Za-z0-9]{16,}/g, "$1-••••")
136
+ .replace(/[A-Za-z0-9_-]{32,}/g, "••••");
137
+ }
138
+
139
+ /** Walk a parsed JSON value and redact every string in it (values, not keys — keys are schema). */
140
+ export function redactJson(value: unknown): unknown {
141
+ if (typeof value === "string") return redact(value);
142
+ if (Array.isArray(value)) return value.map(redactJson);
143
+ if (value && typeof value === "object") {
144
+ const out: Record<string, unknown> = {};
145
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[key] = redactJson(entry);
146
+ return out;
147
+ }
148
+ return value;
149
+ }
150
+
151
+ // ----------------------------------------------------------------- sections
152
+
153
+ /** One zip entry plus the outcome the CLI prints. */
154
+ export interface DiagnosticsSection {
155
+ name: string;
156
+ ok: boolean;
157
+ bytes: number;
158
+ /** Present when the section failed: what the CLI prints after the colon. */
159
+ error?: string;
160
+ }
161
+
162
+ /** The `GET /v1/...` routes that become json sections, in bundle order. */
163
+ const API_SECTIONS: ReadonlyArray<{ name: string; route: string }> = [
164
+ { name: "device.json", route: "/v1/device" },
165
+ { name: "vitals.json", route: "/v1/device/vitals" },
166
+ { name: "env.json", route: "/v1/device/env" },
167
+ { name: "sessions.json", route: "/v1/sessions" },
168
+ { name: "projects.json", route: "/v1/projects" },
169
+ { name: "schedules.json", route: "/v1/schedules" },
170
+ { name: "notify.json", route: "/v1/notify/sinks" },
171
+ ];
172
+
173
+ const jsonText = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
174
+
175
+ /** `runDoctor` over this module's io: same checks, same fakes, doctor's own timeouts and engine floor. */
176
+ function diagnosticsDoctorIo(io: DiagnosticsIo): DoctorIo {
177
+ return {
178
+ ...defaultDoctorIo(),
179
+ env: io.env,
180
+ nodeVersion: io.nodeVersion,
181
+ // doctor's FetchLike wants json(); this io speaks text() — adapt, never reimplement.
182
+ fetchImpl: async (url, init) => {
183
+ const res = await io.fetch(url, init);
184
+ return { ok: res.ok, status: res.status, json: async () => JSON.parse(await res.text()) };
185
+ },
186
+ access: io.accessSync,
187
+ exists: io.existsSync,
188
+ readFile: io.readFileSync,
189
+ homedir: io.homedir,
190
+ };
191
+ }
192
+
193
+ /** One JSON section from the device API: ok → redacted body; failure → `{"error": ...}` and the bundle carries on. */
194
+ async function apiSection(
195
+ io: DiagnosticsIo,
196
+ url: string,
197
+ route: string,
198
+ headers: Record<string, string>,
199
+ ): Promise<{ text: string; ok: boolean; error?: string }> {
200
+ let ok: boolean;
201
+ let status: number;
202
+ let raw: string;
203
+ try {
204
+ const res = await io.fetch(url, { headers, signal: AbortSignal.timeout(SECTION_TIMEOUT_MS) });
205
+ ok = res.ok;
206
+ status = res.status;
207
+ raw = await res.text();
208
+ } catch (error) {
209
+ const detail = describeError(error, SECTION_TIMEOUT_MS);
210
+ return { text: jsonText({ error: `GET ${route} unreachable — ${detail}` }), ok: false, error: detail };
211
+ }
212
+ if (!ok) {
213
+ return { text: jsonText({ error: `GET ${route} → ${status}` }), ok: false, error: String(status) };
214
+ }
215
+ let body: unknown;
216
+ try {
217
+ body = JSON.parse(raw);
218
+ } catch {
219
+ return { text: jsonText({ error: `GET ${route} → non-JSON body` }), ok: false, error: "non-JSON body" };
220
+ }
221
+ return { text: jsonText(redactJson(body)), ok: true };
222
+ }
223
+
224
+ /** The device.log tail: last 400 lines, redacted. Missing → skipped (undefined); unreadable → a failed section. */
225
+ async function logSection(io: DiagnosticsIo, home: string): Promise<{ text: string; ok: boolean; error?: string } | undefined> {
226
+ const logPath = join(home, "device.log");
227
+ if (!(await io.exists(logPath))) return undefined;
228
+ let raw: string;
229
+ try {
230
+ raw = await io.readFile(logPath);
231
+ } catch (error) {
232
+ const detail = describeError(error, 0);
233
+ return { text: `# cannot read ${logPath}: ${detail}\n`, ok: false, error: detail };
234
+ }
235
+ const lines = raw.split(/\r?\n/);
236
+ if (lines.length && lines[lines.length - 1] === "") lines.pop(); // the split's trailing "" is not a line
237
+ const tail = lines.slice(-DEVICE_LOG_LINES);
238
+ return { text: tail.length ? `${redact(tail.join("\n"))}\n` : "", ok: true };
239
+ }
240
+
241
+ // ----------------------------------------------------------------- collect
242
+
243
+ export interface CollectDiagnosticsOptions {
244
+ home: string;
245
+ out: string;
246
+ }
247
+
248
+ export interface CollectDiagnosticsResult {
249
+ path: string;
250
+ sections: DiagnosticsSection[];
251
+ /** Total zip size in bytes — the CLI's "total". */
252
+ bytes: number;
253
+ }
254
+
255
+ /**
256
+ * Collect the bundle into `opts.out` (0600, parent dirs 0700) and touch nothing
257
+ * else. The timestamped default name is the CLI's decision, not this module's.
258
+ */
259
+ export async function collectDiagnostics(
260
+ io: DiagnosticsIo,
261
+ opts: CollectDiagnosticsOptions,
262
+ ): Promise<CollectDiagnosticsResult> {
263
+ if (!opts.home) throw invalid("home is required");
264
+ if (!opts.out) throw invalid("out is required");
265
+ const home = resolve(expand(opts.home, io.homedir()));
266
+ const out = resolve(expand(opts.out, io.homedir()));
267
+
268
+ // The device API the way doctor sees it: $DPI_HOST|$DPI_PORT, token from the env file.
269
+ const doctorIo = diagnosticsDoctorIo(io);
270
+ const cfg = deviceEndpoint(doctorIo);
271
+ const headers = authHeaders(cfg.token);
272
+
273
+ const sections: DiagnosticsSection[] = [];
274
+ const entries: ZipEntry[] = [];
275
+ const push = (name: string, text: string, ok: boolean, error?: string): void => {
276
+ entries.push({ path: name, text });
277
+ sections.push({ name, ok, bytes: Buffer.byteLength(text, "utf8"), ...(error ? { error } : {}) });
278
+ };
279
+
280
+ // doctor.json — doctor's own runner, through this module's io.
281
+ {
282
+ let report: unknown;
283
+ let ok = true;
284
+ let error: string | undefined;
285
+ try {
286
+ report = redactJson(await runDoctor(doctorIo));
287
+ } catch (e) {
288
+ error = describeError(e, 0);
289
+ report = { error: `doctor failed — ${error}` };
290
+ ok = false;
291
+ }
292
+ push("doctor.json", jsonText(report), ok, error);
293
+ }
294
+
295
+ // the seven registry/summary routes — summaries by design (no transcripts)
296
+ for (const section of API_SECTIONS) {
297
+ const r = await apiSection(io, `${cfg.baseUrl}${section.route}`, section.route, headers);
298
+ push(section.name, r.text, r.ok, r.error);
299
+ }
300
+
301
+ // device.log — on-disk facts, tail only, redacted
302
+ {
303
+ const r = await logSection(io, home);
304
+ if (r) push("device.log", r.text, r.ok, r.error);
305
+ }
306
+
307
+ // The manifest is entry 0 (backup.ts's rule), so it lists the sections that
308
+ // actually made it in — including device.log only when the log was there.
309
+ const manifest = redactJson({
310
+ createdAt: new Date(io.now()).toISOString(),
311
+ packageVersion: PACKAGE_VERSION,
312
+ node: io.nodeVersion,
313
+ platform: process.platform,
314
+ arch: process.arch,
315
+ home,
316
+ sections: sections.map((s) => s.name),
317
+ });
318
+ entries.unshift({ path: "manifest.json", text: jsonText(manifest) });
319
+ sections.unshift({ name: "manifest.json", ok: true, bytes: Buffer.byteLength(jsonText(manifest), "utf8") });
320
+
321
+ const zip = zipSync(entries, new Date(io.now()));
322
+ await io.mkdir(dirname(out), DIR_MODE);
323
+ await io.writeFile(out, zip, FILE_MODE);
324
+ await io.chmod(out, FILE_MODE);
325
+ return { path: out, sections, bytes: zip.length };
326
+ }
@@ -31,6 +31,7 @@ const store = await Store.open({
31
31
  name: config.name,
32
32
  provider: config.provider,
33
33
  envFile: config.envFile,
34
+ telegramToken: process.env.DPI_TELEGRAM_TOKEN,
34
35
  });
35
36
 
36
37
  const app = express();
@@ -230,6 +230,21 @@ function coerceRecord(raw: unknown, now: string): ProjectRecord {
230
230
  archivedAt: nonEmptyString(source.archivedAt) ?? null,
231
231
  };
232
232
  if (customName) record.customName = customName;
233
+ // Per-project default model: parse strictly so a corrupted pair cannot enter
234
+ // the registry, but never drop a good one (caught live: the field allowlist
235
+ // here silently erased every project's model on each device boot).
236
+ const rawModel = source.model;
237
+ if (rawModel !== undefined && rawModel !== null && rawModel !== "") {
238
+ if (
239
+ rawModel &&
240
+ typeof rawModel === "object" &&
241
+ nonEmptyString((rawModel as Record<string, unknown>).provider) &&
242
+ nonEmptyString((rawModel as Record<string, unknown>).modelId)
243
+ ) {
244
+ const model = rawModel as { provider: string; modelId: string };
245
+ record.model = { provider: model.provider, modelId: model.modelId };
246
+ }
247
+ }
233
248
  return record;
234
249
  }
235
250