my-durable 0.0.61 → 0.0.62

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.
@@ -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,42 @@ 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
+ /**
220
+ * Race `work` against a wall-clock budget. The loser is NOT cancelled: a create
221
+ * that timed out may still complete later (its session shows up in the tree);
222
+ * that is the documented at-least-once behaviour of the schedule dispatch.
223
+ * The catch-offshoot exists only so a loser that rejects after the race can
224
+ * never become an unhandled rejection.
225
+ */
226
+ async function deadline<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
227
+ let timer: ReturnType<typeof setTimeout> | undefined;
228
+ const timeout = new Promise<never>((_, reject) => {
229
+ timer = setTimeout(() => reject(new ApiFault("timeout", message)), ms);
230
+ timer.unref?.();
231
+ });
232
+ work.catch(() => undefined);
233
+ try {
234
+ return await Promise.race([work, timeout]);
235
+ } finally {
236
+ clearTimeout(timer);
237
+ }
238
+ }
239
+
198
240
  /** Starting point for a per-model usage accumulator. */
199
241
  const ZERO_USAGE: UsageSummary = {
200
242
  tokens: 0,
@@ -498,7 +540,13 @@ export class Store {
498
540
 
499
541
  /** Run the base DDL, then the schema-version check and the known-old-shape ladder. */
500
542
  private prepareCatalog(db: DatabaseSync): DatabaseSync {
543
+ // WAL alone still fsyncs the WAL on EVERY commit (synchronous defaults to FULL);
544
+ // NORMAL only fsyncs at checkpoints — R8 measured catalog commits at 7ms p50
545
+ // under FULL vs 0.11ms under NORMAL on this box (scripts/bench-store.mjs,
546
+ // control.commit phases). The per-session transcript DBs already run
547
+ // NORMAL via pi-durable's openNodeSqliteStorage; this makes the catalog match.
501
548
  db.exec(`PRAGMA journal_mode=WAL;
549
+ PRAGMA synchronous=NORMAL;
502
550
  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
551
  CREATE TABLE IF NOT EXISTS conversation_names(sessionId TEXT NOT NULL,conversationId INTEGER NOT NULL,name TEXT NOT NULL,PRIMARY KEY(sessionId,conversationId));
504
552
  CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
@@ -616,6 +664,13 @@ export class Store {
616
664
  store.schedules = await ScheduleRegistry.open(store.schedulesPath, {
617
665
  warn: (m) => process.emitWarning(`schedules: ${m}`),
618
666
  });
667
+ // R8 2.4: runs left "started" by a crash become a visible "interrupted"
668
+ // gap. The intent marker already stamped lastRunAt, so due() holds the
669
+ // schedule until its next full slot — the run is not silently re-fired.
670
+ for (const record of await store.schedules.recoverInterrupted())
671
+ process.emitWarning(
672
+ `schedules: run of "${record.name}" was interrupted by a restart; run it again or wait for its next slot`,
673
+ );
619
674
  store.sinks = await NotifySinks.open(store.notifyPath, {
620
675
  warn: (m) => process.emitWarning(`notify: ${m}`),
621
676
  // ntfy often lives on the LAN; the operator opts in explicitly.
@@ -2486,12 +2541,7 @@ export class Store {
2486
2541
 
2487
2542
  /** Schedules with their computed next run, for any UI that displays them. */
2488
2543
  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
- }));
2544
+ return this.schedules.list().map((record) => this.scheduleView(record));
2495
2545
  }
2496
2546
 
2497
2547
  async createSchedule(input: ScheduleCreateInput): Promise<ScheduleView> {
@@ -2518,7 +2568,11 @@ export class Store {
2518
2568
  return { removed };
2519
2569
  }
2520
2570
 
2521
- /** Run one schedule now (the "run" button) — same path the timer takes. */
2571
+ /** Run one schedule now (the "run" button) — same path the timer takes.
2572
+ * Throws ApiFault("busy") (HTTP 409, "already running") when the schedule
2573
+ * has a run in flight: the guard lives in the shared dispatch entry point
2574
+ * (R8 2.1), so a double-clicked Run button gets a typed fault instead of a
2575
+ * second concurrent run with duplicated side effects. */
2522
2576
  async runScheduleNow(id: string): Promise<ScheduleView> {
2523
2577
  const record = this.schedules.get(id);
2524
2578
  if (!record) throw notFound(`no schedule ${id}`);
@@ -2527,30 +2581,57 @@ export class Store {
2527
2581
  }
2528
2582
 
2529
2583
  private scheduleView(record: ScheduleRecord): ScheduleView {
2584
+ // The SDK's ScheduleView union (dpi-sdk/src/api.ts) still lists only
2585
+ // "ok" | "failed"; the intermediate outcomes are ordinary wire strings and
2586
+ // dpi-sdk is not this fix's file, so carry the recorded value through with
2587
+ // a narrowing cast. UIs treat the field as opaque text.
2588
+ const { lastOutcome, ...rest } = record;
2530
2589
  return {
2531
- ...record,
2590
+ ...rest,
2591
+ ...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
2532
2592
  nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
2533
2593
  running: this.scheduleInFlight.has(record.id),
2534
2594
  };
2535
2595
  }
2536
2596
 
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. */
2597
+ /** Ids with a run in flight. ONE guarded entry point (dispatchSchedule): the
2598
+ * timer loop and "Run now" both dispatch through it, so the guard cannot be
2599
+ * bypassed the way the old timer-only check was (R8 2.1). */
2539
2600
  private scheduleInFlight = new Set<string>();
2540
2601
  private scheduleTimer?: ReturnType<typeof setTimeout>;
2541
2602
 
2603
+ /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2604
+ * dispatches in milliseconds instead of minutes). */
2605
+ private get scheduleTickMs(): number {
2606
+ return this.options.scheduleTickMs ?? SCHEDULE_TICK_MS;
2607
+ }
2608
+
2609
+ private get dispatchTimeoutMs(): number {
2610
+ return this.options.scheduleDispatchTimeoutMs ?? SCHEDULE_DISPATCH_TIMEOUT_MS;
2611
+ }
2612
+
2613
+ private get settleCapMs(): number {
2614
+ return this.options.scheduleSettleCapMs ?? SCHEDULE_SETTLE_CAP_MS;
2615
+ }
2616
+
2542
2617
  /** The device owns the clock (orca automations): a 30 s tick is plenty for a
2543
2618
  * minute-granularity schedule and costs nothing when there is none. */
2544
2619
  private startScheduler() {
2545
2620
  if (this.scheduleTimer) return;
2546
2621
  const tick = () => {
2547
- this.scheduleTimer = setTimeout(() => {
2548
- void this.runDueSchedules().finally(tick);
2549
- }, SCHEDULE_TICK_MS);
2622
+ // R8 2.2: re-arm BEFORE the pass runs. Chaining the next tick on run
2623
+ // completion (`runDueSchedules().finally(tick)`) let ONE wedged dispatch
2624
+ // — a cwd on a soft-dead NFS mount whose realpath never resolves — hold
2625
+ // the chain open forever and silently halt every schedule on the device.
2626
+ // Dispatches are individually bounded (dispatchSchedule), but the pass
2627
+ // also awaits registry persists and settle waits; the timer must never
2628
+ // depend on any of them. Overlapping passes are safe: the in-flight guard
2629
+ // is per schedule id.
2630
+ this.scheduleTimer = setTimeout(tick, this.scheduleTickMs);
2550
2631
  this.scheduleTimer.unref?.();
2632
+ void this.runDueSchedules().catch(() => undefined);
2551
2633
  };
2552
2634
  tick();
2553
- void this.runDueSchedules();
2554
2635
  }
2555
2636
 
2556
2637
  private stopScheduler() {
@@ -2572,34 +2653,54 @@ export class Store {
2572
2653
  /**
2573
2654
  * A schedule run = a fresh session (so each run has its own transcript and
2574
2655
  * 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.
2656
+ * then the outcome recorded from the session TURN (not from the enqueue).
2657
+ * Failures are recorded, never thrown: a broken schedule must not stop the
2658
+ * loop or the daemon — the one exception is the in-flight guard, which the
2659
+ * caller sees as a typed busy fault.
2660
+ *
2661
+ * R8 2.1: this is the ONE guarded entry point; check and add have no await
2662
+ * between them, so within the process they are atomic.
2663
+ * R8 2.4: the intent marker (`lastRunAt` + outcome "started") is persisted
2664
+ * BEFORE the session is created, so a crash in the create→outcome window
2665
+ * leaves a visible "interrupted" record after restart instead of silently
2666
+ * re-firing the same minute.
2577
2667
  */
2578
- private async dispatchSchedule(record: ScheduleRecord) {
2668
+ private async dispatchSchedule(record: ScheduleRecord): Promise<void> {
2669
+ if (this.scheduleInFlight.has(record.id)) {
2670
+ throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
2671
+ }
2579
2672
  this.scheduleInFlight.add(record.id);
2580
2673
  this.notify();
2581
- let sessionId: string | undefined;
2582
2674
  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);
2675
+ // Persist the intent before any await that can wedge. If this persist
2676
+ // itself fails (disk full), the run still proceeds — it just loses the
2677
+ // crash-safety guarantee, like every version before R8.
2678
+ await this.schedules.markRun(record.id, { outcome: "started" }).catch(() => undefined);
2679
+ await this.dispatchBounded(record);
2680
+ } finally {
2681
+ this.scheduleInFlight.delete(record.id);
2682
+ this.notify();
2683
+ }
2684
+ }
2685
+
2686
+ /**
2687
+ * The bounded body of one dispatch: submit, wait for the turn, record the
2688
+ * outcome. Never throws — every path lands in a recorded outcome.
2689
+ *
2690
+ * R8 2.2: the submission phase (create + resolve + submit) races a wall-clock
2691
+ * deadline, so a wedged cwd becomes a recorded `timeout` and the loop moves
2692
+ * on; the abandoned attempt is NOT cancelled and may still complete later
2693
+ * (at-least-once, visible as a stray session in the tree).
2694
+ * R8 2.3: `send` only enqueues, so the outcome is taken from `settled()` —
2695
+ * `done` → ok, `unanswered` → failed, still queued/pending at the cap →
2696
+ * `timeout` (explicit intermediate, never a green "ok").
2697
+ */
2698
+ private async dispatchBounded(record: ScheduleRecord): Promise<void> {
2699
+ let sessionId: string | undefined;
2700
+ const recordFailure = async (outcome: "failed" | "timeout", detail: string) => {
2600
2701
  await this.schedules.markRun(record.id, {
2601
2702
  ...(sessionId ? { sessionId } : {}),
2602
- outcome: "failed",
2703
+ outcome,
2603
2704
  error: detail.slice(0, 300),
2604
2705
  }).catch(() => undefined);
2605
2706
  void this.notifyEvent({
@@ -2608,9 +2709,60 @@ export class Store {
2608
2709
  body: detail.slice(0, 300),
2609
2710
  data: { scheduleId: record.id },
2610
2711
  });
2611
- } finally {
2612
- this.scheduleInFlight.delete(record.id);
2613
- this.notify();
2712
+ };
2713
+ try {
2714
+ const submitted = await deadline(
2715
+ (async () => {
2716
+ const session = await this.create({
2717
+ name: `${record.name} · ${new Date().toISOString().slice(0, 16).replace("T", " ")}`,
2718
+ cwd: record.cwd,
2719
+ model: record.model,
2720
+ });
2721
+ sessionId = session.id;
2722
+ const { c, h } = await this.resolveAgent(session.id, "main");
2723
+ const submission = await this.send(c, {
2724
+ content: record.prompt,
2725
+ requestId: `schedule-${record.id}-${Date.now()}`,
2726
+ });
2727
+ return { h, submission };
2728
+ })(),
2729
+ this.dispatchTimeoutMs,
2730
+ `dispatch timed out after ${this.dispatchTimeoutMs / 1000}s`,
2731
+ );
2732
+ let result: SendResult;
2733
+ try {
2734
+ // The settle phase: wait (bounded) for the TURN's terminal state.
2735
+ result = await this.settled(submitted.h, submitted.submission.id as number, this.settleCapMs);
2736
+ } catch (e) {
2737
+ await recordFailure("failed", e instanceof Error ? e.message : String(e));
2738
+ return;
2739
+ }
2740
+ if (result.status === "done") {
2741
+ await this.schedules.markRun(record.id, { sessionId, outcome: "ok" }).catch(() => undefined);
2742
+ void this.notifyEvent({
2743
+ kind: "schedule.ok",
2744
+ title: `Schedule ran: ${record.name}`,
2745
+ body: `${this.name} finished a run of "${record.name}" in ${record.cwd} (session ${sessionId}).`,
2746
+ data: { scheduleId: record.id, sessionId },
2747
+ });
2748
+ return;
2749
+ }
2750
+ if (result.status === "unanswered") {
2751
+ await recordFailure(
2752
+ "failed",
2753
+ `schedule turn ended without an answer${result.reason ? `: ${result.reason}` : ""}`,
2754
+ );
2755
+ return;
2756
+ }
2757
+ await recordFailure(
2758
+ "timeout",
2759
+ `turn did not finish within ${this.settleCapMs / 1000}s; it may still complete in session ${sessionId}`,
2760
+ );
2761
+ } catch (e) {
2762
+ // The submission-phase deadline lands here as a typed timeout fault;
2763
+ // everything else is a dispatch error. Both are recorded, never thrown.
2764
+ const timedOut = e instanceof ApiFault && e.code === "timeout";
2765
+ await recordFailure(timedOut ? "timeout" : "failed", e instanceof Error ? e.message : String(e));
2614
2766
  }
2615
2767
  }
2616
2768
 
@@ -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);