my-durable 0.0.76 → 0.0.78

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 (31) hide show
  1. package/apps/dpi-backend/src/archived.ts +54 -9
  2. package/apps/dpi-backend/src/git.ts +178 -78
  3. package/apps/dpi-backend/src/pairing.ts +3 -1
  4. package/apps/dpi-backend/src/salvage.ts +70 -4
  5. package/apps/dpi-backend/src/store.ts +273 -15
  6. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-h81haD43.css → index-BF6mtGF4.css} +1 -1
  7. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DAF9D074.js +82 -0
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  9. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-rules.ts +38 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/git-store.ts +64 -19
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +26 -2
  12. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GitPanel.vue +46 -2
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +11 -3
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +25 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +44 -4
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +52 -6
  17. package/apps/dpi-sdk/src/api.ts +5 -1
  18. package/apps/dpi-sdk/src/models.ts +180 -19
  19. package/apps/dpi-sdk/src/node/config.ts +13 -2
  20. package/apps/dpi-sdk/src/node/ops.ts +33 -6
  21. package/apps/dpi-sdk/src/node/registry-migration.ts +76 -3
  22. package/apps/dpi-sdk/src/node/registry.ts +5 -2
  23. package/apps/dpi-sdk/src/transcript.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +7 -6
  25. package/apps/dpi-tui/src/pairing.ts +15 -11
  26. package/apps/dpi-tui/src/pickers.ts +11 -8
  27. package/apps/dpi-tui/src/sanitize.ts +5 -0
  28. package/apps/dpi-tui/src/views.ts +16 -16
  29. package/apps/dpi-tui/src/welcome.ts +9 -4
  30. package/package.json +1 -1
  31. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +0 -82
@@ -92,11 +92,94 @@ 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
+ * run-8 U5: items also rode the ~16MiB frame ceiling VERBATIM (probe: a
103
+ * 1MiB InboxItem.content retained whole) — cap item count and per-item
104
+ * content like every other retained wire string. */
105
+ const INBOX_MAX_ITEMS = 128;
106
+ const INBOX_ITEM_TEXT_CAP = 64 * 1024;
107
+ function safeInbox(items: unknown): AgentViewState["inbox"] {
108
+ const list = (Array.isArray(items) ? items : []).filter((x) => !!x && typeof x === "object") as AgentViewState["inbox"];
109
+ return list.slice(-INBOX_MAX_ITEMS).map((item) => {
110
+ const content = (item as { content?: unknown }).content;
111
+ if (typeof content === "string" && content.length > INBOX_ITEM_TEXT_CAP) {
112
+ return { ...item, content: Buffer.from(content.slice(0, INBOX_ITEM_TEXT_CAP), "utf8").toString("utf8") + "…[truncated]" } as AgentViewState["inbox"][number];
113
+ }
114
+ return item;
115
+ });
116
+ }
117
+
118
+ /** run-7 D3 F3: live message blocks append unbounded deltas between
119
+ * message_start/message_end — keep a 256Ki flattened tail (the capToolOutput
120
+ * principle, applied to the live accumulator). */
121
+ const LIVE_TEXT_CAP = 256 * 1024;
122
+
123
+ /** run-8 U5: notice strings rode the frame ceiling verbatim — bounded tail,
124
+ * flat slice (V8 SlicedString retention), explicit marker. */
125
+ const NOTICE_TEXT_CAP = 4 * 1024;
126
+ function capNoticeText(text: string): string {
127
+ return text.length > NOTICE_TEXT_CAP
128
+ ? Buffer.from(text.slice(-NOTICE_TEXT_CAP), "utf8").toString("utf8") + "…[truncated]"
129
+ : text;
130
+ }
131
+
132
+ /** run-8 U5: the live assistant message cloned VERBATIM from message_start /
133
+ * snapshot.generation bypassed every delta cap (probe: 1MiB text block
134
+ * retained whole) — cap the text-bearing blocks at clone time. */
135
+ function capLiveMessage(message: WireAssistantMessage): WireAssistantMessage {
136
+ const cloned = structuredClone(message);
137
+ const content = (cloned as { content?: unknown }).content;
138
+ if (!Array.isArray(content)) return cloned;
139
+ for (const block of content) {
140
+ if (!block || typeof block !== "object") continue;
141
+ const b = block as { text?: unknown; thinking?: unknown; arguments?: unknown };
142
+ if (typeof b.text === "string" && b.text.length > LIVE_TEXT_CAP)
143
+ b.text = capLiveText(b.text.slice(-LIVE_TEXT_CAP));
144
+ if (typeof b.thinking === "string" && b.thinking.length > LIVE_TEXT_CAP)
145
+ b.thinking = capLiveText(b.thinking.slice(-LIVE_TEXT_CAP));
146
+ // cold-3 M5: a toolCall block's arguments rode the same frame ceiling in
147
+ // verbatim — the exact defect this clone cap exists for, one block type over.
148
+ if (b.arguments !== undefined) {
149
+ try {
150
+ if (JSON.stringify(b.arguments).length > MAX_LIVE_ARGS) b.arguments = capLiveArgs(b.arguments);
151
+ } catch {
152
+ b.arguments = { truncated: true };
153
+ }
154
+ }
155
+ }
156
+ return cloned;
157
+ }
158
+
159
+ /** cold-3 M5: bound for a cloned toolCall block's arguments (module scope: the
160
+ * clone helper runs before the class body). */
161
+ const MAX_LIVE_ARGS = 64 * 1024;
162
+ function capLiveArgs(args: unknown): unknown {
163
+ try {
164
+ const text = JSON.stringify(args);
165
+ if (text.length <= MAX_LIVE_ARGS) return args;
166
+ return { truncated: true, preview: Buffer.from(text.slice(0, 4_096), "utf8").toString("utf8") };
167
+ } catch {
168
+ return { truncated: true };
169
+ }
170
+ }
171
+
172
+ function capLiveText(text: string): string {
173
+ return text.length > LIVE_TEXT_CAP ? AgentModel.flatSlice(text.slice(text.length - LIVE_TEXT_CAP)) : text;
96
174
  }
97
175
 
98
176
  export function applyMessageChange(message: WireAssistantMessage, change: WireMessageChange): WireAssistantMessage {
99
177
  if (change.type === "message") return structuredClone(change.message);
178
+ // run-7 cold-2 m4: a hostile toolcall_delta path array builds one nested
179
+ // object PER element — bound the depth and each key before any allocation.
180
+ const p = (change as { path?: unknown }).path;
181
+ if (p !== undefined && (!Array.isArray(p) || p.length > 64 || p.some((k) => typeof k === "string" && k.length > 256)))
182
+ return message;
100
183
  const content = [...message.content] as WireAssistantBlock[];
101
184
  const i = change.contentIndex;
102
185
  // R19 (run-5 h10, leader-probed): the wire number was indexed raw — any
@@ -109,14 +192,17 @@ export function applyMessageChange(message: WireAssistantMessage, change: WireMe
109
192
  content[i] = structuredClone((change as { block: WireAssistantBlock }).block);
110
193
  } else if (change.type === "text_delta") {
111
194
  const block = content[i];
112
- content[i] = { type: "text", text: (block?.type === "text" ? block.text : "") + change.delta };
195
+ content[i] = { type: "text", text: capLiveText((block?.type === "text" ? block.text : "") + change.delta) };
113
196
  } else if (change.type === "thinking_delta") {
114
197
  const block = content[i];
115
198
  content[i] = {
116
199
  type: "thinking",
117
- thinking: (block?.type === "thinking" ? block.thinking : "") + change.delta,
200
+ thinking: capLiveText((block?.type === "thinking" ? block.thinking : "") + change.delta),
118
201
  };
119
202
  } else if (change.type === "toolcall_delta") {
203
+ // run-7 cold-3 LOW: a path-less toolcall_delta reached setPath(undefined)
204
+ // and threw (contained by the per-event catch, but drop it cleanly here).
205
+ if (!Array.isArray(change.path)) return message;
120
206
  const block = structuredClone(content[i] ?? { type: "toolCall", id: "", name: "", arguments: {} });
121
207
  setPath(block as unknown as Record<string, unknown>, change.path, change.delta);
122
208
  content[i] = block;
@@ -155,17 +241,40 @@ export class AgentModel extends Emitter {
155
241
  switch (frame.type) {
156
242
  case "snapshot":
157
243
  this.reset(frame.snapshot);
158
- this.state.inbox = frame.inbox;
244
+ this.state.inbox = safeInbox(frame.inbox);
159
245
  break;
160
246
  case "batch":
161
- for (const event of frame.events) this.event(event);
247
+ // run-7 D4-B + cold-1 M6: non-iterable events AND hostile field shapes
248
+ // (message_start.message:null, message_update.changes:5, entry:null)
249
+ // threw inside apply(), which follow() turns into a reconnect loop
250
+ // re-receiving the same hostile frame forever. Drop the hostile
251
+ // EVENT, keep the stream alive.
252
+ for (const event of (Array.isArray(frame.events) ? frame.events : []).filter((e) => !!e && typeof e === "object")) {
253
+ try {
254
+ this.event(event);
255
+ } catch {
256
+ // one hostile event must not kill the stream for the session
257
+ }
258
+ }
162
259
  break;
163
260
  case "inbox":
164
- this.state.inbox = frame.items;
261
+ this.state.inbox = safeInbox(frame.items);
165
262
  break;
166
- case "doc":
167
- this.state.docs = { ...this.state.docs, [frame.kind]: frame.value };
263
+ case "doc": {
264
+ // run-7 D3 F2: docs was the ONE wire-driven map with neither a count
265
+ // cap nor a byte cap — kind strings are device-chosen and values rode
266
+ // the 16MiB wire ceiling verbatim, forever (no eviction either).
267
+ // cold-1 M5: the KIND is the map key — oversized kinds are dropped
268
+ // whole (the 4096-drop discipline), or 64 of them retain ~1GiB.
269
+ if (String(frame.kind).length > 256) break;
270
+ const kinds: Record<string, unknown> = {
271
+ ...this.state.docs,
272
+ [String(frame.kind)]: this.capDocValue(frame.value),
273
+ };
274
+ const kept = Object.keys(kinds).slice(-64); // insertion order: newest 64 survive
275
+ this.state.docs = Object.fromEntries(kept.map((k) => [k, kinds[k]]));
168
276
  break;
277
+ }
169
278
  default:
170
279
  return false;
171
280
  }
@@ -195,11 +304,18 @@ export class AgentModel extends Emitter {
195
304
  }
196
305
 
197
306
  private reset(snapshot: WireSnapshotEvent) {
198
- this.entries = new Map(snapshot.entries.map((entry) => [entry.id, entry]));
307
+ // run-7 D4-B: snapshot carriers arrive as raw JSON.parse casts — a
308
+ // non-array (or null-element) shape threw in these map/filter chains and
309
+ // follow() re-delivered the hostile snapshot forever.
310
+ const snapEntries = (Array.isArray(snapshot.entries) ? snapshot.entries : []).filter((x) => !!x && typeof x === "object");
311
+ const snapTools = (Array.isArray(snapshot.tools) ? snapshot.tools : []).filter((x) => !!x && typeof x === "object");
312
+ const snapNested = (Array.isArray(snapshot.nestedTools) ? snapshot.nestedTools : []).filter((x) => !!x && typeof x === "object");
313
+ const snapCompactions = (Array.isArray(snapshot.compactions) ? snapshot.compactions : []).filter((x) => !!x && typeof x === "object");
314
+ this.entries = new Map(snapEntries.map((entry) => [entry.id, entry]));
199
315
  this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
200
- this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
316
+ this.live = snapshot.generation?.message ? capLiveMessage(snapshot.generation.message) : undefined;
201
317
  this.tools = new Map(
202
- snapshot.tools
318
+ snapTools
203
319
  .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
320
  .slice(-2_000)
205
321
  .map((slot) => [ // R20 h4: hostile snapshot.tools was uncapped — same bound as every other path
@@ -208,7 +324,7 @@ export class AgentModel extends Emitter {
208
324
  ]),
209
325
  );
210
326
  // 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)) {
327
+ 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
328
  const existing = this.tools.get(slot.callId);
213
329
  this.tools.set(slot.callId, {
214
330
  name: slot.name,
@@ -225,7 +341,7 @@ export class AgentModel extends Emitter {
225
341
  this.state.agent = snapshot.agent;
226
342
  this.state.usage = snapshot.usage;
227
343
  this.state.retry = snapshot.generation?.retry;
228
- this.state.compactions = snapshot.compactions.map((c) => c.taskId).slice(-64);
344
+ this.state.compactions = snapCompactions.map((c) => c.taskId).slice(-64);
229
345
  this.state.compactionFailure = snapshot.compactionFailure;
230
346
  this.state.ready = true;
231
347
  }
@@ -299,7 +415,7 @@ export class AgentModel extends Emitter {
299
415
 
300
416
  /** Store a committed entry. Resets (sent as message_end) and compactions start a new context head. */
301
417
  private commit(entry: WireEntry) {
302
- this.entries.set(entry.id, entry);
418
+ this.entries.set(entry.id, this.capEntry(entry));
303
419
  if (entry.kind === "pi.reset" || entry.kind === "pi.compaction") {
304
420
  const head = entry.head ?? entry.id;
305
421
  for (const id of this.entries.keys()) if (id < head) this.entries.delete(id);
@@ -307,6 +423,37 @@ export class AgentModel extends Emitter {
307
423
  this.capEntries();
308
424
  }
309
425
 
426
+ /** run-7 D3 F3: entries were count-capped but byte-uncapped (5000 × the
427
+ * 16MiB wire ceiling, joined again by toTranscript on every rebuild).
428
+ * Assistant text/thinking blocks keep a flattened 256Ki TAIL + marker. */
429
+ private capEntry(entry: WireEntry): WireEntry {
430
+ // WireEntry.model is readonly WireMessage[]; assistant messages carry
431
+ // content blocks whose text/thinking strings are the retention vector.
432
+ if (!Array.isArray(entry.model)) return entry;
433
+ for (const msg of entry.model) {
434
+ const content = (msg as { content?: unknown }).content;
435
+ if (!Array.isArray(content)) continue;
436
+ for (const b of content) {
437
+ const block = b as { text?: unknown; thinking?: unknown };
438
+ for (const f of ["text", "thinking"] as const) {
439
+ const v = block[f];
440
+ if (typeof v === "string" && v.length > LIVE_TEXT_CAP) {
441
+ block[f] = AgentModel.flatSlice(v.slice(v.length - LIVE_TEXT_CAP)) + "…[truncated]";
442
+ }
443
+ }
444
+ }
445
+ }
446
+ return entry;
447
+ }
448
+
449
+ /** run-7 D3 F2: bound a wire doc value — over 64Ki serialized it becomes a
450
+ * flattened 4Ki preview (the capArgs discipline). */
451
+ private capDocValue(value: unknown): unknown {
452
+ const text = safeStringify(value);
453
+ if (text.length > 64 * 1024) return { truncated: true, preview: AgentModel.flatSlice(text.slice(0, 4096)) };
454
+ return value;
455
+ }
456
+
310
457
  private event(event: WireAgentEvent) {
311
458
  switch (event.type) {
312
459
  case "snapshot":
@@ -319,8 +466,7 @@ export class AgentModel extends Emitter {
319
466
  this.live = undefined;
320
467
  return;
321
468
  case "message_start":
322
- if (event.message.role === "assistant")
323
- this.live = structuredClone(event.message as WireAssistantMessage);
469
+ if (event.message.role === "assistant") this.live = capLiveMessage(event.message as WireAssistantMessage);
324
470
  return;
325
471
  case "message_update":
326
472
  if (!this.live)
@@ -363,6 +509,11 @@ export class AgentModel extends Emitter {
363
509
  });
364
510
  return;
365
511
  case "tool_execution_update": {
512
+ // run-7 D3 F1: the R20 cold-3 M1 4096-drop ran on the start path only;
513
+ // this orphan path stored the id as the MAP KEY and the name verbatim
514
+ // (16MiB × 2000 slots ceiling). Same drop discipline.
515
+ if (typeof event.toolCallId !== "string" || event.toolCallId.length > 4_096 || typeof event.toolName !== "string" || event.toolName.length > 4_096)
516
+ return;
366
517
  const tool = this.tools.get(event.toolCallId) ?? {
367
518
  name: event.toolName,
368
519
  status: "running" as const,
@@ -380,12 +531,15 @@ export class AgentModel extends Emitter {
380
531
  if (event.entry) {
381
532
  // A model-issued call renders from its result entry; drop the live slot so it is never duplicated.
382
533
  this.tools.delete(event.toolCallId);
383
- this.entries.set(event.entry.id, event.entry);
384
- this.capEntries();
534
+ this.commit(event.entry);
385
535
  this.capTools();
386
536
  return;
387
537
  }
388
538
  if (event.result) {
539
+ // run-7 D3 F1: same drop discipline as start/update (this path also
540
+ // stored id/name verbatim into the capped-by-count-only map).
541
+ if (typeof event.toolCallId !== "string" || event.toolCallId.length > 4_096 || typeof event.toolName !== "string" || event.toolName.length > 4_096)
542
+ return;
389
543
  // A nested call has no entry: keep the slot so its result still renders, exactly once.
390
544
  const tool = this.tools.get(event.toolCallId) ?? { name: event.toolName, status: "done" as const, output: "" };
391
545
  tool.status = "done";
@@ -423,7 +577,14 @@ export class AgentModel extends Emitter {
423
577
  : undefined;
424
578
  return;
425
579
  case "task_failed":
426
- this.state.notices = [...this.state.notices.slice(-9), `${event.kind} failed: ${event.message}`];
580
+ // run-8 U5: kind/message rode the frame ceiling verbatim — 10 x 16MiB
581
+ // notices froze the FE tab (probe: notice[0].length === 1048592).
582
+ // Same discipline as capToolOutput: bounded tail, flat slice.
583
+ if (typeof event.kind !== "string" || event.kind.length > 64) return;
584
+ this.state.notices = [
585
+ ...this.state.notices.slice(-9),
586
+ `${event.kind} failed: ${capNoticeText(String(event.message ?? ""))}`,
587
+ ];
427
588
  return;
428
589
  default:
429
590
  return;
@@ -155,10 +155,21 @@ export function parseNetworkConfig(text: string, file = NETWORK_FILE): NetworkCo
155
155
  device.ssh = `${device.vm}.exe.xyz`;
156
156
  device.service ??= "systemd";
157
157
  const create = (d.create ?? {}) as Raw;
158
+ // run-8 U9: memory/disk were the ONLY config scalars with no charset gate
159
+ // and they ride `ssh exe.dev new --memory=<v>` argv, which OpenSSH joins
160
+ // into one remote command string the remote shell re-parses. Gate them at
161
+ // parse time like pathish does for every other shell-bound value.
162
+ const sized = (v: unknown, field: string): string | undefined => {
163
+ if (v === undefined) return undefined;
164
+ const text = String(v);
165
+ if (!/^[0-9]+(\.[0-9]+)?[KMGTP]?i?B?$/i.test(text))
166
+ throw Error(`${where}.create.${field} is not a size (e.g. 4G, 512M)`);
167
+ return text;
168
+ };
158
169
  device.create = {
159
170
  ...(create.cpu !== undefined ? { cpu: Number(create.cpu) } : {}),
160
- ...(typeof create.memory === "string" ? { memory: create.memory } : {}),
161
- ...(typeof create.disk === "string" ? { disk: create.disk } : {}),
171
+ ...(sized(create.memory, "memory") !== undefined ? { memory: sized(create.memory, "memory")! } : {}),
172
+ ...(sized(create.disk, "disk") !== undefined ? { disk: sized(create.disk, "disk")! } : {}),
162
173
  };
163
174
  }
164
175
  if ((kind === "ssh" || kind === "exe-dev") && !device.service) throw Error(`${where}.service is required for kind ${kind}`);
@@ -3,6 +3,10 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import type { NetDevice } from "./config.js";
5
5
 
6
+ /** run-8 U9: every device-facing step gets a deadline by default, so a hung or
7
+ * hostile host cannot block the operator's CLI indefinitely. */
8
+ const DEFAULT_TIMEOUT_MS = 60_000;
9
+
6
10
  export interface RunResult {
7
11
  code: number;
8
12
  stdout: string;
@@ -12,6 +16,8 @@ export interface RunResult {
12
16
  export interface RunOptions {
13
17
  stdin?: string;
14
18
  timeoutMs?: number;
19
+ /** run-8 U9: cap on captured stdout/stderr per stream (default 1 MiB). */
20
+ maxBytes?: number;
15
21
  /** Stream output to this process's stdout/stderr while capturing it. */
16
22
  echo?: boolean;
17
23
  cwd?: string;
@@ -29,18 +35,33 @@ export function run(cmd: string, args: string[], options: RunOptions = {}): Prom
29
35
  });
30
36
  let stdout = "";
31
37
  let stderr = "";
32
- const timer = options.timeoutMs
38
+ // run-8 U9: a hostile/hung device controls every byte on these pipes and
39
+ // run() accumulated them without limit, so `net status`/`up` could OOM or
40
+ // hang forever (facts/register/logs passed no timeout at all).
41
+ const cap = options.maxBytes ?? 1024 * 1024;
42
+ let truncatedStdout = false;
43
+ let truncatedStderr = false;
44
+ const take = (current: string, chunk: Buffer, mark: (v: boolean) => void): string => {
45
+ if (current.length >= cap) {
46
+ mark(true);
47
+ return current;
48
+ }
49
+ return current + chunk.toString().slice(0, cap - current.length);
50
+ };
51
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
52
+ const timer = timeoutMs
33
53
  ? setTimeout(() => {
34
54
  child.kill("SIGTERM");
35
- stderr += `\n[timeout after ${options.timeoutMs}ms]`;
36
- }, options.timeoutMs)
55
+ setTimeout(() => child.kill("SIGKILL"), 2000).unref?.();
56
+ stderr = take(stderr, Buffer.from(`\n[timeout after ${timeoutMs}ms]`), (v) => (truncatedStderr = v));
57
+ }, timeoutMs)
37
58
  : undefined;
38
59
  child.stdout.on("data", (chunk: Buffer) => {
39
- stdout += chunk;
60
+ stdout = take(stdout, chunk, (v) => (truncatedStdout = v));
40
61
  if (options.echo) process.stdout.write(chunk);
41
62
  });
42
63
  child.stderr.on("data", (chunk: Buffer) => {
43
- stderr += chunk;
64
+ stderr = take(stderr, chunk, (v) => (truncatedStderr = v));
44
65
  if (options.echo) process.stderr.write(chunk);
45
66
  });
46
67
  child.on("error", (e) => {
@@ -49,7 +70,13 @@ export function run(cmd: string, args: string[], options: RunOptions = {}): Prom
49
70
  });
50
71
  child.on("close", (code) => {
51
72
  if (timer) clearTimeout(timer);
52
- const result = { code: code ?? 1, stdout, stderr };
73
+ // cold-3 L10: a silent cut is indistinguishable from a complete log.
74
+ const marker = `\n[truncated at ${cap} bytes]`;
75
+ const result = {
76
+ code: code ?? 1,
77
+ stdout: truncatedStdout ? stdout + marker : stdout,
78
+ stderr: truncatedStderr ? stderr + marker : stderr,
79
+ };
53
80
  if (result.code !== 0 && !options.allowFail)
54
81
  reject(Object.assign(Error(`${cmd} ${args.slice(0, 3).join(" ")} … failed (exit ${result.code}): ${stderr.trim().slice(-800)}`), { result }));
55
82
  else resolve(result);
@@ -21,6 +21,7 @@ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, openSync, rmSyn
21
21
  import { dirname } from "node:path";
22
22
  import { randomUUID } from "node:crypto";
23
23
  import { ensurePrivateDir } from "./private-dir.js";
24
+ import { normalizeUrl, validateToken } from "./registry.js";
24
25
 
25
26
  export const REGISTRY_SCHEMA_VERSION = 1;
26
27
  const UUID_CANONICAL = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -346,7 +347,19 @@ function openExclusive(path: string, busyTimeoutMs: number): DatabaseSync {
346
347
  }
347
348
 
348
349
  /** v0 preflight: no stray v1 objects, exact column set per v0 table, canonical ids/uids, no duplicates. */
349
- function preflightV0(db: DatabaseSync): void {
350
+ /** Sanitized replacement values for rows whose legacy fields the live writers
351
+ * would refuse or cap. Applied INSIDE the migration transaction (never in the
352
+ * read-only preflight): a preflight write would mutate the v0 file before the
353
+ * WAL-safe backup and before BEGIN, so an aborted migration would silently
354
+ * drop operator tokens. */
355
+ export interface V0Overrides {
356
+ url?: string;
357
+ token?: string | null;
358
+ info?: string | null;
359
+ tree?: string | null;
360
+ }
361
+
362
+ function preflightV0(db: DatabaseSync): Map<string, V0Overrides> {
350
363
  // First: anything the v1 schema owns means this is not a v0 file at all. Refused before
351
364
  // the backup is written and before any write touches the registry (the caller's
352
365
  // `reached(opts, "preflight")` hook still fires only after preflightV0 returns).
@@ -373,9 +386,21 @@ function preflightV0(db: DatabaseSync): void {
373
386
  );
374
387
  }
375
388
  }
376
- const rows = db.prepare("SELECT id, url, device_uid FROM devices").all() as {
389
+ // run-8 U9: the v0 rows predate the writer-side caps and normalisation, and
390
+ // the copy below is verbatim — a pre-run-7 registry could carry a hostile
391
+ // 16MiB last_tree_json (parsed by EVERY NetworkRegistry.list() forever) or a
392
+ // token with CRLF (breaking every client construction). Enforce the same
393
+ // per-field policy at the migration seam: cap the JSON blobs and NULL out a
394
+ // url/token that the live writers would have refused.
395
+ const rows = db.prepare(
396
+ "SELECT id, url, device_uid, token, last_info_json, last_tree_json FROM devices",
397
+ ).all() as {
377
398
  id: string; url: string | null; device_uid: string | null;
399
+ token: string | null; last_info_json: string | null; last_tree_json: string | null;
378
400
  }[];
401
+ const INFO_CAP = 64 * 1024;
402
+ const TREE_CAP = 288 * 1024;
403
+ const overrides = new Map<string, V0Overrides>();
379
404
  const seenUid = new Set<string>();
380
405
  for (const row of rows) {
381
406
  if (!DEVICE_ID_PATTERN.test(row.id)) throw new MigrationError(`non-canonical device id ${JSON.stringify(row.id)} — resolve manually (no trim)`);
@@ -385,7 +410,34 @@ function preflightV0(db: DatabaseSync): void {
385
410
  if (seenUid.has(row.device_uid)) throw new MigrationError(`duplicate device_uid ${row.device_uid} — operator must resolve before migration`);
386
411
  seenUid.add(row.device_uid);
387
412
  }
413
+ let url: string = row.url;
414
+ try {
415
+ url = normalizeUrl(row.url);
416
+ } catch {
417
+ // The live writer would have refused this url; carrying it over would put
418
+ // an arbitrary scheme in every consumer. Fail closed (url is NOT NULL).
419
+ throw new MigrationError(`device ${row.id} has a url the live writer refuses — resolve manually`);
420
+ }
421
+ let token: string | null = row.token;
422
+ if (token !== null) {
423
+ try {
424
+ validateToken(token);
425
+ } catch {
426
+ token = null;
427
+ }
428
+ }
429
+ const capJson = (text: string | null, cap: number): string | null =>
430
+ text !== null && text.length > cap ? null : text;
431
+ const info = capJson(row.last_info_json, INFO_CAP);
432
+ const tree = capJson(row.last_tree_json, TREE_CAP);
433
+ const patch: V0Overrides = {};
434
+ if (url !== row.url) patch.url = url;
435
+ if (token !== row.token) patch.token = token;
436
+ if (info !== row.last_info_json) patch.info = info;
437
+ if (tree !== row.last_tree_json) patch.tree = tree;
438
+ if (Object.keys(patch).length) overrides.set(row.id, patch);
388
439
  }
440
+ return overrides;
389
441
  }
390
442
 
391
443
  /**
@@ -462,7 +514,7 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
462
514
  }
463
515
  assertMigratable(version);
464
516
 
465
- preflightV0(db);
517
+ const overrides = preflightV0(db);
466
518
  reached(opts, "preflight");
467
519
 
468
520
  const preCount = (db.prepare("SELECT count(*) AS n FROM devices").get() as { n: number }).n;
@@ -484,6 +536,27 @@ function migrateV0(db: DatabaseSync, path: string, opts: MigrationOptions): Regi
484
536
  created_at,updated_at,'lan'
485
537
  FROM devices`,
486
538
  );
539
+ // The sanitized legacy values land on the NEW table, inside this
540
+ // transaction: the v0 file is never modified by a migration that aborts.
541
+ if (overrides.size) {
542
+ // cold-3 L11: dropping a legacy token is a behaviour change the operator
543
+ // must be able to see (the refused URL aborts loudly; this must not be
544
+ // silent). Ids + field names only, never the values.
545
+ const fields = [...overrides].map(([id, patch]) => `${id}(${Object.keys(patch).join(",")})`);
546
+ process.emitWarning(
547
+ `registry migration: sanitised ${overrides.size} legacy row(s) — ${fields.join(" ")}; those devices may need re-pairing`,
548
+ );
549
+ const setUrl = db.prepare("UPDATE devices_v1_new SET url=? WHERE id=?");
550
+ const setToken = db.prepare("UPDATE devices_v1_new SET token=? WHERE id=?");
551
+ const setInfo = db.prepare("UPDATE devices_v1_new SET last_info_json=? WHERE id=?");
552
+ const setTree = db.prepare("UPDATE devices_v1_new SET last_tree_json=? WHERE id=?");
553
+ for (const [id, patch] of overrides) {
554
+ if (patch.url !== undefined) setUrl.run(patch.url, id);
555
+ if (patch.token !== undefined) setToken.run(patch.token, id);
556
+ if (patch.info !== undefined) setInfo.run(patch.info, id);
557
+ if (patch.tree !== undefined) setTree.run(patch.tree, id);
558
+ }
559
+ }
487
560
  reached(opts, "mid-transaction");
488
561
  db.exec("DROP TABLE devices; ALTER TABLE devices_v1_new RENAME TO devices;");
489
562
  db.exec(V1_SCHEMA_SQL);
@@ -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
  }
@@ -16,7 +16,7 @@ import type { App } from "./app.ts";
16
16
  import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
17
17
  import { Panel } from "./pickers.ts";
18
18
  import { c } from "./theme.ts";
19
- import { sanitizeTerminal } from "./sanitize.ts";
19
+ import { oneLine } from "./sanitize.ts";
20
20
 
21
21
  export interface PairArgs {
22
22
  code?: string;
@@ -152,32 +152,36 @@ export function pairingViewLines(
152
152
  hubOrigin?: string,
153
153
  ): string[] {
154
154
  const lines: string[] = [c.bold(c.accent("Pair this device"))];
155
- if (hubOrigin) lines.push(c.muted(`hub: ${sanitizeTerminal(hubOrigin)}`));
155
+ if (hubOrigin) lines.push(c.muted(`hub: ${oneLine(hubOrigin)}`));
156
156
  if (!status) {
157
- lines.push(c.muted(sanitizeTerminal(note)));
157
+ lines.push(c.muted(oneLine(note)));
158
158
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
159
159
  }
160
- lines.push(c.muted(sanitizeTerminal(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
160
+ lines.push(c.muted(oneLine(`device: ${status.deviceName ?? status.deviceUid ?? "?"} · uid ${status.deviceUid ?? "?"}`)));
161
161
  lines.push("");
162
162
  lines.push(c.bold("key fingerprint (compare with the hub wizard):"));
163
- for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(sanitizeTerminal(line))}`);
163
+ for (const line of wrapFingerprint(status.fingerprint, width)) lines.push(` ${c.secondary(oneLine(line))}`);
164
164
  lines.push("");
165
165
  if (status.pending) {
166
166
  lines.push(c.warn("Awaiting approval on the hub…"));
167
- if (status.pending.note) lines.push(c.muted(` ${sanitizeTerminal(status.pending.note)}`));
167
+ if (status.pending.note) lines.push(c.muted(` ${oneLine(status.pending.note)}`));
168
168
  } else if (status.lastError) {
169
- lines.push(c.err(sanitizeTerminal(describePairingError(status.lastError))));
169
+ // run-8 U6: the hub relays its own error.message here unbounded, and
170
+ // wrapTextWithAnsi SPLITS on LF — a hostile message forged panel rows
171
+ // right below the real TOFU fingerprint block (probe: 2 rows, one read
172
+ // "Paired to https://good.example (generation 9)").
173
+ lines.push(c.err(oneLine(describePairingError(status.lastError))));
170
174
  if (status.state === "paired")
171
- lines.push(c.muted(sanitizeTerminal(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
175
+ lines.push(c.muted(oneLine(`Existing pairing to ${status.hubOrigin} is unchanged.`)));
172
176
  } else if (status.state === "paired") {
173
- lines.push(c.ok(sanitizeTerminal(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
177
+ lines.push(c.ok(oneLine(`Paired to ${status.hubOrigin} (generation ${status.generation}).`)));
174
178
  lines.push(c.muted("The connector keeps the tunnel up; /pair again to re-pair."));
175
179
  } else if (status.state === "revoked") {
176
180
  lines.push(c.warn("Revoked on the hub. /pair CODE to pair again."));
177
181
  } else {
178
- lines.push(c.muted(sanitizeTerminal(note)));
182
+ lines.push(c.muted(oneLine(note)));
179
183
  }
180
- if (note && status.state !== "pairing") lines.push(c.muted(sanitizeTerminal(note)));
184
+ if (note && status.state !== "pairing") lines.push(c.muted(oneLine(note)));
181
185
  return lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
182
186
  }
183
187