my-durable 0.0.77 → 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.
@@ -7,8 +7,8 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-CRSjEtI_.js"></script>
11
- <link rel="stylesheet" crossorigin href="/assets/index-h81haD43.css">
10
+ <script type="module" crossorigin src="/assets/index-DAF9D074.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-BF6mtGF4.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -0,0 +1,38 @@
1
+ // One place for the FE's copy of the device's git-containment rule.
2
+ // A device serves git ONLY under its configured start dirs (the device stays
3
+ // the enforcer — this is the advisory pre-check that keeps doomed requests off
4
+ // the wire). Kept import-free so both the store and the client wrapper can use
5
+ // it without a cycle.
6
+ export interface GitDeviceFacts {
7
+ startDirs?: unknown;
8
+ platform?: unknown;
9
+ }
10
+
11
+ /** Normalised spelling used for the comparison (win32: slash-fold + case-fold). */
12
+ export function normGitPath(p: string, win: boolean): string {
13
+ const trimmed = String(p ?? "").trim();
14
+ return win
15
+ ? trimmed.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase()
16
+ : trimmed.replace(/\/+$/, "");
17
+ }
18
+
19
+ /** True when the device's start dirs are unknown (allow: the device decides) or
20
+ * `path` IS a start dir / lives under one. */
21
+ export function pathUnderStartDirs(info: GitDeviceFacts | undefined, path: string): boolean {
22
+ const dirs = info?.startDirs;
23
+ if (!Array.isArray(dirs) || dirs.length === 0) return true;
24
+ const win = String(info?.platform ?? "").startsWith("win32");
25
+ const a = normGitPath(path, win);
26
+ return dirs.some((raw) => {
27
+ const b = normGitPath(String(raw), win);
28
+ return !!b && (a === b || a.startsWith(win ? `${b}\\` : `${b}/`));
29
+ });
30
+ }
31
+
32
+ /** Operator-facing sentence naming the roots the device actually serves. */
33
+ export function outsideStartDirsReason(info: GitDeviceFacts | undefined): string {
34
+ const dirs = Array.isArray(info?.startDirs) ? (info!.startDirs as unknown[]).map(String) : [];
35
+ return dirs.length
36
+ ? `outside the device's start dirs (it serves: ${dirs.join(", ")})`
37
+ : "outside the device's start dirs";
38
+ }
@@ -6,6 +6,7 @@ import { reactive, watch } from "vue";
6
6
  import type { GitStatus } from "@sdk/client";
7
7
  import { deviceClient } from "./hub";
8
8
  import { network } from "./store";
9
+ import { pathUnderStartDirs } from "./git-rules";
9
10
 
10
11
  export interface GitEntry {
11
12
  at: number; // last settled fetch (0 = never)
@@ -39,16 +40,29 @@ function gitPathAllowed(deviceId: string, path: string): boolean {
39
40
  const dev = network.devices.value.find((d) => d.id === deviceId) as
40
41
  | { info?: { startDirs?: unknown; platform?: unknown } }
41
42
  | undefined;
42
- const dirs = dev?.info?.startDirs;
43
- if (!Array.isArray(dirs) || dirs.length === 0) return true;
44
- const win = String(dev?.info?.platform ?? "").startsWith("win32");
45
- const norm = (p: string) =>
46
- win ? p.trim().replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase() : p.trim().replace(/\/+$/, "");
47
- const a = norm(path);
48
- return dirs.some((raw) => {
49
- const b = norm(String(raw));
50
- return !!b && (a === b || a.startsWith(win ? b + "\\" : b + "/"));
51
- });
43
+ // One rule, shared with the client wrapper (client/git-rules.ts).
44
+ return pathUnderStartDirs(dev?.info, path);
45
+ }
46
+
47
+ /**
48
+ * run-8 (live console report): panels that call gitOp DIRECTLY (the commit
49
+ * log, PR list, turn list) skipped the pre-check above, so a project left over
50
+ * from other start dirs — or a plain non-repo project — produced a 400 storm
51
+ * on every mount and every network frame. Exported so every git caller asks
52
+ * the same question. `reason` is the operator-facing sentence.
53
+ */
54
+ export function gitAllowedFor(
55
+ deviceId: string,
56
+ path: string,
57
+ ): { ok: true } | { ok: false; reason: string } {
58
+ if (!gitPathAllowed(deviceId, path)) return { ok: false, reason: "outside the device's start dirs" };
59
+ const entry = gitEntry(deviceId, path);
60
+ // cold-3 L9: `repo:false` is only advisory — a folder that became a repo
61
+ // after the page loaded (git init) must be reachable, or the panel reporting
62
+ // it can never refresh. A stale verdict stops blocking after 5s.
63
+ if (entry.status && entry.status.repo === false && Date.now() - entry.at < 5_000)
64
+ return { ok: false, reason: "not a git repository" };
65
+ return { ok: true };
52
66
  }
53
67
 
54
68
  /** Settle an entry from either a real status or the batch's `{error}` shape. */
@@ -109,8 +123,14 @@ export function wireGitAutoRefresh() {
109
123
  );
110
124
  if (!marks.length) continue;
111
125
  for (const key of [...entries.keys()]) {
112
- const [devId, cwd] = key.split("::");
113
- if (devId !== d.id || !cwd) continue;
126
+ // run-8 U4: decode at the FIRST '::' — a cwd containing '::' (legal
127
+ // POSIX bytes, device-controlled per R23) truncated the split() form at
128
+ // its own first '::', never refreshing the real entry and force-
129
+ // refreshing a phantom prefix entry on a matching prefix mark.
130
+ const sep = key.indexOf("::");
131
+ const devId = key.slice(0, sep);
132
+ const cwd = key.slice(sep + 2);
133
+ if (sep < 0 || !devId || devId !== d.id || !cwd) continue;
114
134
  const e = entries.get(key)!;
115
135
  if (!marks.some((m) => cwd === m.root || cwd.startsWith(m.root + "/") || cwd.startsWith(m.root + "\\"))) continue;
116
136
  if (e.loading || now - e.at < 4000) continue; // throttle: bursts coalesce
@@ -3,14 +3,15 @@
3
3
  import { DpiClient } from "@sdk/client";
4
4
  import { DpiError } from "@sdk/errors";
5
5
  import type { ErrorCode, NetworkDevice } from "@sdk/api";
6
- import { notify } from "./store";
6
+ import { network, notify } from "./store";
7
+ import { outsideStartDirsReason, pathUnderStartDirs, type GitDeviceFacts } from "./git-rules";
7
8
 
8
9
  // R13 (R9-6.3 FE): the collapse of identical un-keyed creates is an accepted
9
10
  // retry-safety tradeoff — but it must be VISIBLE. The device's replay verdict
10
11
  // rides the tunnel envelope, the hub surfaces Idempotent-Replay, and the SDK
11
12
  // hook turns it into a toast naming the escape hatch (own idempotency-key).
12
13
  let replayToastAt = 0;
13
- export const deviceClient = (id: string) =>
14
+ const rawDeviceClient = (id: string) =>
14
15
  new DpiClient(`/api/devices/${encodeURIComponent(id)}`, undefined, {
15
16
  onIdempotentReplay: (path) => {
16
17
  // Replays can arrive in bursts (a re-connected UI re-firing identical
@@ -21,6 +22,29 @@ export const deviceClient = (id: string) =>
21
22
  },
22
23
  });
23
24
 
25
+ /**
26
+ * run-8 (live console report): EVERY git caller goes through here, so the
27
+ * start-dirs pre-check belongs here too — not only in the git store. Panels
28
+ * that call gitOp directly (commit log, PR list, toolbar ops) used to send
29
+ * doomed requests for a project left over from other start dirs and answer 400
30
+ * on every mount and every network frame. A rejected call never leaves the tab:
31
+ * the operator sees the verdict instead of a network error storm.
32
+ */
33
+ export const deviceClient = (id: string) => {
34
+ const client = rawDeviceClient(id);
35
+ const facts = (): GitDeviceFacts | undefined =>
36
+ (network.devices.value as { id: string; info?: GitDeviceFacts }[]).find((d) => d.id === id)?.info;
37
+ const rawGitOp = client.gitOp.bind(client);
38
+ client.gitOp = ((path: string, op: never, opts?: never) => {
39
+ const info = facts();
40
+ if (info && path && !pathUnderStartDirs(info, path)) {
41
+ return Promise.reject(new DpiError("invalid", `git ${op} skipped: ${outsideStartDirsReason(info)}`, 400));
42
+ }
43
+ return rawGitOp(path, op, opts);
44
+ }) as typeof client.gitOp;
45
+ return client;
46
+ };
47
+
24
48
  async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
25
49
  const r = await fetch(`/api${path}`, {
26
50
  method,
@@ -34,7 +34,7 @@ import {
34
34
  } from "lucide-vue-next";
35
35
  import { deviceId, network, sessionSummary, notify, select } from "../client/store";
36
36
  import { deviceClient } from "../client/hub";
37
- import { ensureGit, gitEntry, wireGitAutoRefresh } from "../client/git-store";
37
+ import { ensureGit, gitAllowedFor, gitEntry, wireGitAutoRefresh } from "../client/git-store";
38
38
  import { addWorktree as gitAddWorktree, createSessionOn } from "../client/worktree";
39
39
  import type { GitStatus } from "@sdk/client";
40
40
 
@@ -45,6 +45,17 @@ const devId = computed(() => props.deviceId ?? deviceId.value);
45
45
  const entry = computed(() => gitEntry(devId.value || "?", cwd.value || "?"));
46
46
  const status = computed(() => entry.value.status);
47
47
  const loading = computed(() => entry.value.loading);
48
+ /** run-8 (live report): a folder the device does not serve is NOT a transient
49
+ * failure — a retry re-runs the same local verdict forever. Render it as a
50
+ * callout that names the served dirs and says what would actually fix it. */
51
+ const unserved = computed(() => {
52
+ const e = entry.value;
53
+ if (!e.error || !/start dirs/i.test(e.error)) return "";
54
+ const dirs = (network.devices.value.find((d) => d.id === devId.value) as
55
+ | { info?: { startDirs?: unknown } }
56
+ | undefined)?.info?.startDirs;
57
+ return Array.isArray(dirs) && dirs.length ? dirs.map(String).join(", ") : "";
58
+ });
48
59
  const refreshing = computed(() => entry.value.refreshing);
49
60
  const error = computed(() => entry.value.error);
50
61
  const sessionId = computed(() => {
@@ -114,6 +125,12 @@ const prBusy = ref(false);
114
125
  const isGitHub = computed(() => /github\.com|gitlab/i.test(status.value?.remoteUrl ?? ""));
115
126
  const loadPRs = async () => {
116
127
  if (!devId.value || !cwd.value) return;
128
+ const allowed = gitAllowedFor(devId.value, cwd.value);
129
+ if (!allowed.ok) {
130
+ prs.value = [];
131
+ notify(`pull requests unavailable: ${allowed.reason}`);
132
+ return;
133
+ }
117
134
  prBusy.value = true;
118
135
  try {
119
136
  const r = await deviceClient(devId.value).gitOp(cwd.value, "pr-list");
@@ -346,6 +363,11 @@ async function op(
346
363
  extra: { message?: string; rebase?: boolean; setUpstream?: boolean; ref?: string } = {},
347
364
  ) {
348
365
  if (!devId.value || !cwd.value) return;
366
+ const allowed = gitAllowedFor(devId.value, cwd.value);
367
+ if (!allowed.ok) {
368
+ notify(`git ${name} skipped: ${allowed.reason}`);
369
+ return;
370
+ }
349
371
  busy.value = name;
350
372
  out.value = "";
351
373
  try {
@@ -813,6 +835,16 @@ let logAt = 0;
813
835
  async function loadLog(force = false) {
814
836
  if (!devId.value || !cwd.value) return;
815
837
  if (!force && commits.value.length && Date.now() - logAt < 120_000) return;
838
+ // run-8 (live console report): this call bypassed the store's pre-check, so a
839
+ // project outside the device's start dirs (or a plain non-repo project) sent
840
+ // log-list on every mount/frame and answered 400 each time. Ask first.
841
+ const allowed = gitAllowedFor(devId.value, cwd.value);
842
+ if (!allowed.ok) {
843
+ commits.value = [];
844
+ logError.value = allowed.reason;
845
+ logAt = Date.now();
846
+ return;
847
+ }
816
848
  logLoading.value = true;
817
849
  try {
818
850
  const r = await deviceClient(devId.value).gitOp(cwd.value, "log-list");
@@ -879,7 +911,19 @@ const laneX = (lane: number) => lane * 12 + 7;
879
911
  <template v-else>
880
912
  <p v-if="loading" class="hint">loading git…</p>
881
913
  <p v-else-if="refreshing" class="muted-line">refreshing…</p>
882
- <p v-if="error" class="message-error">{{ error }} <button @click="refresh()">retry</button></p>
914
+ <!-- run-8 (live report): a folder the DEVICE does not serve can never be
915
+ fixed by retrying — name the roots it does serve and the real fix. -->
916
+ <div v-if="unserved" class="message-error">
917
+ <p>
918
+ <strong>{{ cwd }}</strong> is not served by this device — its start dirs are
919
+ <code>{{ unserved }}</code>.
920
+ </p>
921
+ <p class="muted-line">
922
+ Add the folder to <code>DPI_START_DIRS</code> on the device (then restart it), or open a session under one of
923
+ the served folders. Retrying will not change this.
924
+ </p>
925
+ </div>
926
+ <p v-else-if="error" class="message-error">{{ error }} <button @click="refresh()">retry</button></p>
883
927
 
884
928
  <div v-if="status" :class="{ stale: !!error || !!refreshing }">
885
929
  <p v-if="!status.repo" class="hint">Not a git repository — run <code>git init</code> (or open a session inside a repo).</p>
@@ -28,10 +28,22 @@ import {
28
28
  } from "../../../../dpi-sdk/src/protocol/limits.js";
29
29
 
30
30
  interface BrowserStream {
31
- send(frame: MuxFrame): void;
31
+ /** run-8 U5: `preSerialized` lets the relay seam (follow) admit on and send
32
+ * the SAME serialization — one stringify per inbound frame, not one per tab. */
33
+ send(frame: MuxFrame, preSerialized?: string): void;
32
34
  upstreams: Map<string, AbortController>;
33
35
  }
34
36
 
37
+ /** run-8 U5: relay admission cap for device->browser frames — the B4
38
+ * discipline (TREE_MAX_BYTES at the monitor seam) applied to EVERY frame the
39
+ * mux forwards, so a hostile device cannot push ~16MiB agent-event frames
40
+ * into per-tab stringify/copy work below the transport ceiling. */
41
+ const RELAY_FRAME_CAP_BYTES = 1024 * 1024;
42
+ /** Trees are legitimately larger (the device-scope tree path is bounded by its
43
+ * own monitor-seam caps) — still far below the 16MiB transport ceiling so a
44
+ * hostile device cannot drive ~16MiB parse/copy work per frame. */
45
+ const RELAY_TREE_CAP_BYTES = 4 * 1024 * 1024;
46
+
35
47
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
36
48
 
37
49
  /**
@@ -155,8 +167,9 @@ export class StreamMux {
155
167
  const writer = pacedSseWriter(res, { budget: this.options.budget, onClose: cleanup });
156
168
  const stream: BrowserStream = {
157
169
  upstreams: new Map(),
158
- send: (frame) => {
159
- if (writer.write(`data: ${JSON.stringify(frame)}\n\n`) === "too-large") {
170
+ send: (frame, preSerialized) => {
171
+ const text = preSerialized ?? JSON.stringify(frame);
172
+ if (writer.write(`data: ${text}\n\n`) === "too-large") {
160
173
  stream.send({
161
174
  sub: frame.sub,
162
175
  frame: {
@@ -267,7 +280,34 @@ export class StreamMux {
267
280
  )) {
268
281
  if (!checkDeviceFrame(frame))
269
282
  throw new DpiError("invalid", "Invalid device stream frame");
270
- stream.send({ sub: sub.key, frame });
283
+ // run-8 U5: admission bound at the relay seam — checkDeviceFrame is
284
+ // shape-only, so agent-event frames rode the ~16MiB transport
285
+ // ceiling into per-tab stringify (B4 capped TREE frames at the
286
+ // monitor seam only). Serialize ONCE here, admit on its byte size,
287
+ // and hand the same string to every tab.
288
+ const text = JSON.stringify({ sub: sub.key, frame });
289
+ // snapshot/agents/network carry whole-document payloads by design
290
+ // (a session snapshot includes entries + inbox) and legitimately
291
+ // exceed the per-event cap — capping them turned a large session's
292
+ // live view into a fault with no reconnect path.
293
+ const cap =
294
+ frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
295
+ ? RELAY_TREE_CAP_BYTES
296
+ : RELAY_FRAME_CAP_BYTES;
297
+ if (Buffer.byteLength(text) > cap) {
298
+ stream.send({
299
+ sub: sub.key,
300
+ frame: {
301
+ type: "fault",
302
+ error: {
303
+ code: "invalid",
304
+ message: `Device stream frame exceeds the relay cap (${cap} bytes)`,
305
+ },
306
+ },
307
+ });
308
+ continue;
309
+ }
310
+ stream.send({ sub: sub.key, frame }, text);
271
311
  if (frame.type === "hello") backoff.reset();
272
312
  }
273
313
  if (signal.aborted) return;
@@ -62,12 +62,26 @@ interface PendingRest {
62
62
  interface Subscription {
63
63
  connectionId: string;
64
64
  deviceId: string;
65
+ /** run-8 U8: every relayed device frame is charged to THIS device's
66
+ * connection share before it is queued (released when consumed), so a
67
+ * hostile device exhausts its own 32 MiB — never the shared hub pool that
68
+ * other devices' REST reservations and chunk assemblies draw from. */
65
69
  push: (frame: Frame) => void;
66
70
  close: (reason: string) => void;
67
71
  signal: AbortSignal;
68
72
  onAbort: () => void;
69
73
  }
70
74
 
75
+ /** run-8 U8: the byte size a relayed frame holds in a viewer queue. One extra
76
+ * serialization per device frame, bounded by the mux relay caps. */
77
+ function relayBytes(frame: Frame): number {
78
+ try {
79
+ return Buffer.byteLength(JSON.stringify(frame));
80
+ } catch {
81
+ return 0;
82
+ }
83
+ }
84
+
71
85
  /** A grace-set entry: which connection owned the correlation, and when it left the pending maps. */
72
86
  interface GraceEntry {
73
87
  connectionId: string;
@@ -636,14 +650,36 @@ export class TunnelDispatcher {
636
650
  throw new DpiError("offline", "No tunnel connection is live", 0);
637
651
  const connectionId = this.server.connectionIdOf(deviceId)!;
638
652
  const subscriptionId = randomUUID();
639
- const queue: Frame[] = [];
653
+ const queue: { frame: Frame; reservation: { release(): void } | null }[] = [];
640
654
  let wakeup: (() => void) | undefined;
641
655
  let closed: string | undefined;
656
+ let budgetFaulted = false;
642
657
  const sub: Subscription = {
643
658
  connectionId,
644
659
  deviceId,
645
660
  push: (frame) => {
646
- queue.push(frame);
661
+ const bytes = relayBytes(frame);
662
+ const reservation = bytes > 0 ? this.budgetFor(connectionId).reserve(bytes) : null;
663
+ if (bytes > 0 && !reservation) {
664
+ // No share left. One fault, then CLOSE: pushing a fault per dropped
665
+ // frame would put an uncharged entry in the queue for every device
666
+ // frame (the cap would stop bounding anything) and relay a fault to
667
+ // every tab until their viewer budgets cut them off.
668
+ if (!budgetFaulted) {
669
+ budgetFaulted = true;
670
+ queue.push({
671
+ frame: {
672
+ type: "fault",
673
+ error: { code: "invalid", message: "device stream exceeded this device's relay budget" },
674
+ } as unknown as Frame,
675
+ reservation: null,
676
+ });
677
+ closed = closed ?? "device stream exceeded this device's relay budget";
678
+ }
679
+ wakeup?.();
680
+ return;
681
+ }
682
+ queue.push({ frame, reservation });
647
683
  wakeup?.();
648
684
  },
649
685
  close: (reason) => {
@@ -663,10 +699,17 @@ export class TunnelDispatcher {
663
699
  sub: input.path,
664
700
  });
665
701
  if (!sent) throw new DpiError("offline", "Tunnel connection closed while subscribing", 0);
666
- while (!closed && !signal.aborted) {
667
- const frame = queue.shift();
668
- if (frame) {
669
- yield frame;
702
+ // Frames already in the queue are CHARGED and delivered before a close
703
+ // takes effect — a budget fault must not swallow the frames that fit.
704
+ while (!signal.aborted) {
705
+ if (closed && queue.length === 0) break;
706
+ const next = queue.shift();
707
+ if (next) {
708
+ try {
709
+ yield next.frame;
710
+ } finally {
711
+ next.reservation?.release();
712
+ }
670
713
  continue;
671
714
  }
672
715
  await new Promise<void>((resolve) => {
@@ -676,6 +719,9 @@ export class TunnelDispatcher {
676
719
  }
677
720
  if (closed && closed !== "consumer aborted") throw new DpiError("offline", closed, 0);
678
721
  } finally {
722
+ // Release every queued byte the device never got to deliver.
723
+ for (const pending of queue) pending.reservation?.release();
724
+ queue.length = 0;
679
725
  this.subs.delete(subscriptionId);
680
726
  this.rememberClosedSubscription(subscriptionId, connectionId);
681
727
  this.reassemblers
@@ -98,15 +98,77 @@ function setPath(target: Record<string | number, unknown>, path: readonly (strin
98
98
  }
99
99
 
100
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. */
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;
102
107
  function safeInbox(items: unknown): AgentViewState["inbox"] {
103
- return (Array.isArray(items) ? items : []).filter((x) => !!x && typeof x === "object") as 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
+ });
104
116
  }
105
117
 
106
118
  /** run-7 D3 F3: live message blocks append unbounded deltas between
107
119
  * message_start/message_end — keep a 256Ki flattened tail (the capToolOutput
108
120
  * principle, applied to the live accumulator). */
109
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
+
110
172
  function capLiveText(text: string): string {
111
173
  return text.length > LIVE_TEXT_CAP ? AgentModel.flatSlice(text.slice(text.length - LIVE_TEXT_CAP)) : text;
112
174
  }
@@ -251,7 +313,7 @@ export class AgentModel extends Emitter {
251
313
  const snapCompactions = (Array.isArray(snapshot.compactions) ? snapshot.compactions : []).filter((x) => !!x && typeof x === "object");
252
314
  this.entries = new Map(snapEntries.map((entry) => [entry.id, entry]));
253
315
  this.capEntries(); // a hostile snapshot is as unbounded as a hostile stream
254
- this.live = snapshot.generation?.message ? structuredClone(snapshot.generation.message) : undefined;
316
+ this.live = snapshot.generation?.message ? capLiveMessage(snapshot.generation.message) : undefined;
255
317
  this.tools = new Map(
256
318
  snapTools
257
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
@@ -404,8 +466,7 @@ export class AgentModel extends Emitter {
404
466
  this.live = undefined;
405
467
  return;
406
468
  case "message_start":
407
- if (event.message.role === "assistant")
408
- this.live = structuredClone(event.message as WireAssistantMessage);
469
+ if (event.message.role === "assistant") this.live = capLiveMessage(event.message as WireAssistantMessage);
409
470
  return;
410
471
  case "message_update":
411
472
  if (!this.live)
@@ -516,7 +577,14 @@ export class AgentModel extends Emitter {
516
577
  : undefined;
517
578
  return;
518
579
  case "task_failed":
519
- 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
+ ];
520
588
  return;
521
589
  default:
522
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);