my-durable 0.0.58 → 0.0.60

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 (36) hide show
  1. package/apps/dpi-backend/src/daemon.ts +48 -0
  2. package/apps/dpi-backend/src/doctor.ts +17 -4
  3. package/apps/dpi-backend/src/errors.ts +68 -1
  4. package/apps/dpi-backend/src/gc-cli.ts +52 -19
  5. package/apps/dpi-backend/src/gc.ts +3 -1
  6. package/apps/dpi-backend/src/main.ts +23 -3
  7. package/apps/dpi-backend/src/pi-config.ts +15 -6
  8. package/apps/dpi-backend/src/store.ts +220 -22
  9. package/apps/dpi-backend/src/tunnel.ts +24 -2
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-4Kyozhl0.js +81 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DxGrKN6X.css → index-BkSQ2clA.css} +1 -1
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/App.vue +9 -2
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/dialog-escape.ts +13 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +70 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/state-draft.ts +72 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +15 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ContextBar.vue +14 -3
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +82 -69
  20. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +22 -4
  21. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PromptDialog.vue +3 -0
  22. package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +19 -0
  23. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +72 -30
  24. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
  25. package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +38 -17
  26. package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
  27. package/apps/dpi-tui/src/app.ts +108 -25
  28. package/apps/dpi-tui/src/commands.ts +16 -8
  29. package/apps/dpi-tui/src/main.ts +46 -19
  30. package/apps/dpi-tui/src/pickers.ts +4 -0
  31. package/apps/dpi-tui/src/scroll.ts +59 -0
  32. package/apps/dpi-tui/src/views.ts +17 -2
  33. package/apps/dpi-tui/src/wrap.ts +42 -0
  34. package/bin/dpi.mjs +83 -0
  35. package/package.json +1 -1
  36. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DC0Iicch.js +0 -81
@@ -172,6 +172,43 @@ const execDefault = (cmd: string, args: string[]) =>
172
172
 
173
173
  const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
174
174
 
175
+ /** R6 cli finding 10: `dpi device stop` twice hung 40s+ with zero output while
176
+ * the daemon stayed healthy. No shutdown step may block forever: race the
177
+ * step against a ceiling; on expiry say so and CONTINUE (the shutdown caller
178
+ * still force-exits). A step that throws rejects normally — only the hang is
179
+ * bounded. Exported so the sequencing is unit-testable. */
180
+ export async function boundedStep<T>(
181
+ label: string,
182
+ ms: number,
183
+ run: () => T | Promise<T>,
184
+ log: (line: string) => void = () => {},
185
+ ): Promise<T | undefined> {
186
+ let done = false;
187
+ let failed: { error: unknown } | undefined;
188
+ const step = Promise.resolve(run()).then(
189
+ (v) => {
190
+ done = true;
191
+ return v;
192
+ },
193
+ (error: unknown) => {
194
+ done = true;
195
+ failed = { error };
196
+ },
197
+ );
198
+ let timer: NodeJS.Timeout | undefined;
199
+ const ceiling = new Promise<void>((resolve) => {
200
+ timer = setTimeout(() => resolve(), ms);
201
+ });
202
+ await Promise.race([step, ceiling]);
203
+ if (timer) clearTimeout(timer);
204
+ if (!done) {
205
+ log(`shutdown: ${label} did not finish within ${ms}ms — continuing without it`);
206
+ return undefined;
207
+ }
208
+ if (failed) throw failed.error;
209
+ return (await step) as T;
210
+ }
211
+
175
212
  function ioOf(opts: RunOpts): Io {
176
213
  return {
177
214
  env: opts.env ?? process.env,
@@ -385,6 +422,17 @@ async function cmdInstall(io: Io): Promise<number> {
385
422
  if (!env.DPI_HOME) env.DPI_HOME = daemonPaths(io.env).home;
386
423
  if (p === "linux") {
387
424
  const unit = join(homedir(), ".config/systemd/user/dpi-device.service");
425
+ // R6 cli finding 8: probe systemd BEFORE writing anything. A host without a
426
+ // user systemd (containers, non-systemd distros) used to get a stray unit
427
+ // file plus an empty "systemctl enable failed:" — daemon-reload is the same
428
+ // first step a real install takes, so it is the honest probe.
429
+ const probe = await io.exec("systemctl", ["--user", "daemon-reload"]);
430
+ if (!probe.ok) {
431
+ const reason = probe.output.trim().split("\n")[0] || "systemctl is not usable on this host";
432
+ io.print(`no systemd --user on this host — nothing was installed (${reason})`);
433
+ io.print("start the daemon after login instead: dpi device start");
434
+ return 1;
435
+ }
388
436
  await io.writeFile(unit, systemdUnit({ node, dpi, env }));
389
437
  await io.exec("systemctl", ["--user", "daemon-reload"]);
390
438
  const enable = await io.exec("systemctl", ["--user", "enable", "--now", "dpi-device.service"]);
@@ -131,6 +131,11 @@ export function splitModel(
131
131
  ): { provider: string; modelId: string } | undefined {
132
132
  const exact = models?.find((m) => `${m.provider}/${m.id}` === defaultModel);
133
133
  if (exact) return { provider: exact.provider, modelId: exact.id };
134
+ // R6 cli finding 7: local catalogs (faux provider) report a BARE id as the
135
+ // defaultModel — match it against models[].id before the split heuristic so
136
+ // healthy faux devices stop warning "no usable defaultModel".
137
+ const bare = models?.find((m) => m.id === defaultModel && m.provider);
138
+ if (bare) return { provider: bare.provider, modelId: bare.id };
134
139
  const i = defaultModel.indexOf("/");
135
140
  if (i <= 0 || i === defaultModel.length - 1) return undefined;
136
141
  return { provider: defaultModel.slice(0, i), modelId: defaultModel.slice(i + 1) };
@@ -321,13 +326,21 @@ async function hubCheck(io: DoctorIo, cfg: DeviceEndpoint): Promise<DoctorCheck>
321
326
  const source = origin ? "DPI_HUB_URL" : "pairing.json";
322
327
  if (!origin) {
323
328
  const file = join(cfg.home, "pairing.json");
324
- try {
325
- if (io.exists(file)) {
329
+ if (io.exists(file)) {
330
+ try {
326
331
  const paired = JSON.parse(io.readFile(file)) as { hubOrigin?: unknown };
327
332
  if (typeof paired.hubOrigin === "string") origin = paired.hubOrigin.trim().replace(/\/+$/, "");
333
+ } catch (error) {
334
+ // R6 cli finding 6: a corrupt/unreadable pairing file is NOT "no hub
335
+ // configured" — the operator must learn the file is broken, because
336
+ // the hub check cannot run at all until it is fixed.
337
+ return {
338
+ id,
339
+ label: "hub",
340
+ status: "warn",
341
+ detail: `pairing.json is corrupt/unreadable — fix or delete ${file} (${describeError(error, 0)})`,
342
+ };
328
343
  }
329
- } catch {
330
- /* unreadable/garbled pairing file: report as not configured */
331
344
  }
332
345
  }
333
346
  if (!origin) return { id, label: "hub", status: "skip", detail: "no hub configured (no DPI_HUB_URL, no saved pairing)" };
@@ -1,5 +1,5 @@
1
1
  import type { ErrorRequestHandler } from "express";
2
- import { ConversationBusy, SessionFailed } from "@earendil-works/pi-durable";
2
+ import { ConversationBusy, SessionFailed, StorageRequestError } from "@earendil-works/pi-durable";
3
3
  import type { ErrorCode } from "../../dpi-sdk/src/api.js";
4
4
  import { ScheduleRegistryError } from "./schedules.js";
5
5
  import { GraphError } from "./graphs.js";
@@ -36,6 +36,58 @@ export class ApiFault extends Error {
36
36
  export const invalid = (message: string) => new ApiFault("invalid", message);
37
37
  export const notFound = (message: string) => new ApiFault("not_found", message);
38
38
 
39
+ /**
40
+ * SQLite faults, mapped to bounded client-facing text (R5 finding 5): node:sqlite
41
+ * reports plain Errors with `code: "ERR_SQLITE_ERROR"` and a numeric `errcode`
42
+ * (5=BUSY, 6=LOCKED, 8=READONLY, 11=CORRUPT, 26=NOTADB). The raw message
43
+ * ("database is locked", "no such column: …") must never reach a client.
44
+ */
45
+ const SQLITE_BUSY = 5;
46
+ const SQLITE_LOCKED = 6;
47
+ const SQLITE_CORRUPT = 11;
48
+ const SQLITE_NOTADB = 26;
49
+
50
+ const sqliteCode = (err: unknown): string | undefined =>
51
+ err instanceof Error ? (err as { code?: unknown }).code as string | undefined : undefined;
52
+
53
+ export const isSqliteError = (err: unknown): err is Error & { errcode?: number } =>
54
+ sqliteCode(err) === "ERR_SQLITE_ERROR" && err instanceof Error;
55
+
56
+ const sqliteErrcode = (err: Error & { errcode?: number }): number | undefined =>
57
+ typeof err.errcode === "number" ? err.errcode : undefined;
58
+
59
+ /** True when a failure means "another connection holds the database" — retryable, not fatal. */
60
+ export const isStorageBusy = (err: unknown): boolean => {
61
+ if (!isSqliteError(err)) return false;
62
+ const errcode = sqliteErrcode(err);
63
+ return errcode === SQLITE_BUSY || errcode === SQLITE_LOCKED || /database (is|table is) locked/i.test(err.message);
64
+ };
65
+
66
+ /** The one retryable storage fault (R5 finding 1): 503, temporary, no sqlite internals. */
67
+ export const storageBusyFault = (): ApiFault =>
68
+ new ApiFault("unavailable", "The device's storage is busy; this failure is temporary — retry shortly");
69
+
70
+ /** True when the database FILE itself is unreadable (corrupt header / not a database / foreign format). */
71
+ export const isUnreadableStorage = (err: unknown): boolean => {
72
+ if (!isSqliteError(err)) return false;
73
+ const errcode = sqliteErrcode(err);
74
+ return (
75
+ errcode === SQLITE_CORRUPT ||
76
+ errcode === SQLITE_NOTADB ||
77
+ /file is not a database|disk image is malformed|unsupported file format/i.test(err.message)
78
+ );
79
+ };
80
+
81
+ /** Map any sqlite error to a bounded typed fault; the raw message never leaves the server. */
82
+ const sqliteFault = (err: Error & { errcode?: number }): ApiFault => {
83
+ if (isStorageBusy(err)) return storageBusyFault();
84
+ if (isUnreadableStorage(err))
85
+ return new ApiFault("unavailable", "The device's storage is unreadable; restart the device to quarantine the corrupt file and rebuild");
86
+ if (/^no such (table|column):/i.test(err.message) || /^unknown column/i.test(err.message))
87
+ return new ApiFault("unavailable", "The device's storage schema does not match this build; restart the device to migrate");
88
+ return new ApiFault("unavailable", "A storage operation failed; retry, or restart the device if it persists");
89
+ };
90
+
39
91
  /** Typed registry failures carry their own 4xx code (`invalid`/`not_found`) — map them
40
92
  * to the matching status with the message intact, instead of a 500 "internal". */
41
93
  const registryFault = (err: unknown): ApiFault | undefined => {
@@ -59,9 +111,24 @@ export const errorMiddleware: ErrorRequestHandler = (err, req, res, _next) => {
59
111
  else if (err instanceof SessionFailed)
60
112
  fault = new ApiFault("unavailable", "The session failed and is closed; it is unavailable until reopened");
61
113
  else if (err instanceof ConversationBusy) fault = new ApiFault("busy", "The agent is busy and the input asked to be rejected while busy");
114
+ // pi-durable's typed "this storage READ was malformed" class (a cursor from
115
+ // another scan, an unknown id): caller error whatever the message text. The
116
+ // old mapping keyed on the message-prefix regex below, so only "Invalid…"
117
+ // wordings scored 400 and any other message leaked as a 500 with raw
118
+ // internal text.
119
+ else if (err instanceof StorageRequestError) fault = invalid(err.message);
62
120
  else if (err?.type === "entity.parse.failed") fault = invalid("Body must be valid JSON");
63
121
  else if (err?.type === "entity.too.large") fault = invalid("Body too large");
122
+ // SQLite faults get a bounded typed shape (R5 finding 5) — before any message
123
+ // regex could touch them, and with the full error still logged server-side.
124
+ else if (isSqliteError(err)) {
125
+ console.error(`[dpi-backend] ${req.method} ${req.path}: storage error:`, err.stack);
126
+ fault = sqliteFault(err);
127
+ }
64
128
  else if (/App State changed while you were editing/.test(String(err?.message))) fault = new ApiFault("conflict", err.message);
129
+ // Message-prefix fallback for dpi-sdk's app-state validation Errors
130
+ // (dpi-sdk/src/app-state.ts throws plain Error with no class of its own).
131
+ // Typed classes are mapped above by instanceof — nothing else relies on this.
65
132
  else if (err instanceof Error && /^(Field|Invalid|Use a JSON Pointer|Increment|The state root|State path|Parent must|Value must|Reserved field|App State must|State is too)/.test(err.message))
66
133
  fault = invalid(err.message);
67
134
  else {
@@ -52,7 +52,25 @@ export function resolveDataDir(argv: readonly string[], io: GcIo): string {
52
52
  return i >= 0 ? argv[i + 1] : undefined;
53
53
  };
54
54
  const envFile = io.env.DPI_ENV_FILE;
55
- const fileEnv = envFile ? readEnvFile(io.readFile(envFile)) : {};
55
+ let fileEnv: Record<string, string> = {};
56
+ if (envFile) {
57
+ // R6 cli finding 2: a missing/unreadable env file used to escape as a raw
58
+ // ENOENT/EACCES stack from deep inside resolution — say it in one line.
59
+ try {
60
+ fileEnv = readEnvFile(io.readFile(envFile));
61
+ } catch (e) {
62
+ const code = (e as NodeJS.ErrnoException)?.code;
63
+ const why =
64
+ code === "ENOENT"
65
+ ? "the file does not exist"
66
+ : code === "EACCES"
67
+ ? "the file is not readable"
68
+ : e instanceof Error
69
+ ? e.message
70
+ : String(e);
71
+ throw new Error(`cannot read DPI_ENV_FILE '${envFile}' — ${why}`);
72
+ }
73
+ }
56
74
  const value = (key: string) =>
57
75
  io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
58
76
  const dataDirArg = flag("--data-dir") ?? value("DPI_DATA_DIR");
@@ -87,27 +105,42 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
87
105
  return 2;
88
106
  }
89
107
  const apply = argv.includes("--yes");
90
- const archiveDir = join(resolveDataDir(argv, io), "archive");
108
+ // R6 cli finding 2: resolveDataDir touches the env file — keep its failures
109
+ // in the one-line pretty-error regime (exit 1), like the plan/apply calls.
110
+ let archiveDir: string;
111
+ try {
112
+ archiveDir = join(resolveDataDir(argv, io), "archive");
113
+ } catch (e) {
114
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
115
+ return 1;
116
+ }
91
117
  const options = { closedBeforeDays: days, now: io.now() };
92
118
 
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.");
119
+ // The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
120
+ // cutoff or unreadable archive used to escape as a raw stack trace.
121
+ try {
122
+ if (!apply) {
123
+ const plan = await gcPlan(archiveDir, options);
124
+ io.print(`archive ${archiveDir}`);
125
+ io.print(`keep last ${argv[at + 1]} — ${plan.total.count} archived session(s), ${humanBytes(plan.total.bytes)}`);
126
+ if (!plan.candidates.length) {
127
+ io.print("nothing to delete.");
128
+ } else {
129
+ io.print(`would delete ${plan.candidates.length} session(s), ${humanBytes(plan.candidateBytes)}:`);
130
+ for (const candidate of plan.candidates.slice(0, 20))
131
+ io.print(` ${candidate.sessionId.slice(0, 8)} ${candidate.ageDays}d old ${humanBytes(candidate.bytes)}`);
132
+ if (plan.candidates.length > 20) io.print(` … and ${plan.candidates.length - 20} more`);
133
+ io.print("re-run with --yes to delete.");
134
+ }
135
+ for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
136
+ return 0;
105
137
  }
106
- for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
138
+
139
+ const { removed, bytes } = await gcApply(archiveDir, options);
140
+ io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
107
141
  return 0;
142
+ } catch (e) {
143
+ io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
144
+ return 2;
108
145
  }
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
146
  }
@@ -78,7 +78,9 @@ export async function archivedEntries(archiveDir: string): Promise<{ entries: Ar
78
78
  export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
79
79
  const now = options.now ?? Date.now();
80
80
  const days = options.closedBeforeDays;
81
- if (!Number.isFinite(days) || days < 1) throw new Error(`closedBeforeDays must be at least 1, got ${String(days)}`);
81
+ // Sub-day cutoffs are legal (R5 finding 6): the CLI advertises 90m/12h and
82
+ // parseDuration delivers them as fractional days. Only non-positive values refuse.
83
+ if (!Number.isFinite(days) || days <= 0) throw new Error(`closedBeforeDays must be positive, got ${String(days)}`);
82
84
  const { entries, skipped } = await archivedEntries(archiveDir);
83
85
  const cutoff = now - days * 86_400_000;
84
86
  const candidates = entries
@@ -14,7 +14,7 @@ import { v1 } from "./routes.js";
14
14
  import { DevicePairing } from "./pairing.js";
15
15
  import { DeviceConnector, readCaPem } from "./tunnel.js";
16
16
  import { PAIR_PAGE_HTML } from "./pair-page.js";
17
- import { parseDeviceSub, runDeviceCommand, daemonPaths } from "./daemon.js";
17
+ import { parseDeviceSub, runDeviceCommand, daemonPaths, boundedStep } from "./daemon.js";
18
18
 
19
19
  // `dpi device start|stop|status|install|uninstall` manage a background daemon
20
20
  // and exit; everything else (bare `dpi device` or flags) runs the daemon here.
@@ -249,15 +249,35 @@ let closing = false;
249
249
  const shutdown = async () => {
250
250
  if (closing) return;
251
251
  closing = true;
252
- connector.stop("backend shutdown"); // readers/pending ops before storage closes
252
+ // R6 cli finding 10: `dpi device stop` hung twice at teardown (40s+, zero
253
+ // output, device stayed healthy; direct SIGTERM exits <5s). No step of the
254
+ // shutdown may block forever:
255
+ // - connector.stop is synchronous; a throw is logged, never fatal;
256
+ // - store.close is raced against a 5s ceiling (boundedStep) and abandoned;
257
+ // - a hard watchdog guarantees the process still exits at 10s.
258
+ const log = (line: string) => console.log(line);
259
+ const watchdog = setTimeout(() => {
260
+ console.log("shutdown: still not down after 10s — forcing exit");
261
+ process.exit(0);
262
+ }, 10_000);
263
+ try {
264
+ await boundedStep("connector.stop", 5_000, () => connector.stop("backend shutdown"), log);
265
+ } catch (e) {
266
+ log(`shutdown: connector stop failed (${e instanceof Error ? e.message : String(e)}) — continuing`);
267
+ }
253
268
  server.close();
254
269
  server.closeAllConnections();
255
- await store.close();
270
+ try {
271
+ await boundedStep("store.close", 5_000, () => store.close(), log);
272
+ } catch (e) {
273
+ log(`shutdown: store close failed (${e instanceof Error ? e.message : String(e)}) — exiting anyway`);
274
+ }
256
275
  try {
257
276
  rmSync(daemonPaths(process.env).pid, { force: true });
258
277
  } catch {
259
278
  /* nothing to clean */
260
279
  }
280
+ clearTimeout(watchdog);
261
281
  process.exit(0);
262
282
  };
263
283
  process.on("SIGTERM", () => void shutdown());
@@ -276,7 +276,9 @@ function assertProviderId(providerId: string): void {
276
276
  );
277
277
  }
278
278
 
279
- /** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix). */
279
+ /** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix).
280
+ * Typed PiConfigError: the device refusing to touch pi's broken file is a
281
+ * caller-facing 4xx with the plain words, not a 500 with a stack. */
280
282
  function readAuthStrict(dir: string): Record<string, Credential> {
281
283
  const path = join(dir, "auth.json");
282
284
  if (!existsSync(path)) return {};
@@ -284,10 +286,10 @@ function readAuthStrict(dir: string): Record<string, Credential> {
284
286
  try {
285
287
  parsed = JSON.parse(readFileSync(path, "utf8"));
286
288
  } catch {
287
- throw Error("auth.json is not valid JSON — fix it with pi, the device will not rewrite it");
289
+ throw new PiConfigError("invalid", "auth.json is not valid JSON — fix it with pi, the device will not rewrite it");
288
290
  }
289
291
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
290
- throw Error("auth.json has an unexpected shape — fix it with pi, the device will not rewrite it");
292
+ throw new PiConfigError("invalid", "auth.json has an unexpected shape — fix it with pi, the device will not rewrite it");
291
293
  return parsed as Record<string, Credential>;
292
294
  }
293
295
 
@@ -305,14 +307,18 @@ function writeAuthAtomic(dir: string, next: Record<string, Credential>): void {
305
307
  renameSync(tmp, path);
306
308
  }
307
309
 
308
- /** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries. */
310
+ /** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries
311
+ * (typed: an oauth conflict is caller error → 4xx, never a 500). */
309
312
  export function writePiApiKey(dir: string, providerId: string, key: string): PiAuthEntry {
310
313
  assertProviderId(providerId);
311
314
  if (!key.trim() || key.length > 4096) throw Error("key must be 1–4096 non-whitespace characters");
312
315
  const auth = readAuthStrict(dir);
313
316
  const existing = auth[providerId];
314
317
  if (existing && existing.type !== "api_key")
315
- throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
318
+ throw new PiConfigError(
319
+ "invalid",
320
+ `${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`,
321
+ );
316
322
  const credential: ApiKeyCredential = { type: "api_key", key };
317
323
  writeAuthAtomic(dir, { ...auth, [providerId]: credential });
318
324
  return { providerId, type: "api_key", source: existing ? "auth.json" : "auth.json", masked: maskPiKey(key) };
@@ -324,7 +330,10 @@ export function removePiApiKey(dir: string, providerId: string): boolean {
324
330
  const auth = readAuthStrict(dir);
325
331
  const existing = auth[providerId];
326
332
  if (existing && existing.type !== "api_key")
327
- throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
333
+ throw new PiConfigError(
334
+ "invalid",
335
+ `${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`,
336
+ );
328
337
  if (!existing) return false;
329
338
  const next = { ...auth };
330
339
  delete next[providerId];