my-durable 0.0.121 → 0.0.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-z0H7S2Vj.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-DgGnG9bL.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-DD66rPUN.css">
12
12
  </head>
13
13
  <body>
@@ -309,7 +309,25 @@ export class DeviceMonitor {
309
309
  const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
310
310
  // R9 cold review: bytes, not UTF-16 units — mirrored with the mux
311
311
  // relay seam so a multibyte payload cannot pass one and fail the other.
312
- const treeText = JSON.stringify(frame.tree);
312
+ // run-15 u1-4 (LOW): JSON.stringify of a wire-legal deeply-nested
313
+ // tree (well under TREE_MAX_BYTES on the wire) throws RangeError
314
+ // past the stack — that used to escape as a device fault: status →
315
+ // offline, backoff, re-probe, repeat (a disconnected churn loop
316
+ // driven by ONE hostile frame). Skip the frame + log instead: the
317
+ // monitor keeps its last good tree, the device keeps its status —
318
+ // no flap, no churn.
319
+ let treeText: string;
320
+ try {
321
+ treeText = JSON.stringify(frame.tree);
322
+ } catch (e) {
323
+ if (e instanceof RangeError) {
324
+ console.warn(
325
+ `[monitor] skipping unserializable tree frame from device ${id}: ${e.message}`,
326
+ );
327
+ continue;
328
+ }
329
+ throw e;
330
+ }
313
331
  const size = treeText ? Buffer.byteLength(treeText) : 0;
314
332
  if (size > TREE_MAX_BYTES || sessions.length > TREE_MAX_SESSIONS) {
315
333
  this.update(id, {
@@ -9,7 +9,7 @@ import type { Request, Response } from "express";
9
9
  import { DpiError } from "../../../../dpi-sdk/src/errors.js";
10
10
  import { transportFor } from "./transport.js";
11
11
  import { reassembledFrameBytes } from "./tunnel-transport.js";
12
- import type { MuxFrame } from "../../../../dpi-sdk/src/api.js";
12
+ import type { Frame, MuxFrame } from "../../../../dpi-sdk/src/api.js";
13
13
  import type { NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
14
14
  import type { DeviceMonitor, TunnelTransportSource } from "./monitor.js";
15
15
  import { ByteBudget } from "../../../../dpi-sdk/src/node/chunk.js";
@@ -79,6 +79,17 @@ function relayWrapperOverhead(key: string): number {
79
79
  * other frame type stays unlimited (scope = h4-5 trees). */
80
80
  const TREE_BUCKET_CAPACITY = 4;
81
81
  const TREE_BUCKET_REFILL_PER_SEC = 2;
82
+ /** Run-15 u1-1 (MED stale-forever): when the h4-5 bucket refuses a tree,
83
+ * the NEWEST refused tree is stashed (ONE slot per follow(), latest-wins)
84
+ * and flushed on an unref'd timer as soon as a token refills — coalescing
85
+ * alone waited for a "next push" that a quiet device never sends, pinning
86
+ * the tab to a stale tree forever (the newest snapshot was exactly the one
87
+ * the bucket refused). Initial arm 600 ms (just past the ~500 ms re-push
88
+ * window a healthy device uses, so it never fires redundantly); retries
89
+ * every 500 ms while the bucket is still exhausted. A delivered tree
90
+ * clears the slot (strictly fresher); a newer refused tree replaces it. */
91
+ const TREE_DEFERRED_FLUSH_MS = 600;
92
+ const TREE_DEFERRED_RETRY_MS = 500;
82
93
 
83
94
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
84
95
 
@@ -343,14 +354,14 @@ export class StreamMux {
343
354
  // Map keyed by sub.key shared across follow() loops let a second tab on
344
355
  // the same key drain this loop's budget, and the entry's deletion on the
345
356
  // OTHER tab's exit lazily re-armed a FULL bucket here — bypassable
346
- // shaping. Local state has neither seam. Reset to full at every
347
- // (re)connect: the device's initial tree (a tab's first full view after a
348
- // flap) always relays.
357
+ // shaping. Local state has neither seam. Full only on the FIRST connect
358
+ // of this follow() (run-15 u1-2 below): the device's initial tree (a
359
+ // tab's first full view) always relays.
349
360
  let treeTokens = TREE_BUCKET_CAPACITY;
350
361
  let treeTokensAt = Date.now();
351
362
  /** Consume one tree token (refill TREE_BUCKET_REFILL_PER_SEC, clamped at
352
363
  * capacity; fractional idle credit kept on refuse). False = exhausted —
353
- * the caller coalesces (snapshots supersede each other; the next tree
364
+ * the caller coalesces (snapshots supersede each other; the next tree
354
365
  * delivers a strictly fresher view). */
355
366
  const admitTree = (): boolean => {
356
367
  const now = Date.now();
@@ -366,144 +377,304 @@ export class StreamMux {
366
377
  treeTokens = tokens - 1;
367
378
  return true;
368
379
  };
369
- while (!signal.aborted) {
370
- await this.monitor.whenOnline(sub.deviceId, signal);
371
- if (signal.aborted) return;
372
- treeTokens = TREE_BUCKET_CAPACITY;
373
- treeTokensAt = Date.now();
374
- const device = this.registry.get(sub.deviceId);
375
- const transport = device ? transportFor(device, this.tunnel) : undefined;
376
- if (!transport?.available) return;
377
- try {
378
- for await (const frame of transport.watch(
379
- { path: sub.path, consumerId: `mux:${sub.key}` },
380
- signal,
381
- )) {
382
- if (!checkDeviceFrame(frame))
383
- throw new DpiError("invalid", "Invalid device stream frame");
384
- // snapshot/agents/network carry whole-document payloads by design
385
- // (a session snapshot includes entries + inbox) and legitimately
386
- // exceed the per-event cap — capping them turned a large session's
387
- // live view into a fault with no reconnect path.
388
- const cap =
389
- frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
390
- ? RELAY_TREE_CAP_BYTES
391
- : RELAY_FRAME_CAP_BYTES;
392
- const relayCapFault = () =>
380
+ // run-15 u1-1 (MED stale-forever): coalescing leaned on "the device
381
+ // re-pushes the next tree within ~500 ms" — a device that goes QUIET
382
+ // right after a burst left the tab pinned to a stale tree forever.
383
+ // Keep the refusal convergent: the newest refused tree occupies ONE
384
+ // per-follow() slot and an unref'd timer delivers it as soon as a token
385
+ // refills (retrying while exhausted). Cap checks, the session-count
386
+ // mirror and fault semantics are untouched — only convergence is added.
387
+ let pendingLatest: { frame: Frame; text?: string } | undefined;
388
+ let pendingTimer: NodeJS.Timeout | undefined;
389
+ const stopPending = () => {
390
+ if (pendingTimer !== undefined) clearTimeout(pendingTimer);
391
+ pendingTimer = undefined;
392
+ pendingLatest = undefined;
393
+ };
394
+ const stashPending = (frame: Frame, text?: string) => {
395
+ pendingLatest = { frame, text };
396
+ if (pendingTimer !== undefined) clearTimeout(pendingTimer);
397
+ pendingTimer = setTimeout(flushPending, TREE_DEFERRED_FLUSH_MS);
398
+ pendingTimer.unref();
399
+ };
400
+ // The stash is trees-only, so its belt-and-braces fault always cites the
401
+ // tree cap (same code/message shape as relayCapFault below).
402
+ const pendingCapFault = () =>
403
+ stream.send({
404
+ sub: sub.key,
405
+ frame: {
406
+ type: "fault",
407
+ error: {
408
+ code: "invalid",
409
+ message: `Device stream frame exceeds the relay cap (${RELAY_TREE_CAP_BYTES} bytes)`,
410
+ },
411
+ },
412
+ });
413
+ const flushPending = () => {
414
+ pendingTimer = undefined;
415
+ if (pendingLatest === undefined || signal.aborted) {
416
+ pendingLatest = undefined;
417
+ return;
418
+ }
419
+ if (!admitTree()) {
420
+ // Bucket still exhausted: keep the newest tree stashed and retry —
421
+ // the timer keeps trying until a token refills (run-15 u1-1).
422
+ pendingTimer = setTimeout(flushPending, TREE_DEFERRED_RETRY_MS);
423
+ pendingTimer.unref();
424
+ return;
425
+ }
426
+ const pending = pendingLatest;
427
+ pendingLatest = undefined;
428
+ let text = pending.text;
429
+ if (text === undefined) {
430
+ // Raw-path stash (admitted but never serialized yet): the ONE
431
+ // stringify of this frame happens now, at flush time.
432
+ try {
433
+ text = JSON.stringify({ sub: sub.key, frame: pending.frame });
434
+ } catch (e) {
435
+ if (e instanceof RangeError) {
436
+ treeTokens += 1; // run-15 u1-3/u1-4: a violation never burns a token
437
+ // r15 review m2: the honest message for a stack-overflow frame —
438
+ // it is NOT over-cap, it is unserializable.
393
439
  stream.send({
394
440
  sub: sub.key,
395
441
  frame: {
396
442
  type: "fault",
397
443
  error: {
398
444
  code: "invalid",
399
- message: `Device stream frame exceeds the relay cap (${cap} bytes)`,
445
+ message: "Device stream frame is unserializable (too deeply nested)",
400
446
  },
401
447
  },
402
448
  });
403
- // Run-9 U5/U8: the monitor seam (state owner) degrades oversized
404
- // trees — but the RELAY is a pipe, and the tunnel chunk path exists
405
- // precisely to deliver legitimately large trees (tunnel-pacing
406
- // contract: a 1.5MB chunked tree arrives intact). The pipe's byte
407
- // cap is RELAY_TREE_CAP_BYTES; here we mirror only the session-COUNT
408
- // policy. Byte parity with the monitor was tried and reverted: it
409
- // dropped the chunked-tree contract. A count violation faults —
410
- // never silently drops (r9 relay contract), never consumes a token,
411
- // and the subscription survives (skip, not cut). Checked FIRST so
412
- // both paths below share it (cold-review r11 f3 ordering).
413
- if (frame.type === "tree") {
414
- const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
415
- if (sessions.length > TREE_RELAY_MAX_SESSIONS) {
416
- this.droppedTreeFrames++;
449
+ return;
450
+ }
451
+ // r15 review m1: this callback runs in a BARE timer context — an
452
+ // uncaught throw here would tear down the hub process. Unreachable
453
+ // for wire-parsed frames (JSON.parse yields no cycles/bigints), but
454
+ // defense in depth: fault instead of crash.
455
+ stream.send({
456
+ sub: sub.key,
457
+ frame: {
458
+ type: "fault",
459
+ error: {
460
+ code: "invalid",
461
+ message: `Device stream frame could not be serialized (${String((e as Error)?.message ?? e).slice(0, 120)})`,
462
+ },
463
+ },
464
+ });
465
+ return;
466
+ }
467
+ }
468
+ if (Buffer.byteLength(text) > RELAY_TREE_CAP_BYTES) {
469
+ // Same belt-and-braces as the live path: non-canonical raw bytes can
470
+ // re-stringify LONGER than raw (run-15 u1-3 expansion encoding).
471
+ treeTokens += 1; // run-15 u1-3: a violation never burns a token
472
+ pendingCapFault();
473
+ return;
474
+ }
475
+ stream.send({ sub: sub.key, frame: pending.frame }, text);
476
+ };
477
+ try {
478
+ while (!signal.aborted) {
479
+ await this.monitor.whenOnline(sub.deviceId, signal);
480
+ if (signal.aborted) return;
481
+ // run-15 u1-2 (LOW): reconnects must NOT mint a fresh bucket — the
482
+ // old reset-to-full on EVERY (re)connect let a device flap its
483
+ // stream after a burst and re-arm 4 full tokens per flap, bypassing
484
+ // the h4-5 coalescing entirely. Only the FIRST connect of this
485
+ // follow() starts full (the declaration above); every later
486
+ // iteration carries the remaining fractional tokens. The refill
487
+ // CLOCK still restarts here, so offline time accrues no credit.
488
+ treeTokensAt = Date.now();
489
+ const device = this.registry.get(sub.deviceId);
490
+ const transport = device ? transportFor(device, this.tunnel) : undefined;
491
+ if (!transport?.available) return;
492
+ try {
493
+ for await (const frame of transport.watch(
494
+ { path: sub.path, consumerId: `mux:${sub.key}` },
495
+ signal,
496
+ )) {
497
+ if (!checkDeviceFrame(frame))
498
+ throw new DpiError("invalid", "Invalid device stream frame");
499
+ // snapshot/agents/network carry whole-document payloads by design
500
+ // (a session snapshot includes entries + inbox) and legitimately
501
+ // exceed the per-event cap — capping them turned a large session's
502
+ // live view into a fault with no reconnect path.
503
+ const cap =
504
+ frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
505
+ ? RELAY_TREE_CAP_BYTES
506
+ : RELAY_FRAME_CAP_BYTES;
507
+ const relayCapFault = () =>
417
508
  stream.send({
418
509
  sub: sub.key,
419
510
  frame: {
420
511
  type: "fault",
421
512
  error: {
422
513
  code: "invalid",
423
- message: `Device tree frame exceeds the relay tree cap (${TREE_RELAY_MAX_SESSIONS} sessions)`,
514
+ message: `Device stream frame exceeds the relay cap (${cap} bytes)`,
424
515
  },
425
516
  },
426
517
  });
518
+ // Run-9 U5/U8: the monitor seam (state owner) degrades oversized
519
+ // trees — but the RELAY is a pipe, and the tunnel chunk path exists
520
+ // precisely to deliver legitimately large trees (tunnel-pacing
521
+ // contract: a 1.5MB chunked tree arrives intact). The pipe's byte
522
+ // cap is RELAY_TREE_CAP_BYTES; here we mirror only the session-COUNT
523
+ // policy. Byte parity with the monitor was tried and reverted: it
524
+ // dropped the chunked-tree contract. A count violation faults —
525
+ // never silently drops (r9 relay contract), never consumes a token,
526
+ // and the subscription survives (skip, not cut). Checked FIRST so
527
+ // both paths below share it (cold-review r11 f3 ordering).
528
+ if (frame.type === "tree") {
529
+ const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
530
+ if (sessions.length > TREE_RELAY_MAX_SESSIONS) {
531
+ this.droppedTreeFrames++;
532
+ stream.send({
533
+ sub: sub.key,
534
+ frame: {
535
+ type: "fault",
536
+ error: {
537
+ code: "invalid",
538
+ message: `Device tree frame exceeds the relay tree cap (${TREE_RELAY_MAX_SESSIONS} sessions)`,
539
+ },
540
+ },
541
+ });
542
+ continue;
543
+ }
544
+ }
545
+ // run-11 h1-1 (Unit A; cold-review r11 f1/f3 rework): chunked
546
+ // (tunnel) frames already know their exact serialized size
547
+ // (reassembledFrameBytes, recorded at the reassembly push seam in
548
+ // tunnel-transport). For them EVERY admission decision precedes the
549
+ // one serialization: an oversized multi-MiB frame faults on
550
+ // raw + EXACT wrapper overhead (relayWrapperOverhead — a constant
551
+ // allowance ≥ the real overhead faulted LEGAL near-cap frames), and
552
+ // a burst tree the token bucket coalesces away costs ZERO
553
+ // stringify. For canonical device JSON (the device's own
554
+ // JSON.stringify — the normal case) the pre-check faults exactly
555
+ // what the authoritative check would; hand-crafted non-canonical
556
+ // raw bytes can only diverge into an early fault (self-harm) or a
557
+ // late catch — the belt-and-braces byteLength(text) check below
558
+ // still gates every admission, so nothing over-cap ever relays.
559
+ const rawBytes = reassembledFrameBytes.get(frame);
560
+ if (rawBytes !== undefined) {
561
+ if (rawBytes + relayWrapperOverhead(sub.key) > cap) {
562
+ relayCapFault();
563
+ continue;
564
+ }
565
+ if (frame.type === "tree" && !admitTree()) {
566
+ // run-11 h4-5 (Unit A): bucket exhausted — coalesce (drop) this
567
+ // legal snapshot silently and count it: unlike the faults above
568
+ // (protocol violations worth surfacing), this is rate shaping of
569
+ // frames that supersede each other; the next tree (a healthy
570
+ // device re-pushes on state change within ~500 ms) delivers a
571
+ // strictly fresher view. Runs AFTER every admission check, so
572
+ // violations still fault and never consume a token.
573
+ this.coalescedTreeFrames++;
574
+ // run-15 u1-1 (MED): that "next push" never comes from a
575
+ // quiet device — stash the NEWEST refused tree (latest-wins
576
+ // slot) so the deferred timer can converge the tab once a
577
+ // token refills.
578
+ stashPending(frame);
579
+ continue;
580
+ }
581
+ // run-8 U5 + h1-1: serialize ONCE — the only stringify on this
582
+ // path — admit on its byte size, hand the same string to the
583
+ // writer. Belt-and-braces after the pre-check: non-canonical raw
584
+ // bytes can re-stringify LONGER than raw (exponent-form numbers,
585
+ // e.g. 1e-9 → 0.000000001), so this check is still load-bearing.
586
+ let text: string;
587
+ try {
588
+ text = JSON.stringify({ sub: sub.key, frame });
589
+ } catch (e) {
590
+ // run-15 u1-4 (LOW): a wire-legal but deeply-nested tree
591
+ // (<cap bytes) drives JSON.stringify past the stack — the
592
+ // RangeError used to escape the loop as an "offline"
593
+ // disconnect + reconnect churn per hostile frame. A
594
+ // serialization failure is a cap-class violation: fault,
595
+ // refund the token this path already consumed (run-15 u1-3:
596
+ // violations never burn a token), keep the subscription.
597
+ if (e instanceof RangeError) {
598
+ if (frame.type === "tree") treeTokens += 1;
599
+ relayCapFault();
600
+ continue;
601
+ }
602
+ throw e;
603
+ }
604
+ if (Buffer.byteLength(text) > cap) {
605
+ relayCapFault();
606
+ // run-15 u1-3 (LOW): refund the token admitTree consumed just
607
+ // above — this fault is a violation, and violations never burn
608
+ // a token (h4-5 invariant). Without the refund, a hostile
609
+ // expansion-encoded tree (raw ≤ cap, canonical > cap — e.g.
610
+ // repeated `1e21` number tokens) drained the bucket once per
611
+ // fault and turned the coalescer into a dropper.
612
+ if (frame.type === "tree") treeTokens += 1;
613
+ continue;
614
+ }
615
+ stream.send({ sub: sub.key, frame }, text);
616
+ // run-15 u1-1: a delivered tree supersedes any stash — a flush
617
+ // now could only deliver a staler view.
618
+ if (frame.type === "tree") stopPending();
619
+ if (frame.type === "hello") backoff.reset();
427
620
  continue;
428
621
  }
429
- }
430
- // run-11 h1-1 (Unit A; cold-review r11 f1/f3 rework): chunked
431
- // (tunnel) frames already know their exact serialized size
432
- // (reassembledFrameBytes, recorded at the reassembly push seam in
433
- // tunnel-transport). For them EVERY admission decision precedes the
434
- // one serialization: an oversized multi-MiB frame faults on
435
- // raw + EXACT wrapper overhead (relayWrapperOverhead — a constant
436
- // allowance ≥ the real overhead faulted LEGAL near-cap frames), and
437
- // a burst tree the token bucket coalesces away costs ZERO
438
- // stringify. For canonical device JSON (the device's own
439
- // JSON.stringify — the normal case) the pre-check faults exactly
440
- // what the authoritative check would; hand-crafted non-canonical
441
- // raw bytes can only diverge into an early fault (self-harm) or a
442
- // late catch — the belt-and-braces byteLength(text) check below
443
- // still gates every admission, so nothing over-cap ever relays.
444
- const rawBytes = reassembledFrameBytes.get(frame);
445
- if (rawBytes !== undefined) {
446
- if (rawBytes + relayWrapperOverhead(sub.key) > cap) {
622
+ // run-8 U5: inline/LAN frames have no raw-bytes side-channel — this
623
+ // stays the authoritative path: serialize ONCE here, admit on its
624
+ // byte size, and hand the same string to every tab.
625
+ let text: string;
626
+ try {
627
+ text = JSON.stringify({ sub: sub.key, frame });
628
+ } catch (e) {
629
+ // run-15 u1-4 (LOW): same RangeError guard as the raw path —
630
+ // fault instead of an "offline" disconnect + reconnect churn.
631
+ // (No refund needed here: the inline path checks the bucket
632
+ // AFTER serialization, so no token was consumed yet.)
633
+ if (e instanceof RangeError) {
634
+ relayCapFault();
635
+ continue;
636
+ }
637
+ throw e;
638
+ }
639
+ if (Buffer.byteLength(text) > cap) {
447
640
  relayCapFault();
448
641
  continue;
449
642
  }
450
643
  if (frame.type === "tree" && !admitTree()) {
451
- // run-11 h4-5 (Unit A): bucket exhausted — coalesce (drop) this
452
- // legal snapshot silently and count it: unlike the faults above
453
- // (protocol violations worth surfacing), this is rate shaping of
454
- // frames that supersede each other; the next tree (a healthy
455
- // device re-pushes on state change within ~500 ms) delivers a
456
- // strictly fresher view. Runs AFTER every admission check, so
457
- // violations still fault and never consume a token.
458
644
  this.coalescedTreeFrames++;
459
- continue;
460
- }
461
- // run-8 U5 + h1-1: serialize ONCE — the only stringify on this
462
- // path — admit on its byte size, hand the same string to the
463
- // writer. Belt-and-braces after the pre-check: non-canonical raw
464
- // bytes can re-stringify LONGER than raw (exponent-form numbers,
465
- // e.g. 1e-9 → 0.000000001), so this check is still load-bearing.
466
- const text = JSON.stringify({ sub: sub.key, frame });
467
- if (Buffer.byteLength(text) > cap) {
468
- relayCapFault();
645
+ // run-15 u1-1 (MED): latest-wins stash — reuse the text this
646
+ // path already serialized, so the deferred flush delivers it
647
+ // without a second stringify.
648
+ stashPending(frame, text);
469
649
  continue;
470
650
  }
471
651
  stream.send({ sub: sub.key, frame }, text);
652
+ // run-15 u1-1: a delivered tree supersedes any stash.
653
+ if (frame.type === "tree") stopPending();
472
654
  if (frame.type === "hello") backoff.reset();
473
- continue;
474
- }
475
- // run-8 U5: inline/LAN frames have no raw-bytes side-channel — this
476
- // stays the authoritative path: serialize ONCE here, admit on its
477
- // byte size, and hand the same string to every tab.
478
- const text = JSON.stringify({ sub: sub.key, frame });
479
- if (Buffer.byteLength(text) > cap) {
480
- relayCapFault();
481
- continue;
482
655
  }
483
- if (frame.type === "tree" && !admitTree()) {
484
- this.coalescedTreeFrames++;
485
- continue;
656
+ if (signal.aborted) return;
657
+ stream.send({ sub: sub.key, frame: { type: "disconnected", reason: "Stream ended" } });
658
+ } catch (e) {
659
+ if (signal.aborted) return;
660
+ const err =
661
+ e instanceof DpiError ? e : new DpiError("offline", String((e as Error)?.message ?? e));
662
+ if (err.code === "not_found" || err.code === "invalid" || err.code === "ambiguous") {
663
+ stream.send({
664
+ sub: sub.key,
665
+ frame: { type: "fault", error: { code: err.code, message: err.message } },
666
+ });
667
+ return;
486
668
  }
487
- stream.send({ sub: sub.key, frame }, text);
488
- if (frame.type === "hello") backoff.reset();
489
- }
490
- if (signal.aborted) return;
491
- stream.send({ sub: sub.key, frame: { type: "disconnected", reason: "Stream ended" } });
492
- } catch (e) {
493
- if (signal.aborted) return;
494
- const err =
495
- e instanceof DpiError ? e : new DpiError("offline", String((e as Error)?.message ?? e));
496
- if (err.code === "not_found" || err.code === "invalid" || err.code === "ambiguous") {
497
- stream.send({
498
- sub: sub.key,
499
- frame: { type: "fault", error: { code: err.code, message: err.message } },
500
- });
501
- return;
669
+ stream.send({ sub: sub.key, frame: { type: "disconnected", reason: err.message } });
502
670
  }
503
- stream.send({ sub: sub.key, frame: { type: "disconnected", reason: err.message } });
671
+ await sleep(backoff.ms, signal);
672
+ backoff.advance();
504
673
  }
505
- await sleep(backoff.ms, signal);
506
- backoff.advance();
674
+ } finally {
675
+ // run-15 u1-1: the deferred timer must never outlive this follow() —
676
+ // every exit (abort, fault-return, loop end) drops the stash + timer.
677
+ stopPending();
507
678
  }
508
679
  }
509
680
  }
@@ -134,7 +134,7 @@ export class LanTransport implements DeviceTransport {
134
134
  const textual = ct === undefined || TEXTUAL_CT_RE.test(ct);
135
135
  const capped = await readBodyCapped(response, textual ? LOGICAL_MESSAGE_MAX_BYTES : BINARY_RESPONSE_MAX_BYTES);
136
136
  if (!capped.ok)
137
- throw new DpiError("invalid", `device answer exceeds ${textual ? "16 MiB" : "12 MB"}`, 413);
137
+ throw new DpiError("invalid", `device answer exceeds ${textual ? "16 MiB" : "12 MiB"}`, 413);
138
138
  const raw = capped.bytes;
139
139
  // Textual responses keep the legacy plain-string shape; binaries are base64-flagged
140
140
  // so the proxy can serve bytes byte-exact (R8 binary passthrough).
@@ -174,10 +174,14 @@ export function transportFor(
174
174
 
175
175
  /**
176
176
  * R17 (run-3 h8): the binary cap mirrors the device connector's own reader
177
- * (tunnel.ts uses 12_000_000 — aligned exactly so a binary that passes one
178
- * leg never surprises the other).
177
+ * so a binary that passes one leg never surprises the other. Run-15 (u4-1):
178
+ * the three binary legs are now ONE cap — 12 MiB (12_582_912 = 12*1024*1024)
179
+ * here, in dpi-backend's tunnel.ts, and in the SDK client's BINARY_BODY_MAX.
180
+ * This leg's old 12_000_000 sat 582_912 bytes under the SDK's 12*1024*1024,
181
+ * so a body could clear one reader and be refused by the next.
182
+ * binary-caps-parity-r15.test.ts pins the trio equal.
179
183
  */
180
- const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
184
+ const BINARY_RESPONSE_MAX_BYTES = 12_582_912;
181
185
 
182
186
  async function readBodyCapped(
183
187
  res: Response,
@@ -14,7 +14,7 @@
14
14
  "test": "tsx --test tests/*.test.ts"
15
15
  },
16
16
  "dependencies": {
17
- "dompurify": "^3.2.0",
17
+ "dompurify": "^3.4.17",
18
18
  "express": "^5.1.0",
19
19
  "lucide-vue-next": "^0.468.0",
20
20
  "marked": "^17.0.0",
@@ -233,7 +233,14 @@ export interface ProjectPatchBody {
233
233
  model?: { provider: string; modelId: string } | "";
234
234
  }
235
235
 
236
- /** One row of the device's env-file view. Secrets arrive masked, never verbatim. */
236
+ /**
237
+ * One row of the device's env-file view. Masking is a NAME heuristic, not a
238
+ * value classifier: keys matching the device's secret-name list (TOKEN /
239
+ * SECRET / PASSWORD / PASSWD / API_KEY / *_KEY / CREDENTIAL) arrive masked;
240
+ * every other key rides verbatim by design — the device cannot know an
241
+ * unlisted key holds a credential (run-15 u4-3 softened the old "secrets
242
+ * arrive masked, never verbatim" promise to match this heuristic).
243
+ */
237
244
  export interface EnvVarView {
238
245
  key: string;
239
246
  masked: string;
@@ -275,6 +282,11 @@ export interface PiAuthWriteResult {
275
282
  restartRequired: true;
276
283
  }
277
284
 
285
+ /**
286
+ * The whole env-file view. Same masking contract as EnvVarView: only keys
287
+ * matching the device's secret-name list arrive masked; other values are
288
+ * verbatim by design (run-15 u4-3).
289
+ */
278
290
  export interface EnvFileView {
279
291
  envFile: string;
280
292
  exists: boolean;
@@ -396,7 +408,10 @@ export interface ScheduleRecord {
396
408
  enabled: boolean;
397
409
  lastRunAt?: number;
398
410
  lastSessionId?: string;
399
- lastOutcome?: "ok" | "failed";
411
+ /** Run-15 (u4-2): the registry's full outcome union — a run parked between
412
+ * start and settle reports "started" (and "interrupted"/"timeout" after a
413
+ * crash/timeout); UIs treat the field as opaque text. */
414
+ lastOutcome?: "ok" | "failed" | "started" | "timeout" | "interrupted";
400
415
  lastError?: string;
401
416
  /** R10: keep the last N runs' sessions live, archive older ones. Absent = never. */
402
417
  keepRuns?: number;
@@ -156,12 +156,16 @@ export interface GitOpResult {
156
156
 
157
157
 
158
158
  /** r10 h3-1: the SDK client is the trust-boundary reader — every hub leg is
159
- * capped (transport.ts readBodyCapped 16MiB textual / 12MB binary), but this
159
+ * capped (transport.ts readBodyCapped 16 MiB textual / 12 MiB binary), but this
160
160
  * client buffered `response.text()` / `arrayBuffer()` whole. A compromised
161
161
  * device answering a multi-GB body OOMs the operator's TUI / net scripts /
162
162
  * browser export. Cap with hub parity: content-length precheck, then a
163
163
  * byte-counting stream read that aborts at the ceiling. Isomorphic: no Buffer. */
164
164
  const TEXT_BODY_MAX = 16 * 1024 * 1024;
165
+ /** Run-15 (u4-1): this 12 MiB (12*1024*1024) is THE parity target — the hub's
166
+ * LanTransport and dpi-backend's tunnel reader were unified to the same
167
+ * number (they were 12_000_000 before, 582_912 bytes apart).
168
+ * binary-caps-parity-r15.test.ts pins all three legs equal. */
165
169
  const BINARY_BODY_MAX = 12 * 1024 * 1024;
166
170
 
167
171
  async function readBodyCapped(response: Response, cap: number, what: string): Promise<Uint8Array> {
@@ -486,7 +490,8 @@ export class DpiClient {
486
490
  response.status,
487
491
  );
488
492
  }
489
- // r10 h3-1: binary leg — 12MB parity with the hub's readBodyCapped.
493
+ // r10 h3-1: binary leg — 12 MiB parity with the hub's readBodyCapped
494
+ // (run-15 u4-1: one cap across all three legs, pinned by the parity test).
490
495
  const bytes = await readBodyCapped(response, BINARY_BODY_MAX, "export body");
491
496
  // `filename="quoted"` (the device's form) or a bare token, per RFC 6266.
492
497
  const disposition = response.headers.get("content-disposition") ?? "";
@@ -224,10 +224,17 @@ function safeAgents(value: unknown): AgentSummary[] {
224
224
  * R20 cold-1 M3: both tasks-bearing frame shapes (session + tasks) pass here
225
225
  * — non-array input ({} / null) crashed the old inline filter itself, and
226
226
  * null/state-less rows crashed the statusbar's every-frame deref.
227
+ * run-15 u3-4 (MED): the filter kept EVERY well-formed row, so a hostile
228
+ * device's 5000-row tasks frame was retained whole and walked on every
229
+ * statusbar pass (per-frame DoS). Keep the NEWEST TASKS_MAX rows — the same
230
+ * bounded-retention discipline as safeInbox's INBOX_MAX_ITEMS (models.ts:105).
227
231
  */
232
+ const TASKS_MAX = 256;
228
233
  function safeTasks(value: unknown): TaskNode[] {
229
234
  if (!Array.isArray(value)) return [];
230
- return value.filter((t): t is TaskNode => !!t && typeof t === "object" && !!(t as { state?: unknown }).state);
235
+ return value
236
+ .filter((t): t is TaskNode => !!t && typeof t === "object" && !!(t as { state?: unknown }).state)
237
+ .slice(-TASKS_MAX);
231
238
  }
232
239
 
233
240
  export class AgentModel extends Emitter {