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.
- package/apps/dpi-backend/src/daemon.ts +48 -0
- package/apps/dpi-backend/src/doctor.ts +17 -4
- package/apps/dpi-backend/src/errors.ts +68 -1
- package/apps/dpi-backend/src/gc-cli.ts +52 -19
- package/apps/dpi-backend/src/gc.ts +3 -1
- package/apps/dpi-backend/src/main.ts +23 -3
- package/apps/dpi-backend/src/pi-config.ts +15 -6
- package/apps/dpi-backend/src/store.ts +220 -22
- package/apps/dpi-backend/src/tunnel.ts +24 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-4Kyozhl0.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DxGrKN6X.css → index-BkSQ2clA.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/App.vue +9 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/dialog-escape.ts +13 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +70 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/state-draft.ts +72 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +15 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ContextBar.vue +14 -3
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +82 -69
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +22 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PromptDialog.vue +3 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +19 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +72 -30
- package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +38 -17
- package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
- package/apps/dpi-tui/src/app.ts +108 -25
- package/apps/dpi-tui/src/commands.ts +16 -8
- package/apps/dpi-tui/src/main.ts +46 -19
- package/apps/dpi-tui/src/pickers.ts +4 -0
- package/apps/dpi-tui/src/scroll.ts +59 -0
- package/apps/dpi-tui/src/views.ts +17 -2
- package/apps/dpi-tui/src/wrap.ts +42 -0
- package/bin/dpi.mjs +83 -0
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DC0Iicch.js +0 -81
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
toTranscript,
|
|
45
45
|
type UsageSummary,
|
|
46
46
|
} from "../../dpi-sdk/src/transcript.js";
|
|
47
|
-
import { ApiFault, invalid, notFound } from "./errors.js";
|
|
47
|
+
import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
|
|
48
48
|
import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
|
|
49
49
|
import { DatabaseSync } from "node:sqlite";
|
|
50
50
|
import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
|
|
@@ -78,7 +78,7 @@ import {
|
|
|
78
78
|
} from "./archived.js";
|
|
79
79
|
import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
|
|
80
80
|
import { zipSync, type ZipEntry } from "./zip.js";
|
|
81
|
-
import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
|
|
81
|
+
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
82
82
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
83
83
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
84
84
|
import { homedir, hostname, platform } from "node:os";
|
|
@@ -217,6 +217,11 @@ const NOT_OPENED_README = [
|
|
|
217
217
|
"",
|
|
218
218
|
].join("\n");
|
|
219
219
|
|
|
220
|
+
/** Catalog schema version of the sessions catalog. The ladder in `prepareCatalog` owns upgrades;
|
|
221
|
+
* a HIGHER version than this build knows refuses cleanly (pi-durable's migrations behavior).
|
|
222
|
+
* Version 1: the R5 baseline — provider column mandatory, version row stamped in meta. */
|
|
223
|
+
const CATALOG_SCHEMA_VERSION = 1;
|
|
224
|
+
|
|
220
225
|
/** "My session #1" → "my-session-1" for the download name. */
|
|
221
226
|
function slugName(input: string): string {
|
|
222
227
|
const slug = input
|
|
@@ -247,7 +252,7 @@ export function lockFile(path: string) {
|
|
|
247
252
|
} catch (e) {
|
|
248
253
|
if ((e as NodeJS.ErrnoException).code !== "ESRCH") alive = true;
|
|
249
254
|
}
|
|
250
|
-
if (alive && pid !== process.pid) throw
|
|
255
|
+
if (alive && pid !== process.pid) throw new DeviceAlreadyRunningError(pid, path);
|
|
251
256
|
unlinkSync(path);
|
|
252
257
|
take();
|
|
253
258
|
}
|
|
@@ -258,6 +263,21 @@ export function lockFile(path: string) {
|
|
|
258
263
|
};
|
|
259
264
|
}
|
|
260
265
|
|
|
266
|
+
/**
|
|
267
|
+
* A second device on one home (R5 finding 7): the catalog lock is held by a live process.
|
|
268
|
+
* Typed so `Store.open` can turn it into a clean exit instead of an uncaught exception
|
|
269
|
+
* and a crash report that tells the operator to file an issue.
|
|
270
|
+
*/
|
|
271
|
+
export class DeviceAlreadyRunningError extends Error {
|
|
272
|
+
constructor(
|
|
273
|
+
readonly pid: number,
|
|
274
|
+
readonly path: string,
|
|
275
|
+
) {
|
|
276
|
+
super(`Database already owned by process ${pid}: ${path}`);
|
|
277
|
+
this.name = "DeviceAlreadyRunningError";
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
261
281
|
type Opened = { harness: Harness; unlock: () => void; unsubscribe: () => void; jobs: Jobs; addons: Addons };
|
|
262
282
|
type Resolved = { row: SessionRow; h: Harness; c: Conversation };
|
|
263
283
|
|
|
@@ -318,6 +338,30 @@ const decodeCursor = (cursor?: string) => {
|
|
|
318
338
|
}
|
|
319
339
|
};
|
|
320
340
|
|
|
341
|
+
/**
|
|
342
|
+
* One name rule for Store.create and Store.rename, matching a schedule's name
|
|
343
|
+
* (`MAX_SCHEDULE_NAME_LENGTH`): a display name, not a description — the old
|
|
344
|
+
* create-side slice(0,100) silently swallowed a 10k paste where rename threw.
|
|
345
|
+
*
|
|
346
|
+
* "search" (ANY casing) is reserved: GET /v1/sessions/search is a literal
|
|
347
|
+
* route ahead of /sessions/:s, and resolveSession matches names
|
|
348
|
+
* case-insensitively, so a session named Search/search/SEARCH is unreachable
|
|
349
|
+
* through the name every client naturally types (TUI `client.session(name)`).
|
|
350
|
+
*/
|
|
351
|
+
const RESERVED_SESSION_NAME = "search";
|
|
352
|
+
function assertSessionName(name: string): string {
|
|
353
|
+
const trimmed = name.trim();
|
|
354
|
+
if (trimmed.length > MAX_SCHEDULE_NAME_LENGTH)
|
|
355
|
+
throw invalid(`name is ${trimmed.length} characters; the limit is ${MAX_SCHEDULE_NAME_LENGTH}`);
|
|
356
|
+
if (trimmed.toLowerCase() === RESERVED_SESSION_NAME) throw invalid(`"${trimmed}" is a reserved session name`);
|
|
357
|
+
// Control characters never belong in a display name: reject rather than
|
|
358
|
+
// store verbatim (a newline) or silently truncate at a NUL. One rule for
|
|
359
|
+
// create AND rename — the old create path accepted \u0007 etc. and then
|
|
360
|
+
// dead-ended at a rename that refused what it had already stored.
|
|
361
|
+
if (/[\u0000-\u001f\u007f]/.test(trimmed)) throw invalid("name must not contain control characters");
|
|
362
|
+
return trimmed;
|
|
363
|
+
}
|
|
364
|
+
|
|
321
365
|
export class Store {
|
|
322
366
|
/** pi's credentials + custom providers on THIS machine (auth.json / models.json). */
|
|
323
367
|
readonly pi = loadPiConfig();
|
|
@@ -412,24 +456,148 @@ export class Store {
|
|
|
412
456
|
}
|
|
413
457
|
ensurePrivateDir(options.dataDir);
|
|
414
458
|
this.unlockCatalog = lockFile(`${this.catalogPath}.lock`);
|
|
415
|
-
this.catalog =
|
|
416
|
-
this.catalog.
|
|
459
|
+
this.catalog = this.openCatalog();
|
|
460
|
+
const uid = this.catalog.prepare("SELECT value FROM meta WHERE key='device_uid'").get() as
|
|
461
|
+
| { value: string }
|
|
462
|
+
| undefined;
|
|
463
|
+
this.uid = uid?.value ?? randomUUID();
|
|
464
|
+
if (!uid) this.catalog.prepare("INSERT INTO meta(key,value) VALUES('device_uid',?)").run(this.uid);
|
|
465
|
+
this.catalog.prepare("DELETE FROM requests WHERE createdAt < ?").run(Date.now() - 24 * 3600_000);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// --------------------------------------- catalog: open, migrate, recover
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Open the catalog with migration and corruption recovery (R5 findings 3+4).
|
|
472
|
+
*
|
|
473
|
+
* An unreadable catalog file used to crash-loop the whole device on every boot
|
|
474
|
+
* (all sessions and the tunnel down) — the JSON registries move corrupt files
|
|
475
|
+
* aside (`.corrupt-<ts>`) and rebuild, but the catalog got nothing. Now the same
|
|
476
|
+
* quarantine applies, a fresh catalog boots, and session rows are re-seeded from
|
|
477
|
+
* the sessions/ directory (per-session best-effort; a session whose db fails to
|
|
478
|
+
* open keeps its row with the failure message the boot loop records).
|
|
479
|
+
*/
|
|
480
|
+
private openCatalog(): DatabaseSync {
|
|
481
|
+
try {
|
|
482
|
+
return this.prepareCatalog(new DatabaseSync(this.catalogPath));
|
|
483
|
+
} catch (e) {
|
|
484
|
+
// Anything else (a future schema version, a held lock) is NOT a corrupt file —
|
|
485
|
+
// a future version must refuse cleanly, never be quarantined away.
|
|
486
|
+
if (!isUnreadableStorage(e)) throw e;
|
|
487
|
+
this.quarantineCatalog();
|
|
488
|
+
const db = this.prepareCatalog(new DatabaseSync(this.catalogPath));
|
|
489
|
+
// Pass the handle: `this.catalog` is still undefined here (our caller is
|
|
490
|
+
// the `this.catalog = this.openCatalog()` assignment) — reading it from
|
|
491
|
+
// inside reseed was an uncaught TypeError that crashed the boot AFTER
|
|
492
|
+
// the quarantine warning (the R5 test caught exactly that sequence).
|
|
493
|
+
this.reseedCatalog(db);
|
|
494
|
+
return db;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Run the base DDL, then the schema-version check and the known-old-shape ladder. */
|
|
499
|
+
private prepareCatalog(db: DatabaseSync): DatabaseSync {
|
|
500
|
+
db.exec(`PRAGMA journal_mode=WAL;
|
|
417
501
|
CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY,name TEXT NOT NULL,cwd TEXT NOT NULL,dbPath TEXT NOT NULL UNIQUE,createdAt INTEGER NOT NULL,model TEXT NOT NULL,provider TEXT NOT NULL);
|
|
418
502
|
CREATE TABLE IF NOT EXISTS conversation_names(sessionId TEXT NOT NULL,conversationId INTEGER NOT NULL,name TEXT NOT NULL,PRIMARY KEY(sessionId,conversationId));
|
|
419
503
|
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
420
504
|
CREATE TABLE IF NOT EXISTS requests(key TEXT PRIMARY KEY,route TEXT NOT NULL,status INTEGER NOT NULL,body TEXT NOT NULL,createdAt INTEGER NOT NULL);
|
|
421
505
|
CREATE TABLE IF NOT EXISTS session_spawns(key TEXT PRIMARY KEY,sessionId TEXT NOT NULL);
|
|
422
506
|
CREATE TABLE IF NOT EXISTS session_compaction(sessionId TEXT PRIMARY KEY,settings TEXT NOT NULL);`);
|
|
423
|
-
const
|
|
507
|
+
const row = db.prepare("SELECT value FROM meta WHERE key='catalog_schema_version'").get() as
|
|
424
508
|
| { value: string }
|
|
425
509
|
| undefined;
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
510
|
+
if (row) {
|
|
511
|
+
const version = Number(row.value);
|
|
512
|
+
if (Number.isFinite(version) && version > CATALOG_SCHEMA_VERSION) {
|
|
513
|
+
db.close();
|
|
514
|
+
// pi-durable's migrations refusal, mirrored: clean bounded message, never a silent attempt.
|
|
515
|
+
throw Error(
|
|
516
|
+
`Catalog schema version ${version} is newer than supported version ${CATALOG_SCHEMA_VERSION}; upgrade my-durable to open this device home`,
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
return db;
|
|
520
|
+
}
|
|
521
|
+
// Pre-versioning catalog (every device before R5): run the ladder for known-old
|
|
522
|
+
// shapes, then stamp the version. A device already at the current shape just gets stamped.
|
|
523
|
+
const columns = new Set(
|
|
524
|
+
(db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[]).map((c) => c.name),
|
|
525
|
+
);
|
|
526
|
+
if (!columns.has("provider")) {
|
|
527
|
+
db.exec("ALTER TABLE sessions ADD COLUMN provider TEXT NOT NULL DEFAULT ''");
|
|
528
|
+
process.emitWarning("catalog: migrated sessions table to schema version 1 (added provider)");
|
|
529
|
+
}
|
|
530
|
+
db.prepare("INSERT INTO meta(key,value) VALUES('catalog_schema_version',?)").run(String(CATALOG_SCHEMA_VERSION));
|
|
531
|
+
return db;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** Rename an unreadable catalog out of the way instead of deleting it: it is the only copy of that data. */
|
|
535
|
+
private quarantineCatalog(): string {
|
|
536
|
+
const aside = `${this.catalogPath}.corrupt-${Date.now()}`;
|
|
537
|
+
for (const suffix of ["", "-wal", "-shm"] as const) {
|
|
538
|
+
try {
|
|
539
|
+
renameSync(`${this.catalogPath}${suffix}`, `${aside}${suffix}`);
|
|
540
|
+
} catch {}
|
|
541
|
+
}
|
|
542
|
+
process.emitWarning(`catalog.sqlite was unreadable; kept it as ${aside} and rebuilt a fresh catalog`);
|
|
543
|
+
return aside;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Re-seed session rows from sessions/ after a catalog quarantine. The catalog is the
|
|
548
|
+
* only place names/cwds/models live, so rows come back with best-effort identity:
|
|
549
|
+
* a placeholder name, the first start dir as cwd, the device default model, and the
|
|
550
|
+
* file mtime as createdAt. openAgent corrects model/provider from the session's own
|
|
551
|
+
* committed storage at boot; a session whose db fails to open keeps its row with the
|
|
552
|
+
* boot loop's failure message. Names are placeholders — the transcript is intact.
|
|
553
|
+
*/
|
|
554
|
+
private reseedCatalog(db: DatabaseSync): void {
|
|
555
|
+
let entries;
|
|
556
|
+
try {
|
|
557
|
+
entries = readdirSync(this.sessionsDir, { withFileTypes: true });
|
|
558
|
+
} catch {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const insert = db.prepare(
|
|
562
|
+
"INSERT OR IGNORE INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)",
|
|
563
|
+
);
|
|
564
|
+
const fallback = this.defaultModelRef();
|
|
565
|
+
for (const entry of entries) {
|
|
566
|
+
if (!entry.isDirectory() || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(entry.name))
|
|
567
|
+
continue;
|
|
568
|
+
const dbPath = join(this.sessionsDir, entry.name, "agent.sqlite");
|
|
569
|
+
let createdAt = Date.now();
|
|
570
|
+
try {
|
|
571
|
+
createdAt = Math.round(statSync(dbPath).mtimeMs);
|
|
572
|
+
} catch {}
|
|
573
|
+
insert.run(
|
|
574
|
+
entry.name,
|
|
575
|
+
`Recovered session ${entry.name.slice(0, 8)}`,
|
|
576
|
+
this.options.startDirs[0] ?? homedir(),
|
|
577
|
+
dbPath,
|
|
578
|
+
createdAt,
|
|
579
|
+
fallback?.modelId ?? "unknown",
|
|
580
|
+
fallback?.provider ?? "unknown",
|
|
581
|
+
);
|
|
582
|
+
}
|
|
429
583
|
}
|
|
430
584
|
|
|
431
585
|
static async open(options: StoreOptions) {
|
|
432
|
-
|
|
586
|
+
let store: Store;
|
|
587
|
+
try {
|
|
588
|
+
store = new Store({ ...options, dataDir: resolve(options.dataDir) });
|
|
589
|
+
} catch (e) {
|
|
590
|
+
// R5 finding 7: a second device start on one home used to die as an uncaught
|
|
591
|
+
// exception plus a crash report telling the operator to file an issue. It is
|
|
592
|
+
// not a crash: detect the own-lock case and exit cleanly, no report.
|
|
593
|
+
if (e instanceof DeviceAlreadyRunningError) {
|
|
594
|
+
process.stdout.write(`dpi: already running (pid ${e.pid}) — ${e.path} is owned by that process\n`);
|
|
595
|
+
// Exit 0: the operator's intent ("start the device") is already satisfied by
|
|
596
|
+
// the live process, so a supervisor's restart loop must not fight it.
|
|
597
|
+
process.exit(0);
|
|
598
|
+
}
|
|
599
|
+
throw e;
|
|
600
|
+
}
|
|
433
601
|
// Start dirs are where new sessions begin; create any that do not exist yet.
|
|
434
602
|
await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
|
|
435
603
|
try {
|
|
@@ -1133,6 +1301,8 @@ export class Store {
|
|
|
1133
1301
|
async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
|
|
1134
1302
|
if (typeof body?.name !== "string") throw invalid("name is required");
|
|
1135
1303
|
if (typeof body.cwd !== "string" || !body.cwd.trim()) throw invalid("cwd is required");
|
|
1304
|
+
// One name rule for create and rename (assertSessionName, module scope): the old
|
|
1305
|
+
// slice(0,100) silently swallowed a 10k paste where rename threw.
|
|
1136
1306
|
const path = body.cwd.trim();
|
|
1137
1307
|
const expanded = path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
|
|
1138
1308
|
let cwd: string;
|
|
@@ -1177,7 +1347,7 @@ export class Store {
|
|
|
1177
1347
|
const id = randomUUID();
|
|
1178
1348
|
const row: SessionRow = {
|
|
1179
1349
|
id,
|
|
1180
|
-
name: body.name
|
|
1350
|
+
name: assertSessionName(body.name) || "Untitled session",
|
|
1181
1351
|
cwd,
|
|
1182
1352
|
dbPath: join(this.sessionsDir, id, "agent.sqlite"),
|
|
1183
1353
|
createdAt: Date.now(),
|
|
@@ -1187,8 +1357,10 @@ export class Store {
|
|
|
1187
1357
|
await this.openAgent(row, true, body.thinkingLevel ?? "medium");
|
|
1188
1358
|
this.catalog.exec("BEGIN");
|
|
1189
1359
|
try {
|
|
1360
|
+
// Named columns (R5 finding 4): a catalog with an extra or missing future
|
|
1361
|
+
// column fails loudly here instead of mis-binding positionally.
|
|
1190
1362
|
this.catalog
|
|
1191
|
-
.prepare("INSERT INTO sessions VALUES(?,?,?,?,?,?,?)")
|
|
1363
|
+
.prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
|
|
1192
1364
|
.run(id, row.name, cwd, row.dbPath, row.createdAt, row.model, row.provider);
|
|
1193
1365
|
if (spawnKey) this.catalog.prepare("INSERT OR REPLACE INTO session_spawns VALUES(?,?)").run(spawnKey, id);
|
|
1194
1366
|
this.catalog.exec("COMMIT");
|
|
@@ -1223,14 +1395,8 @@ export class Store {
|
|
|
1223
1395
|
|
|
1224
1396
|
rename(row: SessionRow, name: unknown) {
|
|
1225
1397
|
if (typeof name !== "string" || !name.trim()) throw invalid("A name is required");
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
// description (the old slice(0,100) silently swallowed a 10k paste).
|
|
1229
|
-
if (trimmed.length > MAX_SCHEDULE_NAME_LENGTH)
|
|
1230
|
-
throw invalid(`name is ${trimmed.length} characters; the limit is ${MAX_SCHEDULE_NAME_LENGTH}`);
|
|
1231
|
-
// Control characters never belong in a display name: reject rather than
|
|
1232
|
-
// store verbatim (a newline) or silently truncate at a NUL.
|
|
1233
|
-
if (/[\u0000-\u001f\u007f]/.test(trimmed)) throw invalid("name must not contain control characters");
|
|
1398
|
+
// assertSessionName owns the whole rule: cap, reserved word, control characters.
|
|
1399
|
+
const trimmed = assertSessionName(name);
|
|
1234
1400
|
this.catalog.prepare("UPDATE sessions SET name=? WHERE id=?").run(trimmed, row.id);
|
|
1235
1401
|
this.notify();
|
|
1236
1402
|
return this.sessionSummary(this.row(row.id));
|
|
@@ -1315,8 +1481,9 @@ export class Store {
|
|
|
1315
1481
|
};
|
|
1316
1482
|
this.catalog.exec("BEGIN");
|
|
1317
1483
|
try {
|
|
1484
|
+
// Named columns, as in create (R5 finding 4).
|
|
1318
1485
|
this.catalog
|
|
1319
|
-
.prepare("INSERT INTO sessions VALUES(?,?,?,?,?,?,?)")
|
|
1486
|
+
.prepare("INSERT INTO sessions(id,name,cwd,dbPath,createdAt,model,provider) VALUES(?,?,?,?,?,?,?)")
|
|
1320
1487
|
.run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
|
|
1321
1488
|
this.catalog.exec("COMMIT");
|
|
1322
1489
|
} catch (e) {
|
|
@@ -1696,10 +1863,41 @@ export class Store {
|
|
|
1696
1863
|
};
|
|
1697
1864
|
}
|
|
1698
1865
|
|
|
1866
|
+
/** Reopens in flight (resolveAgent's one retry): concurrent requests share the attempt instead of stampeding the same db. */
|
|
1867
|
+
private reopenInFlight = new Map<string, Promise<Harness>>();
|
|
1868
|
+
|
|
1869
|
+
/** ONE bounded reopen attempt per session at a time; removes itself when settled. */
|
|
1870
|
+
private reopenOnce(row: SessionRow): Promise<Harness> {
|
|
1871
|
+
const inFlight = this.reopenInFlight.get(row.id);
|
|
1872
|
+
if (inFlight) return inFlight;
|
|
1873
|
+
const attempt = this.openAgent(row).finally(() => this.reopenInFlight.delete(row.id));
|
|
1874
|
+
this.reopenInFlight.set(row.id, attempt);
|
|
1875
|
+
return attempt;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1699
1878
|
/** Agent by numeric id, `main`, or unique name (custom or derived, case-insensitive). */
|
|
1700
1879
|
async resolveAgent(sessionRef: string, agentRef: string): Promise<Resolved> {
|
|
1701
1880
|
const row = this.resolveSession(sessionRef);
|
|
1702
|
-
|
|
1881
|
+
let h: Harness;
|
|
1882
|
+
try {
|
|
1883
|
+
h = this.harness(row);
|
|
1884
|
+
} catch (e) {
|
|
1885
|
+
// R5 finding 1 (the availability brick): once a Session failed (failSession),
|
|
1886
|
+
// EVERY agent route used to answer 503 "Session failed and is unavailable"
|
|
1887
|
+
// for the process lifetime — the reopen path existed only in
|
|
1888
|
+
// sessionTouchedFiles/sessionGitTurns, so a transient storage failure
|
|
1889
|
+
// (another process holding the sqlite lock, a full disk) soft-bricked the
|
|
1890
|
+
// session until the device restarted. The unavailable fault is exactly the
|
|
1891
|
+
// "harness is not open" signal: attempt ONE fresh openAgent here, on the
|
|
1892
|
+
// request path every client hits, before answering.
|
|
1893
|
+
if (!(e instanceof ApiFault) || e.code !== "unavailable") throw e;
|
|
1894
|
+
try {
|
|
1895
|
+
h = await this.reopenOnce(row);
|
|
1896
|
+
} catch (retryError) {
|
|
1897
|
+
if (isStorageBusy(retryError)) throw storageBusyFault();
|
|
1898
|
+
throw e; // the recorded, bounded reason — never the raw storage error
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1703
1901
|
let id: number | undefined;
|
|
1704
1902
|
if (/^\d+$/.test(agentRef)) id = Number(agentRef);
|
|
1705
1903
|
else if (agentRef.toLowerCase() === "main") id = 1;
|
|
@@ -654,10 +654,13 @@ export class DeviceConnector {
|
|
|
654
654
|
void (async () => {
|
|
655
655
|
const check = validateRestRequest({ method: frame.method, path: frame.path });
|
|
656
656
|
if (!check.ok) {
|
|
657
|
+
// Same validator the hub runs first (tunnel-transport request()): the
|
|
658
|
+
// verdict must read the same on both hops — 400 invalid with the
|
|
659
|
+
// validator's message (R5: the device used to answer 404 here).
|
|
657
660
|
send({
|
|
658
661
|
type: "rest-response",
|
|
659
662
|
reqId: frame.reqId,
|
|
660
|
-
status:
|
|
663
|
+
status: 400,
|
|
661
664
|
body: { error: { code: "invalid", message: check.error } },
|
|
662
665
|
});
|
|
663
666
|
return;
|
|
@@ -758,7 +761,26 @@ export class DeviceConnector {
|
|
|
758
761
|
// F07: the hub names the STREAM PATH; scope must reach the device API.
|
|
759
762
|
// Allow-list the three SSE endpoints — a hub can never aim the reader
|
|
760
763
|
// at REST-only or pairing routes.
|
|
761
|
-
if (!isSubscribePathOk(frame.sub))
|
|
764
|
+
if (!isSubscribePathOk(frame.sub)) {
|
|
765
|
+
// R5: a refusal is never silent — the hub (and through it the browser
|
|
766
|
+
// key named in the envelope) gets a fault with its subscriptionId, so
|
|
767
|
+
// the key surfaces an error instead of starving without frames and
|
|
768
|
+
// without a timeout. The path rides the envelope's `sub` field, so the
|
|
769
|
+
// message stays short (the fault schema caps it at 512 chars).
|
|
770
|
+
send({
|
|
771
|
+
type: "tunnel-data",
|
|
772
|
+
frame: {
|
|
773
|
+
type: "fault",
|
|
774
|
+
error: {
|
|
775
|
+
code: "invalid",
|
|
776
|
+
message: "subscribe refused: the device does not serve this stream path",
|
|
777
|
+
},
|
|
778
|
+
},
|
|
779
|
+
subscriptionId: frame.subscriptionId,
|
|
780
|
+
sub: frame.sub,
|
|
781
|
+
});
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
762
784
|
const ctl = new AbortController();
|
|
763
785
|
this.readers.set(frame.subscriptionId, ctl);
|
|
764
786
|
void (async () => {
|