my-durable 0.0.72 → 0.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/README.md +2 -2
  2. package/apps/dpi-backend/API.md +1 -0
  3. package/apps/dpi-backend/src/backup.ts +18 -0
  4. package/apps/dpi-backend/src/notify-sinks.ts +104 -2
  5. package/apps/dpi-backend/src/routes.ts +10 -1
  6. package/apps/dpi-backend/src/store.ts +170 -7
  7. package/apps/dpi-backend/src/telegram.ts +176 -2
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +82 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-h81haD43.css +1 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +43 -4
  12. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +75 -42
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +6 -2
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +6 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +12 -0
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +1 -1
  17. package/apps/dpi-sdk/src/api.ts +13 -1
  18. package/apps/dpi-sdk/src/client.ts +12 -5
  19. package/apps/dpi-sdk/src/models.ts +45 -2
  20. package/apps/dpi-sdk/src/node/config.ts +13 -2
  21. package/apps/dpi-sdk/src/node/drivers.ts +4 -0
  22. package/apps/dpi-tui/src/commands.ts +64 -2
  23. package/apps/dpi-tui/src/pairing.ts +2 -2
  24. package/apps/dpi-tui/src/views.ts +1 -1
  25. package/docs/host-project-checklist.md +1 -1
  26. package/package.json +1 -1
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CpNu1wqa.js +0 -81
  28. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DSU1QhGO.css +0 -1
@@ -99,6 +99,12 @@ export function applyMessageChange(message: WireAssistantMessage, change: WireMe
99
99
  if (change.type === "message") return structuredClone(change.message);
100
100
  const content = [...message.content] as WireAssistantBlock[];
101
101
  const i = change.contentIndex;
102
+ // R19 (run-5 h10, leader-probed): the wire number was indexed raw — any
103
+ // index > content.length creates holes that crash toTranscript's for-of
104
+ // ("Cannot read properties of undefined"), which the SSE follow loop turns
105
+ // into a disconnect/reconnect churn loop; a huge index also allocates a
106
+ // length-2^32 sparse array. Validate like setPath: drop the whole change.
107
+ if (!Number.isInteger(i) || i < 0 || i > content.length) return message;
102
108
  if (change.type === "block" || change.type.endsWith("_start")) {
103
109
  content[i] = structuredClone((change as { block: WireAssistantBlock }).block);
104
110
  } else if (change.type === "text_delta") {
@@ -170,6 +176,7 @@ export class AgentModel extends Emitter {
170
176
 
171
177
  private reset(snapshot: WireSnapshotEvent) {
172
178
  this.entries = new Map(snapshot.entries.map((entry) => [entry.id, entry]));
179
+ this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
173
180
  this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
174
181
  this.tools = new Map(
175
182
  snapshot.tools.map((slot) => [
@@ -178,7 +185,7 @@ export class AgentModel extends Emitter {
178
185
  ]),
179
186
  );
180
187
  // Nested calls of running tools: they have no assistant entry, so the snapshot is the only source on attach.
181
- for (const slot of snapshot.nestedTools) {
188
+ for (const slot of snapshot.nestedTools.slice(-2_000)) {
182
189
  const existing = this.tools.get(slot.callId);
183
190
  this.tools.set(slot.callId, {
184
191
  name: slot.name,
@@ -194,11 +201,41 @@ export class AgentModel extends Emitter {
194
201
  this.state.agent = snapshot.agent;
195
202
  this.state.usage = snapshot.usage;
196
203
  this.state.retry = snapshot.generation?.retry;
197
- this.state.compactions = snapshot.compactions.map((c) => c.taskId);
204
+ this.state.compactions = snapshot.compactions.map((c) => c.taskId).slice(-64);
198
205
  this.state.compactionFailure = snapshot.compactionFailure;
199
206
  this.state.ready = true;
200
207
  }
201
208
 
209
+ /**
210
+ * R19 (run-5 h10, leader-probed): the events stream had NO aggregate cap — a
211
+ * hostile device streaming unique ids under the 16 MiB per-event cap grew this
212
+ * Map linearly (10k entries → +11 MB, no ceiling) until the operator's tab/TUI
213
+ * OOMs. Cold-review MAJOR 3: the cap first lived only in commit(), so the
214
+ * snapshot and tool_execution_end paths bypassed it — it is enforced in ONE
215
+ * place, on every mutation.
216
+ */
217
+ /**
218
+ * R19 cold-review follow-up: `tools` is the SDK's other unbounded map — 30k
219
+ * `tool_execution_start` events grew it to 30k slots AND cost ~140 s of CPU
220
+ * (rebuild → toTranscript is O(tools) per frame, so the stream is quadratic).
221
+ * Same hostile-peer class as the entries cap, so the same bound.
222
+ */
223
+ private capTools() {
224
+ while (this.tools.size > 2_000) {
225
+ const oldest = this.tools.keys().next().value;
226
+ if (oldest === undefined) break;
227
+ this.tools.delete(oldest);
228
+ }
229
+ }
230
+
231
+ private capEntries() {
232
+ while (this.entries.size > 5_000) {
233
+ const oldest = this.entries.keys().next().value;
234
+ if (oldest === undefined) break;
235
+ this.entries.delete(oldest);
236
+ }
237
+ }
238
+
202
239
  /** Store a committed entry. Resets (sent as message_end) and compactions start a new context head. */
203
240
  private commit(entry: WireEntry) {
204
241
  this.entries.set(entry.id, entry);
@@ -206,6 +243,7 @@ export class AgentModel extends Emitter {
206
243
  const head = entry.head ?? entry.id;
207
244
  for (const id of this.entries.keys()) if (id < head) this.entries.delete(id);
208
245
  }
246
+ this.capEntries();
209
247
  }
210
248
 
211
249
  private event(event: WireAgentEvent) {
@@ -242,6 +280,7 @@ export class AgentModel extends Emitter {
242
280
  case "entry_appended":
243
281
  return this.commit(event.entry);
244
282
  case "tool_execution_start":
283
+ this.capTools(); // R19: bound before the insert adds one more
245
284
  this.tools.set(event.toolCallId, {
246
285
  name: event.toolName,
247
286
  status: "running",
@@ -271,6 +310,8 @@ export class AgentModel extends Emitter {
271
310
  // A model-issued call renders from its result entry; drop the live slot so it is never duplicated.
272
311
  this.tools.delete(event.toolCallId);
273
312
  this.entries.set(event.entry.id, event.entry);
313
+ this.capEntries();
314
+ this.capTools();
274
315
  return;
275
316
  }
276
317
  if (event.result) {
@@ -299,6 +340,8 @@ export class AgentModel extends Emitter {
299
340
  return;
300
341
  case "compaction_start":
301
342
  if (!this.state.compactions.includes(event.taskId)) this.state.compactions.push(event.taskId);
343
+ // R19: bound alongside the entries cap — fresh taskIds grow unbounded.
344
+ if (this.state.compactions.length > 64) this.state.compactions = this.state.compactions.slice(-64);
302
345
  return;
303
346
  case "compaction_end":
304
347
  this.state.compactions = this.state.compactions.filter((id) => id !== event.taskId);
@@ -118,7 +118,16 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
118
118
  node: Number(d.node ?? 24),
119
119
  codeDir: pathish(typeof d.code_dir === "string" ? d.code_dir : "~/dpi", "code_dir"),
120
120
  homeDir: pathish(typeof d.home_dir === "string" ? d.home_dir : "~/.dpi", "home_dir"),
121
- startDirs: d.start_dirs === undefined ? [DEFAULT_START_DIR] : strList(d.start_dirs, `${where}.start_dirs`).map((r: string) => pathish(r, "start_dirs")),
121
+ // R18 (run-4 h7): ':' is the DPI_START_DIRS list separator on the device
122
+ // (config.ts splits on it) — an entry containing ':' would smuggle an
123
+ // EXTRA containment root past the operator's declared list.
124
+ startDirs:
125
+ d.start_dirs === undefined
126
+ ? [DEFAULT_START_DIR]
127
+ : strList(d.start_dirs, `${where}.start_dirs`).map((r: string) => {
128
+ if (r.includes(":")) throw Error(`${where}.start_dirs must not contain ':' (the DPI_START_DIRS separator)`);
129
+ return pathish(r, "start_dirs");
130
+ }),
122
131
  host: d.host === undefined ? (kind === "local" ? "127.0.0.1" : "0.0.0.0") : pathish(str(d.host, `${where}.host`), "host"),
123
132
  envKeys: d.env_keys === undefined ? [] : strList(d.env_keys, `${where}.env_keys`),
124
133
  env: {},
@@ -134,7 +143,9 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
134
143
  // R17 (run-3 h12): the ssh scalar is a leading argv element — a leading
135
144
  // dash would be parsed as an ssh OPTION (e.g. -oProxyCommand=…). Accept
136
145
  // only a user@host[:port] shape.
137
- if (!/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+(:\d+)?$/.test(target))
146
+ // R18 (run-4 h7): the user part may not START with a dash either —
147
+ // `-Jjump@evil` is an attached-value ssh option (ProxyJump), not a user.
148
+ if (!/^[A-Za-z0-9._%][A-Za-z0-9._%-]*@[A-Za-z0-9.-]+(:\d+)?$/.test(target))
138
149
  throw Error(`${where}.ssh must be user@host[:port] (no options, no metacharacters)`);
139
150
  device.ssh = target;
140
151
  }
@@ -115,6 +115,10 @@ async function writeEnv(device: NetDevice, ctx: DriverContext, rotate = false) {
115
115
  ctx.log(`warning: device ${device.id} env ${k} has no value or contains a newline — skipped`);
116
116
  // R17 (run-3 h12): config.ts rejects CR/LF in these at parse; the sink
117
117
  // guards too so a future field can never reintroduce the line-injection.
118
+ // R18 (run-4 h7): ':' in a start_dirs entry splits into an EXTRA containment
119
+ // root on the device — refuse at the sink as well.
120
+ if (device.startDirs.some((r) => r.includes(":")))
121
+ throw Error(`device ${device.id}: start_dirs must not contain ':' (the DPI_START_DIRS separator)`);
118
122
  for (const [k, v] of [["DPI_HOST", device.host], ["DPI_START_DIRS", device.startDirs.join(":")]] as const)
119
123
  if (/[\n\r]/.test(v))
120
124
  throw Error(`device ${device.id}: ${k} value contains a newline — refusing to write backend.env`);
@@ -27,6 +27,7 @@ export const COMMANDS: SlashCommand[] = [
27
27
  { name: "reset", description: "start a fresh context", argumentHint: "[handoff note]" },
28
28
  { name: "name", description: "rename this agent", argumentHint: "<name>" },
29
29
  { name: "tasks", description: "live tasks in this session" },
30
+ { name: "find", description: "search every session's transcript on this device", argumentHint: "<text>" },
30
31
  { name: "pair", description: "pair THIS device with a hub", argumentHint: "<CODE|PAIR_URL> [--hub ORIGIN] [--force]" },
31
32
  {
32
33
  name: "git",
@@ -116,6 +117,26 @@ const KEYS: [string, string][] = [
116
117
  ];
117
118
 
118
119
  /** Returns false when `text` is not a command, so the caller sends it to the agent. */
120
+ /**
121
+ * R19 (run-5 h2 + cold-review): every field of a wire row is untrusted at the
122
+ * terminal boundary. sanitizeTerminal strips escape sequences but keeps
123
+ * newlines and tabs, so single-line chrome collapses whitespace too — otherwise
124
+ * a wire id can split the row it belongs to (visual spoof, no escape bytes).
125
+ */
126
+ export function oneLine(text: string): string {
127
+ return sanitizeTerminal(text).replace(/\s+/g, " ");
128
+ }
129
+
130
+ /** R19 (run-5 h2): every field of a TranscriptSearchHit is relay-borne — the
131
+ * numeric `entry` included. The compose site used to interpolate it raw, so a
132
+ * hostile hub/device could ride an OSC/CSI payload in a string-typed `entry`
133
+ * straight into the terminal (pi-tui writes Panel lines verbatim). One
134
+ * chokepoint, one test.
135
+ */
136
+ export function findHitLine(name: string, hit: { agent: string; entry: number; text: string }): string {
137
+ return ` ${oneLine(name)}:${oneLine(hit.agent)} #${oneLine(String(hit.entry))} — ${oneLine(hit.text.slice(0, 140))}`;
138
+ }
139
+
119
140
  export async function runCommand(app: App, text: string): Promise<boolean> {
120
141
  const match = text.match(/^\/(\S+)\s*([\s\S]*)$/);
121
142
  const command = COMMANDS.find((c) => c.name === match?.[1]);
@@ -206,7 +227,10 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
206
227
  let value = arg;
207
228
  if (!value) {
208
229
  const current = app.sessionSummary()?.agents.find((a) => a.id === app.agentId)?.name ?? "";
209
- const typed = await app.prompt("Agent name", current && current !== "main" ? current : "");
230
+ // Agent names ride the wire from device/hub (model-choosable for forks
231
+ // and subagents) and pi-tui's Input renders its value verbatim — seed
232
+ // it sanitized (run-4 h4).
233
+ const typed = await app.prompt("Agent name", current && current !== "main" ? sanitizeTerminal(current) : "");
210
234
  value = (typed ?? "").trim();
211
235
  if (!value) return app.flash("rename cancelled"), true;
212
236
  }
@@ -223,6 +247,38 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
223
247
  case "pair":
224
248
  await runPairing(app, parsePairArgs(arg));
225
249
  break;
250
+ case "find": {
251
+ // R18: transcript search across every session on the device. Transcript
252
+ // text is untrusted — every interpolation below goes through
253
+ // sanitizeTerminal before it reaches chrome (run-3 h5 discipline).
254
+ if (!arg) return app.flash("usage: /find <text> — searches every session's transcript", true), true;
255
+ await app.run(async () => {
256
+ const result = await app.client.searchSessions(arg, "all");
257
+ const shown = result.matches.slice(0, 12);
258
+ app.overlay(
259
+ new Panel(() => {
260
+ const lines = [
261
+ c.bold(c.accent(`"${sanitizeTerminal(arg)}" — ${sanitizeTerminal(String(result.matches.length))} session${result.matches.length === 1 ? "" : "s"}`)),
262
+ "",
263
+ ];
264
+ if (!result.matches.length) lines.push(c.muted("No matches (names, folders, models or transcripts)."));
265
+ for (const m of shown) {
266
+ lines.push(
267
+ `${c.secondary(sanitizeTerminal(m.name))} ${c.muted(sanitizeTerminal(m.cwd))}${m.where.includes("transcript") ? " " + c.warn("◍ transcript") : ""}`,
268
+ );
269
+ for (const hit of (m.hits ?? []).slice(0, 3))
270
+ lines.push(c.muted(findHitLine(m.name, hit)));
271
+ }
272
+ if (result.matches.length > shown.length) lines.push(c.muted(`… ${sanitizeTerminal(String(result.matches.length - shown.length))} more`));
273
+ if (result.scanned?.truncated)
274
+ lines.push(c.muted(`scan budget reached (${sanitizeTerminal(String(result.scanned.entries))} entries) — refine the query`));
275
+ lines.push("", c.muted("esc close"));
276
+ return lines;
277
+ }, () => app.closeOverlay()),
278
+ );
279
+ });
280
+ break;
281
+ }
226
282
  case "tasks":
227
283
  app.overlay(
228
284
  new Panel(() => {
@@ -231,7 +287,13 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
231
287
  if (!tasks.length) lines.push(c.muted("No live tasks."));
232
288
  for (const t of tasks)
233
289
  lines.push(
234
- `${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${t.id} ${sanitizeTerminal(t.kind)} ${c.muted(sanitizeTerminal(`agent #${t.conversationId} │ ${t.state.status}${t.state.phase ? `/${t.state.phase}` : ""}`))}`,
290
+ // R19 cold-review MAJOR 4: task ids are wire-borne too — a hostile
291
+ // relay can type them as strings carrying escape sequences (the
292
+ // same class as the /find `entry` finding). Every scalar goes
293
+ // through the chokepoint.
294
+ // sanitizeTerminal keeps \n/\t, so a one-line row also collapses
295
+ // whitespace — a wire id must not split the row it belongs to.
296
+ `${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${oneLine(String(t.id))} ${oneLine(String(t.kind))} ${c.muted(`agent #${oneLine(String(t.conversationId))} │ ${oneLine(String(t.state.status))}${t.state.phase ? `/${oneLine(String(t.state.phase))}` : ""}`)}`,
235
297
  );
236
298
  lines.push("", c.muted("esc close"));
237
299
  return lines;
@@ -175,9 +175,9 @@ export function pairingViewLines(
175
175
  } else if (status.state === "revoked") {
176
176
  lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
177
177
  } else {
178
- lines.push(c.muted(note));
178
+ lines.push(c.muted(sanitizeTerminal(note)));
179
179
  }
180
- if (note && status.state !== "pairing") lines.push(c.muted(note));
180
+ if (note && status.state !== "pairing") lines.push(c.muted(sanitizeTerminal(note)));
181
181
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
182
182
  }
183
183
 
@@ -239,7 +239,7 @@ export function renderNetwork(
239
239
  const seen = d.lastSeenAt ? ageOf(d.lastSeenAt) : "never";
240
240
  label =
241
241
  `${dot} ${c.bold(row.label)}${row.current ? c.accent(" ▌") : ""} ${c.muted(`[${d.kind}]`)} ` +
242
- `${c.muted(d.transport === "tunnel" ? "tunnel" : "lan")} ${c.muted(d.lastStatus === "online" ? seen : `${d.lastStatus} · ${seen}`)}`;
242
+ `${c.muted(d.transport === "tunnel" ? "tunnel" : "lan")} ${c.muted(d.lastStatus === "online" ? seen : `${sanitizeTerminal(d.lastStatus)} · ${seen}`)}`;
243
243
  } else {
244
244
  const selected = row.sessionId === opts.currentSessionId;
245
245
  const marker = selected ? c.accent("▌") : " ";
@@ -133,7 +133,7 @@ All four are DECIDED (0.0.46, user-approved):
133
133
  |---|---|---|---|---|
134
134
  | MUST | Device vitals endpoint + card | herdr `shared/types.ts:19` (`Device.uptime`, `since`); piggery `top` (`docs/reference.md:22`) | ✅ (`0.0.38`) | GET `/device/vitals` (`vitals.ts`: uptime, loadavg, memory, statfs free, counts) + Inspector **Host** tab (`HostPanel.vue`). On demand only — verified 0 requests until the tab opens |
135
135
  | MUST | `dpi doctor` | piggery `check`/`doctor` (`docs/reference.md:33-34`) | ✅ (`0.0.38`) | `dpi doctor [--json] [--quiet]` (`doctor.ts`): node ≥ 22.19, healthz, start-dir writability, default-model probe, hub reachability; exit 1 only on FAIL, probe/hub are WARN |
136
- | SHOULD | Session search (device-side first) | paseo `packages/server/src/server/agent-history-search.ts` | ✅ (`0.0.38`) | GET `/sessions/search?q=` matches names/cwd/models (never transcripts — FTS first). FE: instant local filter + debounced device call merged as "more on device" |
136
+ | SHOULD | Session search (device-side first) | paseo `packages/server/src/server/agent-history-search.ts` | ✅ (`0.0.38` metadata; `0.0.73` transcripts) | GET `/sessions/search?q=` matches names/cwd/models; `&scope=all` adds a bounded read-only transcript walk (100 sessions / 4k entries per agent / 50k entries total, newest first — one broken session is skipped). FTS stays the upgrade path for large fleets: the transcript DBs are engine-owned (vendored pi-durable), so no FTS tables of our own without an engine change. FE: instant local filter + debounced device call merged as "more on device" (now with transcript hit previews); TUI: `/find` |
137
137
  | SHOULD | Session export bundle | paseo `packages/server/src/server/exports.ts` | ✅ (`0.0.38`) | GET `/sessions/:s/export` → base64 zip (`zip.ts`, zero-dep writer): manifest + session record + per-agent transcript.json/.md + config.json. Import still later |
138
138
 
139
139
  ## Wave 2 — medium
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.72",
3
+ "version": "0.0.74",
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": {