my-durable 0.0.71 → 0.0.73
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/README.md +2 -2
- package/apps/dpi-backend/API.md +1 -0
- package/apps/dpi-backend/src/backup.ts +25 -1
- package/apps/dpi-backend/src/git.ts +34 -2
- package/apps/dpi-backend/src/routes.ts +10 -1
- package/apps/dpi-backend/src/store.ts +149 -2
- package/apps/dpi-backend/src/telegram.ts +141 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BE-fN78Y.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-C9TcDwN6.js +82 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +43 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +32 -3
- package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +18 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +6 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +5 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +59 -3
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +1 -1
- package/apps/dpi-sdk/src/api.ts +13 -1
- package/apps/dpi-sdk/src/client.ts +12 -5
- package/apps/dpi-sdk/src/node/config.ts +34 -5
- package/apps/dpi-sdk/src/node/drivers.ts +15 -1
- package/apps/dpi-tui/src/app.ts +8 -6
- package/apps/dpi-tui/src/commands.ts +44 -4
- package/apps/dpi-tui/src/main.ts +3 -1
- package/apps/dpi-tui/src/pairing.ts +11 -10
- package/apps/dpi-tui/src/views.ts +1 -1
- package/apps/dpi-tui/src/welcome.ts +1 -1
- package/docs/host-project-checklist.md +1 -1
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CpNu1wqa.js +0 -81
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DSU1QhGO.css +0 -1
package/README.md
CHANGED
|
@@ -167,13 +167,13 @@ Fork any agent at any entry, from the transcript or with `/fork`. The fork copie
|
|
|
167
167
|
<img src="images/15_web_client.png" alt="The web client: the network tree with five devices, the inspector's Session tab with the context bar, and an agent's transcript on a cloud VM" width="800">
|
|
168
168
|
</p>
|
|
169
169
|
|
|
170
|
-
The web client has three columns: the **network tree** (device → session → agent), the **inspector** and the **agent**. The inspector tabs are Session (model, thinking, context bar, usage), State, Tasks, Tools and Extend. The composer sends a follow-up, a steer (it joins after the current tool round) or a reject-if-busy, and `/` opens the slash commands. The browser never sees a token. It holds one SSE connection to the hub, and the hub opens the authenticated upstreams.
|
|
170
|
+
The web client has three columns: the **network tree** (device → session → agent), the **inspector** and the **agent**. The inspector tabs are Session (model, thinking, context bar, usage), State, Tasks, Tools and Extend. The composer sends a follow-up, a steer (it joins after the current tool round) or a reject-if-busy, and `/` opens the slash commands. The sidebar's search box matches session names, folders and models — and, across every online device, the text inside their transcripts, so one word finds the session where an agent said it. The browser never sees a token. It holds one SSE connection to the hub, and the hub opens the authenticated upstreams.
|
|
171
171
|
|
|
172
172
|
<p align="center">
|
|
173
173
|
<img src="images/16_terminal_client.svg" alt="dpi-tui attached to vm-1:release-notes: the device, workspace and agent header, write and bash tool rows with results, and the model, context and cost footer" width="780">
|
|
174
174
|
</p>
|
|
175
175
|
|
|
176
|
-
`dpi-tui` is pi's look and keys over the network API. Enter sends or steers, Alt+Enter queues a follow-up, Esc interrupts, and Ctrl+C on an empty prompt exits with the command to reattach. **The agent keeps running.**
|
|
176
|
+
`dpi-tui` is pi's look and keys over the network API. Enter sends or steers, Alt+Enter queues a follow-up, Esc interrupts, and Ctrl+C on an empty prompt exits with the command to reattach. **The agent keeps running.** `/find <text>` searches every session's transcript on the device and shows the agent, entry and snippet of each hit.
|
|
177
177
|
|
|
178
178
|
```bash
|
|
179
179
|
just tui attach <device> # pick or create a session on a device
|
package/apps/dpi-backend/API.md
CHANGED
|
@@ -22,6 +22,7 @@ The contract every Durable Agent Network client uses: the web hub, `dpi-tui`, sc
|
|
|
22
22
|
| `GET /v1/fs/dirs` | `?path=` (empty = start dirs) | `{path, parent, dirs[]}`, one level, directories only |
|
|
23
23
|
| `GET /v1/docs/app.shared-state` | | `{kind, value, revision}` |
|
|
24
24
|
| `GET /v1/sessions` | | `SessionSummary[]` |
|
|
25
|
+
| `GET /v1/sessions/search` | `?q=` (`&scope=all` for transcripts) | metadata matches (`name`/`cwd`/`model`, cap 50). `scope=all` also scans stored history, newest sessions first, with budgets (100 sessions, 4000 entries per agent, 50k entries total): matches gain `where:[…,"transcript"]` and up to 3 `hits:[{agent, entry, kind, text}]` per agent, plus `scanned:{sessions, entries, truncated}`. A session that cannot open is skipped, never fails the search |
|
|
25
26
|
| `POST /v1/sessions` | `{name, cwd, model?:{provider,modelId}, thinkingLevel?}` — model is optional: explicit → the project's default → the device default (`DeviceInfo.defaultModel`) | `201 SessionSummary` |
|
|
26
27
|
| `GET / PATCH / DELETE /v1/sessions/:s` | PATCH `{name}` | summary (with its `compaction` thresholds); DELETE aborts all work, moves the files to `archive/` and returns `{archived}` |
|
|
27
28
|
| `GET / PATCH /v1/sessions/:s/compaction` | PATCH `{enabled?, reserveTokens?, backgroundTokens?, keepRecentTokens?}` | the session's automatic compaction thresholds, read by pi-durable at its next request. Values are margins: the blocking summary starts at the model's context window minus `reserveTokens`, and the background one `backgroundTokens` earlier (0 turns it off). Default: a background summary at 200k tokens and a blocking one at 250k, or pi-durable's margins on smaller windows. Switching an agent to a window the thresholds do not fit refits them |
|
|
@@ -53,6 +53,8 @@ const describeError = (error: unknown) => (error instanceof Error ? error.messag
|
|
|
53
53
|
|
|
54
54
|
/** The in-memory zip build is capped so `createBackup` cannot balloon the device's RAM. */
|
|
55
55
|
export const MAX_BACKUP_BYTES = 256 * 1024 * 1024;
|
|
56
|
+
/** R17: how much of an entry-0 manifest may ride free of the total cap (real manifests are ~150 bytes). */
|
|
57
|
+
const MANIFEST_ALLOWANCE_BYTES = 64 * 1024;
|
|
56
58
|
/** `ensurePrivateDir` (dpi-sdk) is synchronous and not injectable; the io carries the same 0700/0600 rule instead. */
|
|
57
59
|
const DIR_MODE = 0o700;
|
|
58
60
|
const FILE_MODE = 0o600;
|
|
@@ -383,8 +385,12 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
383
385
|
// backup ceiling — a pile of individually-legal entries must not add up
|
|
384
386
|
// to an unbounded restore either. Entry 0 is the writer's own manifest,
|
|
385
387
|
// which the write-side budget (walkHome) never counts, so a ceiling-sized
|
|
386
|
-
// home must stay restorable (R15 cold review P2-1).
|
|
388
|
+
// home must stay restorable (R15 cold review P2-1). R17 (run-3 h2): the
|
|
389
|
+
// exemption is now BOUNDED to a manifest-plausible allowance (the real
|
|
390
|
+
// manifest is a fixed ~150-byte shape) — a hostile entry-0 declaring the
|
|
391
|
+
// full 256 MiB used to ride free and double the retained ceiling.
|
|
387
392
|
if (i > 0 || name !== "manifest.json") totalDeclared += uncompressedSize;
|
|
393
|
+
else totalDeclared += Math.max(0, uncompressedSize - MANIFEST_ALLOWANCE_BYTES);
|
|
388
394
|
if (totalDeclared > MAX_BACKUP_BYTES) {
|
|
389
395
|
throw bad(`archive declares more than ${MAX_BACKUP_BYTES} bytes of entries`);
|
|
390
396
|
}
|
|
@@ -427,6 +433,24 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
|
|
|
427
433
|
|
|
428
434
|
/** Read + parse a backup file; restore and the CLI's plan share the `not_found` mapping. */
|
|
429
435
|
export async function readBackupEntries(io: BackupIo, zipPath: string): Promise<ZipArchiveEntry[]> {
|
|
436
|
+
// R18 (run-4 h2): refuse by physical size BEFORE reading. The file is a
|
|
437
|
+
// 1:1 operator-own artifact, but a typed refusal beats a linear RAM spike
|
|
438
|
+
// into the CLI process (slack covers zip structure overhead: entries +
|
|
439
|
+
// central directory + any comment).
|
|
440
|
+
const PHYSICAL_SLACK_BYTES = 16 * 1024 * 1024;
|
|
441
|
+
try {
|
|
442
|
+
const size = (await io.stat(zipPath)).size;
|
|
443
|
+
if (size > MAX_BACKUP_BYTES + PHYSICAL_SLACK_BYTES) {
|
|
444
|
+
const mbSize = (n: number) => `${(n / (1024 * 1024)).toFixed(1)} MiB`;
|
|
445
|
+
throw new BackupError(
|
|
446
|
+
"invalid",
|
|
447
|
+
`backup ${zipPath} is ${mbSize(size)} on disk — over the ${mbSize(MAX_BACKUP_BYTES)} restore ceiling; refusing to load it`,
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
} catch (error) {
|
|
451
|
+
if (error instanceof BackupError) throw error;
|
|
452
|
+
throw new BackupError("not_found", `cannot read backup ${zipPath}: ${describeError(error)}`);
|
|
453
|
+
}
|
|
430
454
|
let data: Uint8Array;
|
|
431
455
|
try {
|
|
432
456
|
data = await io.readFile(resolve(zipPath));
|
|
@@ -59,8 +59,40 @@ const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
|
|
|
59
59
|
|
|
60
60
|
/** Child-process options, exported so a test can assert the Windows console
|
|
61
61
|
* window stays hidden: a daemon that polls git must never flash a terminal. */
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
/**
|
|
63
|
+
* R17 (run-3 h1 hardening): git/gh children run -C agent-writable repos where
|
|
64
|
+
* hooks/config are plantable. The daemon's process.env carries DPI_TOKEN
|
|
65
|
+
* (loadEnvFile) which shellEnv deliberately strips from agent processes —
|
|
66
|
+
* mirror that allowlist here so the token (and any future backend.env secret)
|
|
67
|
+
* never rides into repo-controlled hook environments.
|
|
68
|
+
*/
|
|
69
|
+
const CHILD_ENV_ALLOWLIST = ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "LANG", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK"];
|
|
70
|
+
// execFile `env` REPLACES the whole environment, and on win32 git/gh resolve
|
|
71
|
+
// home (USERPROFILE chain), config (APPDATA), temp (TEMP/TMP) and TLS
|
|
72
|
+
// (SystemRoot) from these — without them commit identity and gh auth break.
|
|
73
|
+
const WIN32_CHILD_ENV_ALLOWLIST = [
|
|
74
|
+
...CHILD_ENV_ALLOWLIST,
|
|
75
|
+
"SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT",
|
|
76
|
+
"TEMP", "TMP", "USERPROFILE", "HOMEDRIVE", "HOMEPATH",
|
|
77
|
+
"APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA",
|
|
78
|
+
];
|
|
79
|
+
const childEnv = (): NodeJS.ProcessEnv => {
|
|
80
|
+
const allow = process.platform === "win32" ? WIN32_CHILD_ENV_ALLOWLIST : CHILD_ENV_ALLOWLIST;
|
|
81
|
+
return Object.fromEntries(allow.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
|
|
82
|
+
}
|
|
83
|
+
export const GIT_EXEC_OPTS = (timeout: number) => ({
|
|
84
|
+
timeout,
|
|
85
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
env: childEnv(),
|
|
88
|
+
});
|
|
89
|
+
export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({
|
|
90
|
+
cwd,
|
|
91
|
+
timeout,
|
|
92
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
93
|
+
windowsHide: true,
|
|
94
|
+
env: childEnv(),
|
|
95
|
+
});
|
|
64
96
|
|
|
65
97
|
/** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
|
|
66
98
|
* is not redefinable, so `mock.method` cannot reach `execFile`. Pass nothing
|
|
@@ -350,7 +350,16 @@ export function v1(
|
|
|
350
350
|
r.post("/sessions", create, route(async (req, res) => res.status(201).json(await store.create(req.body ?? {}))));
|
|
351
351
|
// Literal route, so it must precede `/sessions/:s` (Express matches in order).
|
|
352
352
|
// Names/cwds/models only — transcript search needs an FTS index, not a LIKE scan.
|
|
353
|
-
r.get(
|
|
353
|
+
r.get(
|
|
354
|
+
"/sessions/search",
|
|
355
|
+
route(async (req, res) => {
|
|
356
|
+
const q = String(req.query.q ?? "");
|
|
357
|
+
// scope=all adds the bounded transcript scan (R18); default stays metadata-only
|
|
358
|
+
// so existing callers see the same shape and cost as before.
|
|
359
|
+
if (String(req.query.scope ?? "") === "all") return res.json(await store.searchSessionsAll(q));
|
|
360
|
+
return res.json(store.searchSessions(q));
|
|
361
|
+
}),
|
|
362
|
+
);
|
|
354
363
|
r.get("/sessions/:s", route(async (_req, res) => res.json(await store.sessionSummary(L(res).row))));
|
|
355
364
|
r.patch("/sessions/:s", route(async (req, res) => res.json(await store.rename(L(res).row, req.body?.name))));
|
|
356
365
|
r.get("/sessions/:s/compaction", route(async (_req, res) => res.json(store.compactionOf(L(res).row.id))));
|
|
@@ -25,6 +25,7 @@ import type {
|
|
|
25
25
|
TaskNode,
|
|
26
26
|
TaskOutcome,
|
|
27
27
|
ThinkingLevel,
|
|
28
|
+
TranscriptSearchHit,
|
|
28
29
|
UsageTotals,
|
|
29
30
|
WhenBusy,
|
|
30
31
|
WireEntry,
|
|
@@ -45,6 +46,7 @@ import {
|
|
|
45
46
|
type UsageSummary,
|
|
46
47
|
} from "../../dpi-sdk/src/transcript.js";
|
|
47
48
|
import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
|
|
49
|
+
import { searchHistory } from "./history.js";
|
|
48
50
|
import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
|
|
49
51
|
import { DatabaseSync } from "node:sqlite";
|
|
50
52
|
import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
|
|
@@ -71,6 +73,7 @@ import {
|
|
|
71
73
|
import {
|
|
72
74
|
listArchived,
|
|
73
75
|
findBundle,
|
|
76
|
+
readArchiveManifest,
|
|
74
77
|
archivedTranscript,
|
|
75
78
|
restoreArchive,
|
|
76
79
|
writeArchiveManifest,
|
|
@@ -80,6 +83,7 @@ import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } fro
|
|
|
80
83
|
import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
|
|
81
84
|
import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
|
|
82
85
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
86
|
+
import { lstat } from "node:fs/promises";
|
|
83
87
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
84
88
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
85
89
|
import { homedir, hostname, platform } from "node:os";
|
|
@@ -197,6 +201,12 @@ const CODE_DIR = resolve(import.meta.dirname, "../../..");
|
|
|
197
201
|
/** Session search result cap: one screen of matches, not a transcript dump. */
|
|
198
202
|
const SEARCH_LIMIT = 50;
|
|
199
203
|
|
|
204
|
+
/** Transcript-search budgets (scope=all): newest-first across sessions, bounded work. */
|
|
205
|
+
const TRANSCRIPT_SESSION_LIMIT = 100;
|
|
206
|
+
const TRANSCRIPT_AGENT_ENTRY_LIMIT = 4000;
|
|
207
|
+
const TRANSCRIPT_ENTRY_BUDGET = 50_000;
|
|
208
|
+
const TRANSCRIPT_HITS_PER_AGENT = 3;
|
|
209
|
+
|
|
200
210
|
/** Scheduler granularity. Schedules are minute-granular, so 30 s is enough and
|
|
201
211
|
* the timer is unref'd: it never holds the process open. */
|
|
202
212
|
const SCHEDULE_TICK_MS = 30_000;
|
|
@@ -1016,7 +1026,29 @@ export class Store {
|
|
|
1016
1026
|
// ancestor was found at all, judging the raw spelling lexically would
|
|
1017
1027
|
// resurrect the exact symlink escape this walk exists to close.
|
|
1018
1028
|
if (resolvedAncestor === undefined) throw invalid("path must live under a start dir");
|
|
1019
|
-
|
|
1029
|
+
// R17 (run-3 h1): lstat every re-appended tail component. The walk only
|
|
1030
|
+
// calls realpath, which cannot see a DANGLING symlink — a link component
|
|
1031
|
+
// pointing at a nonexistent path would ride the tail verbatim and be
|
|
1032
|
+
// judged lexically. Any symlink in the tail is resolved-and-rejudged;
|
|
1033
|
+
// a dangling one is refused (fail closed on what the walk cannot see).
|
|
1034
|
+
let walked = resolvedAncestor;
|
|
1035
|
+
for (const part of tail) {
|
|
1036
|
+
const next = join(walked, part);
|
|
1037
|
+
let isLink = false;
|
|
1038
|
+
try {
|
|
1039
|
+
isLink = (await lstat(next)).isSymbolicLink();
|
|
1040
|
+
} catch {
|
|
1041
|
+
isLink = false; // plain missing component: fine, the path is new
|
|
1042
|
+
}
|
|
1043
|
+
if (isLink) {
|
|
1044
|
+
const linked = await realpath(next).catch(() => undefined);
|
|
1045
|
+
if (linked === undefined) throw invalid("path must live under a start dir"); // dangling link: refuse
|
|
1046
|
+
walked = linked; // existing link target: continue the walk from truth
|
|
1047
|
+
} else {
|
|
1048
|
+
walked = next;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
candidate = walked;
|
|
1020
1052
|
}
|
|
1021
1053
|
if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
|
|
1022
1054
|
return candidate;
|
|
@@ -1563,12 +1595,34 @@ export class Store {
|
|
|
1563
1595
|
async restoreArchivedSession(sessionId: string): Promise<SessionSummary> {
|
|
1564
1596
|
if (this.list().some((r) => r.id === sessionId))
|
|
1565
1597
|
throw invalid("a live session with this id already exists");
|
|
1598
|
+
// R18 (run-4 h1): restore is a session-placement writer, so it enforces
|
|
1599
|
+
// the SAME choke point as create — a planted archive manifest must not
|
|
1600
|
+
// root a restored session (and its tool environment) outside the start
|
|
1601
|
+
// dirs. Leader-probe confirmed the verbatim insert bypassed it. The
|
|
1602
|
+
// validation runs BEFORE restoreArchive moves the bundle, so a refusal
|
|
1603
|
+
// leaves the archive untouched (restorable once the manifest is fixed).
|
|
1604
|
+
const bundleDir = findBundle(this.archiveDir, sessionId);
|
|
1605
|
+
if (!bundleDir) throw notFound(`no archived session ${sessionId}`);
|
|
1606
|
+
const pre = readArchiveManifest(bundleDir);
|
|
1607
|
+
if (pre && pre.sessionId !== sessionId.toLowerCase())
|
|
1608
|
+
throw invalid(`archive manifest claims session ${pre.sessionId}, not ${sessionId} — refusing to restore under a foreign id`);
|
|
1609
|
+
const candidateCwd = pre?.cwd ?? "";
|
|
1610
|
+
if (!candidateCwd.trim())
|
|
1611
|
+
throw invalid(`archive manifest has no usable cwd — restore needs the bundle's session.json to name a start-dir folder`);
|
|
1612
|
+
let restoredCwd: string;
|
|
1613
|
+
try {
|
|
1614
|
+
restoredCwd = await realpath(resolve(candidateCwd));
|
|
1615
|
+
if (!(await stat(restoredCwd)).isDirectory()) throw Error();
|
|
1616
|
+
} catch {
|
|
1617
|
+
throw invalid(`archived cwd is not an existing folder on ${this.name}: ${candidateCwd}`);
|
|
1618
|
+
}
|
|
1619
|
+
await this.assertSessionCwdAllowed(restoredCwd);
|
|
1566
1620
|
const manifest = await restoreArchive(this.archiveDir, this.options.dataDir, sessionId).catch(() => undefined);
|
|
1567
1621
|
if (!manifest) throw notFound(`no archived session ${sessionId}`);
|
|
1568
1622
|
const row: SessionRow = {
|
|
1569
1623
|
id: manifest.sessionId,
|
|
1570
1624
|
name: manifest.name || "Untitled session",
|
|
1571
|
-
cwd:
|
|
1625
|
+
cwd: restoredCwd,
|
|
1572
1626
|
dbPath: join(this.sessionsDir, manifest.sessionId, "agent.sqlite"),
|
|
1573
1627
|
createdAt: manifest.createdAt,
|
|
1574
1628
|
model: manifest.model,
|
|
@@ -2533,6 +2587,99 @@ export class Store {
|
|
|
2533
2587
|
return { query, matches: matches.slice(0, SEARCH_LIMIT) };
|
|
2534
2588
|
}
|
|
2535
2589
|
|
|
2590
|
+
/**
|
|
2591
|
+
* R18 transcript search (scope=all): the metadata pass above, PLUS a
|
|
2592
|
+
* bounded newest-first scan of every session's stored history — the answer
|
|
2593
|
+
* to "which session did the agent say X in?". One broken session (storage
|
|
2594
|
+
* busy, unopenable) is skipped, never fails the search. Budgets: newest
|
|
2595
|
+
* TRANSCRIPT_SESSION_LIMIT sessions, TRANSCRIPT_AGENT_ENTRY_LIMIT entries per
|
|
2596
|
+
* agent, TRANSCRIPT_ENTRY_BUDGET entries total (truncated=true past that).
|
|
2597
|
+
*/
|
|
2598
|
+
async searchSessionsAll(rawQuery: string): Promise<SessionSearchResult> {
|
|
2599
|
+
const query = String(rawQuery ?? "").trim();
|
|
2600
|
+
const result = this.searchSessions(query);
|
|
2601
|
+
if (query.length < 2) return result;
|
|
2602
|
+
const byId = new Map(
|
|
2603
|
+
result.matches.map((m) => [m.id, { ...m, hits: [] as TranscriptSearchHit[] }] as const),
|
|
2604
|
+
);
|
|
2605
|
+
let entriesScanned = 0;
|
|
2606
|
+
let sessionsScanned = 0;
|
|
2607
|
+
let truncated = false;
|
|
2608
|
+
for (const row of this.list()) {
|
|
2609
|
+
if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
|
|
2610
|
+
truncated = true;
|
|
2611
|
+
break;
|
|
2612
|
+
}
|
|
2613
|
+
sessionsScanned += 1;
|
|
2614
|
+
let h: Harness;
|
|
2615
|
+
try {
|
|
2616
|
+
try {
|
|
2617
|
+
h = this.harness(row);
|
|
2618
|
+
} catch {
|
|
2619
|
+
h = await this.reopenOnce(row);
|
|
2620
|
+
}
|
|
2621
|
+
} catch {
|
|
2622
|
+
continue; // a session that cannot open does not block the search
|
|
2623
|
+
}
|
|
2624
|
+
try {
|
|
2625
|
+
let marked = false;
|
|
2626
|
+
const names = this.names(row.id);
|
|
2627
|
+
for (const record of await this.scanAll(h)) {
|
|
2628
|
+
// The TOTAL budget binds inside the conversation loop too: a
|
|
2629
|
+
// fork-heavy session (a flagship feature) has many conversations,
|
|
2630
|
+
// and per-agent caps alone let one session scan past 50k entries
|
|
2631
|
+
// (cold-review major 2 — API.md promises a total budget).
|
|
2632
|
+
if (entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
|
|
2633
|
+
truncated = true;
|
|
2634
|
+
break;
|
|
2635
|
+
}
|
|
2636
|
+
const c = await h.conversation(record.id as ConversationId, ctx);
|
|
2637
|
+
if (!c) continue;
|
|
2638
|
+
const entries: WireEntry[] = [];
|
|
2639
|
+
let cursor: string | undefined;
|
|
2640
|
+
do {
|
|
2641
|
+
const page = await c.entries({}, 2000, decodeCursor(cursor), ctx);
|
|
2642
|
+
entries.push(...(page.items as unknown as WireEntry[]));
|
|
2643
|
+
cursor = encodeCursor(page.next);
|
|
2644
|
+
} while (cursor && entries.length < TRANSCRIPT_AGENT_ENTRY_LIMIT);
|
|
2645
|
+
entriesScanned += entries.length;
|
|
2646
|
+
const hits = searchHistory(entries, { query, order: "newest", limit: TRANSCRIPT_HITS_PER_AGENT }, {}).results;
|
|
2647
|
+
if (!hits.length) continue;
|
|
2648
|
+
const ref = this.agentRef(record, names);
|
|
2649
|
+
const base = byId.get(row.id) ?? {
|
|
2650
|
+
...this.sessionSummaryBase(row),
|
|
2651
|
+
where: [],
|
|
2652
|
+
hits: [] as TranscriptSearchHit[],
|
|
2653
|
+
};
|
|
2654
|
+
if (!marked) {
|
|
2655
|
+
base.where.push("transcript");
|
|
2656
|
+
marked = true;
|
|
2657
|
+
}
|
|
2658
|
+
for (const hit of hits)
|
|
2659
|
+
base.hits!.push({ agent: ref.name, entry: hit.entry, kind: hit.kind, text: hit.text });
|
|
2660
|
+
byId.set(row.id, base);
|
|
2661
|
+
}
|
|
2662
|
+
} catch {
|
|
2663
|
+
continue; // one session's read failure never fails the search
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
// Name hits first, then transcript hits, then the newest — same intent as the metadata pass.
|
|
2667
|
+
const matches = [...byId.values()]
|
|
2668
|
+
.filter((m) => m.where.length)
|
|
2669
|
+
.sort(
|
|
2670
|
+
(a, b) =>
|
|
2671
|
+
Number(b.where.includes("name")) - Number(a.where.includes("name")) ||
|
|
2672
|
+
Number(b.where.includes("transcript")) - Number(a.where.includes("transcript")) ||
|
|
2673
|
+
b.createdAt - a.createdAt,
|
|
2674
|
+
)
|
|
2675
|
+
.slice(0, SEARCH_LIMIT);
|
|
2676
|
+
return {
|
|
2677
|
+
query,
|
|
2678
|
+
matches,
|
|
2679
|
+
scanned: { sessions: sessionsScanned, entries: entriesScanned, truncated },
|
|
2680
|
+
};
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2536
2683
|
/**
|
|
2537
2684
|
* One downloadable archive of a session: manifest, session record, and every
|
|
2538
2685
|
* agent's transcript + config (paseo `exports.ts` shape). Text only, zipped by
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
* the tests run against fakes with zero sockets and zero real time.
|
|
35
35
|
*/
|
|
36
36
|
import { randomBytes } from "node:crypto";
|
|
37
|
-
import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
37
|
+
import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
38
38
|
import { dirname, resolve } from "node:path";
|
|
39
39
|
|
|
40
40
|
/** Bumped only when the on-disk shape changes; `coerceRegistry` owns the upgrade path. */
|
|
@@ -101,6 +101,12 @@ export interface TelegramIo {
|
|
|
101
101
|
/** Returns an unref-able handle, so the bridge never holds the event loop open. */
|
|
102
102
|
setTimeout(cb: () => void, ms: number): { unref(): void };
|
|
103
103
|
clearTimeout(t: { unref(): void }): void;
|
|
104
|
+
/**
|
|
105
|
+
* R18 (run-4 h3): cross-writer mutual exclusion around the registry's
|
|
106
|
+
* read-modify-write (daemon + dpi telegram CLI are two OS processes).
|
|
107
|
+
* Optional so pure in-memory fakes stay small; absent = unlocked caller.
|
|
108
|
+
*/
|
|
109
|
+
withLock?<T>(path: string, fn: () => Promise<T>): Promise<T>;
|
|
104
110
|
}
|
|
105
111
|
|
|
106
112
|
export const defaultTelegramIo = (): TelegramIo => ({
|
|
@@ -121,6 +127,40 @@ export const defaultTelegramIo = (): TelegramIo => ({
|
|
|
121
127
|
}
|
|
122
128
|
},
|
|
123
129
|
chmod: (path, mode) => chmod(path, mode),
|
|
130
|
+
withLock: async <T>(path: string, fn: () => Promise<T>): Promise<T> => {
|
|
131
|
+
// Advisory lock file next to the registry. Both writers are the same OS
|
|
132
|
+
// user, so create-exclusive + stale-break (mtime older than 5 s — a
|
|
133
|
+
// crashed holder never wedges the bridge) is mutual exclusion enough.
|
|
134
|
+
const lockPath = `${path}.lock`;
|
|
135
|
+
const deadline = Date.now() + 10_000;
|
|
136
|
+
for (;;) {
|
|
137
|
+
try {
|
|
138
|
+
const handle = await open(lockPath, "wx", 0o600);
|
|
139
|
+
await handle.write(`${process.pid}\n`);
|
|
140
|
+
await handle.close();
|
|
141
|
+
break;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
144
|
+
let age = 0;
|
|
145
|
+
try {
|
|
146
|
+
age = Date.now() - (await stat(lockPath)).mtimeMs;
|
|
147
|
+
} catch {
|
|
148
|
+
continue; // released between the create attempt and the stat
|
|
149
|
+
}
|
|
150
|
+
if (age > 5_000) {
|
|
151
|
+
await unlink(lockPath).catch(() => undefined); // stale holder — break it
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (Date.now() > deadline) throw new Error(`telegram registry lock busy: ${lockPath}`);
|
|
155
|
+
await new Promise((r) => setTimeout(r, 25));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
return await fn();
|
|
160
|
+
} finally {
|
|
161
|
+
await unlink(lockPath).catch(() => undefined);
|
|
162
|
+
}
|
|
163
|
+
},
|
|
124
164
|
exists: async (path) => {
|
|
125
165
|
try {
|
|
126
166
|
await stat(path);
|
|
@@ -182,7 +222,7 @@ export interface TelegramRegistryFile {
|
|
|
182
222
|
codes: TelegramBindCode[];
|
|
183
223
|
}
|
|
184
224
|
|
|
185
|
-
export type TelegramBridgeErrorCode = "invalid";
|
|
225
|
+
export type TelegramBridgeErrorCode = "invalid" | "registry_changed";
|
|
186
226
|
|
|
187
227
|
/** Typed failure for the mutation paths (`bind`) so a UI can answer without string matching. */
|
|
188
228
|
export class TelegramBridgeError extends Error {
|
|
@@ -465,6 +505,11 @@ export class TelegramBridge {
|
|
|
465
505
|
targetId = sessionId;
|
|
466
506
|
}
|
|
467
507
|
return this.run(async () => {
|
|
508
|
+
// R17 (run-3 h4): the CLI is the SECOND writer — re-read the registry
|
|
509
|
+
// (adopt foreign state) before snapshotting, so a daemon commit that
|
|
510
|
+
// landed since open() is not clobbered by our persist CAS.
|
|
511
|
+
if (!(await this.syncForeign()))
|
|
512
|
+
throw new TelegramBridgeError("registry_changed", `registry ${this.filePath} is missing/unreadable; refusing to bind`);
|
|
468
513
|
const now = this.now();
|
|
469
514
|
const draft = this.snapshot();
|
|
470
515
|
draft.codes = draft.codes.filter((code) => Date.parse(code.expiresAt) > now); // prune the dead ones
|
|
@@ -486,6 +531,8 @@ export class TelegramBridge {
|
|
|
486
531
|
/** Remove the first binding whose chat id starts with `chatPrefix`; returns the chat id, or undefined when none matched. */
|
|
487
532
|
async unbind(chatPrefix: string): Promise<number | undefined> {
|
|
488
533
|
return this.run(async () => {
|
|
534
|
+
// R17 (run-3 h4): same second-writer discipline as bind().
|
|
535
|
+
if (!(await this.syncForeign())) return undefined;
|
|
489
536
|
const draft = this.snapshot();
|
|
490
537
|
const hit = draft.chats.find((binding) => String(binding.chatId).startsWith(chatPrefix));
|
|
491
538
|
if (hit === undefined) return undefined;
|
|
@@ -598,7 +645,23 @@ export class TelegramBridge {
|
|
|
598
645
|
*/
|
|
599
646
|
private async syncForeign(): Promise<boolean> {
|
|
600
647
|
try {
|
|
601
|
-
|
|
648
|
+
// R17 (run-3 h4): an ABSENT registry is either a FRESH device (we have
|
|
649
|
+
// never known a registry: registryText null — load()'s "fresh device"
|
|
650
|
+
// semantics) or the operator revoking by removal while the daemon runs
|
|
651
|
+
// (or an unreadable file: exists() maps every stat failure to absent).
|
|
652
|
+
// Fresh → adopt the empty state and continue (bind works, no bindings
|
|
653
|
+
// exist to authorize anything). Known-then-gone → fail CLOSED: no
|
|
654
|
+
// dispatch on stale memory, and no persist either — a commit would
|
|
655
|
+
// resurrect the deleted file with the revoked bindings.
|
|
656
|
+
if (!(await this.io.exists(this.filePath))) {
|
|
657
|
+
if (this.registryText === null) {
|
|
658
|
+
this.adopt({ version: TELEGRAM_REGISTRY_VERSION, offset: this.offset, chats: [], codes: [] });
|
|
659
|
+
return true; // fresh: nothing to adopt, nothing to clobber
|
|
660
|
+
}
|
|
661
|
+
this.mainIsGood = false; // an absent main must not be "refreshed" into .bak
|
|
662
|
+
this.warn(`registry ${this.filePath} vanished; skipping the update (no dispatch, no persist)`);
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
602
665
|
const text = await this.io.readFile(this.filePath);
|
|
603
666
|
if (text === this.registryText) return true; // still our own last write
|
|
604
667
|
const file = coerceRegistry(JSON.parse(text), this.now());
|
|
@@ -609,6 +672,7 @@ export class TelegramBridge {
|
|
|
609
672
|
// Fail CLOSED (R15 cold review P3-1): with an unreadable/unparseable
|
|
610
673
|
// registry the in-memory bindings cannot be trusted to reflect the
|
|
611
674
|
// operator's intent — authorize nothing until the file is healthy.
|
|
675
|
+
this.mainIsGood = false; // the next persist must NOT bake these bytes into .bak
|
|
612
676
|
this.warn(`could not re-read ${this.filePath} before dispatch; skipping the update`, error);
|
|
613
677
|
return false;
|
|
614
678
|
}
|
|
@@ -639,6 +703,38 @@ export class TelegramBridge {
|
|
|
639
703
|
* new bytes through the io's atomic write, then 0600.
|
|
640
704
|
*/
|
|
641
705
|
private async persist(draft: TelegramRegistryFile): Promise<void> {
|
|
706
|
+
// R18 (run-4 h3): the whole read-modify-write is ONE critical section for
|
|
707
|
+
// every lock-respecting writer (this daemon + the dpi telegram CLI share
|
|
708
|
+
// defaultTelegramIo). Without the lock, a CLI commit landing between the
|
|
709
|
+
// CAS read and the final write is silently clobbered and a revoked binding
|
|
710
|
+
// resurrects (leader-probe confirmed on a0893c1-era code).
|
|
711
|
+
const commit = async (): Promise<void> => {
|
|
712
|
+
// R17 (run-3 h4): the registry has TWO writers (daemon + dpi telegram
|
|
713
|
+
// CLI). Write-after-read validation: if the file's bytes changed since we
|
|
714
|
+
// last saw them, our snapshot is stale — writing it would clobber the
|
|
715
|
+
// foreign commit (un-spend a code, revert a /stop). Fail loudly instead.
|
|
716
|
+
// R18 (run-4 h3): the vanished-registry case is ALSO a foreign change —
|
|
717
|
+
// rewriting from memory would resurrect every revoked binding. Fail closed
|
|
718
|
+
// exactly like syncForeign does.
|
|
719
|
+
if (this.registryText !== null) {
|
|
720
|
+
if (!(await this.io.exists(this.filePath))) {
|
|
721
|
+
this.mainIsGood = false;
|
|
722
|
+
throw new TelegramBridgeError(
|
|
723
|
+
"registry_changed",
|
|
724
|
+
`registry vanished before commit — refusing to resurrect ${this.filePath}`,
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
const current = await this.io.readFile(this.filePath);
|
|
728
|
+
if (current !== this.registryText) {
|
|
729
|
+
this.mainIsGood = false;
|
|
730
|
+
throw new TelegramBridgeError(
|
|
731
|
+
"registry_changed",
|
|
732
|
+
`registry changed under us (foreign write); re-open or retry — refusing to clobber ${this.filePath}`,
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
// registryText === null means no known baseline (fresh device or the
|
|
737
|
+
// load()-time recovery rewrite) — those writes are legitimate.
|
|
642
738
|
if (this.mainIsGood && (await this.io.exists(this.filePath))) {
|
|
643
739
|
try {
|
|
644
740
|
const previous = await this.io.readFile(this.filePath);
|
|
@@ -651,8 +747,49 @@ export class TelegramBridge {
|
|
|
651
747
|
const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
|
|
652
748
|
await this.io.writeFile(this.filePath, payload);
|
|
653
749
|
await this.io.chmod(this.filePath, 0o600);
|
|
750
|
+
// R18 (run-4 h3): the CAS above is separated from the write by several
|
|
751
|
+
// awaited fs ops, so a foreign write can land INSIDE our commit window.
|
|
752
|
+
// Verify after the write: if the bytes on disk are not exactly ours, we
|
|
753
|
+
// clobbered someone — restore THEIR bytes (our offset commit is safely
|
|
754
|
+
// re-delivered by Telegram) and fail loudly. The revoked binding stays
|
|
755
|
+
// revoked instead of silently resurrecting.
|
|
756
|
+
if (this.registryText !== null) {
|
|
757
|
+
try {
|
|
758
|
+
const after = await this.io.readFile(this.filePath);
|
|
759
|
+
if (after !== payload) {
|
|
760
|
+
await this.io.writeFile(this.filePath, after);
|
|
761
|
+
await this.io.chmod(this.filePath, 0o600);
|
|
762
|
+
// Converge memory onto the restored foreign bytes immediately — a
|
|
763
|
+
// stale in-memory binding must not authorize the very next update
|
|
764
|
+
// through syncForeign's "still our own last write" fast path.
|
|
765
|
+
const foreign = coerceRegistry(JSON.parse(after), this.now());
|
|
766
|
+
this.adopt({ ...foreign, offset: Math.max(this.offset, foreign.offset) });
|
|
767
|
+
this.registryText = after;
|
|
768
|
+
this.mainIsGood = false;
|
|
769
|
+
throw new TelegramBridgeError(
|
|
770
|
+
"registry_changed",
|
|
771
|
+
`registry changed during commit; foreign write preserved — refusing to clobber ${this.filePath}`,
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
} catch (error) {
|
|
775
|
+
if (error instanceof TelegramBridgeError) throw error;
|
|
776
|
+
// The verify read itself failed (e.g. deleted again): treat as a
|
|
777
|
+
// foreign change, keep the old non-null baseline so syncForeign stays
|
|
778
|
+
// fail-closed, and fail loudly.
|
|
779
|
+
this.mainIsGood = false;
|
|
780
|
+
throw new TelegramBridgeError(
|
|
781
|
+
"registry_changed",
|
|
782
|
+
`registry unreadable after commit — treating as foreign change on ${this.filePath}`,
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
654
786
|
this.registryText = payload;
|
|
655
787
|
this.mainIsGood = true;
|
|
788
|
+
};
|
|
789
|
+
if (this.io.withLock) return this.io.withLock(this.filePath, commit);
|
|
790
|
+
// Fakes without a lock keep the R17 semantics (CAS + verify) — the lock is
|
|
791
|
+
// what closes the pre-write half of the window for the real two writers.
|
|
792
|
+
return commit();
|
|
656
793
|
}
|
|
657
794
|
|
|
658
795
|
// --------------------------------------------------------------- poll loop
|
|
@@ -724,10 +861,10 @@ export class TelegramBridge {
|
|
|
724
861
|
/** Acknowledge first (persist the new offset), then handle. Never both-half-heartedly. */
|
|
725
862
|
private async handle(update: TelegramUpdate): Promise<void> {
|
|
726
863
|
const synced = await this.syncForeign();
|
|
864
|
+
if (!synced) return; // acknowledged (Telegram will redeliver), NOT authorized and NOT persisted — a stale snapshot must never become file truth again
|
|
727
865
|
await this.commit((draft) => {
|
|
728
866
|
draft.offset = Math.max(draft.offset, update.updateId + 1);
|
|
729
867
|
});
|
|
730
|
-
if (!synced) return; // acknowledged, but NOT authorized on stale state
|
|
731
868
|
if (!update.message) return; // non-message or non-text: acknowledged, ignored
|
|
732
869
|
await this.dispatch(
|
|
733
870
|
update.message.chatId,
|