my-durable 0.0.75 → 0.0.77

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.
@@ -7,7 +7,7 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-BmxTF5DB.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-CRSjEtI_.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-h81haD43.css">
12
12
  </head>
13
13
  <body>
@@ -17,24 +17,80 @@ export interface GitEntry {
17
17
 
18
18
  const entries = new Map<string, GitEntry>();
19
19
  const inflight = new Map<string, Promise<void>>();
20
+ /** run-7 D2: the module-global entry map had NO ceiling — a hostile device's
21
+ * status-batch response (or a hostile tree's cwds) grew it forever until the
22
+ * tab OOMs. Same discipline as the SDK caps: bounded slots, oldest evicted. */
23
+ const MAX_GIT_ENTRIES = 2000;
24
+ function capEntries() {
25
+ while (entries.size > MAX_GIT_ENTRIES) {
26
+ const oldest = entries.keys().next().value as string | undefined;
27
+ if (oldest === undefined) break;
28
+ entries.delete(oldest);
29
+ }
30
+ }
31
+
32
+ /** A device's git surface is bounded by its start dirs (R21, index 400s): a
33
+ * project left over from OTHER start dirs answers 400 on the device, and
34
+ * asking anyway just spams the console with network errors every stale
35
+ * window. The network frame carries each device's startDirs + platform —
36
+ * pre-check client-side (the device stays the enforcer) and settle such
37
+ * paths locally. Unknown device facts → allow: the device decides. */
38
+ function gitPathAllowed(deviceId: string, path: string): boolean {
39
+ const dev = network.devices.value.find((d) => d.id === deviceId) as
40
+ | { info?: { startDirs?: unknown; platform?: unknown } }
41
+ | undefined;
42
+ const dirs = dev?.info?.startDirs;
43
+ if (!Array.isArray(dirs) || dirs.length === 0) return true;
44
+ const win = String(dev?.info?.platform ?? "").startsWith("win32");
45
+ const norm = (p: string) =>
46
+ win ? p.trim().replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p.trim().replace(/\/+$/, "");
47
+ const a = norm(path);
48
+ return dirs.some((raw) => {
49
+ const b = norm(String(raw));
50
+ return !!b && (a === b || a.startsWith(win ? b + "\\" : b + "/"));
51
+ });
52
+ }
53
+
54
+ /** Settle an entry from either a real status or the batch's `{error}` shape. */
55
+ function settleEntry(e: GitEntry, s: GitStatus | { error: string } | undefined) {
56
+ if (s && typeof (s as { error?: unknown }).error === "string") {
57
+ e.status = null;
58
+ e.error = (s as { error: string }).error;
59
+ } else {
60
+ e.status = (s as GitStatus) ?? null;
61
+ e.error = "";
62
+ }
63
+ e.at = Date.now();
64
+ }
20
65
 
21
66
  /** Fill MANY folders in one round-trip (session lists want branch-per-cwd).
22
67
  * Decorative by design: a failed batch stays silent — the Git tab is where
23
68
  * errors belong. */
24
69
  export async function ensureGitBatch(deviceId: string, paths: string[]) {
25
- const stale = paths.filter((p) => !fresh(gitEntry(deviceId, p), staleMsForBatch));
70
+ const stale = paths.filter((p) => !fresh(gitEntry(deviceId, p), staleMsForBatch) && gitPathAllowed(deviceId, p));
26
71
  if (!stale.length) return;
27
- try {
28
- const map = await deviceClient(deviceId).gitStatusBatch(stale, { timeoutMs: 60_000 });
29
- for (const [p, s] of Object.entries(map)) {
30
- const e = gitEntry(deviceId, p);
31
- e.status = s;
32
- e.at = Date.now();
33
- e.error = "";
72
+ // run-7 D2: (a) the device truncates at 50 paths — chunk so every stale
73
+ // path actually settles (beyond-50 paths used to ride every batch forever);
74
+ // (b) 10 chunks max per pass keeps a hostile tree from fanning requests.
75
+ for (let i = 0; i < stale.length && i < 500; i += 50) {
76
+ const chunk = stale.slice(i, i + 50);
77
+ try {
78
+ const map = (await deviceClient(deviceId).gitStatusBatch(chunk, { timeoutMs: 60_000 })) as Record<
79
+ string,
80
+ GitStatus | { error: string }
81
+ >;
82
+ // run-7 D2: settle ONLY the keys WE sent — the response map is hostile-
83
+ // device-controlled and used to be iterated wholesale, letting a device
84
+ // grow this tab's retained state with keys the FE never asked for.
85
+ for (const p of chunk) {
86
+ const s = map[p];
87
+ if (s !== undefined) settleEntry(gitEntry(deviceId, p), s);
88
+ }
89
+ } catch {
90
+ /* decorative: never surface batch failures */
34
91
  }
35
- } catch {
36
- /* decorative: never surface batch failures */
37
92
  }
93
+ capEntries();
38
94
  }
39
95
  const staleMsForBatch = 60_000;
40
96
 
@@ -100,6 +156,11 @@ export async function ensureGit(
100
156
  const k = key(deviceId, cwd);
101
157
  const e = gitEntry(deviceId, cwd);
102
158
  if (!force && fresh(e, staleMs)) return;
159
+ // Outside the device's sandbox: settle locally, never send the doomed 400.
160
+ if (!gitPathAllowed(deviceId, cwd)) {
161
+ settleEntry(e, { error: "outside the device's start dirs" });
162
+ return;
163
+ } capEntries();
103
164
  const running = inflight.get(k);
104
165
  if (running) return running;
105
166
  const first = e.status === null && !e.error;
@@ -147,6 +147,9 @@ export function scrubSecrets(value: string): string {
147
147
  // redacts before any decode). The anchor needs a non-word char before
148
148
  // "share" ("/share", "?shares="), so plain prose never triggers this.
149
149
  if (/(?:^|[^\w\s])shares?/i.test(out)) {
150
+ // run-7 D5: encoded capability shapes must not depend on decode depth —
151
+ // in share-anchor context, any dense %XX cluster is capability material.
152
+ out = out.replace(/(?:%[0-9a-fA-F]{2}){8,}/g, "<redacted>");
150
153
  // Keep the R19 M4 decision: a run whose FIRST char is preceded by
151
154
  // whitespace is prose, not a capability — everything else in anchor
152
155
  // context is redacted (callback sees the true run start; a lookbehind
@@ -173,9 +176,14 @@ export function scrubSecrets(value: string): string {
173
176
  let out = applyRules(value);
174
177
  // The decoded pass sees through %XX spellings of the separator, the first
175
178
  // token characters, or the segment itself; the sample is bounded (≤200
176
- // chars) so a pathological decode cannot explode it. Two rounds: the first
177
- // decode can still carry second-encoding (%2573…) for the second pass.
178
- for (let round = 0; round < 2; round++) {
179
+ // chars) so a pathological decode cannot explode it. run-7 D5 (leader-
180
+ // probed): 2 rounds was one depth short — a 3x-percent-encoded capability
181
+ // never presented a ≥20-char run in ANY pass and exited one decode away
182
+ // from plaintext, persisting in the append-only row past the share's TTL.
183
+ // Eight rounds: denial samples are ≤200 chars, but scrubValue feeds
184
+ // 8192-char values where a 5x-encoded token (~5.8KB) still exits one
185
+ // decode short — loop-until-stable with a generous cap; input-bounded.
186
+ for (let round = 0; round < 8; round++) {
179
187
  try {
180
188
  const decoded = decodeURIComponent(out);
181
189
  if (decoded === out) break;
@@ -576,7 +576,10 @@ if (args.includes("--dev")) {
576
576
  // styles (plus the stylesheet host of the brand fonts), talks only to this hub and cannot be framed.
577
577
  const shellPolicy = [
578
578
  "default-src 'none'",
579
- "script-src 'self'",
579
+ // static.cloudflareinsights.com: Cloudflare Web Analytics auto-injects its
580
+ // beacon into every zone page — blocking it just spams the operator's
581
+ // console with CSP violations on every load.
582
+ "script-src 'self' https://static.cloudflareinsights.com",
580
583
  "style-src 'self' https://fonts.googleapis.com",
581
584
  "font-src https://fonts.gstatic.com",
582
585
  "img-src 'self' data:",
@@ -11,6 +11,12 @@ import type {
11
11
  TunnelDiagnostics,
12
12
  } from "../../../../dpi-sdk/src/api.js";
13
13
  import { toPublic, type NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
14
+
15
+ /** run-7 B4 admission bounds: device-authored status payloads are untrusted —
16
+ * 32 devices x 256KiB keeps the AGGREGATE network frame under the 16MiB
17
+ * writer cap even when every paired device is hostile. */
18
+ const TREE_MAX_BYTES = 256 * 1024;
19
+ const TREE_MAX_SESSIONS = 2000;
14
20
  import { Backoff } from "../../../../dpi-sdk/src/protocol/backoff.js";
15
21
  import { MONITOR_BACKOFF_S } from "../../../../dpi-sdk/src/protocol/limits.js";
16
22
 
@@ -272,7 +278,7 @@ export class DeviceMonitor {
272
278
  if (device.deviceUid && device.deviceUid !== info.uid) {
273
279
  this.update(id, {
274
280
  status: "mismatch",
275
- error: `${device.url} now answers as "${info.name}" (uid ${info.uid.slice(0, 8)}), not the device first seen there (uid ${device.deviceUid.slice(0, 8)})`,
281
+ error: `${device.url} now answers as "${String(info.name ?? "").slice(0, 200)}" (uid ${String(info.uid ?? "").slice(0, 8)}), not the device first seen there (uid ${String(device.deviceUid ?? "").slice(0, 8)})`,
276
282
  });
277
283
  await sleep(30_000, signal);
278
284
  continue;
@@ -294,13 +300,30 @@ export class DeviceMonitor {
294
300
  { path: "/v1/events", consumerId: `monitor:${id}` },
295
301
  signal,
296
302
  )) {
297
- if (frame.type === "tree")
303
+ if (frame.type === "tree") {
304
+ // run-7 B4: the monitor seam had NO admission bound — a hostile
305
+ // device's ≤16MiB wire-legal tree was retained verbatim, persisted
306
+ // uncapped, and fanned out; aggregate network frames over the
307
+ // writer cap were REPLACED by faults, blinding every viewer's
308
+ // network view. Degrade oversized/hostile-shaped trees at the seam.
309
+ const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
310
+ const size = JSON.stringify(frame.tree)?.length ?? 0;
311
+ if (size > TREE_MAX_BYTES || sessions.length > TREE_MAX_SESSIONS) {
312
+ this.update(id, {
313
+ status: "faulted",
314
+ error: `oversized tree frame (${size} bytes, ${sessions.length} sessions)`,
315
+ tree: undefined,
316
+ lastSeenAt: Date.now(),
317
+ });
318
+ continue;
319
+ }
298
320
  this.update(id, {
299
321
  status: "online",
300
322
  error: undefined,
301
323
  tree: frame.tree,
302
324
  lastSeenAt: Date.now(),
303
325
  });
326
+ }
304
327
  }
305
328
  if (signal.aborted) return;
306
329
  // The stream was live until now: that is the last time the device was seen.
@@ -41,7 +41,11 @@ export type DeviceStatus =
41
41
  | "offline"
42
42
  | "unauthorized"
43
43
  | "mismatch"
44
- | "incompatible";
44
+ | "incompatible"
45
+ /** run-7 B4: the hub faulted this device's status payload at the admission
46
+ * seam (oversized/hostile tree frame) — the tree is dropped, the error
47
+ * says why; UIs render it like any unknown-but-textual status. */
48
+ | "faulted";
45
49
  export type ErrorCode =
46
50
  | "unauthorized"
47
51
  | "not_found"
@@ -92,11 +92,32 @@ function setPath(target: Record<string | number, unknown>, path: readonly (strin
92
92
  node = node[key] as Record<string | number, unknown>;
93
93
  }
94
94
  const last = path[path.length - 1];
95
- node[last] = String(node[last] ?? "") + delta;
95
+ // run-7 cold-1 m1: the live toolCall arguments accumulator rode the same
96
+ // 16MiB wire ceiling per delta with no cap — fold into the 256Ki tail.
97
+ node[last] = capLiveText(String(node[last] ?? "") + delta);
98
+ }
99
+
100
+ /** run-7 D4-B: inbox items are wire JSON — non-array or null-element shapes
101
+ * threw in every tasks-tab consumer; same discipline as safeTasks. */
102
+ function safeInbox(items: unknown): AgentViewState["inbox"] {
103
+ return (Array.isArray(items) ? items : []).filter((x) => !!x && typeof x === "object") as AgentViewState["inbox"];
104
+ }
105
+
106
+ /** run-7 D3 F3: live message blocks append unbounded deltas between
107
+ * message_start/message_end — keep a 256Ki flattened tail (the capToolOutput
108
+ * principle, applied to the live accumulator). */
109
+ const LIVE_TEXT_CAP = 256 * 1024;
110
+ function capLiveText(text: string): string {
111
+ return text.length > LIVE_TEXT_CAP ? AgentModel.flatSlice(text.slice(text.length - LIVE_TEXT_CAP)) : text;
96
112
  }
97
113
 
98
114
  export function applyMessageChange(message: WireAssistantMessage, change: WireMessageChange): WireAssistantMessage {
99
115
  if (change.type === "message") return structuredClone(change.message);
116
+ // run-7 cold-2 m4: a hostile toolcall_delta path array builds one nested
117
+ // object PER element — bound the depth and each key before any allocation.
118
+ const p = (change as { path?: unknown }).path;
119
+ if (p !== undefined && (!Array.isArray(p) || p.length > 64 || p.some((k) => typeof k === "string" && k.length > 256)))
120
+ return message;
100
121
  const content = [...message.content] as WireAssistantBlock[];
101
122
  const i = change.contentIndex;
102
123
  // R19 (run-5 h10, leader-probed): the wire number was indexed raw — any
@@ -109,14 +130,17 @@ export function applyMessageChange(message: WireAssistantMessage, change: WireMe
109
130
  content[i] = structuredClone((change as { block: WireAssistantBlock }).block);
110
131
  } else if (change.type === "text_delta") {
111
132
  const block = content[i];
112
- content[i] = { type: "text", text: (block?.type === "text" ? block.text : "") + change.delta };
133
+ content[i] = { type: "text", text: capLiveText((block?.type === "text" ? block.text : "") + change.delta) };
113
134
  } else if (change.type === "thinking_delta") {
114
135
  const block = content[i];
115
136
  content[i] = {
116
137
  type: "thinking",
117
- thinking: (block?.type === "thinking" ? block.thinking : "") + change.delta,
138
+ thinking: capLiveText((block?.type === "thinking" ? block.thinking : "") + change.delta),
118
139
  };
119
140
  } else if (change.type === "toolcall_delta") {
141
+ // run-7 cold-3 LOW: a path-less toolcall_delta reached setPath(undefined)
142
+ // and threw (contained by the per-event catch, but drop it cleanly here).
143
+ if (!Array.isArray(change.path)) return message;
120
144
  const block = structuredClone(content[i] ?? { type: "toolCall", id: "", name: "", arguments: {} });
121
145
  setPath(block as unknown as Record<string, unknown>, change.path, change.delta);
122
146
  content[i] = block;
@@ -155,17 +179,40 @@ export class AgentModel extends Emitter {
155
179
  switch (frame.type) {
156
180
  case "snapshot":
157
181
  this.reset(frame.snapshot);
158
- this.state.inbox = frame.inbox;
182
+ this.state.inbox = safeInbox(frame.inbox);
159
183
  break;
160
184
  case "batch":
161
- for (const event of frame.events) this.event(event);
185
+ // run-7 D4-B + cold-1 M6: non-iterable events AND hostile field shapes
186
+ // (message_start.message:null, message_update.changes:5, entry:null)
187
+ // threw inside apply(), which follow() turns into a reconnect loop
188
+ // re-receiving the same hostile frame forever. Drop the hostile
189
+ // EVENT, keep the stream alive.
190
+ for (const event of (Array.isArray(frame.events) ? frame.events : []).filter((e) => !!e && typeof e === "object")) {
191
+ try {
192
+ this.event(event);
193
+ } catch {
194
+ // one hostile event must not kill the stream for the session
195
+ }
196
+ }
162
197
  break;
163
198
  case "inbox":
164
- this.state.inbox = frame.items;
199
+ this.state.inbox = safeInbox(frame.items);
165
200
  break;
166
- case "doc":
167
- this.state.docs = { ...this.state.docs, [frame.kind]: frame.value };
201
+ case "doc": {
202
+ // run-7 D3 F2: docs was the ONE wire-driven map with neither a count
203
+ // cap nor a byte cap — kind strings are device-chosen and values rode
204
+ // the 16MiB wire ceiling verbatim, forever (no eviction either).
205
+ // cold-1 M5: the KIND is the map key — oversized kinds are dropped
206
+ // whole (the 4096-drop discipline), or 64 of them retain ~1GiB.
207
+ if (String(frame.kind).length > 256) break;
208
+ const kinds: Record<string, unknown> = {
209
+ ...this.state.docs,
210
+ [String(frame.kind)]: this.capDocValue(frame.value),
211
+ };
212
+ const kept = Object.keys(kinds).slice(-64); // insertion order: newest 64 survive
213
+ this.state.docs = Object.fromEntries(kept.map((k) => [k, kinds[k]]));
168
214
  break;
215
+ }
169
216
  default:
170
217
  return false;
171
218
  }
@@ -195,11 +242,18 @@ export class AgentModel extends Emitter {
195
242
  }
196
243
 
197
244
  private reset(snapshot: WireSnapshotEvent) {
198
- this.entries = new Map(snapshot.entries.map((entry) => [entry.id, entry]));
245
+ // run-7 D4-B: snapshot carriers arrive as raw JSON.parse casts — a
246
+ // non-array (or null-element) shape threw in these map/filter chains and
247
+ // follow() re-delivered the hostile snapshot forever.
248
+ const snapEntries = (Array.isArray(snapshot.entries) ? snapshot.entries : []).filter((x) => !!x && typeof x === "object");
249
+ const snapTools = (Array.isArray(snapshot.tools) ? snapshot.tools : []).filter((x) => !!x && typeof x === "object");
250
+ const snapNested = (Array.isArray(snapshot.nestedTools) ? snapshot.nestedTools : []).filter((x) => !!x && typeof x === "object");
251
+ const snapCompactions = (Array.isArray(snapshot.compactions) ? snapshot.compactions : []).filter((x) => !!x && typeof x === "object");
252
+ this.entries = new Map(snapEntries.map((entry) => [entry.id, entry]));
199
253
  this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
200
254
  this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
201
255
  this.tools = new Map(
202
- snapshot.tools
256
+ snapTools
203
257
  .filter((slot) => typeof slot.callId === "string" && slot.callId.length <= 4_096 && typeof slot.name === "string" && slot.name.length <= 4_096) // R20 cold-3 M1: oversized ids/names are dropped, not retained
204
258
  .slice(-2_000)
205
259
  .map((slot) => [ // R20 h4: hostile snapshot.tools was uncapped — same bound as every other path
@@ -208,7 +262,7 @@ export class AgentModel extends Emitter {
208
262
  ]),
209
263
  );
210
264
  // Nested calls of running tools: they have no assistant entry, so the snapshot is the only source on attach.
211
- for (const slot of snapshot.nestedTools.filter((x) => typeof x.callId === "string" && x.callId.length <= 4_096 && typeof x.name === "string" && x.name.length <= 4_096).slice(-2_000)) {
265
+ for (const slot of snapNested.filter((x) => typeof x.callId === "string" && x.callId.length <= 4_096 && typeof x.name === "string" && x.name.length <= 4_096).slice(-2_000)) {
212
266
  const existing = this.tools.get(slot.callId);
213
267
  this.tools.set(slot.callId, {
214
268
  name: slot.name,
@@ -225,7 +279,7 @@ export class AgentModel extends Emitter {
225
279
  this.state.agent = snapshot.agent;
226
280
  this.state.usage = snapshot.usage;
227
281
  this.state.retry = snapshot.generation?.retry;
228
- this.state.compactions = snapshot.compactions.map((c) => c.taskId).slice(-64);
282
+ this.state.compactions = snapCompactions.map((c) => c.taskId).slice(-64);
229
283
  this.state.compactionFailure = snapshot.compactionFailure;
230
284
  this.state.ready = true;
231
285
  }
@@ -299,7 +353,7 @@ export class AgentModel extends Emitter {
299
353
 
300
354
  /** Store a committed entry. Resets (sent as message_end) and compactions start a new context head. */
301
355
  private commit(entry: WireEntry) {
302
- this.entries.set(entry.id, entry);
356
+ this.entries.set(entry.id, this.capEntry(entry));
303
357
  if (entry.kind === "pi.reset" || entry.kind === "pi.compaction") {
304
358
  const head = entry.head ?? entry.id;
305
359
  for (const id of this.entries.keys()) if (id < head) this.entries.delete(id);
@@ -307,6 +361,37 @@ export class AgentModel extends Emitter {
307
361
  this.capEntries();
308
362
  }
309
363
 
364
+ /** run-7 D3 F3: entries were count-capped but byte-uncapped (5000 × the
365
+ * 16MiB wire ceiling, joined again by toTranscript on every rebuild).
366
+ * Assistant text/thinking blocks keep a flattened 256Ki TAIL + marker. */
367
+ private capEntry(entry: WireEntry): WireEntry {
368
+ // WireEntry.model is readonly WireMessage[]; assistant messages carry
369
+ // content blocks whose text/thinking strings are the retention vector.
370
+ if (!Array.isArray(entry.model)) return entry;
371
+ for (const msg of entry.model) {
372
+ const content = (msg as { content?: unknown }).content;
373
+ if (!Array.isArray(content)) continue;
374
+ for (const b of content) {
375
+ const block = b as { text?: unknown; thinking?: unknown };
376
+ for (const f of ["text", "thinking"] as const) {
377
+ const v = block[f];
378
+ if (typeof v === "string" && v.length > LIVE_TEXT_CAP) {
379
+ block[f] = AgentModel.flatSlice(v.slice(v.length - LIVE_TEXT_CAP)) + "…[truncated]";
380
+ }
381
+ }
382
+ }
383
+ }
384
+ return entry;
385
+ }
386
+
387
+ /** run-7 D3 F2: bound a wire doc value — over 64Ki serialized it becomes a
388
+ * flattened 4Ki preview (the capArgs discipline). */
389
+ private capDocValue(value: unknown): unknown {
390
+ const text = safeStringify(value);
391
+ if (text.length > 64 * 1024) return { truncated: true, preview: AgentModel.flatSlice(text.slice(0, 4096)) };
392
+ return value;
393
+ }
394
+
310
395
  private event(event: WireAgentEvent) {
311
396
  switch (event.type) {
312
397
  case "snapshot":
@@ -363,6 +448,11 @@ export class AgentModel extends Emitter {
363
448
  });
364
449
  return;
365
450
  case "tool_execution_update": {
451
+ // run-7 D3 F1: the R20 cold-3 M1 4096-drop ran on the start path only;
452
+ // this orphan path stored the id as the MAP KEY and the name verbatim
453
+ // (16MiB × 2000 slots ceiling). Same drop discipline.
454
+ if (typeof event.toolCallId !== "string" || event.toolCallId.length > 4_096 || typeof event.toolName !== "string" || event.toolName.length > 4_096)
455
+ return;
366
456
  const tool = this.tools.get(event.toolCallId) ?? {
367
457
  name: event.toolName,
368
458
  status: "running" as const,
@@ -380,12 +470,15 @@ export class AgentModel extends Emitter {
380
470
  if (event.entry) {
381
471
  // A model-issued call renders from its result entry; drop the live slot so it is never duplicated.
382
472
  this.tools.delete(event.toolCallId);
383
- this.entries.set(event.entry.id, event.entry);
384
- this.capEntries();
473
+ this.commit(event.entry);
385
474
  this.capTools();
386
475
  return;
387
476
  }
388
477
  if (event.result) {
478
+ // run-7 D3 F1: same drop discipline as start/update (this path also
479
+ // stored id/name verbatim into the capped-by-count-only map).
480
+ if (typeof event.toolCallId !== "string" || event.toolCallId.length > 4_096 || typeof event.toolName !== "string" || event.toolName.length > 4_096)
481
+ return;
389
482
  // A nested call has no entry: keep the slot so its result still renders, exactly once.
390
483
  const tool = this.tools.get(event.toolCallId) ?? { name: event.toolName, status: "done" as const, output: "" };
391
484
  tool.status = "done";
@@ -294,8 +294,11 @@ export class NetworkRegistry {
294
294
  const sets = ["last_status=?", "last_error=?"];
295
295
  const values: (string | number | null)[] = [patch.status, patch.error ?? null];
296
296
  if (patch.seenAt !== undefined) sets.push("last_seen_at=?"), values.push(patch.seenAt);
297
- if (patch.info) sets.push("last_info_json=?"), values.push(JSON.stringify(patch.info));
298
- if (patch.tree) sets.push("last_tree_json=?"), values.push(JSON.stringify(patch.tree));
297
+ // run-7 B4: device-authored JSON is untrusted — cap what a hostile device
298
+ // can rewrite into the registry row every 10s (the uiSet sibling caps UI
299
+ // state at 100k chars; the tree seam already degrades oversized frames).
300
+ if (patch.info) sets.push("last_info_json=?"), values.push(JSON.stringify(patch.info).slice(0, 64 * 1024));
301
+ if (patch.tree) sets.push("last_tree_json=?"), values.push(JSON.stringify(patch.tree).slice(0, 288 * 1024));
299
302
  this.db.prepare(`UPDATE devices SET ${sets.join(",")} WHERE id=?`).run(...values, id);
300
303
  }
301
304
 
@@ -274,6 +274,7 @@ export function sumUsage(state?: Pick<WireUsageState, "models"> | { models: Reco
274
274
  cacheWriteCost: 0,
275
275
  };
276
276
  for (const u of Object.values(state?.models ?? {})) {
277
+ if (!u || typeof u !== "object") continue; // run-7 D4-C: hostile usage frames can carry null entries
277
278
  total.tokens += u.totalTokens ?? u.input + u.output + u.cacheRead + u.cacheWrite;
278
279
  total.cost += u.cost?.total ?? 0;
279
280
  total.input += u.input ?? 0;
@@ -1079,12 +1079,13 @@ export class App {
1079
1079
  const session = this.sessionSummary();
1080
1080
  const agent = session?.agents.find((a) => a.id === this.agentId);
1081
1081
  if (!session || this.agentId === undefined) return undefined;
1082
+ const wireName = (v: unknown) => (typeof v === "string" ? v : ""); // run-7 D4-A: wire names are strings by convention only
1082
1083
  const usable = (name: string) => !name.includes(":") && !name.includes("'");
1083
- const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
1084
+ const same = (a: unknown, b: unknown) => wireName(a).toLowerCase() === wireName(b).toLowerCase();
1084
1085
  const sessionRef =
1085
- usable(session.name) && this.sessions.filter((s) => same(s.name, session.name)).length === 1 ? session.name : session.id;
1086
+ usable(wireName(session.name)) && this.sessions.filter((s) => same(s.name, session.name)).length === 1 ? session.name : session.id;
1086
1087
  const agentRef =
1087
- agent?.named && usable(agent.name) && session.agents.filter((a) => same(a.name, agent.name)).length === 1
1088
+ agent?.named && usable(wireName(agent.name)) && session.agents.filter((a) => same(a.name, agent.name)).length === 1
1088
1089
  ? agent.name
1089
1090
  : this.agentId === 1
1090
1091
  ? "main"
@@ -1228,7 +1229,7 @@ export class App {
1228
1229
  // the web shows a banner — the TUI used to show a healthy branch chip
1229
1230
  // while the repo was mid-merge with conflicts.
1230
1231
  const gitChip = g?.repo
1231
- ? ` ${c.muted("⎇")} ${c.text(oneLine(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)) : ""}`
1232
+ ? ` ${c.muted("⎇")} ${c.text(oneLine(String(g.branch ?? g.head ?? "")))}${(Number(g.staged) || 0) + (Number(g.unstaged) || 0) + (Number(g.untracked) || 0) ? c.warn(` ±${(Number(g.staged) || 0) + (Number(g.unstaged) || 0) + (Number(g.untracked) || 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
1232
1233
  : "";
1233
1234
  lines.push(
1234
1235
  `${c.muted(oneLine(this.device.id))} ${c.muted("›")} ${c.text(oneLine(session?.name ?? "—"))} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
@@ -1239,7 +1240,7 @@ export class App {
1239
1240
  lines.push(
1240
1241
  AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
1241
1242
  c.muted("│"),
1242
- ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(oneLine(this.model.state.agent.model?.modelId?.split("/").pop() ?? "")), // R20 cold-1 M4
1243
+ ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(oneLine(String(this.model.state.agent.model?.modelId ?? "").split("/").pop() ?? "")), // R20 cold-1 M4
1243
1244
  );
1244
1245
  lines.push(c.muted(rep(box.h, w)));
1245
1246
  const inner = h - 3;
@@ -1368,7 +1369,7 @@ export class App {
1368
1369
  ` ${c.muted("thinking")} ${c.text(String(this.model.state.agent.thinkingLevel ?? "low"))} ${c.muted("(y cycles)")}`,
1369
1370
  "",
1370
1371
  ` ${c.muted("device")} ${c.text(oneLine(this.device.id))} ${c.muted(oneLine(this.device.url))}`, // R20 cold-1 M4
1371
- ` ${c.muted("start dirs")} ${c.muted(oneLine(this.info.startDirs.join(", ")).slice(0, w - 18) || "—")}`, // R20 cold-1 M4
1372
+ ` ${c.muted("start dirs")} ${c.muted(oneLine((Array.isArray(this.info.startDirs) ? this.info.startDirs : []).join(", ")).slice(0, w - 18) || "—")}`, // R20 cold-1 M4
1372
1373
  ];
1373
1374
  return lines;
1374
1375
  }
@@ -13,7 +13,7 @@ import {
13
13
  } from "@earendil-works/pi-tui";
14
14
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
15
15
  import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
16
- import { sanitizeTerminal } from "./sanitize.ts";
16
+ import { oneLine, sanitizeTerminal } from "./sanitize.ts";
17
17
  import type { App } from "./app.ts";
18
18
  import { c, selectTheme } from "./theme.ts";
19
19
 
@@ -261,11 +261,14 @@ export async function pickSession(app: App) {
261
261
  const tree = await app.client.tree();
262
262
  const items: SelectItem[] = [
263
263
  { value: "+new", label: "+ New session", description: `choose a directory on ${sanitizeTerminal(app.device.id)}` },
264
- ...tree.sessions.map((s) => ({
265
- value: s.id,
266
- label: sanitizeTerminal(s.name),
267
- description: `${sanitizeTerminal(s.cwd.split("/").slice(-2).join("/"))} │ ${s.agents.length} agent${s.agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
268
- })),
264
+ ...tree.sessions.map((s) => {
265
+ const agents = Array.isArray(s.agents) ? s.agents : [];
266
+ return {
267
+ value: s.id,
268
+ label: oneLine(String(s.name ?? "")),
269
+ description: `${oneLine(String(s.cwd ?? "").split("/").slice(-2).join("/"))} │ ${agents.length} agent${agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
270
+ };
271
+ }),
269
272
  ];
270
273
  app.overlay(
271
274
  new Picker(`Sessions on ${sanitizeTerminal(app.device.id)}`, items, (item) => {
@@ -368,7 +371,7 @@ function chooseModel(app: App, current?: string) {
368
371
  const models = app.info.models;
369
372
  const picker = new Picker(
370
373
  `Model (${sanitizeTerminal(app.device.name)})`,
371
- models.map((m) => ({ value: `${m.provider}/${m.id}`, label: sanitizeTerminal(m.name), description: `${sanitizeTerminal(m.tier)} │ ${sanitizeTerminal(m.provider)}` })),
374
+ models.map((m) => ({ value: `${m.provider}/${m.id}`, label: oneLine(String(m.name ?? "")), description: `${oneLine(String(m.tier ?? ""))} │ ${oneLine(String(m.provider ?? ""))}` })),
372
375
  (item) => {
373
376
  app.closeOverlay();
374
377
  done(models.find((m) => `${m.provider}/${m.id}` === item.value));
@@ -438,7 +441,7 @@ export function pickAgent(app: App) {
438
441
  rows.push({
439
442
  value: String(a.id),
440
443
  label: `${" ".repeat(depth)}${icon} ${sanitizeTerminal(a.name)}${a.busy ? " ●" : ""}`,
441
- description: [a.kind === "fork" ? `fork @ #${a.forkedAt}` : a.kind, a.background ? `${a.background} bg` : ""]
444
+ description: [a.kind === "fork" ? `fork @ #${oneLine(String(a.forkedAt ?? ""))}` : oneLine(String(a.kind ?? "")), a.background ? `${oneLine(String(a.background))} bg` : ""]
442
445
  .filter(Boolean)
443
446
  .join(" │ "),
444
447
  });
@@ -12,6 +12,11 @@ const C0 = /[\u0000-\u0008\u000B-\u001F\u007F\u0080-\u009F]/g;
12
12
 
13
13
  /** Neutralize terminal control sequences in an untrusted string before render/stdout. */
14
14
  export function sanitizeTerminal(s: string): string {
15
+ // run-7 D4-A: wire fields are typed strings only by CONVENTION — a hostile
16
+ // device's name/modelId/branch/error-message arrived as any JSON value and
17
+ // the bare s.replace() below killed the whole TUI render (no try/catch in
18
+ // pi-tui's render loop, no process.on handler installed).
19
+ if (typeof s !== "string") return String(s ?? "");
15
20
  return s.replace(ESC_SEQ, "").replace(C0, "");
16
21
  }
17
22