my-durable 0.0.61 → 0.0.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/apps/dpi-backend/scripts/bench-store.mjs +284 -0
  2. package/apps/dpi-backend/src/archived.ts +1 -1
  3. package/apps/dpi-backend/src/gc.ts +27 -6
  4. package/apps/dpi-backend/src/pairing-files.ts +65 -0
  5. package/apps/dpi-backend/src/pairing.ts +25 -9
  6. package/apps/dpi-backend/src/routes.ts +24 -1
  7. package/apps/dpi-backend/src/schedules.ts +65 -11
  8. package/apps/dpi-backend/src/store.ts +215 -43
  9. package/apps/dpi-backend/src/tunnel.ts +45 -13
  10. package/apps/dpi-backend/src/zip.ts +376 -10
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-4Kyozhl0.js → index-D10XyhhO.js} +23 -23
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BkSQ2clA.css → index-DCz-aq0b.css} +1 -1
  13. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +10 -13
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +1 -1
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +1 -0
  17. package/apps/dpi-playground/apps/dpi-playground-hub/src/credentials.ts +46 -0
  18. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +21 -1
  19. package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +101 -7
  20. package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +19 -5
  21. package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +80 -2
  22. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +25 -4
  23. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +183 -36
  24. package/apps/dpi-sdk/src/client.ts +73 -6
  25. package/apps/dpi-sdk/src/protocol/limits.ts +27 -0
  26. package/apps/dpi-sdk/src/protocol/tunnel.ts +18 -10
  27. package/package.json +1 -1
@@ -4,9 +4,11 @@
4
4
  *
5
5
  * A schedule is a stored intent: "every N minutes" or "daily at HH:MM", plus the
6
6
  * cwd, model and prompt a *new* session should start with. The device owns
7
- * execution — nothing here starts a session; the device loop asks `due()` and,
8
- * after the session turn finishes, reports back with `markRun()`. The hub only
9
- * displays what this file says.
7
+ * execution — nothing here starts a session; the device loop asks `due()` and
8
+ * reports back with `markRun()`: once BEFORE the dispatch (the `started` intent
9
+ * marker, so a crash mid-run cannot silently re-fire after a restart) and once
10
+ * when the session turn settles, with the real outcome. The hub only displays
11
+ * what this file says.
10
12
  *
11
13
  * Modelled on orca's `automations/service.ts:186-211` (scheduled trigger +
12
14
  * precheck + completion watcher): a stored `nextRunAt`-style slot per record, an
@@ -47,6 +49,18 @@ export const MAX_EVERY_MINUTES = 1440;
47
49
  const DAILY_AT_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/;
48
50
  const MINUTE_MS = 60_000;
49
51
 
52
+ /**
53
+ * Outcome of the last run. Terminal states: `ok` (the session turn finished)
54
+ * and `failed` (the dispatch or the turn errored). The intermediate states keep
55
+ * a run that has not landed *visible* instead of silent: `started` is the
56
+ * pre-dispatch intent marker (R8 2.4 — written before the session is created),
57
+ * `timeout` means the run outlived its budget and may still complete later,
58
+ * and `interrupted` is what a restart turns a pending `started` into
59
+ * (`recoverInterrupted`). Registries written before R8 only ever contain
60
+ * `ok`/`failed`; both still parse and render unchanged.
61
+ */
62
+ export type ScheduleRunOutcome = "ok" | "failed" | "started" | "timeout" | "interrupted";
63
+
50
64
  /** The model a scheduled session starts on. Same shape the session API takes. */
51
65
  export interface ScheduleModel {
52
66
  provider: string;
@@ -75,12 +89,13 @@ export interface ScheduleRecord {
75
89
  dailyAt?: string;
76
90
  /** Disabled records are never due and `nextRunAt` answers `undefined`. */
77
91
  enabled: boolean;
78
- /** When the last run *finished*, epoch ms — the base the next interval counts from. */
92
+ /** Epoch ms the next interval counts from: stamped by the pre-dispatch intent
93
+ * marker (run start) and re-stamped when the outcome lands. */
79
94
  lastRunAt?: number;
80
95
  /** Session the last run created, so the UI can link to it. */
81
96
  lastSessionId?: string;
82
97
  /** Outcome of the last run; absent means "never run". */
83
- lastOutcome?: "ok" | "failed";
98
+ lastOutcome?: ScheduleRunOutcome;
84
99
  /** Why the last run failed. Cleared by the next successful run. */
85
100
  lastError?: string;
86
101
  createdAt: number;
@@ -291,7 +306,9 @@ export function computeNextRun(record: ScheduleTiming, from: number = Date.now()
291
306
  return undefined;
292
307
  }
293
308
 
294
- const isOutcome = (value: unknown): value is "ok" | "failed" => value === "ok" || value === "failed";
309
+ const RUN_OUTCOMES: readonly ScheduleRunOutcome[] = ["ok", "failed", "started", "timeout", "interrupted"];
310
+ const isOutcome = (value: unknown): value is ScheduleRunOutcome =>
311
+ typeof value === "string" && (RUN_OUTCOMES as readonly string[]).includes(value);
295
312
  const finiteNumber = (value: unknown): number | undefined =>
296
313
  typeof value === "number" && Number.isFinite(value) ? value : undefined;
297
314
 
@@ -547,13 +564,22 @@ export class ScheduleRegistry {
547
564
  }
548
565
 
549
566
  /**
550
- * Record the outcome of one run (called by the device after the session turn).
567
+ * Record one run. Two call shapes:
568
+ *
569
+ * - BEFORE the dispatch, the intent marker `{ outcome: "started" }`: it stamps
570
+ * `lastRunAt` immediately, so a crash in the create→outcome window cannot
571
+ * re-fire the same minute after a restart (the next slot is a full interval
572
+ * out) and the restart surfaces the gap via `recoverInterrupted` (R8 2.4).
573
+ * - when the run lands, `{ sessionId, outcome }` with the terminal state.
574
+ *
551
575
  * `lastRunAt` is the base the next interval counts from, so this is also what
552
- * makes an offline catch-up land once instead of in a burst.
576
+ * makes an offline catch-up land once instead of in a burst. A non-`ok`
577
+ * outcome records `error`; `ok` (and a fresh intent) clears the previous
578
+ * failure reason.
553
579
  */
554
580
  async markRun(
555
581
  id: string,
556
- result: { sessionId?: string; outcome: "ok" | "failed"; error?: string; at?: number },
582
+ result: { sessionId?: string; outcome: ScheduleRunOutcome; error?: string; at?: number },
557
583
  ): Promise<ScheduleRecord> {
558
584
  if (!isOutcome(result?.outcome)) throw invalid(`unknown run outcome ${String(result?.outcome)}`);
559
585
  const at = result.at ?? this.now();
@@ -570,14 +596,42 @@ export class ScheduleRegistry {
570
596
  if (sessionId) next.lastSessionId = sessionId;
571
597
  else delete next.lastSessionId;
572
598
  const error = nonEmptyString(result.error);
573
- if (result.outcome === "failed" && error) next.lastError = error;
574
- else delete next.lastError; // a success clears the reason the last one failed
599
+ if (result.outcome !== "ok" && error) next.lastError = error;
600
+ else delete next.lastError; // a success (or a fresh intent) clears the reason the last one failed
575
601
  staged.set(next.id, next);
576
602
  await this.commit(staged);
577
603
  return clone(next);
578
604
  });
579
605
  }
580
606
 
607
+ /**
608
+ * Boot-time recovery (R8 2.4): a run still marked `started` never recorded its
609
+ * outcome — the daemon died between the intent marker and the write-back. Flip
610
+ * it to `interrupted` so the gap is VISIBLE (the hub shows why the last run has
611
+ * no outcome) instead of silently re-firing: `lastRunAt` was already stamped
612
+ * by the intent marker, so `due()` holds the schedule until its next full
613
+ * slot. Deliberately at-most-once with a visible gap.
614
+ */
615
+ async recoverInterrupted(): Promise<ScheduleRecord[]> {
616
+ return this.run(async () => {
617
+ const staged = new Map(this.records);
618
+ const touched: ScheduleRecord[] = [];
619
+ const at = this.now();
620
+ for (const record of staged.values()) {
621
+ if (record.lastOutcome !== "started") continue;
622
+ const next = clone(record);
623
+ next.lastOutcome = "interrupted";
624
+ next.lastError =
625
+ nonEmptyString(next.lastError) ?? "run was interrupted by a device restart before it recorded an outcome";
626
+ next.updatedAt = at;
627
+ staged.set(next.id, next);
628
+ touched.push(next);
629
+ }
630
+ if (touched.length) await this.commit(staged);
631
+ return touched.map(clone);
632
+ });
633
+ }
634
+
581
635
  private async load(): Promise<void> {
582
636
  // Same guard as `Store.open`/`ProjectRegistry.open`: the data dir holds
583
637
  // credentials-adjacent state, so it is created 0700 or tightened first.
@@ -182,6 +182,12 @@ export interface StoreOptions {
182
182
  envFile?: string;
183
183
  /** Bot token for the Telegram chat bridge; absent = the bridge stays idle. */
184
184
  telegramToken?: string;
185
+ /** R8 schedule-runner budgets, injectable so tests can exercise a wedged
186
+ * dispatch in milliseconds instead of minutes. Defaults: dispatch 60 s,
187
+ * settle cap 120 s, tick 30 s. */
188
+ scheduleDispatchTimeoutMs?: number;
189
+ scheduleSettleCapMs?: number;
190
+ scheduleTickMs?: number;
185
191
  }
186
192
 
187
193
  /** Agent documents a client may read or stream, by kind. */
@@ -195,6 +201,50 @@ const SEARCH_LIMIT = 50;
195
201
  * the timer is unref'd: it never holds the process open. */
196
202
  const SCHEDULE_TICK_MS = 30_000;
197
203
 
204
+ /** Bound on one dispatch's SUBMISSION phase (create + agent resolve + submit —
205
+ * the cwd realpath walk that wedges on a soft-dead mount lives here, R8 2.2).
206
+ * A dispatch that outlives the bound is recorded `timeout` and the in-flight
207
+ * slot is RELEASED: the abandoned attempt may still land its session later
208
+ * (documented at-least-once cost), but no single wedged cwd may halt the loop.
209
+ * The intent marker already stamped lastRunAt, so the next slot is a full
210
+ * interval out — a timeout cannot cause a same-instant refire. */
211
+ const SCHEDULE_DISPATCH_TIMEOUT_MS = 60_000;
212
+
213
+ /** Bound on waiting for the session turn to settle after submit (R8 2.3): the
214
+ * outcome comes from the turn, not from the enqueue, but a stuck provider must
215
+ * not hold the schedule's slot forever. Past the cap the run is recorded
216
+ * `timeout` — an explicit intermediate outcome, never a green "ok". */
217
+ const SCHEDULE_SETTLE_CAP_MS = 120_000;
218
+
219
+ /** R9 2.1: schedule registry persists (markRun) run OUTSIDE the dispatch
220
+ * deadline — a hung dataDir fs would hold the in-flight guard forever
221
+ * (Run-now 409s indefinitely, due-skips forever). Every markRun await is
222
+ * bounded by this cap; the write itself is fire-and-forget-safe (the registry
223
+ * queue still completes it if the fs recovers, and markRun is idempotent per
224
+ * run), so a timed-out persist only loses the CRASH-safety record, never the guard. */
225
+ const SCHEDULE_REGISTRY_IO_MS = 10_000;
226
+
227
+ /**
228
+ * Race `work` against a wall-clock budget. The loser is NOT cancelled: a create
229
+ * that timed out may still complete later (its session shows up in the tree);
230
+ * that is the documented at-least-once behaviour of the schedule dispatch.
231
+ * The catch-offshoot exists only so a loser that rejects after the race can
232
+ * never become an unhandled rejection.
233
+ */
234
+ async function deadline<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
235
+ let timer: ReturnType<typeof setTimeout> | undefined;
236
+ const timeout = new Promise<never>((_, reject) => {
237
+ timer = setTimeout(() => reject(new ApiFault("timeout", message)), ms);
238
+ timer.unref?.();
239
+ });
240
+ work.catch(() => undefined);
241
+ try {
242
+ return await Promise.race([work, timeout]);
243
+ } finally {
244
+ clearTimeout(timer);
245
+ }
246
+ }
247
+
198
248
  /** Starting point for a per-model usage accumulator. */
199
249
  const ZERO_USAGE: UsageSummary = {
200
250
  tokens: 0,
@@ -498,7 +548,13 @@ export class Store {
498
548
 
499
549
  /** Run the base DDL, then the schema-version check and the known-old-shape ladder. */
500
550
  private prepareCatalog(db: DatabaseSync): DatabaseSync {
551
+ // WAL alone still fsyncs the WAL on EVERY commit (synchronous defaults to FULL);
552
+ // NORMAL only fsyncs at checkpoints — R8 measured catalog commits at 7ms p50
553
+ // under FULL vs 0.11ms under NORMAL on this box (scripts/bench-store.mjs,
554
+ // control.commit phases). The per-session transcript DBs already run
555
+ // NORMAL via pi-durable's openNodeSqliteStorage; this makes the catalog match.
501
556
  db.exec(`PRAGMA journal_mode=WAL;
557
+ PRAGMA synchronous=NORMAL;
502
558
  CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY,name TEXT NOT NULL,cwd TEXT NOT NULL,dbPath TEXT NOT NULL UNIQUE,createdAt INTEGER NOT NULL,model TEXT NOT NULL,provider TEXT NOT NULL);
503
559
  CREATE TABLE IF NOT EXISTS conversation_names(sessionId TEXT NOT NULL,conversationId INTEGER NOT NULL,name TEXT NOT NULL,PRIMARY KEY(sessionId,conversationId));
504
560
  CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
@@ -616,6 +672,13 @@ export class Store {
616
672
  store.schedules = await ScheduleRegistry.open(store.schedulesPath, {
617
673
  warn: (m) => process.emitWarning(`schedules: ${m}`),
618
674
  });
675
+ // R8 2.4: runs left "started" by a crash become a visible "interrupted"
676
+ // gap. The intent marker already stamped lastRunAt, so due() holds the
677
+ // schedule until its next full slot — the run is not silently re-fired.
678
+ for (const record of await store.schedules.recoverInterrupted())
679
+ process.emitWarning(
680
+ `schedules: run of "${record.name}" was interrupted by a restart; run it again or wait for its next slot`,
681
+ );
619
682
  store.sinks = await NotifySinks.open(store.notifyPath, {
620
683
  warn: (m) => process.emitWarning(`notify: ${m}`),
621
684
  // ntfy often lives on the LAN; the operator opts in explicitly.
@@ -2486,12 +2549,7 @@ export class Store {
2486
2549
 
2487
2550
  /** Schedules with their computed next run, for any UI that displays them. */
2488
2551
  scheduleList(): ScheduleView[] {
2489
- const at = Date.now();
2490
- return this.schedules.list().map((record) => ({
2491
- ...record,
2492
- nextRunAt: this.schedules.nextRunAt(record, at) ?? null,
2493
- running: this.scheduleInFlight.has(record.id),
2494
- }));
2552
+ return this.schedules.list().map((record) => this.scheduleView(record));
2495
2553
  }
2496
2554
 
2497
2555
  async createSchedule(input: ScheduleCreateInput): Promise<ScheduleView> {
@@ -2518,7 +2576,11 @@ export class Store {
2518
2576
  return { removed };
2519
2577
  }
2520
2578
 
2521
- /** Run one schedule now (the "run" button) — same path the timer takes. */
2579
+ /** Run one schedule now (the "run" button) — same path the timer takes.
2580
+ * Throws ApiFault("busy") (HTTP 409, "already running") when the schedule
2581
+ * has a run in flight: the guard lives in the shared dispatch entry point
2582
+ * (R8 2.1), so a double-clicked Run button gets a typed fault instead of a
2583
+ * second concurrent run with duplicated side effects. */
2522
2584
  async runScheduleNow(id: string): Promise<ScheduleView> {
2523
2585
  const record = this.schedules.get(id);
2524
2586
  if (!record) throw notFound(`no schedule ${id}`);
@@ -2527,30 +2589,57 @@ export class Store {
2527
2589
  }
2528
2590
 
2529
2591
  private scheduleView(record: ScheduleRecord): ScheduleView {
2592
+ // The SDK's ScheduleView union (dpi-sdk/src/api.ts) still lists only
2593
+ // "ok" | "failed"; the intermediate outcomes are ordinary wire strings and
2594
+ // dpi-sdk is not this fix's file, so carry the recorded value through with
2595
+ // a narrowing cast. UIs treat the field as opaque text.
2596
+ const { lastOutcome, ...rest } = record;
2530
2597
  return {
2531
- ...record,
2598
+ ...rest,
2599
+ ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
2532
2600
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
2533
2601
  running: this.scheduleInFlight.has(record.id),
2534
2602
  };
2535
2603
  }
2536
2604
 
2537
- /** Ids with a turn in flight: `due()` keeps returning a record until `markRun`
2538
- * lands, so the loop must not dispatch the same schedule twice. */
2605
+ /** Ids with a run in flight. ONE guarded entry point (dispatchSchedule): the
2606
+ * timer loop and "Run now" both dispatch through it, so the guard cannot be
2607
+ * bypassed the way the old timer-only check was (R8 2.1). */
2539
2608
  private scheduleInFlight = new Set<string>();
2540
2609
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2541
2610
 
2611
+ /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2612
+ * dispatches in milliseconds instead of minutes). */
2613
+ private get scheduleTickMs(): number {
2614
+ return this.options.scheduleTickMs ?? SCHEDULE_TICK_MS;
2615
+ }
2616
+
2617
+ private get dispatchTimeoutMs(): number {
2618
+ return this.options.scheduleDispatchTimeoutMs ?? SCHEDULE_DISPATCH_TIMEOUT_MS;
2619
+ }
2620
+
2621
+ private get settleCapMs(): number {
2622
+ return this.options.scheduleSettleCapMs ?? SCHEDULE_SETTLE_CAP_MS;
2623
+ }
2624
+
2542
2625
  /** The device owns the clock (orca automations): a 30 s tick is plenty for a
2543
2626
  * minute-granularity schedule and costs nothing when there is none. */
2544
2627
  private startScheduler() {
2545
2628
  if (this.scheduleTimer) return;
2546
2629
  const tick = () => {
2547
- this.scheduleTimer = setTimeout(() => {
2548
- void this.runDueSchedules().finally(tick);
2549
- }, SCHEDULE_TICK_MS);
2630
+ // R8 2.2: re-arm BEFORE the pass runs. Chaining the next tick on run
2631
+ // completion (`runDueSchedules().finally(tick)`) let ONE wedged dispatch
2632
+ // — a cwd on a soft-dead NFS mount whose realpath never resolves — hold
2633
+ // the chain open forever and silently halt every schedule on the device.
2634
+ // Dispatches are individually bounded (dispatchSchedule), but the pass
2635
+ // also awaits registry persists and settle waits; the timer must never
2636
+ // depend on any of them. Overlapping passes are safe: the in-flight guard
2637
+ // is per schedule id.
2638
+ this.scheduleTimer = setTimeout(tick, this.scheduleTickMs);
2550
2639
  this.scheduleTimer.unref?.();
2640
+ void this.runDueSchedules().catch(() => undefined);
2551
2641
  };
2552
2642
  tick();
2553
- void this.runDueSchedules();
2554
2643
  }
2555
2644
 
2556
2645
  private stopScheduler() {
@@ -2572,45 +2661,128 @@ export class Store {
2572
2661
  /**
2573
2662
  * A schedule run = a fresh session (so each run has its own transcript and
2574
2663
  * nothing overwrites yesterday's work), the prompt sent to its root agent,
2575
- * then the outcome recorded. Failures are recorded, never thrown: a broken
2576
- * schedule must not stop the loop or the daemon.
2664
+ * then the outcome recorded from the session TURN (not from the enqueue).
2665
+ * Failures are recorded, never thrown: a broken schedule must not stop the
2666
+ * loop or the daemon — the one exception is the in-flight guard, which the
2667
+ * caller sees as a typed busy fault.
2668
+ *
2669
+ * R8 2.1: this is the ONE guarded entry point; check and add have no await
2670
+ * between them, so within the process they are atomic.
2671
+ * R8 2.4: the intent marker (`lastRunAt` + outcome "started") is persisted
2672
+ * BEFORE the session is created, so a crash in the create→outcome window
2673
+ * leaves a visible "interrupted" record after restart instead of silently
2674
+ * re-firing the same minute.
2577
2675
  */
2578
- private async dispatchSchedule(record: ScheduleRecord) {
2676
+ private async dispatchSchedule(record: ScheduleRecord): Promise<void> {
2677
+ if (this.scheduleInFlight.has(record.id)) {
2678
+ throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
2679
+ }
2579
2680
  this.scheduleInFlight.add(record.id);
2580
2681
  this.notify();
2581
- let sessionId: string | undefined;
2582
2682
  try {
2583
- const session = await this.create({
2584
- name: `${record.name} · ${new Date().toISOString().slice(0, 16).replace("T", " ")}`,
2585
- cwd: record.cwd,
2586
- model: record.model,
2587
- });
2588
- sessionId = session.id;
2589
- const { c } = await this.resolveAgent(session.id, "main");
2590
- await this.send(c, { content: record.prompt, requestId: `schedule-${record.id}-${Date.now()}` });
2591
- await this.schedules.markRun(record.id, { sessionId, outcome: "ok" });
2592
- void this.notifyEvent({
2593
- kind: "schedule.ok",
2594
- title: `Schedule ran: ${record.name}`,
2595
- body: `${this.name} started a session for "${record.name}" in ${record.cwd}.`,
2596
- data: { scheduleId: record.id, sessionId },
2597
- });
2598
- } catch (e) {
2599
- const detail = e instanceof Error ? e.message : String(e);
2600
- await this.schedules.markRun(record.id, {
2601
- ...(sessionId ? { sessionId } : {}),
2602
- outcome: "failed",
2603
- error: detail.slice(0, 300),
2604
- }).catch(() => undefined);
2683
+ // Persist the intent before any await that can wedge. If this persist
2684
+ // itself fails (disk full), the run still proceeds — it just loses the
2685
+ // crash-safety guarantee, like every version before R8.
2686
+ await deadline(
2687
+ this.schedules.markRun(record.id, { outcome: "started" }),
2688
+ SCHEDULE_REGISTRY_IO_MS,
2689
+ "schedule registry write timed out (started)",
2690
+ ).catch(() => undefined);
2691
+ await this.dispatchBounded(record);
2692
+ } finally {
2693
+ this.scheduleInFlight.delete(record.id);
2694
+ this.notify();
2695
+ }
2696
+ }
2697
+
2698
+ /**
2699
+ * The bounded body of one dispatch: submit, wait for the turn, record the
2700
+ * outcome. Never throws — every path lands in a recorded outcome.
2701
+ *
2702
+ * R8 2.2: the submission phase (create + resolve + submit) races a wall-clock
2703
+ * deadline, so a wedged cwd becomes a recorded `timeout` and the loop moves
2704
+ * on; the abandoned attempt is NOT cancelled and may still complete later
2705
+ * (at-least-once, visible as a stray session in the tree).
2706
+ * R8 2.3: `send` only enqueues, so the outcome is taken from `settled()` —
2707
+ * `done` → ok, `unanswered` → failed, still queued/pending at the cap →
2708
+ * `timeout` (explicit intermediate, never a green "ok").
2709
+ */
2710
+ private async dispatchBounded(record: ScheduleRecord): Promise<void> {
2711
+ let sessionId: string | undefined;
2712
+ const recordFailure = async (outcome: "failed" | "timeout", detail: string) => {
2713
+ await deadline(
2714
+ this.schedules.markRun(record.id, {
2715
+ ...(sessionId ? { sessionId } : {}),
2716
+ outcome,
2717
+ error: detail.slice(0, 300),
2718
+ }),
2719
+ SCHEDULE_REGISTRY_IO_MS,
2720
+ "schedule registry write timed out (failure)",
2721
+ ).catch(() => undefined);
2605
2722
  void this.notifyEvent({
2606
2723
  kind: "schedule.failed",
2607
2724
  title: `Schedule failed: ${record.name}`,
2608
2725
  body: detail.slice(0, 300),
2609
2726
  data: { scheduleId: record.id },
2610
2727
  });
2611
- } finally {
2612
- this.scheduleInFlight.delete(record.id);
2613
- this.notify();
2728
+ };
2729
+ try {
2730
+ const submitted = await deadline(
2731
+ (async () => {
2732
+ const session = await this.create({
2733
+ name: `${record.name} · ${new Date().toISOString().slice(0, 16).replace("T", " ")}`,
2734
+ cwd: record.cwd,
2735
+ model: record.model,
2736
+ });
2737
+ sessionId = session.id;
2738
+ const { c, h } = await this.resolveAgent(session.id, "main");
2739
+ const submission = await this.send(c, {
2740
+ content: record.prompt,
2741
+ requestId: `schedule-${record.id}-${Date.now()}`,
2742
+ });
2743
+ return { h, submission };
2744
+ })(),
2745
+ this.dispatchTimeoutMs,
2746
+ `dispatch timed out after ${this.dispatchTimeoutMs / 1000}s`,
2747
+ );
2748
+ let result: SendResult;
2749
+ try {
2750
+ // The settle phase: wait (bounded) for the TURN's terminal state.
2751
+ result = await this.settled(submitted.h, submitted.submission.id as number, this.settleCapMs);
2752
+ } catch (e) {
2753
+ await recordFailure("failed", e instanceof Error ? e.message : String(e));
2754
+ return;
2755
+ }
2756
+ if (result.status === "done") {
2757
+ await deadline(
2758
+ this.schedules.markRun(record.id, { sessionId, outcome: "ok" }),
2759
+ SCHEDULE_REGISTRY_IO_MS,
2760
+ "schedule registry write timed out (ok)",
2761
+ ).catch(() => undefined);
2762
+ void this.notifyEvent({
2763
+ kind: "schedule.ok",
2764
+ title: `Schedule ran: ${record.name}`,
2765
+ body: `${this.name} finished a run of "${record.name}" in ${record.cwd} (session ${sessionId}).`,
2766
+ data: { scheduleId: record.id, sessionId },
2767
+ });
2768
+ return;
2769
+ }
2770
+ if (result.status === "unanswered") {
2771
+ await recordFailure(
2772
+ "failed",
2773
+ `schedule turn ended without an answer${result.reason ? `: ${result.reason}` : ""}`,
2774
+ );
2775
+ return;
2776
+ }
2777
+ await recordFailure(
2778
+ "timeout",
2779
+ `turn did not finish within ${this.settleCapMs / 1000}s; it may still complete in session ${sessionId}`,
2780
+ );
2781
+ } catch (e) {
2782
+ // The submission-phase deadline lands here as a typed timeout fault;
2783
+ // everything else is a dispatch error. Both are recorded, never thrown.
2784
+ const timedOut = e instanceof ApiFault && e.code === "timeout";
2785
+ await recordFailure(timedOut ? "timeout" : "failed", e instanceof Error ? e.message : String(e));
2614
2786
  }
2615
2787
  }
2616
2788
 
@@ -98,16 +98,16 @@ const BACKPRESSURE_CLOSE_GRACE_MS = 1_000;
98
98
  * cap is refused on the headers, an undeclared one is cut off as soon as the bytes read pass it, and in both
99
99
  * cases the loopback connection is abandoned.
100
100
  */
101
- async function readTextCapped(
101
+ async function readBodyCapped(
102
102
  res: Response,
103
103
  cap: number,
104
- ): Promise<{ ok: true; text: string } | { ok: false }> {
104
+ ): Promise<{ ok: true; bytes: Buffer } | { ok: false }> {
105
105
  const declared = Number(res.headers.get("content-length"));
106
106
  if (Number.isFinite(declared) && declared > cap) {
107
107
  await res.body?.cancel().catch(() => {});
108
108
  return { ok: false };
109
109
  }
110
- if (!res.body) return { ok: true, text: "" };
110
+ if (!res.body) return { ok: true, bytes: Buffer.alloc(0) };
111
111
  const reader = res.body.getReader();
112
112
  const parts: Uint8Array[] = [];
113
113
  let total = 0;
@@ -121,9 +121,23 @@ async function readTextCapped(
121
121
  }
122
122
  parts.push(value);
123
123
  }
124
- return { ok: true, text: new TextDecoder().decode(Buffer.concat(parts, total)) };
124
+ return { ok: true, bytes: Buffer.concat(parts, total) };
125
125
  }
126
126
 
127
+ /** Wire-textual content types ride the rest-response envelope as plain UTF-8 (as they always have);
128
+ * anything else (zip, octet-stream, images...) is base64-flagged so the hub can pass bytes through
129
+ * byte-exact. R8 binary passthrough — the envelope gains optional bodyEncoding/contentDisposition,
130
+ * absent for textual responses so older hubs see an unchanged frame. */
131
+ const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
132
+ /** base64 inflates by 4/3 and the serialized envelope must still fit the chunk budget
133
+ * (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom. */
134
+ const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
135
+ const safeHeaderValue = (value: string | null | undefined): string | undefined => {
136
+ if (!value) return undefined;
137
+ const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
138
+ return clean.length > 0 ? clean : undefined;
139
+ };
140
+
127
141
  export type ConnectorState =
128
142
  | "stopped" // not started / stopped by operator or shutdown
129
143
  | "file-error" // pairing.json unreadable at startup; no network attempts
@@ -718,19 +732,37 @@ export class DeviceConnector {
718
732
  });
719
733
  return;
720
734
  }
721
- const read = await readTextCapped(res, LOGICAL_MESSAGE_MAX_BYTES);
735
+ const resCt = res.headers.get("content-type") ?? undefined;
736
+ const textual = resCt === undefined || TEXTUAL_CT_RE.test(resCt);
737
+ const read = await readBodyCapped(res, textual ? LOGICAL_MESSAGE_MAX_BYTES : BINARY_RESPONSE_MAX_BYTES);
722
738
  if (!read.ok) {
723
- tooLarge(`Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`);
739
+ tooLarge(
740
+ textual
741
+ ? `Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`
742
+ : `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget`,
743
+ );
724
744
  return;
725
745
  }
726
746
  // Small responses ride one frame; large ones chunk (hub reassembles).
727
- const envelope = {
728
- type: "rest-response",
729
- reqId: frame.reqId,
730
- status: res.status,
731
- contentType: res.headers.get("content-type") ?? undefined,
732
- body: read.text,
733
- } as const;
747
+ // Textual bodies keep the legacy UTF-8 string envelope; binaries are
748
+ // base64-flagged so the hub can serve bytes byte-exact (R8 export).
749
+ const envelope = textual
750
+ ? ({
751
+ type: "rest-response",
752
+ reqId: frame.reqId,
753
+ status: res.status,
754
+ contentType: resCt,
755
+ body: read.bytes.toString("utf8"),
756
+ } as const)
757
+ : ({
758
+ type: "rest-response",
759
+ reqId: frame.reqId,
760
+ status: res.status,
761
+ contentType: resCt,
762
+ body: read.bytes.toString("base64"),
763
+ bodyEncoding: "base64",
764
+ contentDisposition: safeHeaderValue(res.headers.get("content-disposition")),
765
+ } as const);
734
766
  const serialized = JSON.stringify(envelope);
735
767
  if (Buffer.byteLength(serialized, "utf8") <= INLINE_FRAME_MAX_BYTES) {
736
768
  await sendPaced(serialized);