my-durable 0.0.39 → 0.0.41

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 (27) hide show
  1. package/apps/dpi-backend/src/doctor.ts +29 -9
  2. package/apps/dpi-backend/src/gc-cli.ts +113 -0
  3. package/apps/dpi-backend/src/gc.ts +142 -0
  4. package/apps/dpi-backend/src/notify-cli.ts +211 -0
  5. package/apps/dpi-backend/src/notify-sinks.ts +947 -0
  6. package/apps/dpi-backend/src/routes.ts +17 -0
  7. package/apps/dpi-backend/src/schedule-cli.ts +211 -0
  8. package/apps/dpi-backend/src/schedules.ts +676 -0
  9. package/apps/dpi-backend/src/store.ts +275 -7
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D6ClJqd8.css +1 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMb-n4O-.js +81 -0
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +2 -0
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +4 -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/NotifyPanel.vue +292 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +289 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +13 -1
  19. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +20 -1
  20. package/apps/dpi-sdk/src/api.ts +100 -0
  21. package/apps/dpi-sdk/src/client.ts +38 -0
  22. package/apps/dpi-sdk/src/protocol/rest-routes.ts +12 -0
  23. package/bin/dpi.mjs +22 -0
  24. package/docs/host-project-checklist.md +6 -6
  25. package/package.json +1 -1
  26. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CYZxCPDU.js +0 -81
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-v7IQ7Jg5.css +0 -1
@@ -147,7 +147,9 @@ export function describeError(error: unknown, ms: number): string {
147
147
 
148
148
  // ------------------------------------------------------------------- checks
149
149
 
150
- interface Merged {
150
+ /** Where the local device is and how to authenticate — shared by every CLI that
151
+ * talks to it (`dpi doctor`, `dpi schedule`). */
152
+ export interface DeviceEndpoint {
151
153
  /** process env wins over the env file, like loadConfig's `process.loadEnvFile`. */
152
154
  env: Record<string, string | undefined>;
153
155
  home: string;
@@ -156,7 +158,7 @@ interface Merged {
156
158
  baseUrl: string;
157
159
  }
158
160
 
159
- function mergedConfig(io: DoctorIo): Merged {
161
+ export function deviceEndpoint(io: DoctorIo): DeviceEndpoint {
160
162
  const hd = io.homedir();
161
163
  // `||` not `??`: an empty DPI_HOME/DPI_ENV_FILE means "unset", never the cwd.
162
164
  const home = resolve(expand(io.env.DPI_HOME || join(hd, ".dpi"), hd));
@@ -183,7 +185,7 @@ function mergedConfig(io: DoctorIo): Merged {
183
185
  };
184
186
  }
185
187
 
186
- const authHeaders = (token: string): Record<string, string> =>
188
+ export const authHeaders = (token: string): Record<string, string> =>
187
189
  token ? { authorization: `Bearer ${token}` } : {};
188
190
 
189
191
  async function getJson(
@@ -223,7 +225,7 @@ function nodeCheck(io: DoctorIo): DoctorCheck {
223
225
  }
224
226
 
225
227
  /** 3. start dirs — one check per dir so the failing one is named. */
226
- function startDirChecks(io: DoctorIo, cfg: Merged): DoctorCheck[] {
228
+ function startDirChecks(io: DoctorIo, cfg: DeviceEndpoint): DoctorCheck[] {
227
229
  const raw = cfg.env.DPI_START_DIRS || "~/dpi-work";
228
230
  const dirs = parseStartDirs(raw, io.homedir());
229
231
  if (!dirs.length)
@@ -246,7 +248,7 @@ function startDirChecks(io: DoctorIo, cfg: Merged): DoctorCheck[] {
246
248
  }
247
249
 
248
250
  /** 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> {
251
+ async function probeCheck(io: DoctorIo, cfg: DeviceEndpoint, reachable: boolean): Promise<DoctorCheck> {
250
252
  const id = "model_probe";
251
253
  if (!reachable) return { id, label: "model probe", status: "skip", detail: "device unreachable" };
252
254
  if (!cfg.token) return { id, label: "model probe", status: "skip", detail: `no DPI_TOKEN (looked in ${cfg.envFile})` };
@@ -290,11 +292,29 @@ async function probeCheck(io: DoctorIo, cfg: Merged, reachable: boolean): Promis
290
292
  if (!res.ok) return { id, label, status: "warn", detail: `probe-model → ${res.status}` };
291
293
  const detail = typeof body.detail === "string" && body.detail ? body.detail : body.ok === true ? "answered" : "no answer";
292
294
  // 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) };
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
+ };
294
314
  }
295
315
 
296
316
  /** 5. hub — only when this device actually has one. */
297
- async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
317
+ async function hubCheck(io: DoctorIo, cfg: DeviceEndpoint): Promise<DoctorCheck> {
298
318
  const id = "hub";
299
319
  let origin = (cfg.env.DPI_HUB_URL ?? "").trim().replace(/\/+$/, "");
300
320
  const source = origin ? "DPI_HUB_URL" : "pairing.json";
@@ -327,7 +347,7 @@ async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
327
347
  /** 2. healthz — is the daemon there at all. */
328
348
  async function healthzCheck(
329
349
  io: DoctorIo,
330
- cfg: Merged,
350
+ cfg: DeviceEndpoint,
331
351
  ): Promise<{ check: DoctorCheck; reachable: boolean }> {
332
352
  const url = `${cfg.baseUrl}/healthz`;
333
353
  const label = `healthz ${url}`;
@@ -349,7 +369,7 @@ async function healthzCheck(
349
369
  /** Run every check. Warnings never make `ok` false; only a FAIL does. */
350
370
  export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorReport> {
351
371
  const io: DoctorIo = { ...defaultDoctorIo(), ...opts };
352
- const cfg = mergedConfig(io);
372
+ const cfg = deviceEndpoint(io);
353
373
 
354
374
  const checks: DoctorCheck[] = [nodeCheck(io)];
355
375
  const health = await healthzCheck(io, cfg);
@@ -0,0 +1,113 @@
1
+ /**
2
+ * `dpi gc` — retention for archived sessions (checklist Wave 2, policy gate #3).
3
+ *
4
+ * Deliberately dry-run by default: the *policy* (how long to keep work) is the
5
+ * operator's call, not ours, so nothing is ever deleted without `--yes`.
6
+ * Mirrors piggery's `gc --closed-before DURATION [--dry-run]`.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { homedir } from "node:os";
11
+ import { gcApply, gcPlan, humanBytes, parseDuration } from "./gc.js";
12
+ import { expand, readEnvFile } from "./doctor.js";
13
+
14
+ export interface GcArgs {
15
+ argv: readonly string[];
16
+ }
17
+
18
+ export interface GcIo {
19
+ print: (line: string) => void;
20
+ printErr: (line: string) => void;
21
+ env: Record<string, string | undefined>;
22
+ readFile: (path: string) => string;
23
+ homedir: () => string;
24
+ now: () => number;
25
+ }
26
+
27
+ export const defaultGcIo = (): GcIo => ({
28
+ print: (line) => process.stdout.write(`${line}\n`),
29
+ printErr: (line) => process.stderr.write(`${line}\n`),
30
+ env: process.env as Record<string, string | undefined>,
31
+ readFile: (path) => readFileSync(path, "utf8"),
32
+ homedir,
33
+ now: () => Date.now(),
34
+ });
35
+
36
+ const HELP = `dpi gc — retention for archived sessions
37
+
38
+ dpi gc --closed-before 30d [--dry-run | --yes] [--home <dir>] [--data-dir <dir>]
39
+
40
+ --closed-before D age cutoff: 90m, 12h, 30d, 2w
41
+ --dry-run show what would be deleted (the default)
42
+ --yes actually delete it
43
+ --home <dir> device home (default: $DPI_HOME, else ~/.dpi)
44
+ --data-dir <dir> device data dir (default: <home>/backend)
45
+
46
+ Nothing is deleted without --yes: the retention policy is the operator's call.`;
47
+
48
+ /** Device data dir, resolved the same way the daemon does (`config.ts`). */
49
+ export function resolveDataDir(argv: readonly string[], io: GcIo): string {
50
+ const flag = (name: string) => {
51
+ const i = argv.indexOf(name);
52
+ return i >= 0 ? argv[i + 1] : undefined;
53
+ };
54
+ const envFile = io.env.DPI_ENV_FILE;
55
+ const fileEnv = envFile ? readEnvFile(io.readFile(envFile)) : {};
56
+ const value = (key: string) =>
57
+ io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
58
+ const dataDirArg = flag("--data-dir") ?? value("DPI_DATA_DIR");
59
+ if (dataDirArg) return expand(dataDirArg, io.homedir());
60
+ const home = flag("--home") ?? value("DPI_HOME") ?? join(io.homedir(), ".dpi");
61
+ return join(expand(home, io.homedir()), "backend");
62
+ }
63
+
64
+ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<number> {
65
+ const argv = args.argv;
66
+ if (argv.includes("--help") || argv.includes("-h")) {
67
+ io.print(HELP);
68
+ return 0;
69
+ }
70
+ const known = new Set(["--closed-before", "--dry-run", "--yes", "--home", "--data-dir"]);
71
+ for (const arg of argv) {
72
+ if (arg.startsWith("-") && !known.has(arg)) {
73
+ io.printErr(`dpi gc: unknown flag '${arg}'\n\n${HELP}`);
74
+ return 2;
75
+ }
76
+ }
77
+ const at = argv.indexOf("--closed-before");
78
+ if (at < 0 || !argv[at + 1]) {
79
+ io.printErr(`dpi gc: --closed-before DURATION is required (e.g. 30d)\n\n${HELP}`);
80
+ return 2;
81
+ }
82
+ let days: number;
83
+ try {
84
+ days = parseDuration(argv[at + 1]);
85
+ } catch (e) {
86
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
87
+ return 2;
88
+ }
89
+ const apply = argv.includes("--yes");
90
+ const archiveDir = join(resolveDataDir(argv, io), "archive");
91
+ const options = { closedBeforeDays: days, now: io.now() };
92
+
93
+ if (!apply) {
94
+ const plan = await gcPlan(archiveDir, options);
95
+ io.print(`archive ${archiveDir}`);
96
+ io.print(`keep last ${days}d — ${plan.total.count} archived session(s), ${humanBytes(plan.total.bytes)}`);
97
+ if (!plan.candidates.length) {
98
+ io.print("nothing to delete.");
99
+ } else {
100
+ io.print(`would delete ${plan.candidates.length} session(s), ${humanBytes(plan.candidateBytes)}:`);
101
+ for (const candidate of plan.candidates.slice(0, 20))
102
+ io.print(` ${candidate.sessionId.slice(0, 8)} ${candidate.ageDays}d old ${humanBytes(candidate.bytes)}`);
103
+ if (plan.candidates.length > 20) io.print(` … and ${plan.candidates.length - 20} more`);
104
+ io.print("re-run with --yes to delete.");
105
+ }
106
+ for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
107
+ return 0;
108
+ }
109
+
110
+ const { removed, bytes } = await gcApply(archiveDir, options);
111
+ io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
112
+ return 0;
113
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Retention / auto-GC for archived sessions — checklist Wave 2, policy gate #3.
3
+ *
4
+ * The policy decision (what the defaults should be) is the leader's, so this
5
+ * module ships **no defaults and no timer**: it only answers "what would be
6
+ * deleted" (`gcPlan`) and deletes exactly that, when someone asks for it
7
+ * explicitly. `--dry-run` is the default at the CLI, following piggery's
8
+ * `gc --closed-before DURATION [--dry-run]` shape.
9
+ *
10
+ * An archived session directory is `<archiveDir>/<sessionId>-<closedAtMs>`, so
11
+ * age and size are readable without opening any database.
12
+ */
13
+ import { readdir, rm, stat } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+
16
+ export interface ArchivedEntry {
17
+ /** Directory name inside archive/. */
18
+ name: string;
19
+ path: string;
20
+ /** Session id parsed out of the directory name (the archived session's own id). */
21
+ sessionId: string;
22
+ /** When the session was archived (from the directory name, ms). */
23
+ closedAt: number;
24
+ bytes: number;
25
+ }
26
+
27
+ export interface GcCandidate extends ArchivedEntry {
28
+ /** Whole days since it was archived, as a human reasons about it. */
29
+ ageDays: number;
30
+ }
31
+
32
+ export interface GcPlan {
33
+ /** Everything in archive/. */
34
+ total: { count: number; bytes: number };
35
+ /** What a `closedBeforeDays` cutoff selects. */
36
+ candidates: GcCandidate[];
37
+ candidateBytes: number;
38
+ /** Directories we could not read (kept, never deleted). */
39
+ skipped: { name: string; reason: string }[];
40
+ }
41
+
42
+ async function dirBytes(path: string): Promise<number> {
43
+ let total = 0;
44
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
45
+ const child = join(path, entry.name);
46
+ if (entry.isDirectory()) total += await dirBytes(child);
47
+ else total += await stat(child).then((s) => s.size, () => 0);
48
+ }
49
+ return total;
50
+ }
51
+
52
+ /** Parse `<sessionId>-<closedAtMs>`; anything else is reported as skipped, never guessed at. */
53
+ export function parseArchivedName(name: string): { sessionId: string; closedAt: number } | undefined {
54
+ const match = /^(.+)-(\d{10,})$/u.exec(name);
55
+ if (!match) return undefined;
56
+ const closedAt = Number(match[2]);
57
+ if (!Number.isFinite(closedAt) || closedAt <= 0) return undefined;
58
+ return { sessionId: match[1], closedAt };
59
+ }
60
+
61
+ export async function archivedEntries(archiveDir: string): Promise<{ entries: ArchivedEntry[]; skipped: GcPlan["skipped"] }> {
62
+ const entries: ArchivedEntry[] = [];
63
+ const skipped: GcPlan["skipped"] = [];
64
+ for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
65
+ if (!entry.isDirectory()) continue;
66
+ const parsed = parseArchivedName(entry.name);
67
+ if (!parsed) {
68
+ skipped.push({ name: entry.name, reason: "not an archived-session directory" });
69
+ continue;
70
+ }
71
+ const path = join(archiveDir, entry.name);
72
+ entries.push({ name: entry.name, path, ...parsed, bytes: await dirBytes(path) });
73
+ }
74
+ return { entries: entries.sort((a, b) => b.closedAt - a.closedAt), skipped };
75
+ }
76
+
77
+ /** What a retention policy would delete. Pure read: nothing is touched. */
78
+ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
79
+ const now = options.now ?? Date.now();
80
+ const days = options.closedBeforeDays;
81
+ if (!Number.isFinite(days) || days < 1) throw new Error(`closedBeforeDays must be at least 1, got ${String(days)}`);
82
+ const { entries, skipped } = await archivedEntries(archiveDir);
83
+ const cutoff = now - days * 86_400_000;
84
+ const candidates = entries
85
+ .filter((entry) => entry.closedAt <= cutoff)
86
+ .map((entry) => ({ ...entry, ageDays: Math.floor((now - entry.closedAt) / 86_400_000) }));
87
+ return {
88
+ total: { count: entries.length, bytes: entries.reduce((n, e) => n + e.bytes, 0) },
89
+ candidates,
90
+ candidateBytes: candidates.reduce((n, e) => n + e.bytes, 0),
91
+ skipped,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Delete exactly the candidates the plan named — re-planned at delete time so a
97
+ * session archived between the preview and the delete is never removed by a
98
+ * stale list. Returns what was actually removed.
99
+ */
100
+ export async function gcApply(
101
+ archiveDir: string,
102
+ options: { closedBeforeDays: number; now?: number },
103
+ ): Promise<{ removed: GcCandidate[]; bytes: number }> {
104
+ const plan = await gcPlan(archiveDir, options);
105
+ const removed: GcCandidate[] = [];
106
+ for (const candidate of plan.candidates) {
107
+ try {
108
+ await rm(candidate.path, { recursive: true, force: true });
109
+ removed.push(candidate);
110
+ } catch {
111
+ // A directory that cannot be removed stays in the archive; the next run
112
+ // reports it again rather than pretending it is gone.
113
+ }
114
+ }
115
+ return { removed, bytes: removed.reduce((n, e) => n + e.bytes, 0) };
116
+ }
117
+
118
+ /**
119
+ * "30d", "12h", "90m", "2w" → days (fractional). Days is the unit the plan
120
+ * reasons in, so hours/weeks are converted here rather than refused.
121
+ */
122
+ export function parseDuration(input: string): number {
123
+ const match = /^(\d+(?:\.\d+)?)\s*([smhdw])$/iu.exec(String(input ?? "").trim());
124
+ if (!match) throw new Error(`expected a duration like 30d, 12h or 2w — got ${JSON.stringify(input)}`);
125
+ const value = Number(match[1]);
126
+ const unit = match[2].toLowerCase();
127
+ const days = unit === "s" ? value / 86_400 : unit === "m" ? value / 1440 : unit === "h" ? value / 24 : unit === "w" ? value * 7 : value;
128
+ if (!(days > 0)) throw new Error(`duration must be positive — got ${JSON.stringify(input)}`);
129
+ return days;
130
+ }
131
+
132
+ export function humanBytes(bytes: number): string {
133
+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
134
+ const units = ["B", "KiB", "MiB", "GiB"];
135
+ let value = bytes;
136
+ let unit = 0;
137
+ while (value >= 1024 && unit < units.length - 1) {
138
+ value /= 1024;
139
+ unit += 1;
140
+ }
141
+ return `${value >= 100 || unit === 0 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
142
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * `dpi notify` — outbound notification sinks (webhook / ntfy) from the CLI.
3
+ *
4
+ * Same shape as `dpi schedule`: the CLI edits the device's own records over its
5
+ * local API, so a running daemon picks changes up immediately.
6
+ */
7
+ import { authHeaders, deviceEndpoint, defaultDoctorIo } from "./doctor.js";
8
+ import type { ScheduleIo } from "./schedule-cli.js";
9
+
10
+ export interface SinkView {
11
+ id: string;
12
+ kind: "webhook" | "ntfy";
13
+ url: string;
14
+ enabled: boolean;
15
+ events?: string[];
16
+ label?: string;
17
+ lastDeliveryAt?: number;
18
+ lastError?: string;
19
+ lastStatus?: number;
20
+ }
21
+
22
+ export interface Delivery {
23
+ id: string;
24
+ kind: string;
25
+ status: "sent" | "skipped" | "failed";
26
+ detail?: string;
27
+ }
28
+
29
+ export const NOTIFY_HELP = `dpi notify — outbound notifications (webhook / ntfy)
30
+
31
+ dpi notify list
32
+ dpi notify add --kind webhook|ntfy --url <url> [--events a,b|schedule.*] [--label <text>]
33
+ [--priority min|low|default|high|max] [--tags a,b] [--disabled]
34
+ dpi notify enable|disable <id-prefix>
35
+ dpi notify remove <id-prefix>
36
+ dpi notify test
37
+ dpi notify events
38
+ The event kinds this device emits today.
39
+
40
+ LAN sinks (http://192.168.x.x, http://localhost) are refused by default:
41
+ start the device with DPI_NOTIFY_ALLOW_PRIVATE=1 to allow them.`;
42
+
43
+ export const EMITTED_EVENTS = ["session.failed", "schedule.ok", "schedule.failed", "test"] as const;
44
+
45
+ export const defaultNotifyIo = (): ScheduleIo => ({
46
+ ...defaultDoctorIo(),
47
+ print: (line) => process.stdout.write(`${line}\n`),
48
+ printErr: (line) => process.stderr.write(`${line}\n`),
49
+ });
50
+
51
+ const flag = (argv: readonly string[], name: string): string | undefined => {
52
+ const i = argv.indexOf(name);
53
+ return i >= 0 ? argv[i + 1] : undefined;
54
+ };
55
+ const positional = (argv: readonly string[]): string[] =>
56
+ argv.filter((arg, i) => !arg.startsWith("--") && !(i > 0 && argv[i - 1]?.startsWith("--")));
57
+
58
+ async function call<T>(
59
+ io: ScheduleIo,
60
+ method: string,
61
+ path: string,
62
+ body?: unknown,
63
+ ): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
64
+ const cfg = deviceEndpoint(io);
65
+ if (!cfg.token) return { ok: false, error: `no DPI_TOKEN (looked in ${cfg.envFile})` };
66
+ try {
67
+ const res = await io.fetchImpl(`${cfg.baseUrl}${path}`, {
68
+ method,
69
+ headers: {
70
+ ...authHeaders(cfg.token),
71
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
72
+ },
73
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
74
+ signal: AbortSignal.timeout(io.timeoutMs),
75
+ });
76
+ const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
77
+ if (!res.ok) return { ok: false, error: `${res.status} ${(data.error as { message?: string })?.message ?? ""}`.trim() };
78
+ return { ok: true, data: data as T };
79
+ } catch (e) {
80
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
81
+ }
82
+ }
83
+
84
+ const ago = (at?: number): string => {
85
+ if (!at) return "never";
86
+ const mins = Math.round((Date.now() - at) / 60_000);
87
+ return mins < 1 ? "just now" : mins < 60 ? `${mins}m ago` : `${Math.round(mins / 60)}h ago`;
88
+ };
89
+
90
+ export function formatSinks(list: readonly SinkView[]): string[] {
91
+ if (!list.length) return ["no sinks. Add one with `dpi notify add --url <url> --kind webhook|ntfy`."];
92
+ return list.map((s) => {
93
+ const filters = s.events?.length ? s.events.join(",") : "all events";
94
+ const last = s.lastError ? `last failed: ${s.lastError.slice(0, 60)}` : `last sent ${ago(s.lastDeliveryAt)}`;
95
+ return `${s.id.slice(0, 8)} ${s.kind} ${s.enabled ? "" : "(disabled) "}${s.label ?? ""}\n ${s.url}\n ${filters} · ${last}`;
96
+ });
97
+ }
98
+
99
+ export function matchSink(list: readonly SinkView[], prefix: string): SinkView[] {
100
+ const needle = prefix.toLowerCase();
101
+ return list.filter((s) => s.id.toLowerCase().startsWith(needle));
102
+ }
103
+
104
+ export function formatResults(results: readonly Delivery[]): string[] {
105
+ if (!results.length) return ["no enabled sinks matched — nothing was sent."];
106
+ return results.map((r) => {
107
+ const tail = r.detail ? ` — ${r.detail}` : "";
108
+ return `${r.status.padEnd(7)} ${r.kind} ${r.id.slice(0, 8)}${tail}`;
109
+ });
110
+ }
111
+
112
+ export async function notifyCli(argv: readonly string[], io: ScheduleIo = defaultNotifyIo()): Promise<number> {
113
+ const [sub, ...rest] = argv;
114
+ if (sub === "--help" || sub === "-h") {
115
+ io.print(NOTIFY_HELP);
116
+ return 0;
117
+ }
118
+ if (sub === "events") {
119
+ io.print(`events this device emits: ${EMITTED_EVENTS.join(", ")}`);
120
+ return 0;
121
+ }
122
+ if (!sub || sub === "list") {
123
+ const listed = await call<{ sinks: SinkView[] }>(io, "GET", "/v1/notify/sinks");
124
+ if (!listed.ok) {
125
+ io.printErr(`dpi notify: ${listed.error}`);
126
+ return 1;
127
+ }
128
+ for (const line of formatSinks(listed.data.sinks ?? [])) io.print(line);
129
+ return 0;
130
+ }
131
+
132
+ if (sub === "test") {
133
+ const sent = await call<{ results: Delivery[] }>(io, "POST", "/v1/notify/test", {});
134
+ if (!sent.ok) {
135
+ io.printErr(`dpi notify: ${sent.error}`);
136
+ return 1;
137
+ }
138
+ for (const line of formatResults(sent.data.results ?? [])) io.print(line);
139
+ return (sent.data.results ?? []).some((r) => r.status === "failed") ? 1 : 0;
140
+ }
141
+
142
+ if (sub === "add") {
143
+ const kind = flag(rest, "--kind") ?? "webhook";
144
+ const url = flag(rest, "--url");
145
+ if (!url || (kind !== "webhook" && kind !== "ntfy")) {
146
+ io.printErr(`dpi notify add: --url is required and --kind is webhook|ntfy\n\n${NOTIFY_HELP}`);
147
+ return 2;
148
+ }
149
+ const events = flag(rest, "--events");
150
+ const tags = flag(rest, "--tags");
151
+ const body = {
152
+ kind,
153
+ url,
154
+ ...(flag(rest, "--label") ? { label: flag(rest, "--label") } : {}),
155
+ ...(events ? { events: events.split(",").map((e) => e.trim()).filter(Boolean) } : {}),
156
+ ...(flag(rest, "--priority") ? { priority: flag(rest, "--priority") } : {}),
157
+ ...(tags ? { tags: tags.split(",").map((t) => t.trim()).filter(Boolean) } : {}),
158
+ ...(rest.includes("--disabled") ? { enabled: false } : {}),
159
+ };
160
+ const created = await call<SinkView>(io, "POST", "/v1/notify/sinks", body);
161
+ if (!created.ok) {
162
+ io.printErr(`dpi notify: ${created.error}`);
163
+ return 1;
164
+ }
165
+ io.print(`created ${created.data.id.slice(0, 8)} — ${created.data.kind} ${created.data.url}`);
166
+ return 0;
167
+ }
168
+
169
+ const prefix = positional(rest)[0];
170
+ if (!prefix) {
171
+ io.printErr(`dpi notify ${sub}: an id prefix is required\n\n${NOTIFY_HELP}`);
172
+ return 2;
173
+ }
174
+ const listed = await call<{ sinks: SinkView[] }>(io, "GET", "/v1/notify/sinks");
175
+ if (!listed.ok) {
176
+ io.printErr(`dpi notify: ${listed.error}`);
177
+ return 1;
178
+ }
179
+ const matches = matchSink(listed.data.sinks ?? [], prefix);
180
+ if (!matches.length) {
181
+ io.printErr(`dpi notify: no sink starts with '${prefix}'`);
182
+ return 1;
183
+ }
184
+ if (matches.length > 1) {
185
+ io.printErr(`dpi notify: '${prefix}' matches ${matches.length} sinks — be more specific:`);
186
+ for (const m of matches) io.printErr(` ${m.id.slice(0, 8)} ${m.kind} ${m.url}`);
187
+ return 2;
188
+ }
189
+ const target = matches[0];
190
+
191
+ if (sub === "enable" || sub === "disable") {
192
+ const patched = await call<SinkView>(io, "PATCH", `/v1/notify/sinks/${target.id}`, { enabled: sub === "enable" });
193
+ if (!patched.ok) {
194
+ io.printErr(`dpi notify: ${patched.error}`);
195
+ return 1;
196
+ }
197
+ io.print(`${sub}d ${target.id.slice(0, 8)} — ${target.kind} ${target.url}`);
198
+ return 0;
199
+ }
200
+ if (sub === "remove") {
201
+ const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/notify/sinks/${target.id}`);
202
+ if (!removed.ok) {
203
+ io.printErr(`dpi notify: ${removed.error}`);
204
+ return 1;
205
+ }
206
+ io.print(`removed ${target.id.slice(0, 8)} — ${target.url}`);
207
+ return 0;
208
+ }
209
+ io.printErr(`dpi notify: unknown subcommand '${sub}'\n\n${NOTIFY_HELP}`);
210
+ return 2;
211
+ }