my-durable 0.0.58 → 0.0.59
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/errors.ts +68 -1
- package/apps/dpi-backend/src/gc-cli.ts +24 -17
- package/apps/dpi-backend/src/gc.ts +3 -1
- 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-hub/src/main.ts +67 -29
- package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
- 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/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/package.json +1 -1
|
@@ -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 {
|
|
@@ -90,24 +90,31 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
|
|
|
90
90
|
const archiveDir = join(resolveDataDir(argv, io), "archive");
|
|
91
91
|
const options = { closedBeforeDays: days, now: io.now() };
|
|
92
92
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
io.print(
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
93
|
+
// The plan/apply calls live inside the pretty-error path (R5 finding 6): a bad
|
|
94
|
+
// cutoff or unreadable archive used to escape as a raw stack trace.
|
|
95
|
+
try {
|
|
96
|
+
if (!apply) {
|
|
97
|
+
const plan = await gcPlan(archiveDir, options);
|
|
98
|
+
io.print(`archive ${archiveDir}`);
|
|
99
|
+
io.print(`keep last ${argv[at + 1]} — ${plan.total.count} archived session(s), ${humanBytes(plan.total.bytes)}`);
|
|
100
|
+
if (!plan.candidates.length) {
|
|
101
|
+
io.print("nothing to delete.");
|
|
102
|
+
} else {
|
|
103
|
+
io.print(`would delete ${plan.candidates.length} session(s), ${humanBytes(plan.candidateBytes)}:`);
|
|
104
|
+
for (const candidate of plan.candidates.slice(0, 20))
|
|
105
|
+
io.print(` ${candidate.sessionId.slice(0, 8)} ${candidate.ageDays}d old ${humanBytes(candidate.bytes)}`);
|
|
106
|
+
if (plan.candidates.length > 20) io.print(` … and ${plan.candidates.length - 20} more`);
|
|
107
|
+
io.print("re-run with --yes to delete.");
|
|
108
|
+
}
|
|
109
|
+
for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
|
|
110
|
+
return 0;
|
|
105
111
|
}
|
|
106
|
-
|
|
112
|
+
|
|
113
|
+
const { removed, bytes } = await gcApply(archiveDir, options);
|
|
114
|
+
io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
|
|
107
115
|
return 0;
|
|
116
|
+
} catch (e) {
|
|
117
|
+
io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
|
|
118
|
+
return 2;
|
|
108
119
|
}
|
|
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
120
|
}
|
|
@@ -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
|
-
|
|
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
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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];
|
|
@@ -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 () => {
|
|
@@ -130,6 +130,14 @@ const app = express();
|
|
|
130
130
|
// non-loopback direct connection is ignored (proxy-addr semantics).
|
|
131
131
|
app.set("trust proxy", isTrustedProxy);
|
|
132
132
|
app.disable("x-powered-by");
|
|
133
|
+
// Case-sensitive routes, matching the device: "/API/NETWORK" is a miss, not a
|
|
134
|
+
// silent alias of /api/network (route uniformity with the 0.0.58 device fix).
|
|
135
|
+
// Every hub caller already spells the mount lowercase — FE client (/api/...),
|
|
136
|
+
// TUI hub-feed/hub-mux (api/network, api/stream), and the public pairing
|
|
137
|
+
// ingress below; a case variant never carried different auth (audit R5).
|
|
138
|
+
// The app setting's name is Express's spelled-out form — "caseSensitive" is
|
|
139
|
+
// the Router option, silently ignored here (caught by the R5 test).
|
|
140
|
+
app.set("case sensitive routing", true);
|
|
133
141
|
// Every answer is non-sniffable; the admin API is never cacheable (it carries pairing codes and, on the
|
|
134
142
|
// pairing routes, a credential). Registered first so that refusals made further down carry them too.
|
|
135
143
|
app.use((req, res, next) => {
|
|
@@ -343,6 +351,39 @@ app.post(
|
|
|
343
351
|
},
|
|
344
352
|
);
|
|
345
353
|
|
|
354
|
+
// ------------------------------------------------ conversation shares
|
|
355
|
+
// The shell (which holds the tunnel credentials) uploads prepared transcripts;
|
|
356
|
+
// the hub mints a tokenized PUBLIC link. The token is the capability, every
|
|
357
|
+
// share expires (retention is explicit — the checklist row demanded that
|
|
358
|
+
// decision up front), and the admin routes can kill one early.
|
|
359
|
+
//
|
|
360
|
+
// Registered BEFORE the global /api chain (same pattern as the pairing
|
|
361
|
+
// ingress): the chain's 256 KiB parser consumed the body first, so a 300 KB
|
|
362
|
+
// share 413'd before this route's 10 MiB parser ever ran (the 2 MB/agent,
|
|
363
|
+
// 8 MB/total limits in shares.ts were unreachable), and its apiRate bucket
|
|
364
|
+
// was charged twice. The full guard stack travels with the route.
|
|
365
|
+
const shares = await Shares.open(join(dpiHome(), "shares"));
|
|
366
|
+
app.post(
|
|
367
|
+
"/api/shares",
|
|
368
|
+
denialLogging(audit),
|
|
369
|
+
guard(allowedHosts),
|
|
370
|
+
apiRate,
|
|
371
|
+
express.json({ limit: "10mb" }),
|
|
372
|
+
adminAuth,
|
|
373
|
+
(req, res) => {
|
|
374
|
+
const body = req.body ?? {};
|
|
375
|
+
void shares
|
|
376
|
+
.create({ title: String(body.title ?? ""), agents: Array.isArray(body.agents) ? body.agents : [] })
|
|
377
|
+
.then((meta) =>
|
|
378
|
+
res.status(201).json({ token: meta.token, url: `/share/${meta.token}`, expiresAt: meta.expiresAt }),
|
|
379
|
+
)
|
|
380
|
+
.catch((e: unknown) => {
|
|
381
|
+
if (e instanceof ShareError) return res.status(400).json(err("invalid", e.message));
|
|
382
|
+
throw e;
|
|
383
|
+
});
|
|
384
|
+
},
|
|
385
|
+
);
|
|
386
|
+
|
|
346
387
|
// Admin /api surface: guarded, rate-bucketed per real client IP, 256 KiB JSON,
|
|
347
388
|
// and behind the admin credential (cookie or bearer).
|
|
348
389
|
app.use(
|
|
@@ -456,46 +497,28 @@ app.put(
|
|
|
456
497
|
res.json({ ok: true });
|
|
457
498
|
}),
|
|
458
499
|
);
|
|
459
|
-
//
|
|
460
|
-
//
|
|
461
|
-
// the hub mints a tokenized PUBLIC link. The token is the capability, every
|
|
462
|
-
// share expires (retention is explicit — the checklist row demanded that
|
|
463
|
-
// decision up front), and the admin routes can kill one early.
|
|
464
|
-
const shares = await Shares.open(join(dpiHome(), "shares"));
|
|
465
|
-
app.post(
|
|
466
|
-
"/api/shares",
|
|
467
|
-
denialLogging(audit),
|
|
468
|
-
apiRate,
|
|
469
|
-
express.json({ limit: "10mb" }),
|
|
470
|
-
adminAuth,
|
|
471
|
-
(req, res) => {
|
|
472
|
-
const body = req.body ?? {};
|
|
473
|
-
void shares
|
|
474
|
-
.create({ title: String(body.title ?? ""), agents: Array.isArray(body.agents) ? body.agents : [] })
|
|
475
|
-
.then((meta) =>
|
|
476
|
-
res.status(201).json({ token: meta.token, url: `/share/${meta.token}`, expiresAt: meta.expiresAt }),
|
|
477
|
-
)
|
|
478
|
-
.catch((e: unknown) => {
|
|
479
|
-
if (e instanceof ShareError) return res.status(400).json(err("invalid", e.message));
|
|
480
|
-
throw e;
|
|
481
|
-
});
|
|
482
|
-
},
|
|
483
|
-
);
|
|
500
|
+
// Share admin reads/kill (the POST lives above the global chain — its body
|
|
501
|
+
// needs the 10 MiB parser); the chain's adminAuth + 256 KiB parser cover these.
|
|
484
502
|
app.get("/api/shares", adminAuth, (_req, res) => void shares.list().then((list) => res.json({ shares: list })));
|
|
485
503
|
app.delete("/api/shares/:token", adminAuth, (req, res) =>
|
|
486
504
|
void shares.remove(String(req.params.token ?? "")).then((removed) => res.json({ removed })),
|
|
487
505
|
);
|
|
488
506
|
// The public page: transcripts only, no app shell, no scripts, inline-styled.
|
|
507
|
+
// Framing is refused explicitly: frame-ancestors is NOT a fetch directive, so
|
|
508
|
+
// it does not fall back to default-src and must be spelled out (a share page
|
|
509
|
+
// is public content — a frame is a clickjacking channel).
|
|
489
510
|
app.get("/share/:token", (req, res) => {
|
|
490
511
|
void shares.get(String(req.params.token ?? "")).then((doc) => {
|
|
491
512
|
if (!doc) {
|
|
492
513
|
res.status(404);
|
|
493
514
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
494
|
-
res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'");
|
|
515
|
+
res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
|
|
516
|
+
res.set("X-Frame-Options", "DENY");
|
|
495
517
|
return res.send(renderShareNotFound());
|
|
496
518
|
}
|
|
497
519
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
498
|
-
res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'");
|
|
520
|
+
res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
|
|
521
|
+
res.set("X-Frame-Options", "DENY");
|
|
499
522
|
res.set("Cache-Control", "no-store");
|
|
500
523
|
res.send(renderSharePage(doc));
|
|
501
524
|
});
|
|
@@ -546,11 +569,26 @@ if (args.includes("--dev")) {
|
|
|
546
569
|
});
|
|
547
570
|
next();
|
|
548
571
|
});
|
|
549
|
-
|
|
572
|
+
const dist = resolve(appDir, "apps/dpi-playground-fe/dist");
|
|
573
|
+
// Vite content-addresses /assets/* filenames, so they can cache forever; the
|
|
574
|
+
// documents that reference them (index.html and the SPA shell) must
|
|
575
|
+
// revalidate or a deploy would serve stale HTML pointing at dead hashes.
|
|
576
|
+
app.use("/assets", express.static(join(dist, "assets"), { immutable: true, maxAge: "365d" }));
|
|
577
|
+
app.use(
|
|
578
|
+
express.static(dist, {
|
|
579
|
+
setHeaders: (res, filePath) => {
|
|
580
|
+
if (filePath.endsWith(".html")) res.setHeader("Cache-Control", "no-cache");
|
|
581
|
+
},
|
|
582
|
+
}),
|
|
583
|
+
);
|
|
550
584
|
app.get("/{*path}", (req, res, next) => {
|
|
551
585
|
// A path that names a file is an asset that does not exist, not a page of the app.
|
|
552
586
|
if (extname(req.path)) return void next();
|
|
553
|
-
|
|
587
|
+
// An /api-shaped path is never a page — not even case-mangled (uniformity
|
|
588
|
+
// with the device: /API/NETWORK is a 404 miss, not the app shell).
|
|
589
|
+
if (/^\/api(\/|$)/i.test(req.path)) return void next();
|
|
590
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
591
|
+
res.sendFile(join(dist, "index.html"));
|
|
554
592
|
});
|
|
555
593
|
}
|
|
556
594
|
app.use((_req, res) => res.status(404).json(err("not_found", "Not found")));
|
|
@@ -56,11 +56,17 @@ const KEY =
|
|
|
56
56
|
|
|
57
57
|
const invalidKey = () => Object.assign(Error("Invalid subscription key"), { status: 400 });
|
|
58
58
|
|
|
59
|
+
/** R5 cap mirror: the device's SUBSCRIBE_PATH_OK (dpi-backend/src/tunnel.ts) accepts at most 256
|
|
60
|
+
* characters after `?`. A docs list longer than that would open a subscription the device refuses —
|
|
61
|
+
* refuse it HERE (400 to the PUT caller) instead of signing the browser up for a silent starvation. */
|
|
62
|
+
const SUB_QUERY_MAX_CHARS = 256;
|
|
63
|
+
|
|
59
64
|
export function parseSubKey(key: string) {
|
|
60
65
|
const m = key.match(KEY);
|
|
61
66
|
if (!m) throw invalidKey();
|
|
62
67
|
const [, deviceId, scope, a, b, docs] = m;
|
|
63
68
|
const q = docs ? `?docs=${docs}` : "";
|
|
69
|
+
if (q.length - 1 > SUB_QUERY_MAX_CHARS) throw invalidKey();
|
|
64
70
|
const enc = (part: string) => {
|
|
65
71
|
try {
|
|
66
72
|
return encodeURIComponent(decodeURIComponent(part));
|
|
@@ -182,6 +188,12 @@ export class StreamMux {
|
|
|
182
188
|
const wanted = new Map(
|
|
183
189
|
(keys as string[]).filter((k) => k !== "network").map((k) => [k, parseSubKey(k)]),
|
|
184
190
|
);
|
|
191
|
+
// All-or-nothing like the parse above (R5): every device the PUT names must exist BEFORE
|
|
192
|
+
// anything is closed or opened, so an unknown device cannot leave upstreams opened and
|
|
193
|
+
// reader slots acquired by earlier keys in the same PUT dangling behind a 404.
|
|
194
|
+
for (const [key, sub] of wanted)
|
|
195
|
+
if (!stream.upstreams.has(key) && !this.registry.get(sub.deviceId))
|
|
196
|
+
throw Object.assign(Error(`No device ${sub.deviceId}`), { status: 404 });
|
|
185
197
|
for (const [key, ctl] of stream.upstreams)
|
|
186
198
|
if (!wanted.has(key)) {
|
|
187
199
|
ctl.abort();
|
|
@@ -190,10 +202,9 @@ export class StreamMux {
|
|
|
190
202
|
}
|
|
191
203
|
for (const [key, sub] of wanted)
|
|
192
204
|
if (!stream.upstreams.has(key)) {
|
|
193
|
-
if (!this.registry.get(sub.deviceId))
|
|
194
|
-
throw Object.assign(Error(`No device ${sub.deviceId}`), { status: 404 });
|
|
195
205
|
// Reader caps (04 §8): 128/device incl. the monitor's reader, 1024
|
|
196
206
|
// hub-wide. A rejected NEW reader must not disturb existing readers.
|
|
207
|
+
// (The registry check ran before any mutation — see above.)
|
|
197
208
|
if (
|
|
198
209
|
this.readerCount(sub.deviceId) >= READERS_PER_DEVICE ||
|
|
199
210
|
this.hubReaderCount() >= READERS_PER_HUB
|
|
@@ -203,8 +203,14 @@ export class Shares {
|
|
|
203
203
|
// Rendered server-side: the share page is public and must not load the app
|
|
204
204
|
// shell (which holds credentials), any script, or any external asset.
|
|
205
205
|
|
|
206
|
+
// Text nodes get the entity treatment for the HTML metacharacters, and C0/C1
|
|
207
|
+
// controls are STRIPPED (except tab/newline/carriage-return, which transcript
|
|
208
|
+
// text legitimately carries): a U+0001 or U+0007 in a markdown paste lands in
|
|
209
|
+
// the page raw otherwise — layout damage a reader cannot see or edit.
|
|
206
210
|
const escapeHtml = (text: string) =>
|
|
207
|
-
text
|
|
211
|
+
text
|
|
212
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "")
|
|
213
|
+
.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
|
208
214
|
|
|
209
215
|
const PAGE_STYLE = `:root{color-scheme:dark}body{margin:0;background:#16181d;color:#e6e6e6;font:16px/1.6 ui-sans-serif,system-ui,sans-serif}
|
|
210
216
|
main{max-width:52rem;margin:0 auto;padding:2rem 1rem}h1{font-size:1.3rem;margin:0 0 .25rem}
|
package/apps/dpi-tui/src/app.ts
CHANGED
|
@@ -8,7 +8,9 @@ import {
|
|
|
8
8
|
ProcessTerminal,
|
|
9
9
|
TuiAltScreen,
|
|
10
10
|
matchesKey,
|
|
11
|
+
sliceByColumn,
|
|
11
12
|
truncateToWidth,
|
|
13
|
+
visibleWidth,
|
|
12
14
|
type Component,
|
|
13
15
|
type OverlayHandle,
|
|
14
16
|
type TuiInputListenerResult,
|
|
@@ -35,6 +37,7 @@ import {
|
|
|
35
37
|
renderNetwork,
|
|
36
38
|
renderStatusbar,
|
|
37
39
|
renderViewbar,
|
|
40
|
+
gitStateSuffix,
|
|
38
41
|
herdRows,
|
|
39
42
|
joinPanel,
|
|
40
43
|
networkRows,
|
|
@@ -43,6 +46,8 @@ import {
|
|
|
43
46
|
import { appendFileSync } from "node:fs";
|
|
44
47
|
import { fetchHubNetwork } from "./hub-feed.ts";
|
|
45
48
|
import { HubMux, type MuxState } from "./hub-mux.ts";
|
|
49
|
+
import { FOLLOW_TAIL, scrollBy, viewportTop, type ScrollState } from "./scroll.ts";
|
|
50
|
+
import { wrapByColumn } from "./wrap.ts";
|
|
46
51
|
import { box, c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
|
|
47
52
|
|
|
48
53
|
export interface DeviceRef {
|
|
@@ -162,7 +167,20 @@ export class App {
|
|
|
162
167
|
helpOpen = false;
|
|
163
168
|
toast = "";
|
|
164
169
|
toastTicks = 0;
|
|
165
|
-
|
|
170
|
+
/** Transcript viewport (R5 findings 2+3): offset counts lines BACK from the
|
|
171
|
+
* tail (0 = follow it); scroll.ts holds the absolute-anchor math. */
|
|
172
|
+
private scrollState: ScrollState = FOLLOW_TAIL;
|
|
173
|
+
/** Public read for tests/debug: lines back from the tail. */
|
|
174
|
+
get scrollOffset(): number {
|
|
175
|
+
return this.scrollState.offset;
|
|
176
|
+
}
|
|
177
|
+
/** Last rendered transcript content length / inner height — scrollBy needs
|
|
178
|
+
* them at keypress time, when no frame width is known. */
|
|
179
|
+
private lastContentLen = 0;
|
|
180
|
+
private lastInner = 0;
|
|
181
|
+
/** Transcript length when last following the tail — content growth beyond
|
|
182
|
+
* this while scrolled up lights the "↓ new output" indicator (R5 finding 3). */
|
|
183
|
+
private followLen = 0;
|
|
166
184
|
/** ctrl+o: show full tool output instead of the first lines. */
|
|
167
185
|
expand = false;
|
|
168
186
|
/** Slash autocomplete: which suggestion row is selected (0 = first). */
|
|
@@ -300,7 +318,7 @@ export class App {
|
|
|
300
318
|
this.handle = this.client.agent(sessionId, agentId);
|
|
301
319
|
this.model.clear();
|
|
302
320
|
if (!sameSession) this.session.clear();
|
|
303
|
-
this.
|
|
321
|
+
this.scrollState = FOLLOW_TAIL;
|
|
304
322
|
void this.refreshSessions();
|
|
305
323
|
const handle = this.handle;
|
|
306
324
|
// Hub-routed devices stream through the mux (same upstreams the web rides);
|
|
@@ -419,6 +437,16 @@ export class App {
|
|
|
419
437
|
// Frames flow again: re-fetch the network rows that froze with the old
|
|
420
438
|
// connection (R4 finding 6 — the view stayed empty through every switch).
|
|
421
439
|
this.refreshHubNetwork();
|
|
440
|
+
// …and re-fetch the device info (R5 finding 5): the model catalog rode
|
|
441
|
+
// the boot-time /device fetch, so after a reconnect the cached catalog
|
|
442
|
+
// could miss the session's model and the ctx bar died ("ctx —").
|
|
443
|
+
void this.client
|
|
444
|
+
.device({ timeoutMs: 10_000 })
|
|
445
|
+
.then((info) => {
|
|
446
|
+
this.info = info;
|
|
447
|
+
this.requestRender();
|
|
448
|
+
})
|
|
449
|
+
.catch(() => {});
|
|
422
450
|
}
|
|
423
451
|
this.requestRender();
|
|
424
452
|
}
|
|
@@ -446,7 +474,7 @@ export class App {
|
|
|
446
474
|
setView(view: View) {
|
|
447
475
|
this.view = view;
|
|
448
476
|
this.cursor = 0;
|
|
449
|
-
this.
|
|
477
|
+
this.scrollState = FOLLOW_TAIL;
|
|
450
478
|
if (view === "herd") void this.refreshSessions();
|
|
451
479
|
if (view === "herd") this.refreshBranches();
|
|
452
480
|
if (view === "network") {
|
|
@@ -863,7 +891,12 @@ export class App {
|
|
|
863
891
|
private move(delta: number) {
|
|
864
892
|
if (this.view === "agent" && this.tab === "transcript") {
|
|
865
893
|
// Scroll the transcript instead of moving a cursor (herdr H04's lesson).
|
|
866
|
-
|
|
894
|
+
// R5 finding 2: the offset counts lines BACK from the tail, so adding the
|
|
895
|
+
// raw movement delta scrolled INTO history on j and clamped k dead at the
|
|
896
|
+
// bottom — exactly inverted. scrollBy's delta moves the absolute top
|
|
897
|
+
// line instead: j/↓ = +1 = toward newer, k/↑ = -1 = toward older — the
|
|
898
|
+
// directions the help panel has always promised.
|
|
899
|
+
this.scrollState = scrollBy(this.scrollState, delta, this.lastContentLen, this.lastInner);
|
|
867
900
|
this.requestRender();
|
|
868
901
|
return;
|
|
869
902
|
}
|
|
@@ -910,7 +943,7 @@ export class App {
|
|
|
910
943
|
}
|
|
911
944
|
const index = AGENT_TABS.findIndex((t) => t.id === this.tab);
|
|
912
945
|
this.tab = AGENT_TABS[(index + delta + AGENT_TABS.length) % AGENT_TABS.length]!.id;
|
|
913
|
-
this.
|
|
946
|
+
this.scrollState = FOLLOW_TAIL;
|
|
914
947
|
this.requestRender();
|
|
915
948
|
}
|
|
916
949
|
|
|
@@ -1175,11 +1208,17 @@ export class App {
|
|
|
1175
1208
|
const filled = ctx === undefined ? 0 : Math.round((ctx / 100) * barW);
|
|
1176
1209
|
const g = this.gitOf(session?.cwd);
|
|
1177
1210
|
if (session?.cwd) this.refreshGit(session.cwd);
|
|
1178
|
-
|
|
1211
|
+
// Merge/detached join the chip (R5 finding 4): the backend reports both,
|
|
1212
|
+
// the web shows a banner — the TUI used to show a healthy branch chip
|
|
1213
|
+
// while the repo was mid-merge with conflicts.
|
|
1214
|
+
const gitChip = g?.repo
|
|
1215
|
+
? ` ${c.muted("⎇")} ${c.text(g.branch ?? g.head ?? "")}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
|
|
1216
|
+
: "";
|
|
1179
1217
|
lines.push(
|
|
1180
1218
|
`${c.muted(this.device.id)} ${c.muted("›")} ${c.text(session?.name ?? "—")} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
|
|
1181
1219
|
`${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
|
|
1182
|
-
|
|
1220
|
+
// Catalog miss renders "?" not "—" (R5 finding 5): unknown window ≠ no usage.
|
|
1221
|
+
`${c.muted("ctx")} ${ctx === undefined ? c.muted("?") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
|
|
1183
1222
|
);
|
|
1184
1223
|
lines.push(
|
|
1185
1224
|
AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
|
|
@@ -1189,19 +1228,44 @@ export class App {
|
|
|
1189
1228
|
lines.push(c.muted(rep(box.h, w)));
|
|
1190
1229
|
const inner = h - 3;
|
|
1191
1230
|
const content = this.agentContent(w);
|
|
1192
|
-
|
|
1193
|
-
|
|
1231
|
+
// R5 finding 3: the viewport top is an ABSOLUTE anchor while scrolled up —
|
|
1232
|
+
// new frames must not slide the page under the user. Only offset 0 (tail)
|
|
1233
|
+
// follows the growth.
|
|
1234
|
+
const view = viewportTop(this.scrollState, content.length, inner);
|
|
1235
|
+
this.scrollState = view.state;
|
|
1236
|
+
const newBelow = this.scrollState.offset > 0 && content.length > this.followLen;
|
|
1237
|
+
if (this.scrollState.offset === 0) this.followLen = content.length;
|
|
1238
|
+
this.lastContentLen = content.length;
|
|
1239
|
+
this.lastInner = inner;
|
|
1240
|
+
for (const line of content.slice(view.from, view.from + inner)) lines.push(line);
|
|
1241
|
+
if (newBelow) {
|
|
1242
|
+
// The "↓ new output" hint configured on the TuiAltScreen never renders —
|
|
1243
|
+
// pi-tui draws it only for its own scroll views, and ours is app-owned
|
|
1244
|
+
// (R5 finding 3). Center it on the last body row while scrolled up and
|
|
1245
|
+
// frames landed below.
|
|
1246
|
+
const at = lines.length - 1;
|
|
1247
|
+
lines[at] = this.composeIndicator(lines[at] ?? "", w);
|
|
1248
|
+
}
|
|
1194
1249
|
return lines.slice(0, h);
|
|
1195
1250
|
}
|
|
1196
1251
|
|
|
1252
|
+
/** Overlay the "↓ new output" label onto a body row, centered, content kept. */
|
|
1253
|
+
private composeIndicator(row: string, width: number): string {
|
|
1254
|
+
const label = truncateToWidth(c.muted(" ↓ new output "), Math.max(0, width - 2), "");
|
|
1255
|
+
const labelWidth = visibleWidth(label);
|
|
1256
|
+
if (!labelWidth) return row;
|
|
1257
|
+
const col = Math.max(0, Math.floor((width - labelWidth) / 2));
|
|
1258
|
+
const left = truncateToWidth(row, col, "");
|
|
1259
|
+
const right = sliceByColumn(row, col + labelWidth, Math.max(0, width - col - labelWidth), true);
|
|
1260
|
+
return left + label + right;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1197
1263
|
/** The transcript/tasks/tools/state/config tabs, from the REAL model state. */
|
|
1198
1264
|
private agentContent(w: number): string[] {
|
|
1199
1265
|
const s = this.model.state;
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
.flatMap((l) => (l.length > w - 4 ? [l.slice(0, w - 4), l.slice(w - 4)] : [l]))
|
|
1204
|
-
.map((l) => indent + l);
|
|
1266
|
+
// Display-width loop wrap (R5 finding 1): the old single-split leaked the
|
|
1267
|
+
// remainder of every overlong line to pi-tui's hard clip. See wrap.ts.
|
|
1268
|
+
const wrap = (text: string, indent = " ") => wrapByColumn(text, w, indent);
|
|
1205
1269
|
if (this.tab === "transcript") {
|
|
1206
1270
|
const lines: string[] = [];
|
|
1207
1271
|
let turn = 0;
|
|
@@ -1375,20 +1439,39 @@ export class App {
|
|
|
1375
1439
|
|
|
1376
1440
|
private helpPanel(w: number, h: number): string[] {
|
|
1377
1441
|
const width = Math.min(76, w - 4);
|
|
1442
|
+
// Column-aligned by MEASURED visible width (R5 finding 6): the hand-spaced
|
|
1443
|
+
// rows drifted every time a label changed — "↵"-style keys made raw
|
|
1444
|
+
// padding lie, so pad on visibleWidth before styling.
|
|
1445
|
+
const keys: { k1: string; d1: string; k2?: string; d2?: string; muted?: boolean }[] = [
|
|
1446
|
+
{ k1: "j k ↑ ↓", d1: "move/scroll", k2: "1-4", d2: "views: net/herd/agent/log" },
|
|
1447
|
+
{ k1: "↵", d1: "open", k2: "g N L", d2: "same views, aliases" },
|
|
1448
|
+
{ k1: "[ ] t", d1: "agent tabs", k2: "m", d2: "message (enter sends)" },
|
|
1449
|
+
// esc is BACK only (R5 finding 7): it never interrupts (the 0.0.52/0.0.58
|
|
1450
|
+
// invariant — interrupting a running turn is destructive and keeps its
|
|
1451
|
+
// own key, `i`). The old "back/interrupt" label taught a key that does
|
|
1452
|
+
// nothing and hid the one that does.
|
|
1453
|
+
{ k1: "esc", d1: "back", k2: "i", d2: "interrupt ≠ kill" },
|
|
1454
|
+
{ k1: "F", d1: "fork", k2: "c", d2: "compact context" },
|
|
1455
|
+
{ k1: "y", d1: "thinking level", k2: "x", d2: "reset (y/n confirm)" },
|
|
1456
|
+
{ k1: "alt+↵", d1: "send now, no steer", k2: "ctrl+l", d2: "model picker", muted: true },
|
|
1457
|
+
{ k1: "tab", d1: "complete /command", k2: "↑", d2: "recall sent", muted: true },
|
|
1458
|
+
{ k1: "ctrl+o", d1: "expand tool output", muted: true },
|
|
1459
|
+
{ k1: ":", d1: "palette", k2: "f", d2: "filter rows" },
|
|
1460
|
+
{ k1: "n", d1: "new session", k2: "/", d2: "message // commands" },
|
|
1461
|
+
];
|
|
1462
|
+
const padCell = (s: string, n: number) => s + rep(" ", Math.max(0, n - visibleWidth(s)));
|
|
1463
|
+
const k1w = Math.max(...keys.map((r) => visibleWidth(r.k1))) + 2;
|
|
1464
|
+
const d1w = Math.max(...keys.map((r) => visibleWidth(r.d1))) + 3;
|
|
1465
|
+
const k2w = Math.max(...keys.filter((r) => r.k2).map((r) => visibleWidth(r.k2!))) + 2;
|
|
1466
|
+
const keyRow = (r: (typeof keys)[number]) => {
|
|
1467
|
+
const key = r.muted ? c.muted : c.accent;
|
|
1468
|
+
const desc = r.muted ? c.muted : (s: string) => s;
|
|
1469
|
+
return key(padCell(r.k1, k1w)) + desc(padCell(r.d1, d1w)) + (r.k2 ? key(padCell(r.k2, k2w)) + desc(r.d2 ?? "") : "");
|
|
1470
|
+
};
|
|
1378
1471
|
const rows = [
|
|
1379
1472
|
`${c.accent("▲")} ${c.bold("dpi keymap (herdr template)")}`,
|
|
1380
1473
|
"",
|
|
1381
|
-
|
|
1382
|
-
`${c.accent("↵")} open ${c.accent("g N L")} same views, aliases`,
|
|
1383
|
-
`${c.accent("[ ] t")} agent tabs ${c.accent("m")} message (enter sends)`,
|
|
1384
|
-
`${c.accent("esc")} back/interrupt ${c.accent("i")} interrupt ≠ kill`,
|
|
1385
|
-
`${c.accent("F")} fork ${c.accent("c")} compact context`,
|
|
1386
|
-
`${c.accent("y")} thinking level ${c.accent("x")} reset (y/n confirm)`,
|
|
1387
|
-
`${c.muted("alt+↵")} send now, no steer ${c.muted("ctrl+l")} model picker`,
|
|
1388
|
-
`${c.muted("tab")} complete /command ${c.muted("↑")} recall sent`,
|
|
1389
|
-
`${c.muted("ctrl+o")} expand tool output`,
|
|
1390
|
-
`${c.accent(":")} palette ${c.accent("f")} filter rows`,
|
|
1391
|
-
`${c.accent("n")} new session ${c.accent("/")} message // commands`,
|
|
1474
|
+
...keys.map(keyRow),
|
|
1392
1475
|
"",
|
|
1393
1476
|
c.muted("Durability"),
|
|
1394
1477
|
`${c.muted("·")} every turn is checkpointed on the device`,
|
|
@@ -4,6 +4,7 @@ import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
|
|
|
4
4
|
import type { App } from "./app.ts";
|
|
5
5
|
import { Panel, pickAgent, pickDevice, pickModel, pickSession, pickThinking } from "./pickers.ts";
|
|
6
6
|
import { parsePairArgs, runPairing } from "./pairing.ts";
|
|
7
|
+
import { gitStateSuffix } from "./views.ts";
|
|
7
8
|
import { c } from "./theme.ts";
|
|
8
9
|
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
9
10
|
|
|
@@ -28,10 +29,10 @@ export const COMMANDS: SlashCommand[] = [
|
|
|
28
29
|
{ name: "pair", description: "pair THIS device with a hub", argumentHint: "<CODE|PAIR_URL> [--hub ORIGIN] [--force]" },
|
|
29
30
|
{
|
|
30
31
|
name: "git",
|
|
31
|
-
description: "git on the session's folder: status, diff, log, pull, fetch, branch, switch, commit, worktree",
|
|
32
|
-
argumentHint: "[status|diff|log|fetch|pull|branch|switch <b>|commit <msg>|worktree [new <b>|remove <path>]]",
|
|
32
|
+
description: "git on the session's folder: status, diff, log, pull, fetch, branch, switch, commit, worktree, merge-abort",
|
|
33
|
+
argumentHint: "[status|diff|log|fetch|pull|branch|switch <b>|commit <msg>|worktree [new <b>|remove <path>]|merge-abort]",
|
|
33
34
|
getArgumentCompletions: (prefix) =>
|
|
34
|
-
["status", "diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree"]
|
|
35
|
+
["status", "diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "merge-abort"]
|
|
35
36
|
.filter((s) => s.startsWith(prefix))
|
|
36
37
|
.map((s) => ({ value: s, label: s })),
|
|
37
38
|
},
|
|
@@ -39,7 +40,7 @@ export const COMMANDS: SlashCommand[] = [
|
|
|
39
40
|
{ name: "quit", description: "exit (the agent keeps running)" },
|
|
40
41
|
];
|
|
41
42
|
|
|
42
|
-
const GIT_OPS = new Set(["diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "status", "wt"]);
|
|
43
|
+
const GIT_OPS = new Set(["diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "status", "wt", "merge-abort"]);
|
|
43
44
|
|
|
44
45
|
/** /git — the device's own git, spoken through its whitelisted API. */
|
|
45
46
|
async function gitCommand(app: App, arg: string) {
|
|
@@ -52,8 +53,13 @@ async function gitCommand(app: App, arg: string) {
|
|
|
52
53
|
const s = await app.client.gitStatus(cwd);
|
|
53
54
|
if (!s.repo) return app.notify(`${cwd} is not a git repository`);
|
|
54
55
|
const dirty = (s.staged ?? 0) + (s.unstaged ?? 0) + (s.untracked ?? 0);
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
// Merge/detached ride the toast (R5 finding 4): a mid-merge repo with
|
|
57
|
+
// conflicts used to show a healthy branch line, same blind spot the
|
|
58
|
+
// header chip had — the web's GitPanel has banner'd this state all along.
|
|
59
|
+
app.notify(
|
|
60
|
+
`⎇ ${s.branch ?? s.head} ±${dirty}${s.ahead ? ` ↑${s.ahead}` : ""}${s.behind ? ` ↓${s.behind}` : ""}${gitStateSuffix(s)}`,
|
|
61
|
+
);
|
|
62
|
+
app.logEvent("git", `${cwd} · ${s.branch ?? s.head}${s.merge ? " · MERGING" : s.detached ? " · detached" : ""}${s.upstream ? ` → ${s.upstream}` : ""} · +${s.staged ?? 0}/~${s.unstaged ?? 0}/?${s.untracked ?? 0}${s.worktreeOf ? ` · worktree of ${s.worktreeOf}` : ""}`);
|
|
57
63
|
for (const w of s.worktrees ?? []) app.logEvent("git", ` ${w.path} ${w.branch ? `⎇ ${w.branch}` : w.head}`);
|
|
58
64
|
return;
|
|
59
65
|
}
|
|
@@ -81,7 +87,8 @@ async function gitCommand(app: App, arg: string) {
|
|
|
81
87
|
app.notify(`${s.worktrees?.length ?? 0} worktree${s.worktrees?.length === 1 ? "" : "s"} (log view)`);
|
|
82
88
|
return;
|
|
83
89
|
}
|
|
84
|
-
if (!GIT_OPS.has(op))
|
|
90
|
+
if (!GIT_OPS.has(op))
|
|
91
|
+
return app.notify(`unknown git op "${op}" — status diff log fetch pull branch switch commit worktree merge-abort`);
|
|
85
92
|
if (op === "switch" && !a1) return app.notify("usage: /git switch <branch>");
|
|
86
93
|
if (op === "commit" && !rest.length) return app.notify("usage: /git commit <message>");
|
|
87
94
|
const out = await app.client.gitOp(cwd, op as never, {
|
|
@@ -98,7 +105,8 @@ async function gitCommand(app: App, arg: string) {
|
|
|
98
105
|
const KEYS: [string, string][] = [
|
|
99
106
|
["enter", "send; steers the agent while it works"],
|
|
100
107
|
["alt+enter", "queue as a follow-up"],
|
|
101
|
-
["esc", "
|
|
108
|
+
["esc", "back — it never interrupts"],
|
|
109
|
+
["i", "interrupt the running turn"],
|
|
102
110
|
["shift+tab", "cycle thinking level"],
|
|
103
111
|
["ctrl+l", "model picker"],
|
|
104
112
|
["ctrl+o", "expand tool output and thinking"],
|
|
@@ -100,6 +100,10 @@ export class Picker extends Box {
|
|
|
100
100
|
// arrow sequences it already understands.
|
|
101
101
|
if (data === "j") return this.list.handleInput("\x1b[B");
|
|
102
102
|
if (data === "k") return this.list.handleInput("\x1b[A");
|
|
103
|
+
// Enter on a ZERO-match list closes the picker (R5 finding 6): SelectList
|
|
104
|
+
// drops the key when nothing is selected — a silent no-op that stranded
|
|
105
|
+
// the user on a dead overlay with only esc as a way out.
|
|
106
|
+
if (matchesKey(data, "enter") && !this.list.getSelectedItem()) return this.onCancel();
|
|
103
107
|
if (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "enter") || matchesKey(data, "escape"))
|
|
104
108
|
return this.list.handleInput(data);
|
|
105
109
|
if (matchesKey(data, "backspace")) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Transcript viewport math (R5 findings 2+3). Pure — no TTY, no timers — so
|
|
2
|
+
// the scroll model is unit-testable exactly like the views.
|
|
3
|
+
//
|
|
4
|
+
// The old model stored ONLY an offset counted back from the END of the
|
|
5
|
+
// content and recomputed the top as `content.length - inner - offset` every
|
|
6
|
+
// frame. Two bugs fell out of that:
|
|
7
|
+
// • j/k deltas added straight onto the offset, so j scrolled INTO history
|
|
8
|
+
// and k clamped dead at the bottom (the offset's direction was inverted
|
|
9
|
+
// relative to the keys);
|
|
10
|
+
// • every new frame grew content.length, which SLID a scrolled-back viewport
|
|
11
|
+
// down through history (top row AGENT #10 → #11) — autoscroll fighting the
|
|
12
|
+
// user who had explicitly scrolled away from the tail.
|
|
13
|
+
// ScrollState fixes both: `top` is an ABSOLUTE line index pinned while
|
|
14
|
+
// offset > 0, and scrollBy()'s delta moves the top line, not the tail
|
|
15
|
+
// distance — j/↓ = +1 = toward newer, k/↑ = -1 = toward older.
|
|
16
|
+
|
|
17
|
+
export interface ScrollState {
|
|
18
|
+
/** Lines back from the tail; 0 = follow the tail (top is ignored). */
|
|
19
|
+
offset: number;
|
|
20
|
+
/** Absolute top line of the viewport while offset > 0. */
|
|
21
|
+
top: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Following the tail: offset 0, newest content visible. */
|
|
25
|
+
export const FOLLOW_TAIL: ScrollState = { offset: 0, top: 0 };
|
|
26
|
+
|
|
27
|
+
const tailTopOf = (contentLen: number, inner: number) => Math.max(0, contentLen - inner);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Step the viewport. `deltaTop > 0` moves the top line DOWN the document
|
|
31
|
+
* (toward newer content — the j/↓ direction), `deltaTop < 0` moves it UP
|
|
32
|
+
* (toward older — k/↑). From the follow-tail state, scrolling up first pins
|
|
33
|
+
* the anchor at the tail top, then steps it; scrolling back down to the tail
|
|
34
|
+
* releases the anchor (offset 0 again).
|
|
35
|
+
*/
|
|
36
|
+
export function scrollBy(s: ScrollState, deltaTop: number, contentLen: number, inner: number): ScrollState {
|
|
37
|
+
const tailTop = tailTopOf(contentLen, inner);
|
|
38
|
+
const base = s.offset === 0 ? tailTop : s.top;
|
|
39
|
+
const top = Math.max(0, Math.min(tailTop, base + deltaTop));
|
|
40
|
+
return top >= tailTop ? FOLLOW_TAIL : { offset: tailTop - top, top };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The viewport's absolute top line for a render, with the state to persist.
|
|
45
|
+
* While offset > 0 the anchor is honored as-is (clamped into range): content
|
|
46
|
+
* growth must NOT slide the viewport. While offset = 0 the tail is followed.
|
|
47
|
+
* The returned state is re-clamped, so a shrunken transcript falls back to the
|
|
48
|
+
* tail instead of pinning past the end.
|
|
49
|
+
*/
|
|
50
|
+
export function viewportTop(
|
|
51
|
+
s: ScrollState,
|
|
52
|
+
contentLen: number,
|
|
53
|
+
inner: number,
|
|
54
|
+
): { from: number; state: ScrollState } {
|
|
55
|
+
const tailTop = tailTopOf(contentLen, inner);
|
|
56
|
+
if (s.offset === 0) return { from: tailTop, state: FOLLOW_TAIL };
|
|
57
|
+
const from = Math.max(0, Math.min(tailTop, s.top));
|
|
58
|
+
return from >= tailTop ? { from, state: FOLLOW_TAIL } : { from, state: { offset: tailTop - from, top: from } };
|
|
59
|
+
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// unit-testable exactly like the reference's frame(w, h).
|
|
5
5
|
import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
|
|
6
6
|
import type { SessionSummary } from "../../dpi-sdk/src/api.ts";
|
|
7
|
+
import type { GitStatus } from "../../dpi-sdk/src/client.ts";
|
|
7
8
|
import type { DeviceRow } from "../../dpi-sdk/src/node/registry.ts";
|
|
8
9
|
import { c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
|
|
9
10
|
|
|
@@ -55,6 +56,18 @@ export const ageOf = (createdAt: number, now = Date.now()) => {
|
|
|
55
56
|
|
|
56
57
|
export const sessionState = (s: SessionSummary): RowState =>
|
|
57
58
|
s.error ? "error" : s.busy ? "busy" : "idle";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The state suffix the /git toast and the agent-header chip append after
|
|
62
|
+
* branch ±dirty (R5 finding 4): a merge in progress and a detached HEAD used
|
|
63
|
+
* to be invisible in the TUI while the backend already reported both — the
|
|
64
|
+
* web's GitPanel has carried a merge banner all along. Mirrors the FE text.
|
|
65
|
+
*/
|
|
66
|
+
export function gitStateSuffix(g: Pick<GitStatus, "merge" | "conflicts" | "detached">): string {
|
|
67
|
+
if (g.merge) return ` · merging (${g.conflicts ?? 0} conflicts)`;
|
|
68
|
+
if (g.detached) return " (detached)";
|
|
69
|
+
return "";
|
|
70
|
+
}
|
|
58
71
|
export const deviceState = (d: DeviceRow): RowState =>
|
|
59
72
|
d.lastStatus === "online"
|
|
60
73
|
? "busy"
|
|
@@ -259,7 +272,9 @@ export function renderStatusbar(
|
|
|
259
272
|
: opts.view === "agent"
|
|
260
273
|
? ["g herd", "N network", "L log", "[ ] tabs", "m message"]
|
|
261
274
|
: ["j/k move", "↵ open", "1-4 views", "⇥ tabs", "esc agent"];
|
|
262
|
-
|
|
275
|
+
// Catalog miss degrades to "?" (R5 finding 5): "—" read as "no usage yet",
|
|
276
|
+
// when it actually means the window is unknown — a different problem.
|
|
277
|
+
const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("?") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(opts.device, 18))}`;
|
|
263
278
|
const left = `${chip} ${keys.map((k) => c.muted(k)).join(c.muted(" • "))}`;
|
|
264
279
|
const gap = Math.max(1, w - visibleWidth(left) - visibleWidth(right));
|
|
265
280
|
return c.inverse(padTo(fit(`${left}${rep(" ", gap)}${right}`, w), w));
|
|
@@ -338,7 +353,7 @@ export function renderHerdPanel(
|
|
|
338
353
|
` ${c.muted("agents")} ${agents.length ? agents[0] : "—"}`,
|
|
339
354
|
...agents.slice(1, 8).map((a) => ` ${c.muted(a)}`),
|
|
340
355
|
"",
|
|
341
|
-
` ${c.muted("ctx")} ${ctxLeft === undefined ? c.muted("
|
|
356
|
+
` ${c.muted("ctx")} ${ctxLeft === undefined ? c.muted("?") : c.text(`${ctxLeft}% left`)}`,
|
|
342
357
|
` ${c.muted("age")} ${c.muted(ageOf(s.createdAt))}`,
|
|
343
358
|
` ${c.muted("tokens")} ${c.muted(compact(s.agents.reduce((n, a) => n + a.background, 0)) + " bg")}`,
|
|
344
359
|
];
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Display-width transcript wrapping (R5 finding 1). Pure — unit-testable like
|
|
2
|
+
// the views.
|
|
3
|
+
//
|
|
4
|
+
// The old wrap split each line exactly ONCE on UTF-16 code units
|
|
5
|
+
// (`[l.slice(0, w-4), l.slice(w-4)]`): the remainder was never re-wrapped, so
|
|
6
|
+
// pi-tui hard-clipped the tail of every overlong row — a 400-char message
|
|
7
|
+
// showed ~154 chars at 80 columns. And `l.length` counts UTF-16 units, not
|
|
8
|
+
// terminal columns, so CJK/emoji (2 cells each) overflowed their budget and
|
|
9
|
+
// got clipped too.
|
|
10
|
+
//
|
|
11
|
+
// wrapByColumn walks grapheme COLUMNS instead, pi-tui sliceByColumn/truncate
|
|
12
|
+
// semantics (the 0.0.53 panelLine lesson): every visible column lands on some
|
|
13
|
+
// row (no content loss), and a wide char that would straddle the budget moves
|
|
14
|
+
// whole to the next row (strict slice) instead of being clipped mid-glyph.
|
|
15
|
+
import { sliceByColumn, visibleWidth } from "@earendil-works/pi-tui";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Hard-wrap `text` on newlines, then to a display-column budget per row, and
|
|
19
|
+
* indent every row. Budget = width - 4 - indent, the old `w - 4` margin kept
|
|
20
|
+
* (with the indent now counted) so wrapped rows can never reach the frame's
|
|
21
|
+
* hard-clip edge even if a grapheme measures one cell wide in practice.
|
|
22
|
+
*/
|
|
23
|
+
export function wrapByColumn(text: string, width: number, indent = " "): string[] {
|
|
24
|
+
const budget = Math.max(4, width - 4 - visibleWidth(indent));
|
|
25
|
+
const out: string[] = [];
|
|
26
|
+
for (const line of text.split("\n")) {
|
|
27
|
+
const total = visibleWidth(line);
|
|
28
|
+
if (total <= budget) {
|
|
29
|
+
out.push(line);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
let col = 0;
|
|
33
|
+
while (col < total) {
|
|
34
|
+
const part = sliceByColumn(line, col, budget, true);
|
|
35
|
+
const partWidth = visibleWidth(part);
|
|
36
|
+
if (partWidth <= 0) break; // only zero-width columns remain — nothing visible lost
|
|
37
|
+
out.push(part);
|
|
38
|
+
col += partWidth;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out.map((l) => indent + l);
|
|
42
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.59",
|
|
4
4
|
"description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|