my-durable 0.0.60 → 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.
- package/apps/dpi-backend/scripts/bench-store.mjs +284 -0
- package/apps/dpi-backend/src/archived.ts +1 -1
- package/apps/dpi-backend/src/daemon.ts +7 -1
- package/apps/dpi-backend/src/gc.ts +27 -6
- package/apps/dpi-backend/src/main.ts +6 -0
- package/apps/dpi-backend/src/routes.ts +24 -1
- package/apps/dpi-backend/src/salvage.ts +187 -0
- package/apps/dpi-backend/src/schedules.ts +65 -11
- package/apps/dpi-backend/src/store.ts +255 -47
- package/apps/dpi-backend/src/tunnel.ts +45 -13
- package/apps/dpi-backend/src/vitals.ts +72 -0
- package/apps/dpi-backend/src/zip.ts +387 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-4Kyozhl0.js → index-D10XyhhO.js} +23 -23
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BkSQ2clA.css → index-DCz-aq0b.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +10 -13
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +1 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +19 -5
- package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +25 -4
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +23 -1
- package/apps/dpi-sdk/src/client.ts +73 -6
- package/apps/dpi-sdk/src/protocol/tunnel.ts +4 -0
- 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
|
-
*
|
|
9
|
-
*
|
|
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
|
-
/**
|
|
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?:
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
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.
|
|
@@ -77,7 +77,8 @@ import {
|
|
|
77
77
|
type ArchivedView,
|
|
78
78
|
} from "./archived.js";
|
|
79
79
|
import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
|
|
80
|
-
import { zipSync, type ZipEntry } from "./zip.js";
|
|
80
|
+
import { zipSync, EXPORT_RAW_LIMIT_BYTES, type ZipEntry } from "./zip.js";
|
|
81
|
+
import { salvageFailureNote, salvageSessionDb } from "./salvage.js";
|
|
81
82
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync, statSync } from "node:fs";
|
|
82
83
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
83
84
|
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
@@ -181,6 +182,12 @@ export interface StoreOptions {
|
|
|
181
182
|
envFile?: string;
|
|
182
183
|
/** Bot token for the Telegram chat bridge; absent = the bridge stays idle. */
|
|
183
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;
|
|
184
191
|
}
|
|
185
192
|
|
|
186
193
|
/** Agent documents a client may read or stream, by kind. */
|
|
@@ -194,6 +201,42 @@ const SEARCH_LIMIT = 50;
|
|
|
194
201
|
* the timer is unref'd: it never holds the process open. */
|
|
195
202
|
const SCHEDULE_TICK_MS = 30_000;
|
|
196
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
|
+
|
|
197
240
|
/** Starting point for a per-model usage accumulator. */
|
|
198
241
|
const ZERO_USAGE: UsageSummary = {
|
|
199
242
|
tokens: 0,
|
|
@@ -497,7 +540,13 @@ export class Store {
|
|
|
497
540
|
|
|
498
541
|
/** Run the base DDL, then the schema-version check and the known-old-shape ladder. */
|
|
499
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.
|
|
500
548
|
db.exec(`PRAGMA journal_mode=WAL;
|
|
549
|
+
PRAGMA synchronous=NORMAL;
|
|
501
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);
|
|
502
551
|
CREATE TABLE IF NOT EXISTS conversation_names(sessionId TEXT NOT NULL,conversationId INTEGER NOT NULL,name TEXT NOT NULL,PRIMARY KEY(sessionId,conversationId));
|
|
503
552
|
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
@@ -615,6 +664,13 @@ export class Store {
|
|
|
615
664
|
store.schedules = await ScheduleRegistry.open(store.schedulesPath, {
|
|
616
665
|
warn: (m) => process.emitWarning(`schedules: ${m}`),
|
|
617
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
|
+
);
|
|
618
674
|
store.sinks = await NotifySinks.open(store.notifyPath, {
|
|
619
675
|
warn: (m) => process.emitWarning(`notify: ${m}`),
|
|
620
676
|
// ntfy often lives on the LAN; the operator opts in explicitly.
|
|
@@ -1516,8 +1572,43 @@ export class Store {
|
|
|
1516
1572
|
// Custom extensions are installed but not selected: an agent turns them on in its own selection.
|
|
1517
1573
|
const addons = createAddons({ offline: this.options.provider === "faux" });
|
|
1518
1574
|
for (const extension of addons.list) registry.install(extension);
|
|
1575
|
+
// R7: an unreadable db (a corrupt header, per the R5 audit recipe — garbage
|
|
1576
|
+
// bytes 32-64) used to hide intact data forever: the close-path checkpoint
|
|
1577
|
+
// folds the WAL into the corrupt main file without fixing page 1, and the
|
|
1578
|
+
// only recovery was a manual header patch. Before failing the open, ONE
|
|
1579
|
+
// bounded salvage on a COPY (header patch + integrity_check + atomic
|
|
1580
|
+
// promote; see salvage.ts). The original file is never modified — a failed
|
|
1581
|
+
// salvage leaves it byte-identical and the failure surface says so. Any other
|
|
1582
|
+
// open error (a held lock, a schema mismatch) keeps its existing behavior.
|
|
1583
|
+
let storage: Awaited<ReturnType<typeof openNodeSqliteStorage>>;
|
|
1584
|
+
try {
|
|
1585
|
+
storage = await openNodeSqliteStorage(row.dbPath);
|
|
1586
|
+
} catch (error) {
|
|
1587
|
+
if (create || !isUnreadableStorage(error)) throw error;
|
|
1588
|
+
const outcome = await salvageSessionDb(row.dbPath);
|
|
1589
|
+
if (!outcome.recovered) {
|
|
1590
|
+
const note = salvageFailureNote(outcome);
|
|
1591
|
+
const previous = this.errors.get(row.id);
|
|
1592
|
+
this.errors.set(row.id, note); // rides the session summary and every later fault
|
|
1593
|
+
this.notify();
|
|
1594
|
+
// Same operator visibility failSession gives a mid-run failure — once per
|
|
1595
|
+
// distinct note, so repeated failed opens do not spam the sinks.
|
|
1596
|
+
if (previous !== note)
|
|
1597
|
+
void this.notifyEvent({
|
|
1598
|
+
kind: "session.failed",
|
|
1599
|
+
title: `Session failed on ${this.name}`,
|
|
1600
|
+
body: `${this.sessionName(row.id)}: ${note}`,
|
|
1601
|
+
data: { sessionId: row.id, device: this.name },
|
|
1602
|
+
});
|
|
1603
|
+
throw new ApiFault("unavailable", note);
|
|
1604
|
+
}
|
|
1605
|
+
process.emitWarning(
|
|
1606
|
+
`[dpi-backend] session ${row.id}'s database was unreadable; salvaged a copy (original kept as ${outcome.keptAs})`,
|
|
1607
|
+
);
|
|
1608
|
+
storage = await openNodeSqliteStorage(row.dbPath); // the ONE retry, on the promoted copy
|
|
1609
|
+
}
|
|
1519
1610
|
const harness = await Harness.open(
|
|
1520
|
-
|
|
1611
|
+
storage,
|
|
1521
1612
|
{
|
|
1522
1613
|
models: this.models,
|
|
1523
1614
|
registry,
|
|
@@ -1895,6 +1986,10 @@ export class Store {
|
|
|
1895
1986
|
h = await this.reopenOnce(row);
|
|
1896
1987
|
} catch (retryError) {
|
|
1897
1988
|
if (isStorageBusy(retryError)) throw storageBusyFault();
|
|
1989
|
+
// R7: a reopen that failed with its own typed fault (a salvage that was
|
|
1990
|
+
// attempted and did not recover) is MORE specific than the recorded
|
|
1991
|
+
// "Session X is unavailable" this path used to re-throw — surface it.
|
|
1992
|
+
if (retryError instanceof ApiFault) throw retryError;
|
|
1898
1993
|
throw e; // the recorded, bounded reason — never the raw storage error
|
|
1899
1994
|
}
|
|
1900
1995
|
}
|
|
@@ -2404,19 +2499,35 @@ export class Store {
|
|
|
2404
2499
|
session: { id: row.id, name: row.name, cwd: row.cwd, model: row.model, createdAt: row.createdAt },
|
|
2405
2500
|
agents: agents.map((a) => ({ id: a.id, name: a.name, kind: a.kind })),
|
|
2406
2501
|
};
|
|
2407
|
-
files.push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
|
|
2408
|
-
files.push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
|
|
2409
2502
|
const opened = this.opened.get(row.id);
|
|
2503
|
+
// R7 memory guard: every entry text is held in RAM at zip time, and the zip
|
|
2504
|
+
// writer adds deflate + base64 copies (≈2-3× raw). Refuse over the raw limit
|
|
2505
|
+
// BEFORE the second copy exists — checked as files accumulate so a huge
|
|
2506
|
+
// transcript also skips the per-agent extras that would follow it.
|
|
2507
|
+
let rawBytes = 0;
|
|
2508
|
+
const push = (entry: ZipEntry) => {
|
|
2509
|
+
rawBytes += Buffer.byteLength(entry.text, "utf8");
|
|
2510
|
+
if (rawBytes > EXPORT_RAW_LIMIT_BYTES) {
|
|
2511
|
+
const mb = (n: number) => `${(n / (1024 * 1024)).toFixed(1)} MiB`;
|
|
2512
|
+
throw invalid(
|
|
2513
|
+
`Export refused: transcripts are ${mb(rawBytes)} of text, over the ${mb(EXPORT_RAW_LIMIT_BYTES)} in-memory limit. ` +
|
|
2514
|
+
`Compact the session first, then export again`,
|
|
2515
|
+
);
|
|
2516
|
+
}
|
|
2517
|
+
files.push(entry);
|
|
2518
|
+
};
|
|
2519
|
+
push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
|
|
2520
|
+
push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
|
|
2410
2521
|
for (const agent of agents) {
|
|
2411
2522
|
const c = opened ? await opened.harness.conversation(agent.id as ConversationId, ctx) : undefined;
|
|
2412
2523
|
if (!c) continue;
|
|
2413
2524
|
const dir = `agents/${agent.id}`;
|
|
2414
|
-
|
|
2525
|
+
push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
|
|
2415
2526
|
const md = await this.transcript(c, "markdown");
|
|
2416
|
-
if (typeof md.text === "string")
|
|
2417
|
-
|
|
2527
|
+
if (typeof md.text === "string") push({ path: `${dir}/transcript.md`, text: md.text });
|
|
2528
|
+
push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
|
|
2418
2529
|
}
|
|
2419
|
-
if (!agents.length)
|
|
2530
|
+
if (!agents.length) push({ path: "README.txt", text: NOT_OPENED_README });
|
|
2420
2531
|
const zip = zipSync(files);
|
|
2421
2532
|
return {
|
|
2422
2533
|
filename: `${slugName(row.name || row.id)}.bundle.zip`,
|
|
@@ -2430,12 +2541,7 @@ export class Store {
|
|
|
2430
2541
|
|
|
2431
2542
|
/** Schedules with their computed next run, for any UI that displays them. */
|
|
2432
2543
|
scheduleList(): ScheduleView[] {
|
|
2433
|
-
|
|
2434
|
-
return this.schedules.list().map((record) => ({
|
|
2435
|
-
...record,
|
|
2436
|
-
nextRunAt: this.schedules.nextRunAt(record, at) ?? null,
|
|
2437
|
-
running: this.scheduleInFlight.has(record.id),
|
|
2438
|
-
}));
|
|
2544
|
+
return this.schedules.list().map((record) => this.scheduleView(record));
|
|
2439
2545
|
}
|
|
2440
2546
|
|
|
2441
2547
|
async createSchedule(input: ScheduleCreateInput): Promise<ScheduleView> {
|
|
@@ -2462,7 +2568,11 @@ export class Store {
|
|
|
2462
2568
|
return { removed };
|
|
2463
2569
|
}
|
|
2464
2570
|
|
|
2465
|
-
/** 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. */
|
|
2466
2576
|
async runScheduleNow(id: string): Promise<ScheduleView> {
|
|
2467
2577
|
const record = this.schedules.get(id);
|
|
2468
2578
|
if (!record) throw notFound(`no schedule ${id}`);
|
|
@@ -2471,30 +2581,57 @@ export class Store {
|
|
|
2471
2581
|
}
|
|
2472
2582
|
|
|
2473
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;
|
|
2474
2589
|
return {
|
|
2475
|
-
...
|
|
2590
|
+
...rest,
|
|
2591
|
+
...(lastOutcome === undefined ? {} : { lastOutcome: lastOutcome as ScheduleView["lastOutcome"] }),
|
|
2476
2592
|
nextRunAt: this.schedules.nextRunAt(record, Date.now()) ?? null,
|
|
2477
2593
|
running: this.scheduleInFlight.has(record.id),
|
|
2478
2594
|
};
|
|
2479
2595
|
}
|
|
2480
2596
|
|
|
2481
|
-
/** Ids with a
|
|
2482
|
-
*
|
|
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). */
|
|
2483
2600
|
private scheduleInFlight = new Set<string>();
|
|
2484
2601
|
private scheduleTimer?: ReturnType<typeof setTimeout>;
|
|
2485
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
|
+
|
|
2486
2617
|
/** The device owns the clock (orca automations): a 30 s tick is plenty for a
|
|
2487
2618
|
* minute-granularity schedule and costs nothing when there is none. */
|
|
2488
2619
|
private startScheduler() {
|
|
2489
2620
|
if (this.scheduleTimer) return;
|
|
2490
2621
|
const tick = () => {
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
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);
|
|
2494
2631
|
this.scheduleTimer.unref?.();
|
|
2632
|
+
void this.runDueSchedules().catch(() => undefined);
|
|
2495
2633
|
};
|
|
2496
2634
|
tick();
|
|
2497
|
-
void this.runDueSchedules();
|
|
2498
2635
|
}
|
|
2499
2636
|
|
|
2500
2637
|
private stopScheduler() {
|
|
@@ -2516,34 +2653,54 @@ export class Store {
|
|
|
2516
2653
|
/**
|
|
2517
2654
|
* A schedule run = a fresh session (so each run has its own transcript and
|
|
2518
2655
|
* nothing overwrites yesterday's work), the prompt sent to its root agent,
|
|
2519
|
-
* then the outcome recorded
|
|
2520
|
-
* schedule must not stop the
|
|
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.
|
|
2521
2667
|
*/
|
|
2522
|
-
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
|
+
}
|
|
2523
2672
|
this.scheduleInFlight.add(record.id);
|
|
2524
2673
|
this.notify();
|
|
2525
|
-
let sessionId: string | undefined;
|
|
2526
2674
|
try {
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
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) => {
|
|
2544
2701
|
await this.schedules.markRun(record.id, {
|
|
2545
2702
|
...(sessionId ? { sessionId } : {}),
|
|
2546
|
-
outcome
|
|
2703
|
+
outcome,
|
|
2547
2704
|
error: detail.slice(0, 300),
|
|
2548
2705
|
}).catch(() => undefined);
|
|
2549
2706
|
void this.notifyEvent({
|
|
@@ -2552,9 +2709,60 @@ export class Store {
|
|
|
2552
2709
|
body: detail.slice(0, 300),
|
|
2553
2710
|
data: { scheduleId: record.id },
|
|
2554
2711
|
});
|
|
2555
|
-
}
|
|
2556
|
-
|
|
2557
|
-
|
|
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));
|
|
2558
2766
|
}
|
|
2559
2767
|
}
|
|
2560
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
|
|
101
|
+
async function readBodyCapped(
|
|
102
102
|
res: Response,
|
|
103
103
|
cap: number,
|
|
104
|
-
): Promise<{ ok: true;
|
|
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,
|
|
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,
|
|
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
|
|
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(
|
|
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
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
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);
|