my-durable 0.0.38 → 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 (28) 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/projects.ts +587 -0
  5. package/apps/dpi-backend/src/routes.ts +27 -0
  6. package/apps/dpi-backend/src/schedule-cli.ts +211 -0
  7. package/apps/dpi-backend/src/schedules.ts +676 -0
  8. package/apps/dpi-backend/src/store.ts +304 -2
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMJMesxP.css +1 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jDhVa5sg.js +81 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +2 -0
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +4 -0
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +8 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +23 -1
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +284 -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-fe/src/components/UsagePanel.vue +406 -0
  20. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +20 -1
  21. package/apps/dpi-sdk/src/api.ts +100 -0
  22. package/apps/dpi-sdk/src/client.ts +42 -0
  23. package/apps/dpi-sdk/src/protocol/rest-routes.ts +12 -0
  24. package/bin/dpi.mjs +15 -0
  25. package/docs/host-project-checklist.md +6 -6
  26. package/package.json +1 -1
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D4M8tCcs.js +0 -81
  28. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-xOvj8ub1.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
+ }