my-durable 0.0.37 → 0.0.39

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.
package/README.md CHANGED
@@ -22,6 +22,7 @@ dpi device install # OS service: systemd --user + linger (Linux) · LaunchA
22
22
  # run `dpi device start` after login
23
23
  dpi device uninstall
24
24
  dpi tui # terminal admin client
25
+ dpi doctor # one-shot health check (node, healthz, start dirs, model probe, hub); exit 1 on a failed check
25
26
  dpi --help # commands, flags and environment variables
26
27
  dpi update --check # is a newer published version available?
27
28
  dpi update # install it (npm i -g my-durable@latest)
@@ -0,0 +1,426 @@
1
+ /**
2
+ * `dpi doctor` — one-shot health check for THIS machine's device.
3
+ *
4
+ * Five checks, each printed as ok / warn / fail / skip with a one-line detail:
5
+ *
6
+ * 1. node — the one hard block in the project (>= 22.19.0, the
7
+ * engines floor; the comparison is `satisfiesEngine` from
8
+ * bin/update.mjs so both surfaces cannot drift).
9
+ * 2. healthz — is the device daemon actually answering on its port.
10
+ * 3. start_dirs — every configured start dir must exist and be writable;
11
+ * a device whose sessions cannot write is a broken device.
12
+ * 4. model probe — the local-only `/v1/device/probe-model` route. A dead
13
+ * provider is a WARN, never a fail: the UI rotates past
14
+ * dead providers, and doctor is not a provider pager.
15
+ * 5. hub — the paired/configured hub's /healthz, only when this
16
+ * device has a hub at all (otherwise `skip`).
17
+ *
18
+ * Exit code: 1 when any check FAILED, 0 otherwise (warnings included).
19
+ * Everything is injectable (env, fetch, fs, node version) so the unit tests run
20
+ * against fakes and never touch the network or the real filesystem.
21
+ */
22
+ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join, resolve } from "node:path";
25
+ // Reuse the updater's engine comparison instead of a second semver implementation.
26
+ import { satisfiesEngine } from "../../../bin/update.mjs";
27
+
28
+ export type DoctorStatus = "ok" | "warn" | "fail" | "skip";
29
+
30
+ export interface DoctorCheck {
31
+ id: string;
32
+ label: string;
33
+ status: DoctorStatus;
34
+ /** One line, already human shaped — the printer adds nothing but the marker. */
35
+ detail: string;
36
+ }
37
+
38
+ export interface DoctorReport {
39
+ checks: DoctorCheck[];
40
+ /** False when at least one check FAILED (warnings do not fail a report). */
41
+ ok: boolean;
42
+ }
43
+
44
+ /** The floor from package.json `engines` — declared here so a test can lower it. */
45
+ export const REQUIRED_NODE = ">=22.19.0";
46
+
47
+ /** The check ids in report order — stable for machine consumers.
48
+ * (start dirs carry an index suffix when more than one is configured.) */
49
+ export const DOCTOR_HEALTH_IDS = ["node", "healthz", "start_dir", "model_probe", "hub"] as const;
50
+
51
+ /** Narrow fetch surface: fakes stay three lines, no Response mock needed. */
52
+ export interface HttpResponse {
53
+ ok: boolean;
54
+ status: number;
55
+ json(): Promise<unknown>;
56
+ }
57
+ export type FetchLike = (
58
+ url: string,
59
+ init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
60
+ ) => Promise<HttpResponse>;
61
+
62
+ export interface DoctorIo {
63
+ env: Record<string, string | undefined>;
64
+ nodeVersion: string;
65
+ fetchImpl: FetchLike;
66
+ /** fs.accessSync-shaped: throws when the path is missing or not writable. */
67
+ access: (path: string, mode?: number) => void;
68
+ exists: (path: string) => boolean;
69
+ readFile: (path: string) => string;
70
+ homedir: () => string;
71
+ /** healthz timeout. */
72
+ timeoutMs: number;
73
+ /** The hub may be across an ocean and behind TLS — a loopback-sized timeout would lie. */
74
+ hubTimeoutMs: number;
75
+ /** probe-model timeout: it runs one throwaway turn, so it is not a health ping. */
76
+ probeTimeoutMs: number;
77
+ requiredNode: string;
78
+ }
79
+
80
+ const realFetch: FetchLike = async (url, init) => fetch(url, init as RequestInit);
81
+
82
+ export const defaultDoctorIo = (): DoctorIo => ({
83
+ env: process.env,
84
+ nodeVersion: process.versions.node,
85
+ fetchImpl: realFetch,
86
+ access: (path, mode) => accessSync(path, mode),
87
+ exists: existsSync,
88
+ readFile: (path) => readFileSync(path, "utf8"),
89
+ homedir,
90
+ timeoutMs: 3_000,
91
+ /** The hub may be across an ocean, behind TLS and a cold proxy — 8s keeps the
92
+ * check honest without turning flaky latency into daily warnings. */
93
+ hubTimeoutMs: 8_000,
94
+ probeTimeoutMs: 60_000,
95
+ requiredNode: REQUIRED_NODE,
96
+ });
97
+
98
+ // --------------------------------------------------------------- config bits
99
+
100
+ /** `~` / `~/x` expansion — same rule as config.ts and daemon.ts. */
101
+ export const expand = (p: string, hd: string = homedir()): string =>
102
+ p === "~" ? hd : p.startsWith("~/") ? join(hd, p.slice(2)) : p;
103
+
104
+ /**
105
+ * The start dirs exactly as `config.ts` sees them: ":"-separated, expanded and
106
+ * resolved. Doctor must report the dirs the DEVICE uses, so the rule is copied
107
+ * rather than invented (a comma is not a separator for the device either).
108
+ */
109
+ export const parseStartDirs = (raw: string, hd: string = homedir()): string[] =>
110
+ raw
111
+ .split(":")
112
+ .filter(Boolean)
113
+ .map((p) => resolve(expand(p, hd)));
114
+
115
+ /** KEY=VALUE lines of backend.env (the daemon's own file, no shell quoting). */
116
+ export function readEnvFile(text: string): Record<string, string> {
117
+ const out: Record<string, string> = {};
118
+ for (const line of text.split(/\r?\n/)) {
119
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
120
+ if (!m) continue;
121
+ out[m[1]] = m[2].trim().replace(/^(['"])(.*)\1$/, "$2");
122
+ }
123
+ return out;
124
+ }
125
+
126
+ /** "provider/modelId" → the two halves probe-model wants. OpenRouter ids carry their own slash. */
127
+ export function splitModel(
128
+ defaultModel: string,
129
+ models?: ReadonlyArray<{ provider: string; id: string }>,
130
+ ): { provider: string; modelId: string } | undefined {
131
+ const exact = models?.find((m) => `${m.provider}/${m.id}` === defaultModel);
132
+ if (exact) return { provider: exact.provider, modelId: exact.id };
133
+ const i = defaultModel.indexOf("/");
134
+ if (i <= 0 || i === defaultModel.length - 1) return undefined;
135
+ return { provider: defaultModel.slice(0, i), modelId: defaultModel.slice(i + 1) };
136
+ }
137
+
138
+ /** Why a request failed, in words an operator can act on. */
139
+ export function describeError(error: unknown, ms: number): string {
140
+ const e = error as { name?: string; message?: string; cause?: { code?: string; message?: string } };
141
+ const cause = e?.cause?.code ?? e?.cause?.message;
142
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") return `timed out after ${ms}ms`;
143
+ const message = e?.message ?? String(error);
144
+ if (!cause || message.includes(cause)) return message;
145
+ return `${message} (${cause})`;
146
+ }
147
+
148
+ // ------------------------------------------------------------------- checks
149
+
150
+ interface Merged {
151
+ /** process env wins over the env file, like loadConfig's `process.loadEnvFile`. */
152
+ env: Record<string, string | undefined>;
153
+ home: string;
154
+ envFile: string;
155
+ token: string;
156
+ baseUrl: string;
157
+ }
158
+
159
+ function mergedConfig(io: DoctorIo): Merged {
160
+ const hd = io.homedir();
161
+ // `||` not `??`: an empty DPI_HOME/DPI_ENV_FILE means "unset", never the cwd.
162
+ const home = resolve(expand(io.env.DPI_HOME || join(hd, ".dpi"), hd));
163
+ const envFile = resolve(expand(io.env.DPI_ENV_FILE || join(home, "backend.env"), hd));
164
+ let fileEnv: Record<string, string> = {};
165
+ if (io.exists(envFile)) {
166
+ try {
167
+ fileEnv = readEnvFile(io.readFile(envFile));
168
+ } catch {
169
+ /* unreadable env file: fall back to process env */
170
+ }
171
+ }
172
+ const env: Record<string, string | undefined> = { ...fileEnv, ...io.env };
173
+ const host = env.DPI_HOST || "127.0.0.1";
174
+ // A device listening on every interface is still reached over loopback here.
175
+ const probeHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
176
+ const port = Number(env.DPI_PORT || "4780");
177
+ return {
178
+ env,
179
+ home,
180
+ envFile,
181
+ token: env.DPI_TOKEN || "",
182
+ baseUrl: `http://${probeHost}:${Number.isInteger(port) && port > 0 ? port : 4780}`,
183
+ };
184
+ }
185
+
186
+ const authHeaders = (token: string): Record<string, string> =>
187
+ token ? { authorization: `Bearer ${token}` } : {};
188
+
189
+ async function getJson(
190
+ io: DoctorIo,
191
+ url: string,
192
+ headers: Record<string, string>,
193
+ ms: number,
194
+ ): Promise<{ ok: true; status: number; body: Record<string, unknown> } | { ok: false; detail: string }> {
195
+ let res: HttpResponse;
196
+ try {
197
+ res = await io.fetchImpl(url, { headers, signal: AbortSignal.timeout(ms) });
198
+ } catch (error) {
199
+ return { ok: false, detail: `${url} unreachable — ${describeError(error, ms)}` };
200
+ }
201
+ let body: Record<string, unknown> = {};
202
+ try {
203
+ body = (await res.json()) as Record<string, unknown>;
204
+ } catch {
205
+ /* non-JSON */
206
+ }
207
+ return { ok: true, status: res.status, body };
208
+ }
209
+
210
+ /** 1. node — the only hard block. */
211
+ function nodeCheck(io: DoctorIo): DoctorCheck {
212
+ const required = io.requiredNode;
213
+ const status: DoctorStatus = satisfiesEngine(io.nodeVersion, required) ? "ok" : "fail";
214
+ return {
215
+ id: "node",
216
+ label: `node ${io.nodeVersion}`,
217
+ status,
218
+ detail:
219
+ status === "ok"
220
+ ? `satisfies engines node ${required}`
221
+ : `below engines node ${required} — upgrade Node (nvm install --lts / winget upgrade OpenJS.NodeJS.LTS)`,
222
+ };
223
+ }
224
+
225
+ /** 3. start dirs — one check per dir so the failing one is named. */
226
+ function startDirChecks(io: DoctorIo, cfg: Merged): DoctorCheck[] {
227
+ const raw = cfg.env.DPI_START_DIRS || "~/dpi-work";
228
+ const dirs = parseStartDirs(raw, io.homedir());
229
+ if (!dirs.length)
230
+ return [{ id: "start_dirs", label: "start dirs", status: "warn", detail: "DPI_START_DIRS is empty — no cwd is browsable or writable" }];
231
+ return dirs.map((dir, i) => {
232
+ const check = (status: DoctorStatus, detail: string): DoctorCheck => ({
233
+ id: `start_dir${dirs.length > 1 ? `_${i + 1}` : ""}`,
234
+ label: `start dir ${dir}`,
235
+ status,
236
+ detail,
237
+ });
238
+ if (!io.exists(dir)) return check("fail", "missing — create it or fix DPI_START_DIRS");
239
+ try {
240
+ io.access(dir, fsConstants.W_OK);
241
+ } catch (error) {
242
+ return check("fail", `not writable — ${describeError(error, 0)}`);
243
+ }
244
+ return check("ok", "writable");
245
+ });
246
+ }
247
+
248
+ /** 4. model probe — the device's own default model, through the local-only route. */
249
+ async function probeCheck(io: DoctorIo, cfg: Merged, reachable: boolean): Promise<DoctorCheck> {
250
+ const id = "model_probe";
251
+ if (!reachable) return { id, label: "model probe", status: "skip", detail: "device unreachable" };
252
+ if (!cfg.token) return { id, label: "model probe", status: "skip", detail: `no DPI_TOKEN (looked in ${cfg.envFile})` };
253
+
254
+ const headers = authHeaders(cfg.token);
255
+ const device = await getJson(io, `${cfg.baseUrl}/v1/device`, headers, Math.min(io.timeoutMs * 2, 10_000));
256
+ if (!device.ok) return { id, label: "model probe", status: "warn", detail: device.detail };
257
+ if (device.status !== 200)
258
+ return {
259
+ id,
260
+ label: "model probe",
261
+ status: "warn",
262
+ detail: `GET /v1/device → ${device.status}${device.status === 401 ? " (token mismatch?)" : ""}`,
263
+ };
264
+
265
+ const defaultModel = typeof device.body.defaultModel === "string" ? device.body.defaultModel : "";
266
+ const models = Array.isArray(device.body.models)
267
+ ? (device.body.models as Array<{ provider: string; id: string }>).filter((m) => m && m.provider && m.id)
268
+ : undefined;
269
+ const target = defaultModel ? splitModel(defaultModel, models) : undefined;
270
+ const label = `model probe ${defaultModel || "(no default)"}`;
271
+ if (!target) return { id, label, status: "warn", detail: "device reports no usable defaultModel" };
272
+
273
+ let res: HttpResponse;
274
+ try {
275
+ res = await io.fetchImpl(`${cfg.baseUrl}/v1/device/probe-model`, {
276
+ method: "POST",
277
+ headers: { ...headers, "content-type": "application/json" },
278
+ body: JSON.stringify(target),
279
+ signal: AbortSignal.timeout(io.probeTimeoutMs),
280
+ });
281
+ } catch (error) {
282
+ return { id, label, status: "warn", detail: describeError(error, io.probeTimeoutMs) };
283
+ }
284
+ let body: Record<string, unknown> = {};
285
+ try {
286
+ body = (await res.json()) as Record<string, unknown>;
287
+ } catch {
288
+ /* non-JSON */
289
+ }
290
+ if (!res.ok) return { id, label, status: "warn", detail: `probe-model → ${res.status}` };
291
+ const detail = typeof body.detail === "string" && body.detail ? body.detail : body.ok === true ? "answered" : "no answer";
292
+ // A dead provider is a WARN by design: the FE rotates past it, the device is fine.
293
+ return { id, label, status: body.ok === true ? "ok" : "warn", detail: detail.slice(0, 160) };
294
+ }
295
+
296
+ /** 5. hub — only when this device actually has one. */
297
+ async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
298
+ const id = "hub";
299
+ let origin = (cfg.env.DPI_HUB_URL ?? "").trim().replace(/\/+$/, "");
300
+ const source = origin ? "DPI_HUB_URL" : "pairing.json";
301
+ if (!origin) {
302
+ const file = join(cfg.home, "pairing.json");
303
+ try {
304
+ if (io.exists(file)) {
305
+ const paired = JSON.parse(io.readFile(file)) as { hubOrigin?: unknown };
306
+ if (typeof paired.hubOrigin === "string") origin = paired.hubOrigin.trim().replace(/\/+$/, "");
307
+ }
308
+ } catch {
309
+ /* unreadable/garbled pairing file: report as not configured */
310
+ }
311
+ }
312
+ if (!origin) return { id, label: "hub", status: "skip", detail: "no hub configured (no DPI_HUB_URL, no saved pairing)" };
313
+
314
+ const label = `hub ${origin}`;
315
+ const url = `${origin}/healthz`;
316
+ const ms = Math.max(io.hubTimeoutMs, io.timeoutMs);
317
+ let res: HttpResponse;
318
+ try {
319
+ res = await io.fetchImpl(url, { signal: AbortSignal.timeout(ms) });
320
+ } catch (error) {
321
+ return { id, label, status: "warn", detail: `${url} unreachable — ${describeError(error, ms)} (${source})` };
322
+ }
323
+ if (!res.ok) return { id, label, status: "warn", detail: `${url} → ${res.status} (${source})` };
324
+ return { id, label, status: "ok", detail: `${url} answered (${source})` };
325
+ }
326
+
327
+ /** 2. healthz — is the daemon there at all. */
328
+ async function healthzCheck(
329
+ io: DoctorIo,
330
+ cfg: Merged,
331
+ ): Promise<{ check: DoctorCheck; reachable: boolean }> {
332
+ const url = `${cfg.baseUrl}/healthz`;
333
+ const label = `healthz ${url}`;
334
+ let res: HttpResponse;
335
+ try {
336
+ res = await io.fetchImpl(url, { signal: AbortSignal.timeout(io.timeoutMs) });
337
+ } catch (error) {
338
+ return {
339
+ check: { id: "healthz", label, status: "fail", detail: `unreachable — ${describeError(error, io.timeoutMs)} (is the device running? "dpi device start")` },
340
+ reachable: false,
341
+ };
342
+ }
343
+ if (!res.ok) return { check: { id: "healthz", label, status: "fail", detail: `responded ${res.status}` }, reachable: false };
344
+ return { check: { id: "healthz", label, status: "ok", detail: "device answered" }, reachable: true };
345
+ }
346
+
347
+ // ------------------------------------------------------------------- driver
348
+
349
+ /** Run every check. Warnings never make `ok` false; only a FAIL does. */
350
+ export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorReport> {
351
+ const io: DoctorIo = { ...defaultDoctorIo(), ...opts };
352
+ const cfg = mergedConfig(io);
353
+
354
+ const checks: DoctorCheck[] = [nodeCheck(io)];
355
+ const health = await healthzCheck(io, cfg);
356
+ checks.push(health.check);
357
+ checks.push(...startDirChecks(io, cfg));
358
+ checks.push(await probeCheck(io, cfg, health.reachable));
359
+ checks.push(await hubCheck(io, cfg));
360
+
361
+ return { checks, ok: checks.every((c) => c.status !== "fail") };
362
+ }
363
+
364
+ /** 1 when anything FAILED, 0 otherwise — the only thing that touches process.exit. */
365
+ export const exitCode = (report: DoctorReport): 0 | 1 => (report.ok ? 0 : 1);
366
+
367
+ const MARK: Record<DoctorStatus, string> = { ok: "ok ", warn: "warn", fail: "fail", skip: "skip" };
368
+
369
+ /** Human lines. `quiet` keeps warnings and failures (and always the verdict). */
370
+ export function formatReport(report: DoctorReport, opts: { quiet?: boolean } = {}): string[] {
371
+ const shown = opts.quiet ? report.checks.filter((c) => c.status === "warn" || c.status === "fail") : report.checks;
372
+ const lines = shown.map((c) => `${MARK[c.status]} ${c.label} — ${c.detail}`);
373
+ const failed = report.checks.filter((c) => c.status === "fail").length;
374
+ const warned = report.checks.filter((c) => c.status === "warn").length;
375
+ if (report.ok) {
376
+ const counts = `${report.checks.length} checks`;
377
+ const tail = warned ? `${warned} warning${warned === 1 ? "" : "s"}` : "all good";
378
+ if (!lines.length) lines.push(`doctor: OK — ${counts}, ${tail}`);
379
+ else lines.push("", `doctor: OK — ${counts}, ${tail}`);
380
+ return lines;
381
+ }
382
+ lines.push("", `doctor: ${failed} check${failed === 1 ? "" : "s"} failed${warned ? `, ${warned} warning${warned === 1 ? "" : "s"}` : ""}`);
383
+ return lines;
384
+ }
385
+
386
+ export interface DoctorCliDeps extends Partial<DoctorIo> {
387
+ print?: (line: string) => void;
388
+ printErr?: (line: string) => void;
389
+ }
390
+
391
+ /**
392
+ * `dpi doctor [--json] [--quiet]` — parse, run, print, return the exit code.
393
+ * Kept here (not in bin/dpi.mjs) so the exit-code derivation is unit-testable.
394
+ */
395
+ export async function doctorCli(argv: string[] = [], deps: DoctorCliDeps = {}): Promise<0 | 1> {
396
+ const print = deps.print ?? ((line: string) => process.stdout.write(`${line}\n`));
397
+ const printErr = deps.printErr ?? ((line: string) => process.stderr.write(`${line}\n`));
398
+ const json = argv.includes("--json");
399
+ const quiet = argv.includes("--quiet") || argv.includes("-q");
400
+ const unknown = argv.filter((a) => !["--json", "--quiet", "-q", "--help", "-h"].includes(a));
401
+ if (argv.includes("--help") || argv.includes("-h")) {
402
+ print(DOCTOR_HELP);
403
+ return 0;
404
+ }
405
+ if (unknown.length) {
406
+ printErr(`dpi doctor: unknown flag '${unknown[0]}'\n\n${DOCTOR_HELP}`);
407
+ return 1;
408
+ }
409
+
410
+ const { print: _p, printErr: _e, ...io } = deps;
411
+ const report = await runDoctor(io);
412
+ if (json) print(JSON.stringify(report, null, 2));
413
+ else for (const line of formatReport(report, { quiet })) print(line);
414
+ return exitCode(report);
415
+ }
416
+
417
+ export const DOCTOR_HELP = `dpi doctor [--json] [--quiet]
418
+
419
+ One-shot health check for this machine's device: node >= 22.19.0, healthz,
420
+ start-dir writability, the default-model probe and the hub's /healthz.
421
+
422
+ --json machine-readable { checks: [{ id, label, status, detail }], ok }
423
+ --quiet print only warnings and failures
424
+
425
+ Exit code: 1 when a check fails, 0 otherwise (warnings are not failures).
426
+ `;