my-durable 0.0.74 → 0.0.76

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.
@@ -102,7 +102,18 @@ export function writeArchiveManifest(bundleDir: string, m: ArchiveManifest): voi
102
102
  */
103
103
  export function readArchiveManifest(bundleDir: string): ArchiveManifest | undefined {
104
104
  try {
105
- const parsed: unknown = JSON.parse(readFileSync(join(bundleDir, MANIFEST_NAME), "utf8"));
105
+ const manifestPath = join(bundleDir, MANIFEST_NAME);
106
+ // R20 (run-6 h6): a manifest written by store.archive() is a few hundred
107
+ // bytes; a planted one had NO ceiling — restore and the archive LISTING
108
+ // read the whole file into RAM per cheap request (leader probe: a 150 MB
109
+ // plant cost ~770 ms and ~600 MB RSS per refused restore, repeatable).
110
+ // Refuse oversized manifests without reading them.
111
+ if (statSync(manifestPath).size > 1024 * 1024) return undefined;
112
+ const text = readFileSync(manifestPath, "utf8");
113
+ // R20 cold-1 M5: a same-user planter can swap the file between stat and
114
+ // read — the cap is enforced on the BYTES WE ACTUALLY READ, not the stat.
115
+ if (text.length > 1024 * 1024) return undefined;
116
+ const parsed: unknown = JSON.parse(text);
106
117
  if (typeof parsed !== "object" || parsed === null) return undefined;
107
118
  const m = parsed as Record<string, unknown>;
108
119
  if (
@@ -151,21 +162,23 @@ function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number
151
162
  let db: DatabaseSync | undefined;
152
163
  try {
153
164
  db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
154
- const rows = db.prepare("SELECT record FROM entries").all() as unknown[];
155
- let turns = 0;
165
+ // R20 cold-1 M5: this used to materialize EVERY entries row into RAM and
166
+ // JSON.parse each one per LISTING request — a planted multi-GB bundle was
167
+ // a repeatable per-request stall (the manifest-cap class). Aggregates run
168
+ // inside SQLite; json_extract tolerates non-JSON rows by yielding NULL.
169
+ const turnsRow = db
170
+ .prepare(
171
+ "SELECT COUNT(*) AS n FROM entries WHERE json_extract(record,'$.kind') IN ('pi.user','pi.assistant')",
172
+ )
173
+ .get() as { n?: number } | undefined;
174
+ const turns = typeof turnsRow?.n === "number" ? turnsRow.n : 0;
156
175
  let lastMessageAt: number | null = null;
157
- for (const row of rows) {
158
- const entry = parseRecord((row as { record?: unknown }).record);
159
- if (!entry) continue;
160
- if (entry.kind === "pi.user" || entry.kind === "pi.assistant") turns += 1;
161
- if (!Array.isArray(entry.model)) continue;
162
- for (const message of entry.model) {
163
- const timestamp = (message as { timestamp?: unknown } | null)?.timestamp;
164
- if (typeof timestamp === "number" && (lastMessageAt === null || timestamp > lastMessageAt)) {
165
- lastMessageAt = timestamp;
166
- }
167
- }
168
- }
176
+ const atRow = db
177
+ .prepare(
178
+ "SELECT MAX(json_extract(json_each.value,'$.timestamp')) AS t FROM entries, json_each(json_extract(record,'$.model')) WHERE json_extract(record,'$.model') IS NOT NULL",
179
+ )
180
+ .get() as { t?: unknown } | undefined;
181
+ if (typeof atRow?.t === "number") lastMessageAt = atRow.t;
169
182
  return { turns, lastMessageAt };
170
183
  } catch {
171
184
  return { turns: -1, lastMessageAt: null };
@@ -192,6 +205,9 @@ function dirBytes(dir: string, depth = 0): number {
192
205
  return 0;
193
206
  }
194
207
  if (depth >= 64) return total;
208
+ // R20 cold-1 M5: breadth cap — a planted million-entry directory allocated
209
+ // a giant dirent array per bundle per listing (depth alone bounded nothing).
210
+ if (entries.length > 100_000) return 0;
195
211
  for (const e of entries) {
196
212
  try {
197
213
  if (e.isDirectory()) total += dirBytes(join(dir, e.name), depth + 1);
@@ -279,13 +295,24 @@ export function findBundle(archiveDir: string, sessionId: string): string | null
279
295
  export function archivedTranscript(bundleDir: string, format: "markdown" | "json"): ArchivedTranscript {
280
296
  let db: DatabaseSync | undefined;
281
297
  const entries: WireEntry[] = [];
298
+ let truncated = 0;
282
299
  try {
283
300
  db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
284
- const rows = db.prepare("SELECT record FROM entries ORDER BY conversation_id, commit_seq").all() as unknown[];
301
+ // R20 cold-1 M5: the transcript view read the WHOLE entries table per
302
+ // request — same planted-bundle amplification. A hard entry cap keeps the
303
+ // newest turns (the ORDER BY is commit order; truncating from the front
304
+ // loses the oldest context, which a viewer can still get from the bundle).
305
+ const cap = 5_000;
306
+ const totalRow = db.prepare("SELECT COUNT(*) AS n FROM entries").get() as { n?: number } | undefined;
307
+ const total = typeof totalRow?.n === "number" ? totalRow.n : 0;
308
+ const rows = db
309
+ .prepare("SELECT record FROM entries ORDER BY conversation_id, commit_seq LIMIT ? OFFSET ?")
310
+ .all(Math.min(total, cap), Math.max(0, total - Math.min(total, cap))) as unknown[];
285
311
  for (const row of rows) {
286
312
  const entry = parseRecord((row as { record?: unknown }).record);
287
313
  if (entry) entries.push(entry as unknown as WireEntry);
288
314
  }
315
+ truncated = Math.max(0, total - entries.length);
289
316
  } catch {
290
317
  throw new Error("archive bundle unreadable");
291
318
  } finally {
@@ -296,7 +323,12 @@ export function archivedTranscript(bundleDir: string, format: "markdown" | "json
296
323
  }
297
324
  }
298
325
  const items = toTranscript(entries);
299
- return format === "markdown" ? { format: "markdown", text: toMarkdown(items) } : { format: "json", items };
326
+ // R20 cold-2 minor: the truncation marker used to be a dead array property —
327
+ // surface it in the rendered text the viewer actually reads.
328
+ const notice = truncated > 0 ? `> Showing the newest ${entries.length} entries — ${truncated} older entries truncated.
329
+
330
+ ` : "";
331
+ return format === "markdown" ? { format: "markdown", text: notice + toMarkdown(items) } : { format: "json", items };
300
332
  }
301
333
 
302
334
  /**
@@ -171,9 +171,21 @@ export interface GitStatus {
171
171
 
172
172
  /** One status for MANY paths — what a session list needs. The per-path cache
173
173
  * keeps repeat polls cheap on big repos. */
174
- export async function gitStatusBatch(paths: string[]): Promise<Record<string, GitStatus>> {
174
+ export async function gitStatusBatch(paths: string[]): Promise<Record<string, GitStatus | { error: string }>> {
175
175
  const unique = [...new Set(paths.filter(Boolean))];
176
- const entries = await Promise.all(unique.map(async (p) => [p, await gitStatus(p)] as const));
176
+ // R21 (index 400s): one failing path (permissions, a git binary error, a
177
+ // timeout on a huge checkout) used to reject the WHOLE batch — every
178
+ // project's chip died with it. Settle each path separately: failures become
179
+ // bounded `{error}` entries the FE caches instead of retry-hammering.
180
+ const entries = await Promise.all(
181
+ unique.map(async (p): Promise<[string, GitStatus | { error: string }]> => {
182
+ try {
183
+ return [p, await gitStatus(p)];
184
+ } catch (e) {
185
+ return [p, { error: String((e as Error)?.message ?? e).slice(0, 120) }];
186
+ }
187
+ }),
188
+ );
177
189
  return Object.fromEntries(entries);
178
190
  }
179
191
 
@@ -14,7 +14,7 @@ import type { DevicePairing } from "./pairing.js";
14
14
 
15
15
  type Async = (req: Request, res: Response) => Promise<unknown>;
16
16
  const route = (fn: Async) => (req: Request, res: Response, next: NextFunction) => fn(req, res).catch(next);
17
- import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp } from "./git.js";
17
+ import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp, type GitStatus } from "./git.js";
18
18
  const GIT_OPS: GitOp[] = ["diff", "log", "log-list", "fetch", "pull", "push", "switch", "branch", "commit", "stage", "unstage", "discard", "diff-file", "stash-push", "stash-pop", "compare", "merge-abort", "show-files", "ignore", "checkpoint", "checkpoints", "rewind", "resolve", "submodule-update", "pr-create", "pr-list", "pr-merge", "pr-checks", "pr-comment", "worktree-list", "worktree-add", "worktree-remove"];
19
19
 
20
20
  interface Locals {
@@ -180,12 +180,28 @@ export function v1(
180
180
  }));
181
181
  r.post("/git/status-batch", route(async (req, res) => {
182
182
  const raw: string[] = Array.isArray(req.body?.paths) ? req.body.paths.map(String).filter(Boolean).slice(0, 50) : [];
183
- const paths = await Promise.all(raw.map((p) => store.containedPath(p)));
184
- try {
185
- res.json(await gitStatusBatch(paths));
186
- } catch (e) {
187
- throw gitFault(e, paths[0] ?? "");
183
+ // R21 (index 400s): a project left over from OTHER start dirs (device
184
+ // restarted with a narrower sandbox) used to reject the WHOLE batch from
185
+ // Promise.all — every project's chip died with it and the FE retried the
186
+ // doomed request every stale window. Settle containment per path: foreign
187
+ // paths answer a bounded `{error}` entry keyed by the path AS SENT (the
188
+ // FE's cache key), the rest keep their real status.
189
+ const settled = await Promise.all(
190
+ raw.map(async (p): Promise<[string, string | undefined]> => {
191
+ try {
192
+ return [p, await store.containedPath(p)];
193
+ } catch {
194
+ return [p, undefined];
195
+ }
196
+ }),
197
+ );
198
+ const contained = settled.filter((e): e is [string, string] => e[1] !== undefined).map(([, c]) => c);
199
+ const statuses = await gitStatusBatch(contained);
200
+ const out: Record<string, GitStatus | { error: string }> = {};
201
+ for (const [p, c] of settled) {
202
+ out[p] = c === undefined ? { error: "path must live under a start dir" } : (statuses[c] ?? { error: "git status unavailable" });
188
203
  }
204
+ res.json(out);
189
205
  }));
190
206
  r.post("/git", route(async (req, res) => {
191
207
  const body = req.body ?? {};
@@ -1535,7 +1535,6 @@ export class Store {
1535
1535
 
1536
1536
  /** Stop all work, close the harness and move its files to archive/. Nothing is deleted. */
1537
1537
  async archive(row: SessionRow) {
1538
- this.salvageFailedSessions.delete(row.id); // R19: the bundle left this process's view
1539
1538
  const opened = this.opened.get(row.id);
1540
1539
  if (opened) {
1541
1540
  for (const record of await this.scanAll(opened.harness)) {
@@ -1573,6 +1572,7 @@ export class Store {
1573
1572
  });
1574
1573
  this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
1575
1574
  this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
1575
+ this.salvageFailedSessions.delete(row.id); // R20 h6: clear AFTER the move commits — a failed rename must not re-arm salvage
1576
1576
  this.errors.delete(row.id);
1577
1577
  this.notify();
1578
1578
  return { archived: target };
@@ -1603,7 +1603,6 @@ export class Store {
1603
1603
  // raw, so an uppercase-hex id could bypass the live-session refusal and
1604
1604
  // strand the bundle. Every check below now sees the same canonical value.
1605
1605
  sessionId = sessionId.toLowerCase();
1606
- this.salvageFailedSessions.delete(sessionId); // R19: the bundle came back — judge it fresh
1607
1606
  if (this.list().some((r) => r.id === sessionId))
1608
1607
  throw invalid("a live session with this id already exists");
1609
1608
  // R18 (run-4 h1): restore is a session-placement writer, so it enforces
@@ -1655,6 +1654,8 @@ export class Store {
1655
1654
  throw e;
1656
1655
  }
1657
1656
  this.notify();
1657
+ this.salvageFailedSessions.delete(sessionId); // R20 h6: clear AFTER the bundle actually came back — a REFUSED restore must not re-arm salvage
1658
+ this.errors.delete(sessionId); // R20 cold-1 minor: the fast-fault note may predate the archive — do not surface a stale reason
1658
1659
  // sessionSummary handles a not-yet-opened session (the closed-bundle path).
1659
1660
  return await this.sessionSummary(row);
1660
1661
  }
@@ -1662,6 +1663,12 @@ export class Store {
1662
1663
  async openAgent(row: SessionRow, create = false, thinkingLevel: ThinkingLevel = "medium") {
1663
1664
  const current = this.opened.get(row.id);
1664
1665
  if (current) return current.harness;
1666
+ // R20 (run-6 h6): attempt-once — the memo was only read by the search
1667
+ // path, so every agent-touching request re-ran the FULL salvage (leader
1668
+ // probe: 5.0 s per request on a corrupt session, unbounded). Fail fast
1669
+ // from the recorded fault without touching storage.
1670
+ if (!create && this.salvageFailedSessions.has(row.id))
1671
+ throw new ApiFault("unavailable", this.errors.get(row.id) ?? "session database is unreadable (salvage failed)");
1665
1672
  if (!create) await stat(row.dbPath);
1666
1673
  await mkdir(dirname(row.dbPath), { recursive: true });
1667
1674
  const unlock = lockFile(`${row.dbPath}.lock`);
@@ -18,19 +18,50 @@ export interface GitEntry {
18
18
  const entries = new Map<string, GitEntry>();
19
19
  const inflight = new Map<string, Promise<void>>();
20
20
 
21
+ /** A device's git surface is bounded by its start dirs (R21, index 400s): a
22
+ * project left over from OTHER start dirs answers 400 on the device, and
23
+ * asking anyway just spams the console with network errors every stale
24
+ * window. The network frame carries each device's startDirs + platform —
25
+ * pre-check client-side (the device stays the enforcer) and settle such
26
+ * paths locally. Unknown device facts → allow: the device decides. */
27
+ function gitPathAllowed(deviceId: string, path: string): boolean {
28
+ const dev = network.devices.value.find((d) => d.id === deviceId) as
29
+ | { info?: { startDirs?: unknown; platform?: unknown } }
30
+ | undefined;
31
+ const dirs = dev?.info?.startDirs;
32
+ if (!Array.isArray(dirs) || dirs.length === 0) return true;
33
+ const win = String(dev?.info?.platform ?? "").startsWith("win32");
34
+ const norm = (p: string) =>
35
+ win ? p.trim().replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p.trim().replace(/\/+$/, "");
36
+ const a = norm(path);
37
+ return dirs.some((raw) => {
38
+ const b = norm(String(raw));
39
+ return !!b && (a === b || a.startsWith(win ? b + "\\" : b + "/"));
40
+ });
41
+ }
42
+
43
+ /** Settle an entry from either a real status or the batch's `{error}` shape. */
44
+ function settleEntry(e: GitEntry, s: GitStatus | { error: string } | undefined) {
45
+ if (s && typeof (s as { error?: unknown }).error === "string") {
46
+ e.status = null;
47
+ e.error = (s as { error: string }).error;
48
+ } else {
49
+ e.status = (s as GitStatus) ?? null;
50
+ e.error = "";
51
+ }
52
+ e.at = Date.now();
53
+ }
54
+
21
55
  /** Fill MANY folders in one round-trip (session lists want branch-per-cwd).
22
56
  * Decorative by design: a failed batch stays silent — the Git tab is where
23
57
  * errors belong. */
24
58
  export async function ensureGitBatch(deviceId: string, paths: string[]) {
25
- const stale = paths.filter((p) => !fresh(gitEntry(deviceId, p), staleMsForBatch));
59
+ const stale = paths.filter((p) => !fresh(gitEntry(deviceId, p), staleMsForBatch) && gitPathAllowed(deviceId, p));
26
60
  if (!stale.length) return;
27
61
  try {
28
62
  const map = await deviceClient(deviceId).gitStatusBatch(stale, { timeoutMs: 60_000 });
29
63
  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 = "";
64
+ settleEntry(gitEntry(deviceId, p), s as GitStatus | { error: string });
34
65
  }
35
66
  } catch {
36
67
  /* decorative: never surface batch failures */
@@ -100,6 +131,11 @@ export async function ensureGit(
100
131
  const k = key(deviceId, cwd);
101
132
  const e = gitEntry(deviceId, cwd);
102
133
  if (!force && fresh(e, staleMs)) return;
134
+ // Outside the device's sandbox: settle locally, never send the doomed 400.
135
+ if (!gitPathAllowed(deviceId, cwd)) {
136
+ settleEntry(e, { error: "outside the device's start dirs" });
137
+ return;
138
+ }
103
139
  const running = inflight.get(k);
104
140
  if (running) return running;
105
141
  const first = e.status === null && !e.error;
@@ -135,6 +135,29 @@ export function scrubSecrets(value: string): string {
135
135
  // percent characters (the optimizer would otherwise retry every split).
136
136
  const percentBearing = /(\/[^\s"'%]*%[^\s"']{0,64}\/)[^\s"']{0,64}?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/gi;
137
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
+ }
138
161
  // Credential material without its prefix (slices, echo): 43-char base64url runs.
139
162
  out = out.replace(/(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g, "<redacted>");
140
163
  // Pairing codes as standalone values ("code":"AB2C7DEF" / "ABCD2345EF67") but not ordinary words.
@@ -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:",
@@ -124,6 +124,26 @@ export function applyMessageChange(message: WireAssistantMessage, change: WireMe
124
124
  return { ...message, content };
125
125
  }
126
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
+
127
147
  export class AgentModel extends Emitter {
128
148
  state: AgentViewState = emptyAgentState();
129
149
  private entries = new Map<number, WireEntry>();
@@ -179,24 +199,28 @@ export class AgentModel extends Emitter {
179
199
  this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
180
200
  this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
181
201
  this.tools = new Map(
182
- snapshot.tools.map((slot) => [
183
- slot.callId,
184
- { name: slot.name, status: slot.status, output: slot.output ?? "" },
185
- ]),
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
+ ]),
186
209
  );
187
210
  // Nested calls of running tools: they have no assistant entry, so the snapshot is the only source on attach.
188
- for (const slot of snapshot.nestedTools.slice(-2_000)) {
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)) {
189
212
  const existing = this.tools.get(slot.callId);
190
213
  this.tools.set(slot.callId, {
191
214
  name: slot.name,
192
215
  status: slot.status,
193
- output: slot.output ?? "",
194
- args: slot.arguments,
216
+ output: this.capToolOutput(slot.output ?? ""),
217
+ args: this.capArgs(slot.arguments), // R20 cold-2 M1
195
218
  nested: { parentCallId: slot.parentCallId, parentTaskId: slot.parentTaskId, taskId: slot.taskId },
196
219
  ...(slot.summary ? { summary: slot.summary } : {}),
197
220
  ...(existing ?? {}),
198
221
  });
199
222
  }
223
+ this.capTools(); // R20 cold-1 M2: snapshot.tools(≤2000) + nestedTools(≤2000) must UNION to ≤2000
200
224
  this.state.running = !!snapshot.run;
201
225
  this.state.agent = snapshot.agent;
202
226
  this.state.usage = snapshot.usage;
@@ -220,6 +244,43 @@ export class AgentModel extends Emitter {
220
244
  * (rebuild → toTranscript is O(tools) per frame, so the stream is quadratic).
221
245
  * Same hostile-peer class as the entries cap, so the same bound.
222
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
+
223
284
  private capTools() {
224
285
  while (this.tools.size > 2_000) {
225
286
  const oldest = this.tools.keys().next().value;
@@ -280,12 +341,21 @@ export class AgentModel extends Emitter {
280
341
  case "entry_appended":
281
342
  return this.commit(event.entry);
282
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;
283
353
  this.capTools(); // R19: bound before the insert adds one more
284
354
  this.tools.set(event.toolCallId, {
285
355
  name: event.toolName,
286
356
  status: "running",
287
357
  output: "",
288
- args: event.args,
358
+ args: this.capArgs(event.args), // R20 cold-2 M1: bounded like output
289
359
  // A nested call names the call that made it; a model-issued call has no parent.
290
360
  ...(event.parentToolCallId !== undefined && event.parentTaskId !== undefined && event.taskId !== undefined
291
361
  ? { nested: { parentCallId: event.parentToolCallId, parentTaskId: event.parentTaskId, taskId: event.taskId } }
@@ -299,9 +369,10 @@ export class AgentModel extends Emitter {
299
369
  output: "",
300
370
  };
301
371
  const output = event.output;
302
- if (output && "set" in output) tool.output = output.set;
303
- 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 ?? ""));
304
374
  tool.status = "running";
375
+ this.capTools(); // R20 h4: orphan-creating path — unseen callIds must not grow the map either
305
376
  this.tools.set(event.toolCallId, tool);
306
377
  return;
307
378
  }
@@ -320,6 +391,7 @@ export class AgentModel extends Emitter {
320
391
  tool.status = "done";
321
392
  tool.result = { text: nestedResultText(event.result), isError: event.result.isError };
322
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
323
395
  this.tools.set(event.toolCallId, tool);
324
396
  return;
325
397
  }
@@ -377,9 +449,15 @@ export class SessionModel extends Emitter {
377
449
 
378
450
  apply(frame: Frame): boolean {
379
451
  if (frame.type === "session") {
380
- this.state = { agents: frame.agents, tasks: frame.tasks, usage: frame.usage, ready: true };
381
- } else if (frame.type === "agents") this.state = { ...this.state, agents: frame.agents };
382
- 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) };
383
461
  else if (frame.type === "usage") this.state = { ...this.state, usage: frame.usage };
384
462
  else return false;
385
463
  this.emit();
@@ -401,11 +479,11 @@ export class SessionModel extends Emitter {
401
479
  }
402
480
 
403
481
  foregroundBusy(agentId: number) {
404
- 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);
405
483
  }
406
484
 
407
485
  backgroundTasks(agentId?: number) {
408
- 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));
409
487
  }
410
488
  }
411
489
 
@@ -461,7 +539,9 @@ export const agentKey = (deviceId: string, sessionId: string, agentId: number) =
461
539
  /** Nest agents under the agent they forked from or the agent whose task owns them. */
462
540
  export function agentTree(deviceId: string, session: SessionSummary, stale: boolean): TreeNode[] {
463
541
  const nodes = new Map<number, Extract<TreeNode, { type: "agent" }>>();
464
- 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"))
465
545
  nodes.set(agent.id, {
466
546
  type: "agent",
467
547
  key: agentKey(deviceId, session.id, agent.id),
@@ -505,7 +585,18 @@ export class NetworkModel extends Emitter {
505
585
  devices: NetworkDevice[] = [];
506
586
  apply(frame: Frame): boolean {
507
587
  if (frame.type !== "network") return false;
508
- 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
+ });
509
600
  this.emit();
510
601
  return true;
511
602
  }
@@ -521,6 +612,17 @@ export class NetworkModel extends Emitter {
521
612
  function nestedResultText(result: WireNestedToolResult): string {
522
613
  const value = result.structuredOutput;
523
614
  if (value === undefined || value === null) return "";
524
- const text = typeof value === "string" ? value : JSON.stringify(value);
525
- 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
+ }
526
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
 
@@ -2,7 +2,8 @@
2
2
  import type { SlashCommand } from "@earendil-works/pi-tui";
3
3
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
4
4
  import type { App } from "./app.ts";
5
- import { sanitizeTerminal } from "./sanitize.ts";
5
+ import { sanitizeTerminal, oneLine } from "./sanitize.ts";
6
+ export { oneLine };
6
7
  import { Panel, pickAgent, pickDevice, pickModel, pickSession, pickThinking } from "./pickers.ts";
7
8
  import { parsePairArgs, runPairing } from "./pairing.ts";
8
9
  import { gitStateSuffix } from "./views.ts";
@@ -117,16 +118,6 @@ const KEYS: [string, string][] = [
117
118
  ];
118
119
 
119
120
  /** Returns false when `text` is not a command, so the caller sends it to the agent. */
120
- /**
121
- * R19 (run-5 h2 + cold-review): every field of a wire row is untrusted at the
122
- * terminal boundary. sanitizeTerminal strips escape sequences but keeps
123
- * newlines and tabs, so single-line chrome collapses whitespace too — otherwise
124
- * a wire id can split the row it belongs to (visual spoof, no escape bytes).
125
- */
126
- export function oneLine(text: string): string {
127
- return sanitizeTerminal(text).replace(/\s+/g, " ");
128
- }
129
-
130
121
  /** R19 (run-5 h2): every field of a TranscriptSearchHit is relay-borne — the
131
122
  * numeric `entry` included. The compose site used to interpolate it raw, so a
132
123
  * hostile hub/device could ride an OSC/CSI payload in a string-typed `entry`
@@ -215,7 +206,8 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
215
206
  // not skip that gate (R4 finding 4: the palette entry used to wipe the
216
207
  // context unconditionally). A typed handoff note carries its own intent.
217
208
  if (!arg) {
218
- const ok = await app.prompt(`Reset ${sanitizeTerminal(app.sessionSummary()?.name ?? "context")}? y/n`, "");
209
+ // R20 cold-1 M4: same gate text as the x-key door — oneLine, not sanitize-only.
210
+ const ok = await app.prompt(`Reset ${oneLine(app.sessionSummary()?.name ?? "context")}? y/n`, "");
219
211
  if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
220
212
  return app.flash("reset cancelled"), true;
221
213
  }
@@ -230,7 +222,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
230
222
  // Agent names ride the wire from device/hub (model-choosable for forks
231
223
  // and subagents) and pi-tui's Input renders its value verbatim — seed
232
224
  // it sanitized (run-4 h4).
233
- const typed = await app.prompt("Agent name", current && current !== "main" ? sanitizeTerminal(current) : "");
225
+ const typed = await app.prompt("Agent name", current && current !== "main" ? oneLine(current) : ""); // R20 cold-2 minor: Input renders verbatim — one-line it
234
226
  value = (typed ?? "").trim();
235
227
  if (!value) return app.flash("rename cancelled"), true;
236
228
  }
@@ -264,7 +256,9 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
264
256
  if (!result.matches.length) lines.push(c.muted("No matches (names, folders, models or transcripts)."));
265
257
  for (const m of shown) {
266
258
  lines.push(
267
- `${c.secondary(sanitizeTerminal(m.name))} ${c.muted(sanitizeTerminal(m.cwd))}${m.where.includes("transcript") ? " " + c.warn("◍ transcript") : ""}`,
259
+ // R20 h5: the match header is in the SAME panel as the fixed hit
260
+ // lines — a \n in a session name split the row above the hits.
261
+ `${c.secondary(oneLine(m.name))} ${c.muted(oneLine(m.cwd))}${m.where.includes("transcript") ? " " + c.warn("◍ transcript") : ""}`,
268
262
  );
269
263
  for (const hit of (m.hits ?? []).slice(0, 3))
270
264
  lines.push(c.muted(findHitLine(m.name, hit)));
@@ -283,7 +277,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
283
277
  app.overlay(
284
278
  new Panel(() => {
285
279
  const tasks = app.session.state.tasks;
286
- const lines = [c.bold(c.accent(`Live tasks in ${sanitizeTerminal(app.sessionSummary()?.name ?? "session")}`)), ""];
280
+ const lines = [c.bold(c.accent(`Live tasks in ${oneLine(app.sessionSummary()?.name ?? "session")}`)), ""]; // R20 cold-2 minor
287
281
  if (!tasks.length) lines.push(c.muted("No live tasks."));
288
282
  for (const t of tasks)
289
283
  lines.push(
@@ -293,7 +287,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
293
287
  // through the chokepoint.
294
288
  // sanitizeTerminal keeps \n/\t, so a one-line row also collapses
295
289
  // whitespace — a wire id must not split the row it belongs to.
296
- `${t.background ? c.secondary("◌ bg") : c.warn("● fg")} #${oneLine(String(t.id))} ${oneLine(String(t.kind))} ${c.muted(`agent #${oneLine(String(t.conversationId))} │ ${oneLine(String(t.state.status))}${t.state.phase ? `/${oneLine(String(t.state.phase))}` : ""}`)}`,
290
+ `${t?.background === true ? c.secondary("◌ bg") : c.warn("● fg")} #${oneLine(String(t?.id ?? "?"))} ${oneLine(String(t?.kind ?? "?"))} ${c.muted(`agent #${oneLine(String(t?.conversationId ?? "?"))} │ ${oneLine(String(t.state?.status ?? ""))}${t.state?.phase ? `/${oneLine(String(t.state.phase))}` : ""}`)}`,
297
291
  );
298
292
  lines.push("", c.muted("esc close"));
299
293
  return lines;
@@ -305,7 +299,7 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
305
299
  new Panel(
306
300
  () => [
307
301
  c.bold(c.accent("dpi-tui")),
308
- c.muted(`${sanitizeTerminal(app.device.id)} │ ${sanitizeTerminal(app.device.url)}`),
302
+ c.muted(`${oneLine(app.device.id)} │ ${oneLine(app.device.url)}`), // R20 cold-1 M4
309
303
  "",
310
304
  ...KEYS.map(([k, d]) => `${c.secondary(k.padEnd(11))} ${d}`),
311
305
  "",
@@ -14,3 +14,15 @@ const C0 = /[\u0000-\u0008\u000B-\u001F\u007F\u0080-\u009F]/g;
14
14
  export function sanitizeTerminal(s: string): string {
15
15
  return s.replace(ESC_SEQ, "").replace(C0, "");
16
16
  }
17
+
18
+ /**
19
+ * R20 (run-6 h5): single-line chrome compose chokepoint. sanitizeTerminal
20
+ * strips escape sequences but KEEPS \n/\t by design (multi-line content is
21
+ * legitimate elsewhere) — a wire string interpolated into a one-line frame row
22
+ * must also collapse whitespace, or it splits its own row and forges chrome
23
+ * below it. Hoisted here from commands.ts so every compose site shares one
24
+ * definition.
25
+ */
26
+ export function oneLine(text: string): string {
27
+ return sanitizeTerminal(text).replace(/\s+/g, " ");
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.74",
3
+ "version": "0.0.76",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {