my-durable 0.0.39 → 0.0.40

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 (24) hide show
  1. package/apps/dpi-backend/src/doctor.ts +10 -8
  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/routes.ts +9 -0
  5. package/apps/dpi-backend/src/schedule-cli.ts +211 -0
  6. package/apps/dpi-backend/src/schedules.ts +676 -0
  7. package/apps/dpi-backend/src/store.ts +151 -0
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMJMesxP.css +1 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jDhVa5sg.js +81 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +2 -0
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +4 -0
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +4 -0
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +289 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +13 -1
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +20 -1
  17. package/apps/dpi-sdk/src/api.ts +46 -0
  18. package/apps/dpi-sdk/src/client.ts +18 -0
  19. package/apps/dpi-sdk/src/protocol/rest-routes.ts +6 -0
  20. package/bin/dpi.mjs +15 -0
  21. package/docs/host-project-checklist.md +4 -4
  22. package/package.json +1 -1
  23. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CYZxCPDU.js +0 -81
  24. 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})` };
@@ -294,7 +296,7 @@ async function probeCheck(io: DoctorIo, cfg: Merged, reachable: boolean): Promis
294
296
  }
295
297
 
296
298
  /** 5. hub — only when this device actually has one. */
297
- async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
299
+ async function hubCheck(io: DoctorIo, cfg: DeviceEndpoint): Promise<DoctorCheck> {
298
300
  const id = "hub";
299
301
  let origin = (cfg.env.DPI_HUB_URL ?? "").trim().replace(/\/+$/, "");
300
302
  const source = origin ? "DPI_HUB_URL" : "pairing.json";
@@ -327,7 +329,7 @@ async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
327
329
  /** 2. healthz — is the daemon there at all. */
328
330
  async function healthzCheck(
329
331
  io: DoctorIo,
330
- cfg: Merged,
332
+ cfg: DeviceEndpoint,
331
333
  ): Promise<{ check: DoctorCheck; reachable: boolean }> {
332
334
  const url = `${cfg.baseUrl}/healthz`;
333
335
  const label = `healthz ${url}`;
@@ -349,7 +351,7 @@ async function healthzCheck(
349
351
  /** Run every check. Warnings never make `ok` false; only a FAIL does. */
350
352
  export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorReport> {
351
353
  const io: DoctorIo = { ...defaultDoctorIo(), ...opts };
352
- const cfg = mergedConfig(io);
354
+ const cfg = deviceEndpoint(io);
353
355
 
354
356
  const checks: DoctorCheck[] = [nodeCheck(io)];
355
357
  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
+ }
@@ -188,6 +188,15 @@ export function v1(
188
188
  r.post("/projects/:id/archive", route(async (req, res) => res.json(await store.archiveProject(param(req, "id")))));
189
189
  r.post("/projects/:id/unarchive", route(async (req, res) => res.json(await store.unarchiveProject(param(req, "id")))));
190
190
 
191
+ // -------------------------------------------------------- schedules
192
+ // The device owns execution (systemd/cron are deliberately rejected by config);
193
+ // these routes only read and edit the schedule records.
194
+ r.get("/schedules", (_req, res) => res.json({ schedules: store.scheduleList() }));
195
+ r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
196
+ r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
197
+ r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
198
+ r.post("/schedules/:id/run", route(async (req, res) => res.json(await store.runScheduleNow(param(req, "id")))));
199
+
191
200
  // ---------------------------------------------------------- sessions
192
201
  r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
193
202
  r.post("/sessions", create, route(async (req, res) => res.status(201).json(await store.create(req.body ?? {}))));
@@ -0,0 +1,211 @@
1
+ /**
2
+ * `dpi schedule` — scheduled sessions from the CLI (checklist Wave 2).
3
+ *
4
+ * The device owns the clock: this command only edits and reads the schedule
5
+ * records over the local device API, so the running daemon picks changes up
6
+ * without a restart. Same endpoint resolution as `dpi doctor`.
7
+ */
8
+ import { authHeaders, deviceEndpoint, defaultDoctorIo, type DoctorIo } from "./doctor.js";
9
+
10
+ export interface ScheduleView {
11
+ id: string;
12
+ name: string;
13
+ cwd: string;
14
+ model: { provider: string; modelId: string };
15
+ prompt: string;
16
+ everyMinutes?: number;
17
+ dailyAt?: string;
18
+ enabled: boolean;
19
+ nextRunAt: number | null;
20
+ lastRunAt?: number;
21
+ lastSessionId?: string;
22
+ lastOutcome?: "ok" | "failed";
23
+ lastError?: string;
24
+ running: boolean;
25
+ }
26
+
27
+ export const SCHEDULE_HELP = `dpi schedule — scheduled sessions (the device owns the clock)
28
+
29
+ dpi schedule list
30
+ dpi schedule add --name <name> --cwd <dir> --prompt <text> --model <provider>/<model>
31
+ (--every <minutes> | --daily HH:MM) [--disabled]
32
+ dpi schedule enable|disable <id-prefix>
33
+ dpi schedule run <id-prefix>
34
+ dpi schedule remove <id-prefix>
35
+
36
+ --every N interval trigger, 5–1440 minutes
37
+ --daily HH:MM daily trigger, local time
38
+ A run creates a fresh session (named "<schedule> · <time>") and sends the prompt
39
+ to its root agent.`;
40
+
41
+ /** doctor's IO (env file, token, fetch) plus the two print hooks a CLI needs. */
42
+ export interface ScheduleIo extends DoctorIo {
43
+ print: (line: string) => void;
44
+ printErr: (line: string) => void;
45
+ }
46
+
47
+ export const defaultScheduleIo = (): ScheduleIo => ({
48
+ ...defaultDoctorIo(),
49
+ print: (line) => process.stdout.write(`${line}\n`),
50
+ printErr: (line) => process.stderr.write(`${line}\n`),
51
+ });
52
+
53
+ const flag = (argv: readonly string[], name: string): string | undefined => {
54
+ const i = argv.indexOf(name);
55
+ return i >= 0 ? argv[i + 1] : undefined;
56
+ };
57
+ const positional = (argv: readonly string[]): string[] =>
58
+ argv.filter((arg, i) => !arg.startsWith("--") && !(i > 0 && argv[i - 1]?.startsWith("--")));
59
+
60
+ async function call<T>(
61
+ io: ScheduleIo,
62
+ method: string,
63
+ path: string,
64
+ body?: unknown,
65
+ ): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
66
+ const cfg = deviceEndpoint(io);
67
+ if (!cfg.token) return { ok: false, error: `no DPI_TOKEN (looked in ${cfg.envFile})` };
68
+ try {
69
+ const res = await io.fetchImpl(`${cfg.baseUrl}${path}`, {
70
+ method,
71
+ headers: {
72
+ ...authHeaders(cfg.token),
73
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
74
+ },
75
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
76
+ signal: AbortSignal.timeout(io.timeoutMs),
77
+ });
78
+ const parsed = (await res.json().catch(() => ({}))) as Record<string, unknown>;
79
+ if (!res.ok) return { ok: false, error: `${res.status} ${(parsed as { error?: { message?: string } })?.error?.message ?? ""}`.trim() };
80
+ return { ok: true, data: parsed as T };
81
+ } catch (e) {
82
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
83
+ }
84
+ }
85
+
86
+ const when = (at: number | null | undefined): string => {
87
+ if (!at) return "—";
88
+ const delta = at - Date.now();
89
+ const mins = Math.round(Math.abs(delta) / 60_000);
90
+ const human = mins < 60 ? `${mins}m` : mins < 1440 ? `${Math.round(mins / 60)}h` : `${Math.round(mins / 1440)}d`;
91
+ return delta >= 0 ? `in ${human}` : `${human} ago`;
92
+ };
93
+
94
+ const trigger = (s: ScheduleView) => (s.everyMinutes ? `every ${s.everyMinutes}m` : `daily ${s.dailyAt}`);
95
+
96
+ export function formatSchedules(list: readonly ScheduleView[]): string[] {
97
+ if (!list.length) return ["no schedules. Add one with `dpi schedule add --help`."];
98
+ return list.map((s) => {
99
+ const state = !s.enabled ? "disabled" : s.running ? "running" : "enabled";
100
+ const outcome = s.lastOutcome ? ` last ${s.lastOutcome}${s.lastError ? ` (${s.lastError.slice(0, 40)})` : ""}` : "";
101
+ return `${s.id.slice(0, 8)} ${s.name} — ${trigger(s)}, ${state}, next ${when(s.nextRunAt)}${outcome}\n ${s.cwd}`;
102
+ });
103
+ }
104
+
105
+ /** Resolve an id prefix the way a human types it (`dpi schedule run 3f2a`). */
106
+ export function matchSchedule(list: readonly ScheduleView[], prefix: string): ScheduleView[] {
107
+ const needle = prefix.toLowerCase();
108
+ return list.filter((s) => s.id.toLowerCase().startsWith(needle));
109
+ }
110
+
111
+ export async function scheduleCli(argv: readonly string[], io: ScheduleIo = defaultScheduleIo()): Promise<number> {
112
+ const [sub, ...rest] = argv;
113
+ if (sub === "--help" || sub === "-h") {
114
+ io.print(SCHEDULE_HELP);
115
+ return 0;
116
+ }
117
+ // No subcommand lists, like `dpi device` with no verb shows the device.
118
+ if (!sub || sub === "list") {
119
+ const listed = await call<{ schedules: ScheduleView[] }>(io, "GET", "/v1/schedules");
120
+ if (!listed.ok) {
121
+ io.printErr(`dpi schedule: ${listed.error}`);
122
+ return 1;
123
+ }
124
+ for (const line of formatSchedules(listed.data.schedules ?? [])) io.print(line);
125
+ return 0;
126
+ }
127
+
128
+ if (sub === "add") {
129
+ const every = flag(rest, "--every");
130
+ const daily = flag(rest, "--daily");
131
+ const body = {
132
+ name: flag(rest, "--name"),
133
+ cwd: flag(rest, "--cwd"),
134
+ prompt: flag(rest, "--prompt"),
135
+ model: (() => {
136
+ const raw = flag(rest, "--model") ?? "";
137
+ const slash = raw.indexOf("/");
138
+ return slash > 0 ? { provider: raw.slice(0, slash), modelId: raw.slice(slash + 1) } : undefined;
139
+ })(),
140
+ ...(every ? { everyMinutes: Number(every) } : {}),
141
+ ...(daily ? { dailyAt: daily } : {}),
142
+ ...(rest.includes("--disabled") ? { enabled: false } : {}),
143
+ };
144
+ if (!body.name || !body.cwd || !body.prompt || !body.model) {
145
+ io.printErr(`dpi schedule add: --name, --cwd, --prompt and --model are required\n\n${SCHEDULE_HELP}`);
146
+ return 2;
147
+ }
148
+ const created = await call<ScheduleView>(io, "POST", "/v1/schedules", body);
149
+ if (!created.ok) {
150
+ io.printErr(`dpi schedule: ${created.error}`);
151
+ return 1;
152
+ }
153
+ io.print(`created ${created.data.id.slice(0, 8)} — ${created.data.name}, ${trigger(created.data)}, next ${when(created.data.nextRunAt)}`);
154
+ return 0;
155
+ }
156
+
157
+ const prefix = positional(rest)[0];
158
+ if (!prefix) {
159
+ io.printErr(`dpi schedule ${sub}: an id prefix is required\n\n${SCHEDULE_HELP}`);
160
+ return 2;
161
+ }
162
+ const listed = await call<{ schedules: ScheduleView[] }>(io, "GET", "/v1/schedules");
163
+ if (!listed.ok) {
164
+ io.printErr(`dpi schedule: ${listed.error}`);
165
+ return 1;
166
+ }
167
+ const matches = matchSchedule(listed.data.schedules ?? [], prefix);
168
+ if (!matches.length) {
169
+ io.printErr(`dpi schedule: no schedule starts with '${prefix}'`);
170
+ return 1;
171
+ }
172
+ if (matches.length > 1) {
173
+ io.printErr(`dpi schedule: '${prefix}' matches ${matches.length} schedules — be more specific:`);
174
+ for (const m of matches) io.printErr(` ${m.id.slice(0, 8)} ${m.name}`);
175
+ return 2;
176
+ }
177
+ const target = matches[0];
178
+
179
+ if (sub === "enable" || sub === "disable") {
180
+ const patched = await call<ScheduleView>(io, "PATCH", `/v1/schedules/${target.id}`, {
181
+ enabled: sub === "enable",
182
+ });
183
+ if (!patched.ok) {
184
+ io.printErr(`dpi schedule: ${patched.error}`);
185
+ return 1;
186
+ }
187
+ io.print(`${sub}d ${target.id.slice(0, 8)} — next ${when(patched.data.nextRunAt)}`);
188
+ return 0;
189
+ }
190
+ if (sub === "run") {
191
+ io.print(`${target.name}: running…`);
192
+ const ran = await call<ScheduleView>(io, "POST", `/v1/schedules/${target.id}/run`, {});
193
+ if (!ran.ok) {
194
+ io.printErr(`dpi schedule: ${ran.error}`);
195
+ return 1;
196
+ }
197
+ io.print(`${ran.data.lastOutcome ?? "ok"}${ran.data.lastError ? ` — ${ran.data.lastError}` : ""}; next ${when(ran.data.nextRunAt)}`);
198
+ return ran.data.lastOutcome === "failed" ? 1 : 0;
199
+ }
200
+ if (sub === "remove") {
201
+ const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/schedules/${target.id}`);
202
+ if (!removed.ok) {
203
+ io.printErr(`dpi schedule: ${removed.error}`);
204
+ return 1;
205
+ }
206
+ io.print(`removed ${target.id.slice(0, 8)} — ${target.name}`);
207
+ return 0;
208
+ }
209
+ io.printErr(`dpi schedule: unknown subcommand '${sub}'\n\n${SCHEDULE_HELP}`);
210
+ return 2;
211
+ }