my-durable 0.0.44 → 0.0.45

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.
@@ -40,7 +40,14 @@ export const NOTIFY_HELP = `dpi notify — outbound notifications (webhook / ntf
40
40
  LAN sinks (http://192.168.x.x, http://localhost) are refused by default:
41
41
  start the device with DPI_NOTIFY_ALLOW_PRIVATE=1 to allow them.`;
42
42
 
43
- export const EMITTED_EVENTS = ["session.failed", "schedule.ok", "schedule.failed", "test"] as const;
43
+ export const EMITTED_EVENTS = [
44
+ "session.failed",
45
+ "schedule.ok",
46
+ "schedule.failed",
47
+ "graph.ok",
48
+ "graph.failed",
49
+ "test",
50
+ ] as const;
44
51
 
45
52
  export const defaultNotifyIo = (): ScheduleIo => ({
46
53
  ...defaultDoctorIo(),
@@ -5,7 +5,7 @@ import type { Conversation, Harness } from "@earendil-works/pi-durable";
5
5
  import { DEVICE_DOC_KINDS, type SessionRow, type Store } from "./store.js";
6
6
  import { agentStream, deviceStream, sessionStream } from "./streams.js";
7
7
  import { idempotent } from "./idempotency.js";
8
- import { invalid } from "./errors.js";
8
+ import { invalid, notFound } from "./errors.js";
9
9
  import type { DevicePairing } from "./pairing.js";
10
10
 
11
11
  type Async = (req: Request, res: Response) => Promise<unknown>;
@@ -216,6 +216,23 @@ export function v1(
216
216
  r.delete("/notify/sinks/:id", route(async (req, res) => res.json(await store.removeNotifySink(param(req, "id")))));
217
217
  r.post("/notify/test", route(async (_req, res) => res.json({ results: await store.testNotifySinks() })));
218
218
 
219
+ // ----------------------------------------------------- task-graphs
220
+ // The device owns execution (sequential, topological); these routes only
221
+ // read, edit and START a run — the answer streams back through the tree.
222
+ r.get("/graphs", (req, res) => {
223
+ const includeArchived = req.query.includeArchived === "1" || req.query.includeArchived === "true";
224
+ res.json({ graphs: store.graphList(includeArchived) });
225
+ });
226
+ r.get("/graphs/:id", route(async (req, res) => {
227
+ const found = store.graphGet(param(req, "id"));
228
+ if (!found) throw notFound(`no graph ${param(req, "id")}`);
229
+ res.json(found);
230
+ }));
231
+ r.post("/graphs", route(async (req, res) => res.status(201).json(await store.createGraph(req.body ?? {}))));
232
+ r.patch("/graphs/:id", route(async (req, res) => res.json(await store.updateGraph(param(req, "id"), req.body ?? {}))));
233
+ r.delete("/graphs/:id", route(async (req, res) => res.json(await store.removeGraph(param(req, "id")))));
234
+ r.post("/graphs/:id/run", route(async (req, res) => res.status(202).json(await store.runGraphNow(param(req, "id")))));
235
+
219
236
  // -------------------------------------------------------- schedules
220
237
  // The device owns execution (systemd/cron are deliberately rejected by config);
221
238
  // these routes only read and edit the schedule records.
@@ -53,6 +53,14 @@ import { ProjectRegistry, type ProjectRecord } from "./projects.js";
53
53
  import { EnvFileEditor, type EnvFileView } from "./env-vars.js";
54
54
  import { KeepAwake } from "./awake.js";
55
55
  import { TelegramBridge, defaultTelegramIo, type TelegramBroker } from "./telegram.js";
56
+ import {
57
+ GraphRegistry,
58
+ readyTasks,
59
+ topoOrder,
60
+ type GraphRecord,
61
+ type GraphRunRecord,
62
+ type GraphTask,
63
+ } from "./graphs.js";
56
64
  import { ScheduleRegistry, type ScheduleCreateInput, type ScheduleRecord } from "./schedules.js";
57
65
  import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
58
66
  import { zipSync, type ZipEntry } from "./zip.js";
@@ -291,6 +299,9 @@ export class Store {
291
299
  private awakeTimer?: ReturnType<typeof setTimeout>;
292
300
  /** Telegram chat bridge (Wave 3): bound chats talk to sessions. */
293
301
  telegram?: TelegramBridge;
302
+ /** Task-graphs (Wave 3): a DAG of prompt-tasks, each run as a fresh session. */
303
+ graphs!: GraphRegistry;
304
+ private graphRunsInFlight = new Set<string>();
294
305
  uid!: string;
295
306
  modelList: ModelInfo[] = [];
296
307
  private unlockCatalog: () => void;
@@ -325,6 +336,9 @@ export class Store {
325
336
  get telegramPath() {
326
337
  return join(this.options.dataDir, "telegram.json");
327
338
  }
339
+ get graphsPath() {
340
+ return join(this.options.dataDir, "graphs.json");
341
+ }
328
342
  get name() {
329
343
  return this.options.name;
330
344
  }
@@ -401,6 +415,13 @@ export class Store {
401
415
  warn: (m) => process.emitWarning(`telegram: ${m}`),
402
416
  });
403
417
  if (options.telegramToken) store.telegram.start(options.telegramToken);
418
+ store.graphs = await GraphRegistry.open(store.graphsPath, {
419
+ warn: (m) => process.emitWarning(`graphs: ${m}`),
420
+ });
421
+ // A restart mid-run never loses the graph: the run flips to interrupted
422
+ // with its running tasks back to pending, and `run` continues from there.
423
+ for (const run of await store.graphs.recoverInterrupted())
424
+ process.emitWarning(`graphs: run ${run.id} of ${run.graphId} was interrupted by a restart; run it again to continue`);
404
425
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
405
426
  store.shared = await SharedState.open(store.sharedStatePath);
406
427
  store.shared.harness.subscribeCommits(() => store.notify());
@@ -842,6 +863,126 @@ export class Store {
842
863
  };
843
864
  }
844
865
 
866
+ // ------------------------------------------------ task-graphs (Wave 3)
867
+
868
+ graphList(includeArchived = false): Array<GraphRecord & { lastRun?: GraphRunRecord }> {
869
+ return this.graphs.list({ includeArchived }).map((g) => ({ ...g, lastRun: this.graphs.lastRun(g.id) }));
870
+ }
871
+
872
+ graphGet(id: string): { graph: GraphRecord; runs: GraphRunRecord[] } | undefined {
873
+ const graph = this.graphs.get(id);
874
+ if (!graph) return undefined;
875
+ return { graph, runs: this.graphs.runs(id) };
876
+ }
877
+
878
+ async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
879
+ const created = await this.graphs.create(body as never);
880
+ this.notify();
881
+ return created;
882
+ }
883
+
884
+ async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
885
+ const updated = await this.graphs.update(id, body as never);
886
+ this.notify();
887
+ return updated;
888
+ }
889
+
890
+ async removeGraph(id: string): Promise<{ removed: boolean }> {
891
+ if (this.graphRunsInFlight.has(id)) throw invalid("this graph is running");
892
+ const removed = await this.graphs.remove(id);
893
+ this.notify();
894
+ return { removed };
895
+ }
896
+
897
+ /**
898
+ * Start a run. Execution is sequential in topological order — deterministic
899
+ * and debuggable on a single device — and happens in the background: the
900
+ * route answers with the run record immediately, statuses flow through the
901
+ * tree and GET /graphs/:id.
902
+ */
903
+ async runGraphNow(id: string): Promise<{ run: GraphRunRecord }> {
904
+ const record = this.graphs.get(id);
905
+ if (!record) throw notFound(`no graph ${id}`);
906
+ if (this.graphRunsInFlight.has(record.id)) throw invalid("this graph is already running");
907
+ const run = await this.graphs.beginRun(record.id);
908
+ this.graphRunsInFlight.add(record.id);
909
+ this.notify();
910
+ void this.executeGraphRun(record, run.id).catch(() => undefined);
911
+ return { run };
912
+ }
913
+
914
+ /** One task = one fresh session (the schedules rule: never overwrite prior work). */
915
+ private async executeGraphTask(record: GraphRecord, runId: string, taskId: string) {
916
+ const task = record.tasks.find((t) => t.id === taskId);
917
+ if (!task) return;
918
+ await this.graphs.markTask(record.id, runId, taskId, { status: "running" });
919
+ this.notify();
920
+ try {
921
+ const session = await this.create({
922
+ name: `${record.name} · ${task.name}`,
923
+ cwd: record.cwd,
924
+ ...(task.model ? { model: task.model } : {}),
925
+ });
926
+ await this.graphs.markTask(record.id, runId, taskId, { sessionId: session.id });
927
+ const row = this.resolveSession(session.id);
928
+ const h = this.harness(row);
929
+ const { c } = await this.resolveAgent(session.id, "main");
930
+ const submission = await this.send(c, {
931
+ content: task.prompt,
932
+ whenBusy: "followUp",
933
+ requestId: `graph-${runId}-${taskId}`,
934
+ });
935
+ const outcome = await this.waitForGraphAnswer(h, submission.id as number);
936
+ await this.graphs.markTask(record.id, runId, taskId, outcome.ok ? { status: "ok" } : { status: "failed", error: outcome.error });
937
+ } catch (e) {
938
+ const error = String(e instanceof Error ? e.message : e).slice(0, 300);
939
+ await this.graphs.markTask(record.id, runId, taskId, { status: "failed", error }).catch(() => undefined);
940
+ }
941
+ this.notify();
942
+ }
943
+
944
+ /** A task turn gets 30 minutes; `settled` waits ≤5 min a call, so this polls. */
945
+ private async waitForGraphAnswer(h: Harness, submissionId: number): Promise<{ ok: true } | { ok: false; error: string }> {
946
+ const deadline = Date.now() + 30 * 60_000;
947
+ for (;;) {
948
+ try {
949
+ const r = await this.settled(h, submissionId, 60_000);
950
+ if ("answer" in r) return { ok: true };
951
+ if (r.status === "unanswered") return { ok: false, error: `unanswered: ${r.reason}` };
952
+ } catch (e) {
953
+ return { ok: false, error: String(e instanceof Error ? e.message : e).slice(0, 300) };
954
+ }
955
+ if (Date.now() >= deadline) return { ok: false, error: "timed out after 30 minutes" };
956
+ }
957
+ }
958
+
959
+ private async executeGraphRun(record: GraphRecord, runId: string) {
960
+ try {
961
+ const order = topoOrder(record.tasks);
962
+ for (;;) {
963
+ const run = this.graphs.runs(record.id).find((r) => r.id === runId);
964
+ if (!run || run.status !== "running") break;
965
+ const ready = readyTasks(record.tasks, run.tasks).sort((a, b) => order.indexOf(a) - order.indexOf(b));
966
+ if (!ready.length) break; // complete (or fully skipped) — the registry closed it
967
+ await this.executeGraphTask(record, runId, ready[0]!);
968
+ }
969
+ const final = this.graphs.runs(record.id).find((r) => r.id === runId);
970
+ if (final?.status === "ok" || final?.status === "failed")
971
+ void this.notifyEvent({
972
+ kind: final.status === "ok" ? "graph.ok" : "graph.failed",
973
+ title: `Graph ${final.status === "ok" ? "finished" : "failed"}: ${record.name}`,
974
+ body:
975
+ final.status === "ok"
976
+ ? `Every task of "${record.name}" finished ok on ${this.name}.`
977
+ : `A task of "${record.name}" failed on ${this.name}; its dependants were skipped.`,
978
+ data: { graphId: record.id, runId: final.id },
979
+ });
980
+ } finally {
981
+ this.graphRunsInFlight.delete(record.id);
982
+ this.notify();
983
+ }
984
+ }
985
+
845
986
  /** `spawnKey` records which tool call created the session, in the same transaction as the session row. */
846
987
  async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
847
988
  if (typeof body?.name !== "string") throw invalid("name is required");
@@ -2177,6 +2318,8 @@ export class Store {
2177
2318
  if (this.awakeTimer) clearTimeout(this.awakeTimer);
2178
2319
  this.awake.stop();
2179
2320
  this.telegram?.stop();
2321
+ // A graceful stop marks an in-flight graph run interrupted (not lost).
2322
+ await this.graphs?.recoverInterrupted().catch(() => undefined);
2180
2323
  for (const { harness, unlock, unsubscribe } of this.opened.values()) {
2181
2324
  unsubscribe();
2182
2325
  try {