my-durable 0.0.73 → 0.0.75

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.
@@ -91,62 +91,104 @@ export class AuditUnavailableError extends Error {
91
91
 
92
92
  /** Redact every secret shape, including substrings, from arbitrary strings. */
93
93
  export function scrubSecrets(value: string): string {
94
- let out = value;
95
- out = out.replace(/dpt_[A-Za-z0-9_-]{1,64}/g, "dpt_<redacted>");
96
- out = out.replace(/dpi_[A-Za-z0-9_-]{1,64}/g, "dpi_<redacted>");
97
- // The hub's own admin token (adm_ + 32 random bytes, base64url).
98
- out = out.replace(/adm_[A-Za-z0-9_-]{32,}/g, "adm_<redacted>");
99
- out = out.replace(
100
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g,
101
- "<private-key-redacted>",
102
- );
103
- out = out.replace(/(authorization\s*[:=]\s*)(\S+)/gi, "$1<redacted>");
104
- out = out.replace(/(bearer\s+)([A-Za-z0-9._-]{8,})/gi, "$1<redacted>");
105
- out = out.replace(/([?&]code=)[A-Za-z0-9_-]+/g, "$1<redacted>");
106
- // v2 offer links: the secret IS the #offer= fragment payload — redact it wherever a URL shows up.
107
- out = out.replace(/(#offer=)[A-Za-z0-9_-]+/g, "$1<redacted>");
108
- // R16 (run-2 h7) + R17 (run-3 h10): a denied request lands the FULL share
109
- // capability token in audit path samples — the token IS the secret. The
110
- // prefix spelling is ATTACKER-CONTROLLED (/share/, /api/shares/, /Share/,
111
- // /%73hare/...), so anchor on a *share-shaped* path segment (case-blind,
112
- // percent-encoding tolerated) followed by the token run — not on any one
113
- // literal prefix. Bare token-shaped values elsewhere (audit enums like
114
- // "foreign_subscription") stay readable.
115
- // R18 (run-4 h6): three deliberate spellings still escaped — a non-token
116
- // separator byte wedged between segment and token ('/api/shares/.<tok>'),
117
- // a padded run longer than 32 chars, and percent-encoded spellings the
118
- // literal pass cannot see. Tolerate 0-2 separator bytes, drop the upper
119
- // bound, and re-run both rules on a percent-decoded copy.
120
- // Cold-review minor 1: a decoded `/api/shares/<word>%2F<token>` leaves the
121
- // token behind a short extra path segment — tolerate one such segment AND
122
- // keep the direct 0–2 non-token separator (run-4 h6) before the run.
123
- const shareShaped =
124
- /(\/[a-z0-9%]*shares?\/)(?:[^\s"']{0,8}\/)?[^\w\n]{0,2}[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
125
- // Encoded spellings (/%73hare/) hide the literal "share" — any
126
- // percent-bearing path segment followed by a token-shaped run is treated
127
- // the same.
128
- const percentBearing = /(\/[^\s"']*%[^\s"']*\/)[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
129
- const scrubTokens = (s: string): string => s.replace(shareShaped, "$1<redacted>").replace(percentBearing, "$1<redacted>");
130
- out = scrubTokens(out);
94
+ // R19 (run-5 h5, leader-confirmed): the share-shaped gap used to tolerate
95
+ // only 2 separator bytes (or one ≤8-byte segment ending in '/'), so 3+
96
+ // requester-spelled gap bytes ('/share/...<tok>', ';;;', '%20%20%20',
97
+ // ';x=', double-encoded forms) left the capability intact. The gap is now
98
+ // any ≤16-byte non-space run (requester-controlled spelling, sample ≤200
99
+ // chars), and the FULL rule set re-runs on the decoded string (≤2 decode
100
+ // rounds) — not just the two share rules.
101
+ const applyRules = (s: string): string => {
102
+ let out = s;
103
+ out = out.replace(/dpt_[A-Za-z0-9_-]{1,64}/g, "dpt_<redacted>");
104
+ out = out.replace(/dpi_[A-Za-z0-9_-]{1,64}/g, "dpi_<redacted>");
105
+ // The hub's own admin token (adm_ + 32 random bytes, base64url).
106
+ out = out.replace(/adm_[A-Za-z0-9_-]{32,}/g, "adm_<redacted>");
107
+ out = out.replace(
108
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g,
109
+ "<private-key-redacted>",
110
+ );
111
+ out = out.replace(/(authorization\s*[:=]\s*)(\S+)/gi, "$1<redacted>");
112
+ out = out.replace(/(bearer\s+)([A-Za-z0-9._-]{8,})/gi, "$1<redacted>");
113
+ out = out.replace(/([?&]code=)[A-Za-z0-9_-]+/g, "$1<redacted>");
114
+ // v2 offer links: the secret IS the #offer= fragment payload — redact it wherever a URL shows up.
115
+ out = out.replace(/(#offer=)[A-Za-z0-9_-]+/g, "$1<redacted>");
116
+ // R16 (run-2 h7) + R17 (run-3 h10): a denied request lands the FULL share
117
+ // capability token in audit path samples — the token IS the secret. The
118
+ // prefix spelling is ATTACKER-CONTROLLED (/share/, /api/shares/, /Share/,
119
+ // /%73hare/...), so anchor on a *share-shaped* path segment (case-blind,
120
+ // percent-encoding tolerated) followed by the token run — not on any one
121
+ // literal prefix. Bare token-shaped values elsewhere (audit enums like
122
+ // "foreign_subscription") stay readable.
123
+ // Cold-review minors: the gap must not stop at 16 bytes (a 17-byte spelling
124
+ // leaked), the no-slash branch must not treat whitespace as a separator
125
+ // ("(/api/shares <word>" is readable prose, not a capability), and the gap
126
+ // is BOUNDED at 64 bytes: an unbounded lazy gap combined with `[^\s"']*`
127
+ // before `%` is catastrophic backtracking on '/a%'-style input (measured
128
+ // 1.6 s at 600 chars, 2.4 s at 800). 64 bytes covers every real spelling
129
+ // and keeps the scan linear.
130
+ const shareShaped =
131
+ /(\/[a-z0-9%]*shares?(?:\/|(?=[^a-z0-9_%\s]|$)))[^\s"']{0,64}?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
132
+ // Encoded spellings (/%73hare/) hide the literal "share" — any
133
+ // percent-bearing path segment followed by a token-shaped run is treated
134
+ // the same. The leading run excludes `%` so the quantifier cannot nest on
135
+ // percent characters (the optimizer would otherwise retry every split).
136
+ const percentBearing = /(\/[^\s"'%]*%[^\s"']{0,64}\/)[^\s"']{0,64}?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
137
+ out = out.replace(shareShaped, "$1<redacted>").replace(percentBearing, "$1<redacted>");
138
+ // R20 (run-6 h2): the two rules above are FIRST-SATISFYING-MATCH regexes —
139
+ // a requester-spelled decoy ≥20-char run ('/share/aaaa…/<tok>'), a >64-byte
140
+ // gap, a raw quote separator, or a zero-separator concatenation
141
+ // ('/share<tok>') spends the match on attacker bytes and leaves the real
142
+ // 24-char capability token behind. Once ANY share-shaped anchor is present
143
+ // the whole sample is capability context: redact EVERY token-shaped run.
144
+ // A run preceded by whitespace is exempt — the R19 M4 decision stands: a
145
+ // space is prose, not a capability separator (and an encoded space %20
146
+ // still leaks its token here: the digits glue into the run, which round 1
147
+ // redacts before any decode). The anchor needs a non-word char before
148
+ // "share" ("/share", "?shares="), so plain prose never triggers this.
149
+ if (/(?:^|[^\w\s])shares?/i.test(out)) {
150
+ // Keep the R19 M4 decision: a run whose FIRST char is preceded by
151
+ // whitespace is prose, not a capability — everything else in anchor
152
+ // context is redacted (callback sees the true run start; a lookbehind
153
+ // would just shift the match one char into the run).
154
+ out = out.replace(/[A-Za-z0-9_-]{20,}/g, (run, offset: number, whole: string) =>
155
+ // R20 cold-1 M1: JS \s includes NBSP/U+2000-200A — a raw NBSP before
156
+ // the token exempted it while no gap rule could cross it either. The
157
+ // M4 prose decision is about an ASCII SPACE; narrow to exactly that.
158
+ offset > 0 && whole[offset - 1] === " " ? run : "<redacted>",
159
+ );
160
+ }
161
+ // Credential material without its prefix (slices, echo): 43-char base64url runs.
162
+ out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
163
+ // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
164
+ out = out.replace(/(["'?=:,\s])([A-Z2-7]{12}|[A-Z2-7]{8})(?=["'?\s:,}]|$)/g, "$1<code-redacted>");
165
+ // A MINTED code is a canonical UUID v4. Only a value LABELLED a code is a secret here: an audit
166
+ // row's own codeId/enrollmentId are correlation ids and must stay readable.
167
+ out = out.replace(
168
+ /(\bcode["']?\s*[:=]\s*["']?)([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?=["'?\s:,}&]|$)/gi,
169
+ "$1<code-redacted>",
170
+ );
171
+ return out;
172
+ };
173
+ let out = applyRules(value);
131
174
  // The decoded pass sees through %XX spellings of the separator, the first
132
175
  // token characters, or the segment itself; the sample is bounded (≤200
133
- // chars) so a pathological decode cannot explode it.
134
- try {
135
- const decoded = decodeURIComponent(out);
136
- if (decoded !== out) out = scrubTokens(decoded);
137
- } catch {
138
- // malformed percent escapes stay as the literal pass left them
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
+ try {
180
+ const decoded = decodeURIComponent(out);
181
+ if (decoded === out) break;
182
+ out = applyRules(decoded);
183
+ } catch {
184
+ break; // malformed percent escapes stay as the previous pass left them
185
+ }
139
186
  }
140
- // Credential material without its prefix (slices, echo): 43-char base64url runs.
141
- out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
142
- // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
143
- out = out.replace(/(["'?=:,\s])([A-Z2-7]{12}|[A-Z2-7]{8})(?=["'?\s:,}]|$)/g, "$1<code-redacted>");
144
- // A MINTED code is a canonical UUID v4. Only a value LABELLED a code is a secret here: an audit
145
- // row's own codeId/enrollmentId are correlation ids and must stay readable.
146
- out = out.replace(
147
- /(\bcode["']?\s*[:=]\s*["']?)([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?=["'?\s:,}&]|$)/gi,
148
- "$1<code-redacted>",
149
- );
187
+ // R19 cold-review MAJOR 5: decoding can RESURRECT encoded control characters
188
+ // (a double-encoded newline survives into the sample), which would forge
189
+ // extra lines in the audit log. Scrub the sample to printable single-line
190
+ // text — audit rows are one line. U+2028/U+2029 are line breaks too.
191
+ out = out.replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u2028\u2029]/g, "\uFFFD");
150
192
  return out;
151
193
  }
152
194
 
@@ -491,7 +491,7 @@ export interface SessionSearchMatch {
491
491
  dbPath: string;
492
492
  compaction?: CompactionSettings;
493
493
  where: Array<"name" | "cwd" | "model" | "transcript">;
494
- /** Present when scope=all found transcript text (up to a few per session, newest first). */
494
+ /** Present when scope=all found transcript text (up to 12 per session, newest first — R19 cap). */
495
495
  hits?: TranscriptSearchHit[];
496
496
  }
497
497
 
@@ -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") {
@@ -118,6 +124,26 @@ export function applyMessageChange(message: WireAssistantMessage, change: WireMe
118
124
  return { ...message, content };
119
125
  }
120
126
 
127
+ /**
128
+ * R20 cold-2 M2: agents elements ride the same JSON.parse cast — [null]
129
+ * threw in lineage()/find() from the FE's always-render breadcrumb. Same
130
+ * boundary discipline as safeTasks.
131
+ */
132
+ function safeAgents(value: unknown): AgentSummary[] {
133
+ if (!Array.isArray(value)) return [];
134
+ return value.filter((a): a is AgentSummary => !!a && typeof a === "object");
135
+ }
136
+
137
+ /**
138
+ * R20 cold-1 M3: both tasks-bearing frame shapes (session + tasks) pass here
139
+ * — non-array input ({} / null) crashed the old inline filter itself, and
140
+ * null/state-less rows crashed the statusbar's every-frame deref.
141
+ */
142
+ function safeTasks(value: unknown): TaskNode[] {
143
+ if (!Array.isArray(value)) return [];
144
+ return value.filter((t): t is TaskNode => !!t && typeof t === "object" && !!(t as { state?: unknown }).state);
145
+ }
146
+
121
147
  export class AgentModel extends Emitter {
122
148
  state: AgentViewState = emptyAgentState();
123
149
  private entries = new Map<number, WireEntry>();
@@ -170,35 +196,107 @@ export class AgentModel extends Emitter {
170
196
 
171
197
  private reset(snapshot: WireSnapshotEvent) {
172
198
  this.entries = new Map(snapshot.entries.map((entry) => [entry.id, entry]));
199
+ this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
173
200
  this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
174
201
  this.tools = new Map(
175
- snapshot.tools.map((slot) => [
176
- slot.callId,
177
- { name: slot.name, status: slot.status, output: slot.output ?? "" },
178
- ]),
202
+ snapshot.tools
203
+ .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
+ .slice(-2_000)
205
+ .map((slot) => [ // R20 h4: hostile snapshot.tools was uncapped — same bound as every other path
206
+ slot.callId,
207
+ { name: slot.name, status: slot.status, output: this.capToolOutput(slot.output ?? "") },
208
+ ]),
179
209
  );
180
210
  // 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) {
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)) {
182
212
  const existing = this.tools.get(slot.callId);
183
213
  this.tools.set(slot.callId, {
184
214
  name: slot.name,
185
215
  status: slot.status,
186
- output: slot.output ?? "",
187
- args: slot.arguments,
216
+ output: this.capToolOutput(slot.output ?? ""),
217
+ args: this.capArgs(slot.arguments), // R20 cold-2 M1
188
218
  nested: { parentCallId: slot.parentCallId, parentTaskId: slot.parentTaskId, taskId: slot.taskId },
189
219
  ...(slot.summary ? { summary: slot.summary } : {}),
190
220
  ...(existing ?? {}),
191
221
  });
192
222
  }
223
+ this.capTools(); // R20 cold-1 M2: snapshot.tools(≤2000) + nestedTools(≤2000) must UNION to ≤2000
193
224
  this.state.running = !!snapshot.run;
194
225
  this.state.agent = snapshot.agent;
195
226
  this.state.usage = snapshot.usage;
196
227
  this.state.retry = snapshot.generation?.retry;
197
- this.state.compactions = snapshot.compactions.map((c) => c.taskId);
228
+ this.state.compactions = snapshot.compactions.map((c) => c.taskId).slice(-64);
198
229
  this.state.compactionFailure = snapshot.compactionFailure;
199
230
  this.state.ready = true;
200
231
  }
201
232
 
233
+ /**
234
+ * R19 (run-5 h10, leader-probed): the events stream had NO aggregate cap — a
235
+ * hostile device streaming unique ids under the 16 MiB per-event cap grew this
236
+ * Map linearly (10k entries → +11 MB, no ceiling) until the operator's tab/TUI
237
+ * OOMs. Cold-review MAJOR 3: the cap first lived only in commit(), so the
238
+ * snapshot and tool_execution_end paths bypassed it — it is enforced in ONE
239
+ * place, on every mutation.
240
+ */
241
+ /**
242
+ * R19 cold-review follow-up: `tools` is the SDK's other unbounded map — 30k
243
+ * `tool_execution_start` events grew it to 30k slots AND cost ~140 s of CPU
244
+ * (rebuild → toTranscript is O(tools) per frame, so the stream is quadratic).
245
+ * Same hostile-peer class as the entries cap, so the same bound.
246
+ */
247
+ /**
248
+ * R20 cold-1 M2: capTools bounds the NUMBER of slots, not the bytes in one
249
+ * slot — 100 update events each appending ~16 MiB (the per-event cap) onto
250
+ * ONE callId retained ~1.6 GB in client state. Keep only the tail.
251
+ */
252
+ private static readonly MAX_TOOL_OUTPUT = 256 * 1024;
253
+ private capToolOutput(text: string): string {
254
+ return text.length > AgentModel.MAX_TOOL_OUTPUT ? AgentModel.flatSlice(text.slice(-AgentModel.MAX_TOOL_OUTPUT)) : text;
255
+ }
256
+
257
+ /**
258
+ * R20 cold-2 M1 (probe follow-up): a V8 SlicedString RETAINS its parent —
259
+ * a 4 KiB preview of a 2 MiB JSON kept the whole 2 MiB alive (measured
260
+ * 607 MiB retained for 300 "bounded" slots). Round-tripping through bytes
261
+ * detaches the slice from the parent.
262
+ */
263
+ static flatSlice(text: string): string { // module fns (nestedResultText) share it
264
+ return Buffer.from(text, "utf8").toString("utf8");
265
+ }
266
+
267
+ /**
268
+ * R20 cold-2 M1: `args` rode the same 16 MiB per-event ceiling as output —
269
+ * 2000 slots x 16 MiB of verbatim args was a ~32 GiB retention path the
270
+ * output cap did not touch. Oversized args become a bounded preview.
271
+ */
272
+ private static readonly MAX_ARGS = 64 * 1024;
273
+ private capArgs(args: unknown): unknown {
274
+ if (args === undefined || args === null) return args;
275
+ try {
276
+ const text = JSON.stringify(args);
277
+ if (text.length <= AgentModel.MAX_ARGS) return args;
278
+ return { truncated: true, preview: AgentModel.flatSlice(text.slice(0, 4_096)) };
279
+ } catch {
280
+ return { truncated: true };
281
+ }
282
+ }
283
+
284
+ private capTools() {
285
+ while (this.tools.size > 2_000) {
286
+ const oldest = this.tools.keys().next().value;
287
+ if (oldest === undefined) break;
288
+ this.tools.delete(oldest);
289
+ }
290
+ }
291
+
292
+ private capEntries() {
293
+ while (this.entries.size > 5_000) {
294
+ const oldest = this.entries.keys().next().value;
295
+ if (oldest === undefined) break;
296
+ this.entries.delete(oldest);
297
+ }
298
+ }
299
+
202
300
  /** Store a committed entry. Resets (sent as message_end) and compactions start a new context head. */
203
301
  private commit(entry: WireEntry) {
204
302
  this.entries.set(entry.id, entry);
@@ -206,6 +304,7 @@ export class AgentModel extends Emitter {
206
304
  const head = entry.head ?? entry.id;
207
305
  for (const id of this.entries.keys()) if (id < head) this.entries.delete(id);
208
306
  }
307
+ this.capEntries();
209
308
  }
210
309
 
211
310
  private event(event: WireAgentEvent) {
@@ -242,11 +341,21 @@ export class AgentModel extends Emitter {
242
341
  case "entry_appended":
243
342
  return this.commit(event.entry);
244
343
  case "tool_execution_start":
344
+ // R20 cold-3 M1: name/callId rode the same 16 MiB per-event ceiling as
345
+ // args — the engine's ids/names are tens of bytes, so oversized ones
346
+ // are hostile bytes and the slot is dropped, not stored verbatim.
347
+ if (
348
+ typeof event.toolCallId !== "string" || event.toolCallId.length > 4_096 ||
349
+ typeof event.toolName !== "string" || event.toolName.length > 4_096 ||
350
+ (event.parentToolCallId !== undefined && typeof event.parentToolCallId === "string" && event.parentToolCallId.length > 4_096)
351
+ )
352
+ return;
353
+ this.capTools(); // R19: bound before the insert adds one more
245
354
  this.tools.set(event.toolCallId, {
246
355
  name: event.toolName,
247
356
  status: "running",
248
357
  output: "",
249
- args: event.args,
358
+ args: this.capArgs(event.args), // R20 cold-2 M1: bounded like output
250
359
  // A nested call names the call that made it; a model-issued call has no parent.
251
360
  ...(event.parentToolCallId !== undefined && event.parentTaskId !== undefined && event.taskId !== undefined
252
361
  ? { nested: { parentCallId: event.parentToolCallId, parentTaskId: event.parentTaskId, taskId: event.taskId } }
@@ -260,9 +369,10 @@ export class AgentModel extends Emitter {
260
369
  output: "",
261
370
  };
262
371
  const output = event.output;
263
- if (output && "set" in output) tool.output = output.set;
264
- else if (output) tool.output = tool.output.slice(output.trimStart ?? 0) + (output.append ?? "");
372
+ if (output && "set" in output) tool.output = this.capToolOutput(output.set);
373
+ else if (output) tool.output = this.capToolOutput(tool.output.slice(output.trimStart ?? 0) + (output.append ?? ""));
265
374
  tool.status = "running";
375
+ this.capTools(); // R20 h4: orphan-creating path — unseen callIds must not grow the map either
266
376
  this.tools.set(event.toolCallId, tool);
267
377
  return;
268
378
  }
@@ -271,6 +381,8 @@ export class AgentModel extends Emitter {
271
381
  // A model-issued call renders from its result entry; drop the live slot so it is never duplicated.
272
382
  this.tools.delete(event.toolCallId);
273
383
  this.entries.set(event.entry.id, event.entry);
384
+ this.capEntries();
385
+ this.capTools();
274
386
  return;
275
387
  }
276
388
  if (event.result) {
@@ -279,6 +391,7 @@ export class AgentModel extends Emitter {
279
391
  tool.status = "done";
280
392
  tool.result = { text: nestedResultText(event.result), isError: event.result.isError };
281
393
  tool.summary = { isError: event.result.isError, durationMs: event.result.durationMs };
394
+ this.capTools(); // R20 h4: orphan-creating path — unseen callIds must not grow the map either
282
395
  this.tools.set(event.toolCallId, tool);
283
396
  return;
284
397
  }
@@ -299,6 +412,8 @@ export class AgentModel extends Emitter {
299
412
  return;
300
413
  case "compaction_start":
301
414
  if (!this.state.compactions.includes(event.taskId)) this.state.compactions.push(event.taskId);
415
+ // R19: bound alongside the entries cap — fresh taskIds grow unbounded.
416
+ if (this.state.compactions.length > 64) this.state.compactions = this.state.compactions.slice(-64);
302
417
  return;
303
418
  case "compaction_end":
304
419
  this.state.compactions = this.state.compactions.filter((id) => id !== event.taskId);
@@ -334,9 +449,15 @@ export class SessionModel extends Emitter {
334
449
 
335
450
  apply(frame: Frame): boolean {
336
451
  if (frame.type === "session") {
337
- this.state = { agents: frame.agents, tasks: frame.tasks, usage: frame.usage, ready: true };
338
- } else if (frame.type === "agents") this.state = { ...this.state, agents: frame.agents };
339
- else if (frame.type === "tasks") this.state = { ...this.state, tasks: frame.tasks };
452
+ // R20 cold-1 M3: the session frame is the FIRST frame every client gets
453
+ // — its tasks/agents ride the same JSON.parse cast. One shared guard.
454
+ this.state = { agents: safeAgents(frame.agents), tasks: safeTasks(frame.tasks), usage: frame.usage, ready: true };
455
+ } else if (frame.type === "agents") this.state = { ...this.state, agents: safeAgents(frame.agents) };
456
+ else if (frame.type === "tasks")
457
+ // R20 h5: wire task rows are unvalidated (SSE frames are JSON.parse casts)
458
+ // — a null/state-less element threw TypeError in backgroundTasks, which
459
+ // the statusbar runs EVERY frame. Drop malformed rows at the boundary.
460
+ this.state = { ...this.state, tasks: safeTasks(frame.tasks) };
340
461
  else if (frame.type === "usage") this.state = { ...this.state, usage: frame.usage };
341
462
  else return false;
342
463
  this.emit();
@@ -358,11 +479,11 @@ export class SessionModel extends Emitter {
358
479
  }
359
480
 
360
481
  foregroundBusy(agentId: number) {
361
- return this.state.tasks.some((t) => !t.background && t.conversationId === agentId);
482
+ return this.state.tasks.some((t) => !!t && t?.background !== true && t.conversationId === agentId);
362
483
  }
363
484
 
364
485
  backgroundTasks(agentId?: number) {
365
- return this.state.tasks.filter((t) => t.background && (agentId === undefined || t.conversationId === agentId));
486
+ return this.state.tasks.filter((t) => !!t && t?.background === true && (agentId === undefined || t.conversationId === agentId));
366
487
  }
367
488
  }
368
489
 
@@ -418,7 +539,9 @@ export const agentKey = (deviceId: string, sessionId: string, agentId: number) =
418
539
  /** Nest agents under the agent they forked from or the agent whose task owns them. */
419
540
  export function agentTree(deviceId: string, session: SessionSummary, stale: boolean): TreeNode[] {
420
541
  const nodes = new Map<number, Extract<TreeNode, { type: "agent" }>>();
421
- for (const agent of session.agents)
542
+ // R20 cold-3 M3: tree data is hub-relayed and unvalidated — a null element
543
+ // threw here on EVERY sidebar build (always-render). Same guard as safeAgents.
544
+ for (const agent of (Array.isArray(session.agents) ? session.agents : []).filter((a) => !!a && typeof a === "object"))
422
545
  nodes.set(agent.id, {
423
546
  type: "agent",
424
547
  key: agentKey(deviceId, session.id, agent.id),
@@ -462,7 +585,18 @@ export class NetworkModel extends Emitter {
462
585
  devices: NetworkDevice[] = [];
463
586
  apply(frame: Frame): boolean {
464
587
  if (frame.type !== "network") return false;
465
- this.devices = frame.devices;
588
+ // R20 cold-3 M3: hub-relayed trees are unvalidated — null agent/session/
589
+ // device elements threw in FE renders (TreeRow reduce, sidebar tree) and
590
+ // in agentTree. Sanitize at the ONE ingestion point.
591
+ this.devices = (Array.isArray(frame.devices) ? frame.devices : [])
592
+ .filter((d) => !!d && typeof d === "object")
593
+ .map((d) => {
594
+ const sessions = Array.isArray(d.tree?.sessions) ? d.tree!.sessions.filter((x) => !!x && typeof x === "object") : [];
595
+ return {
596
+ ...d,
597
+ ...(d.tree ? { tree: { ...d.tree, sessions: sessions.map((x) => ({ ...x, agents: (Array.isArray(x.agents) ? x.agents : []).filter((a) => !!a && typeof a === "object") })) } } : {}),
598
+ };
599
+ });
466
600
  this.emit();
467
601
  return true;
468
602
  }
@@ -478,6 +612,17 @@ export class NetworkModel extends Emitter {
478
612
  function nestedResultText(result: WireNestedToolResult): string {
479
613
  const value = result.structuredOutput;
480
614
  if (value === undefined || value === null) return "";
481
- const text = typeof value === "string" ? value : JSON.stringify(value);
482
- return text.length > 4000 ? `${text.slice(0, 4000)}…` : text;
615
+ const text = typeof value === "string" ? value : safeStringify(value);
616
+ // R20 cold-3 M2: the slice MUST be flattened — an unflattened V8 slice
617
+ // retains its <=16 MiB parent behind a 4 KiB result (the 607 MiB class).
618
+ return text.length > 4000 ? `${AgentModel.flatSlice(text.slice(0, 4000))}…` : text;
619
+ }
620
+
621
+ /** R20 cold-3 M1: stringify that never throws (cyclic structuredOutput). */
622
+ function safeStringify(value: unknown): string {
623
+ try {
624
+ return JSON.stringify(value) ?? "";
625
+ } catch {
626
+ return "";
627
+ }
483
628
  }
@@ -49,7 +49,7 @@ import { HubMux, type MuxState } from "./hub-mux.ts";
49
49
  import { FOLLOW_TAIL, scrollBy, viewportTop, type ScrollState } from "./scroll.ts";
50
50
  import { wrapByColumn } from "./wrap.ts";
51
51
  import { box, c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
52
- import { sanitizeTerminal } from "./sanitize.ts";
52
+ import { sanitizeTerminal, oneLine } from "./sanitize.ts";
53
53
 
54
54
  export interface DeviceRef {
55
55
  id: string;
@@ -398,7 +398,13 @@ export class App {
398
398
 
399
399
  private async refreshSessions() {
400
400
  try {
401
- this.sessions = (await this.client.tree()).sessions;
401
+ // R20 cold-3 M3: the device's tree is hostile-capable — null agent
402
+ // elements threw in find()/reduce() across every TUI consumer. Drop
403
+ // them at the ONE ingestion point.
404
+ this.sessions = (await this.client.tree()).sessions.map((s) => ({
405
+ ...s,
406
+ agents: (Array.isArray(s.agents) ? s.agents : []).filter((a) => !!a && typeof a === "object"),
407
+ }));
402
408
  this.deviceOnline = true;
403
409
  this.requestRender();
404
410
  } catch {
@@ -655,7 +661,7 @@ export class App {
655
661
  setPending(text: string | null) {
656
662
  // R17 (run-3 h5): pending notes interpolate device-sourced paths/names
657
663
  // (walkDirs/newSession feed them) — sanitize at the chokepoint.
658
- this.pendingNote = text === null ? null : sanitizeTerminal(text);
664
+ this.pendingNote = text === null ? null : oneLine(text); // R20 h5: single-line chrome
659
665
  this.requestRender();
660
666
  }
661
667
 
@@ -710,7 +716,7 @@ export class App {
710
716
  this.input!.value = "/";
711
717
  } else if (data === "f") this.beginInput("filter", "filter ❯ ");
712
718
  else if (data === "n") this.beginInput("new", "new session › ");
713
- else if (data === "x") this.beginInput("kill", `reset ${sanitizeTerminal(this.sessionSummary()?.name ?? "context")}? y/n`);
719
+ else if (data === "x") this.beginInput("kill", `reset ${oneLine(this.sessionSummary()?.name ?? "context")}? y/n`);
714
720
  else if (data === "g") this.setView("herd");
715
721
  else if (data === "N") this.setView("network");
716
722
  else if (data === "L") this.setView("log");
@@ -1026,7 +1032,7 @@ export class App {
1026
1032
  notify(message: string, error = false) {
1027
1033
  // Audit run-1: toast text often carries device/hub error messages —
1028
1034
  // strip control sequences before the toast renders to the terminal.
1029
- this.toast = (error ? "✗ " : "") + sanitizeTerminal(message);
1035
+ this.toast = (error ? "✗ " : "") + oneLine(message); // R20 h5: toasts are single-line chrome — collapse \\n too
1030
1036
  this.toastTicks = 50;
1031
1037
  this.requestRender();
1032
1038
  }
@@ -1157,7 +1163,7 @@ export class App {
1157
1163
  const session = this.sessions.find((x) => x.id === this.sessionId);
1158
1164
  const right =
1159
1165
  this.view === "agent" && session
1160
- ? `${sanitizeTerminal(this.device.id)}:${sanitizeTerminal(session.name)}:${this.agentId ?? 1}`
1166
+ ? `${oneLine(this.device.id)}:${oneLine(session.name)}:${this.agentId ?? 1}` // R20 cold-1 M4
1161
1167
  : this.view === "agent"
1162
1168
  ? "no workspace"
1163
1169
  : "j/k move · ↵ open";
@@ -1222,10 +1228,10 @@ export class App {
1222
1228
  // the web shows a banner — the TUI used to show a healthy branch chip
1223
1229
  // while the repo was mid-merge with conflicts.
1224
1230
  const gitChip = g?.repo
1225
- ? ` ${c.muted("⎇")} ${c.text(sanitizeTerminal(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)) : ""}`
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)) : ""}`
1226
1232
  : "";
1227
1233
  lines.push(
1228
- `${c.muted(sanitizeTerminal(this.device.id))} ${c.muted("›")} ${c.text(sanitizeTerminal(session?.name ?? "—"))} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1234
+ `${c.muted(oneLine(this.device.id))} ${c.muted("›")} ${c.text(oneLine(session?.name ?? "—"))} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1229
1235
  `${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
1230
1236
  // Catalog miss renders "?" not "—" (R5 finding 5): unknown window ≠ no usage.
1231
1237
  `${c.muted("ctx")} ${ctx === undefined ? c.muted("?") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
@@ -1233,7 +1239,7 @@ export class App {
1233
1239
  lines.push(
1234
1240
  AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
1235
1241
  c.muted("│"),
1236
- ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(sanitizeTerminal(this.model.state.agent.model?.modelId?.split("/").pop() ?? "")),
1242
+ ) + c.muted(rep(" ", Math.max(0, w - 62))) + c.muted(oneLine(this.model.state.agent.model?.modelId?.split("/").pop() ?? "")), // R20 cold-1 M4
1237
1243
  );
1238
1244
  lines.push(c.muted(rep(box.h, w)));
1239
1245
  const inner = h - 3;
@@ -1331,7 +1337,7 @@ export class App {
1331
1337
  for (const [name, n] of [...counts.entries()].sort((a, b) => b[1] - a[1])) {
1332
1338
  const barW = 16;
1333
1339
  const filled = Math.round((n / max) * barW);
1334
- lines.push(` ${c.text(sanitizeTerminal(name).padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
1340
+ lines.push(` ${c.text(oneLine(name).padEnd(14))} ${c.muted(rep("▮", filled))}${c.muted(rep("▯", barW - filled))} ${c.muted(String(n))}`);
1335
1341
  }
1336
1342
  if (!counts.size) lines.push(c.muted(" no tool calls yet"));
1337
1343
  return lines;
@@ -1357,12 +1363,12 @@ export class App {
1357
1363
  // config tab
1358
1364
  const model = this.model.state.agent.model;
1359
1365
  const lines = [
1360
- ` ${c.muted("model")} ${c.text(sanitizeTerminal(model?.modelId ?? "—"))}`,
1361
- ` ${c.muted("provider")} ${c.muted(sanitizeTerminal(model?.provider ?? "—"))}`,
1366
+ ` ${c.muted("model")} ${c.text(oneLine(model?.modelId ?? "—"))}`, // R20 cold-1 M4
1367
+ ` ${c.muted("provider")} ${c.muted(oneLine(model?.provider ?? "—"))}`, // R20 cold-1 M4
1362
1368
  ` ${c.muted("thinking")} ${c.text(String(this.model.state.agent.thinkingLevel ?? "low"))} ${c.muted("(y cycles)")}`,
1363
1369
  "",
1364
- ` ${c.muted("device")} ${c.text(sanitizeTerminal(this.device.id))} ${c.muted(sanitizeTerminal(this.device.url))}`,
1365
- ` ${c.muted("start dirs")} ${c.muted(sanitizeTerminal(this.info.startDirs.join(", ")).slice(0, w - 18) || "—")}`,
1370
+ ` ${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
1366
1372
  ];
1367
1373
  return lines;
1368
1374
  }
@@ -1377,7 +1383,7 @@ export class App {
1377
1383
  if (this.filter)
1378
1384
  lines.push(c.warn(` filter: ${this.filter} · ${rows.length}/${this.events.length} shown — esc clears`));
1379
1385
  const visible = h - lines.length;
1380
- for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(sanitizeTerminal(e.text).slice(0, w - 18))}`);
1386
+ for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(oneLine(e.text).slice(0, w - 18))}`);
1381
1387
  return lines;
1382
1388
  }
1383
1389