my-durable 0.0.40 → 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.
@@ -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. */
@@ -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
+ }