my-durable 0.0.44 → 0.0.46
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/src/config.ts +7 -1
- package/apps/dpi-backend/src/crash.ts +338 -0
- package/apps/dpi-backend/src/doctor.ts +16 -1
- package/apps/dpi-backend/src/graph-cli.ts +446 -0
- package/apps/dpi-backend/src/graphs.ts +960 -0
- package/apps/dpi-backend/src/main.ts +33 -2
- package/apps/dpi-backend/src/notify-cli.ts +8 -1
- package/apps/dpi-backend/src/pi-config.ts +102 -1
- package/apps/dpi-backend/src/routes.ts +29 -1
- package/apps/dpi-backend/src/store.ts +173 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-B5d1JP_j.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BDY9dgTQ.js → index-CAtBlkjt.js} +4 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/EnvPanel.vue +136 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GraphPanel.vue +309 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +4 -0
- package/apps/dpi-sdk/src/api.ts +56 -0
- package/apps/dpi-sdk/src/client.ts +34 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +10 -0
- package/bin/dpi.mjs +7 -0
- package/docs/host-project-checklist.md +4 -4
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CraiQho0.css +0 -1
|
@@ -5,8 +5,9 @@ import { assertLimitsConfig } from "../../dpi-sdk/src/protocol/limits.js";
|
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
6
|
import { writeFileSync, rmSync } from "node:fs";
|
|
7
7
|
import { networkInterfaces } from "node:os";
|
|
8
|
-
import { loadConfig } from "./config.js";
|
|
9
|
-
import { Store } from "./store.js";
|
|
8
|
+
import { loadConfig, deviceHome } from "./config.js";
|
|
9
|
+
import { Store, PACKAGE_VERSION } from "./store.js";
|
|
10
|
+
import { installCrashHandlers } from "./crash.js";
|
|
10
11
|
import { bearerAuth } from "./auth.js";
|
|
11
12
|
import { errorMiddleware } from "./errors.js";
|
|
12
13
|
import { v1 } from "./routes.js";
|
|
@@ -24,6 +25,35 @@ import { parseDeviceSub, runDeviceCommand, daemonPaths } from "./daemon.js";
|
|
|
24
25
|
|
|
25
26
|
assertLimitsConfig();
|
|
26
27
|
|
|
28
|
+
// Crash reports (policy gate #1) are installed FIRST, before anything below can
|
|
29
|
+
// throw: a config or store failure still leaves a redacted local report (nothing
|
|
30
|
+
// is ever uploaded). The state getter reads the store lazily — before it opens,
|
|
31
|
+
// every count is simply "unknown".
|
|
32
|
+
let crashStore: Store | null = null;
|
|
33
|
+
installCrashHandlers({
|
|
34
|
+
home: deviceHome(),
|
|
35
|
+
version: PACKAGE_VERSION,
|
|
36
|
+
startedAt: Date.now(),
|
|
37
|
+
state: () => {
|
|
38
|
+
if (!crashStore) return {};
|
|
39
|
+
const n = <T,>(f: () => T): T | undefined => {
|
|
40
|
+
try {
|
|
41
|
+
return f();
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
openSessions: n(() => crashStore!.list().length),
|
|
48
|
+
totalSessions: n(() => crashStore!.list().length),
|
|
49
|
+
schedules: n(() => crashStore!.schedules.list().length),
|
|
50
|
+
graphs: n(() => crashStore!.graphList(true).length),
|
|
51
|
+
runsInFlight: [...crashStore.graphRunsInFlight],
|
|
52
|
+
notifySinks: n(() => crashStore!.notifySinkList().length),
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
27
57
|
const config = await loadConfig();
|
|
28
58
|
const store = await Store.open({
|
|
29
59
|
dataDir: config.dataDir,
|
|
@@ -33,6 +63,7 @@ const store = await Store.open({
|
|
|
33
63
|
envFile: config.envFile,
|
|
34
64
|
telegramToken: process.env.DPI_TELEGRAM_TOKEN,
|
|
35
65
|
});
|
|
66
|
+
crashStore = store;
|
|
36
67
|
|
|
37
68
|
const app = express();
|
|
38
69
|
app.disable("x-powered-by");
|
|
@@ -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 = [
|
|
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(),
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* pi's files: its credential store is a read-only view, so a headless daemon
|
|
12
12
|
* cannot corrupt an interactive login.
|
|
13
13
|
*/
|
|
14
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { closeSync, copyFileSync, existsSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
|
|
15
15
|
import { homedir } from "node:os";
|
|
16
16
|
import { join } from "node:path";
|
|
17
17
|
import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
|
|
@@ -204,3 +204,104 @@ export function loadPiConfig(env: NodeJS.ProcessEnv = process.env): PiConfig {
|
|
|
204
204
|
skipped,
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Writable provider keys (policy gate #2, decided 0.0.46): the device may SET
|
|
211
|
+
* or REMOVE an api_key entry in pi's OWN auth.json — write-only. The rules that
|
|
212
|
+
* keep pi and the device from fighting over the file:
|
|
213
|
+
*
|
|
214
|
+
* - values are never returned: the view carries a masked tail (`••••••••t123`)
|
|
215
|
+
* so an operator can confirm a rotation, nothing more;
|
|
216
|
+
* - pi's INTERACTIVE logins (oauth entries) are untouchable — a headless
|
|
217
|
+
* daemon must not clobber what `pi /login` established;
|
|
218
|
+
* - a corrupt auth.json is refused, not rewritten: the fix belongs to pi;
|
|
219
|
+
* - writes are atomic (tmp + rename, 0600) with a `.bak` of the previous
|
|
220
|
+
* file, and every OTHER entry survives byte-for-byte.
|
|
221
|
+
*/
|
|
222
|
+
export interface PiAuthEntry {
|
|
223
|
+
providerId: string;
|
|
224
|
+
type: string;
|
|
225
|
+
source: "auth.json" | "models.json" | "both";
|
|
226
|
+
/** `••••••••` + last 4 — the only form a value ever leaves the file in. */
|
|
227
|
+
masked: string;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function maskPiKey(key: string): string {
|
|
231
|
+
return `••••••••${key.slice(-4)}`;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The write-only view: names, types, sources, masked tails — never values. */
|
|
235
|
+
export function piAuthView(auth: Record<string, Credential>, modelsJson: PiModelsJson): PiAuthEntry[] {
|
|
236
|
+
const ids = [...new Set([...Object.keys(auth), ...Object.keys(modelsJson.providers ?? {})])].sort();
|
|
237
|
+
return ids.map((providerId) => {
|
|
238
|
+
const fromAuth = auth[providerId];
|
|
239
|
+
const fromModels = modelsJson.providers?.[providerId]?.apiKey;
|
|
240
|
+
const key: string | undefined =
|
|
241
|
+
fromAuth?.type === "api_key" ? fromAuth.key : (fromModels ?? undefined);
|
|
242
|
+
return {
|
|
243
|
+
providerId,
|
|
244
|
+
type: fromAuth?.type ?? "api_key",
|
|
245
|
+
source: fromAuth && fromModels ? "both" : fromAuth ? "auth.json" : "models.json",
|
|
246
|
+
masked: key ? maskPiKey(key) : "(none)",
|
|
247
|
+
};
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const PROVIDER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
252
|
+
|
|
253
|
+
/** Read auth.json strictly: absent → {}, corrupt → REFUSE (pi owns the fix). */
|
|
254
|
+
function readAuthStrict(dir: string): Record<string, Credential> {
|
|
255
|
+
const path = join(dir, "auth.json");
|
|
256
|
+
if (!existsSync(path)) return {};
|
|
257
|
+
let parsed: unknown;
|
|
258
|
+
try {
|
|
259
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
260
|
+
} catch {
|
|
261
|
+
throw Error("auth.json is not valid JSON — fix it with pi, the device will not rewrite it");
|
|
262
|
+
}
|
|
263
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
264
|
+
throw Error("auth.json has an unexpected shape — fix it with pi, the device will not rewrite it");
|
|
265
|
+
return parsed as Record<string, Credential>;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Atomic 0600 write with a `.bak` of the previous file (house registry style). */
|
|
269
|
+
function writeAuthAtomic(dir: string, next: Record<string, Credential>): void {
|
|
270
|
+
const path = join(dir, "auth.json");
|
|
271
|
+
if (existsSync(path)) copyFileSync(path, `${path}.bak`);
|
|
272
|
+
const tmp = join(dir, `auth.json.tmp-${process.pid}`);
|
|
273
|
+
const fd = openSync(tmp, "w", 0o600);
|
|
274
|
+
try {
|
|
275
|
+
writeSync(fd, `${JSON.stringify(next, null, 2)}\n`);
|
|
276
|
+
} finally {
|
|
277
|
+
closeSync(fd);
|
|
278
|
+
}
|
|
279
|
+
renameSync(tmp, path);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Set one api_key. Refuses invalid ids, oversized keys, and oauth entries. */
|
|
283
|
+
export function writePiApiKey(dir: string, providerId: string, key: string): PiAuthEntry {
|
|
284
|
+
if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
|
|
285
|
+
if (!key.trim() || key.length > 4096) throw Error("key must be 1–4096 non-whitespace characters");
|
|
286
|
+
const auth = readAuthStrict(dir);
|
|
287
|
+
const existing = auth[providerId];
|
|
288
|
+
if (existing && existing.type !== "api_key")
|
|
289
|
+
throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
|
|
290
|
+
const credential: ApiKeyCredential = { type: "api_key", key };
|
|
291
|
+
writeAuthAtomic(dir, { ...auth, [providerId]: credential });
|
|
292
|
+
return { providerId, type: "api_key", source: existing ? "auth.json" : "auth.json", masked: maskPiKey(key) };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Remove one api_key entry. Same refusals; returns whether it existed. */
|
|
296
|
+
export function removePiApiKey(dir: string, providerId: string): boolean {
|
|
297
|
+
if (!PROVIDER_ID.test(providerId)) throw Error(`invalid provider id: ${JSON.stringify(providerId)}`);
|
|
298
|
+
const auth = readAuthStrict(dir);
|
|
299
|
+
const existing = auth[providerId];
|
|
300
|
+
if (existing && existing.type !== "api_key")
|
|
301
|
+
throw Error(`${providerId} uses an interactive pi login (${existing.type}) — edit it with pi, not here`);
|
|
302
|
+
if (!existing) return false;
|
|
303
|
+
const next = { ...auth };
|
|
304
|
+
delete next[providerId];
|
|
305
|
+
writeAuthAtomic(dir, next);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
@@ -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>;
|
|
@@ -208,6 +208,17 @@ export function v1(
|
|
|
208
208
|
}));
|
|
209
209
|
r.delete("/device/env/:key", route(async (req, res) => res.json(await store.removeEnvVar(param(req, "key")))));
|
|
210
210
|
|
|
211
|
+
// -------------------------------------------------- pi provider keys
|
|
212
|
+
// WRITE-ONLY over pi's own auth.json (gate #2): values are never returned —
|
|
213
|
+
// masked tails only — and pi's interactive oauth logins are untouchable.
|
|
214
|
+
r.get("/device/pi-auth", (_req, res) => res.json({ entries: store.piAuthView() }));
|
|
215
|
+
r.put("/device/pi-auth/:provider", route(async (req, res) => {
|
|
216
|
+
const body = req.body ?? {};
|
|
217
|
+
if (typeof body.key !== "string" || !body.key.trim()) throw invalid("key is required");
|
|
218
|
+
res.json(store.setPiApiKey(param(req, "provider"), body.key));
|
|
219
|
+
}));
|
|
220
|
+
r.delete("/device/pi-auth/:provider", route(async (req, res) => res.json(store.removePiApiKey(param(req, "provider")))));
|
|
221
|
+
|
|
211
222
|
// ---------------------------------------------------- notifications
|
|
212
223
|
// Outbound fan-out (webhook/ntfy). Configured here, delivered by the device.
|
|
213
224
|
r.get("/notify/sinks", (_req, res) => res.json({ sinks: store.notifySinkList() }));
|
|
@@ -216,6 +227,23 @@ export function v1(
|
|
|
216
227
|
r.delete("/notify/sinks/:id", route(async (req, res) => res.json(await store.removeNotifySink(param(req, "id")))));
|
|
217
228
|
r.post("/notify/test", route(async (_req, res) => res.json({ results: await store.testNotifySinks() })));
|
|
218
229
|
|
|
230
|
+
// ----------------------------------------------------- task-graphs
|
|
231
|
+
// The device owns execution (sequential, topological); these routes only
|
|
232
|
+
// read, edit and START a run — the answer streams back through the tree.
|
|
233
|
+
r.get("/graphs", (req, res) => {
|
|
234
|
+
const includeArchived = req.query.includeArchived === "1" || req.query.includeArchived === "true";
|
|
235
|
+
res.json({ graphs: store.graphList(includeArchived) });
|
|
236
|
+
});
|
|
237
|
+
r.get("/graphs/:id", route(async (req, res) => {
|
|
238
|
+
const found = store.graphGet(param(req, "id"));
|
|
239
|
+
if (!found) throw notFound(`no graph ${param(req, "id")}`);
|
|
240
|
+
res.json(found);
|
|
241
|
+
}));
|
|
242
|
+
r.post("/graphs", route(async (req, res) => res.status(201).json(await store.createGraph(req.body ?? {}))));
|
|
243
|
+
r.patch("/graphs/:id", route(async (req, res) => res.json(await store.updateGraph(param(req, "id"), req.body ?? {}))));
|
|
244
|
+
r.delete("/graphs/:id", route(async (req, res) => res.json(await store.removeGraph(param(req, "id")))));
|
|
245
|
+
r.post("/graphs/:id/run", route(async (req, res) => res.status(202).json(await store.runGraphNow(param(req, "id")))));
|
|
246
|
+
|
|
219
247
|
// -------------------------------------------------------- schedules
|
|
220
248
|
// The device owns execution (systemd/cron are deliberately rejected by config);
|
|
221
249
|
// 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";
|
|
@@ -66,7 +74,16 @@ import { BACKGROUND_CONTEXT as ctx, withAbortSignal } from "@earendil-works/chor
|
|
|
66
74
|
import { createModels } from "@earendil-works/pi-ai/models";
|
|
67
75
|
import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
|
|
68
76
|
import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
|
|
69
|
-
import {
|
|
77
|
+
import {
|
|
78
|
+
loadPiConfig,
|
|
79
|
+
piAuthView as piAuthViewExport,
|
|
80
|
+
readPiAuth,
|
|
81
|
+
readPiModelsJson,
|
|
82
|
+
writePiApiKey,
|
|
83
|
+
removePiApiKey as removePiApiKeyFn,
|
|
84
|
+
piAgentDir,
|
|
85
|
+
type PiAuthEntry,
|
|
86
|
+
} from "./pi-config.js";
|
|
70
87
|
import { curatedModels, defaultModelId } from "./model-catalog.js";
|
|
71
88
|
import { fauxModels, installFaux } from "./faux.js";
|
|
72
89
|
import {
|
|
@@ -291,6 +308,10 @@ export class Store {
|
|
|
291
308
|
private awakeTimer?: ReturnType<typeof setTimeout>;
|
|
292
309
|
/** Telegram chat bridge (Wave 3): bound chats talk to sessions. */
|
|
293
310
|
telegram?: TelegramBridge;
|
|
311
|
+
/** Task-graphs (Wave 3): a DAG of prompt-tasks, each run as a fresh session. */
|
|
312
|
+
graphs!: GraphRegistry;
|
|
313
|
+
/** Public read-only use: the crash snapshot lists ids mid-run. */
|
|
314
|
+
graphRunsInFlight = new Set<string>();
|
|
294
315
|
uid!: string;
|
|
295
316
|
modelList: ModelInfo[] = [];
|
|
296
317
|
private unlockCatalog: () => void;
|
|
@@ -325,6 +346,9 @@ export class Store {
|
|
|
325
346
|
get telegramPath() {
|
|
326
347
|
return join(this.options.dataDir, "telegram.json");
|
|
327
348
|
}
|
|
349
|
+
get graphsPath() {
|
|
350
|
+
return join(this.options.dataDir, "graphs.json");
|
|
351
|
+
}
|
|
328
352
|
get name() {
|
|
329
353
|
return this.options.name;
|
|
330
354
|
}
|
|
@@ -401,6 +425,13 @@ export class Store {
|
|
|
401
425
|
warn: (m) => process.emitWarning(`telegram: ${m}`),
|
|
402
426
|
});
|
|
403
427
|
if (options.telegramToken) store.telegram.start(options.telegramToken);
|
|
428
|
+
store.graphs = await GraphRegistry.open(store.graphsPath, {
|
|
429
|
+
warn: (m) => process.emitWarning(`graphs: ${m}`),
|
|
430
|
+
});
|
|
431
|
+
// A restart mid-run never loses the graph: the run flips to interrupted
|
|
432
|
+
// with its running tasks back to pending, and `run` continues from there.
|
|
433
|
+
for (const run of await store.graphs.recoverInterrupted())
|
|
434
|
+
process.emitWarning(`graphs: run ${run.id} of ${run.graphId} was interrupted by a restart; run it again to continue`);
|
|
404
435
|
store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
|
|
405
436
|
store.shared = await SharedState.open(store.sharedStatePath);
|
|
406
437
|
store.shared.harness.subscribeCommits(() => store.notify());
|
|
@@ -799,6 +830,25 @@ export class Store {
|
|
|
799
830
|
});
|
|
800
831
|
}
|
|
801
832
|
|
|
833
|
+
/**
|
|
834
|
+
* pi provider keys (gate #2): WRITE-ONLY surface. The view re-reads pi's
|
|
835
|
+
* files (not the boot snapshot) so a rotation is visible immediately;
|
|
836
|
+
* values never leave — masked tails only.
|
|
837
|
+
*/
|
|
838
|
+
piAuthView(): PiAuthEntry[] {
|
|
839
|
+
const dir = piAgentDir();
|
|
840
|
+
return piAuthViewExport(readPiAuth(dir), readPiModelsJson(dir));
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
setPiApiKey(providerId: string, key: string): { providerId: string; masked: string; restartRequired: true } {
|
|
844
|
+
const entry = writePiApiKey(piAgentDir(), providerId, key);
|
|
845
|
+
return { providerId: entry.providerId, masked: entry.masked, restartRequired: true };
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
removePiApiKey(providerId: string): { removed: boolean; restartRequired: true } {
|
|
849
|
+
return { removed: removePiApiKeyFn(piAgentDir(), providerId), restartRequired: true };
|
|
850
|
+
}
|
|
851
|
+
|
|
802
852
|
/** The env-file view (secrets masked, process-only vars read-only). */
|
|
803
853
|
envView(): Promise<EnvFileView> {
|
|
804
854
|
return this.env.view();
|
|
@@ -842,6 +892,126 @@ export class Store {
|
|
|
842
892
|
};
|
|
843
893
|
}
|
|
844
894
|
|
|
895
|
+
// ------------------------------------------------ task-graphs (Wave 3)
|
|
896
|
+
|
|
897
|
+
graphList(includeArchived = false): Array<GraphRecord & { lastRun?: GraphRunRecord }> {
|
|
898
|
+
return this.graphs.list({ includeArchived }).map((g) => ({ ...g, lastRun: this.graphs.lastRun(g.id) }));
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
graphGet(id: string): { graph: GraphRecord; runs: GraphRunRecord[] } | undefined {
|
|
902
|
+
const graph = this.graphs.get(id);
|
|
903
|
+
if (!graph) return undefined;
|
|
904
|
+
return { graph, runs: this.graphs.runs(id) };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
async createGraph(body: Record<string, unknown>): Promise<GraphRecord> {
|
|
908
|
+
const created = await this.graphs.create(body as never);
|
|
909
|
+
this.notify();
|
|
910
|
+
return created;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async updateGraph(id: string, body: Record<string, unknown>): Promise<GraphRecord> {
|
|
914
|
+
const updated = await this.graphs.update(id, body as never);
|
|
915
|
+
this.notify();
|
|
916
|
+
return updated;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
async removeGraph(id: string): Promise<{ removed: boolean }> {
|
|
920
|
+
if (this.graphRunsInFlight.has(id)) throw invalid("this graph is running");
|
|
921
|
+
const removed = await this.graphs.remove(id);
|
|
922
|
+
this.notify();
|
|
923
|
+
return { removed };
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Start a run. Execution is sequential in topological order — deterministic
|
|
928
|
+
* and debuggable on a single device — and happens in the background: the
|
|
929
|
+
* route answers with the run record immediately, statuses flow through the
|
|
930
|
+
* tree and GET /graphs/:id.
|
|
931
|
+
*/
|
|
932
|
+
async runGraphNow(id: string): Promise<{ run: GraphRunRecord }> {
|
|
933
|
+
const record = this.graphs.get(id);
|
|
934
|
+
if (!record) throw notFound(`no graph ${id}`);
|
|
935
|
+
if (this.graphRunsInFlight.has(record.id)) throw invalid("this graph is already running");
|
|
936
|
+
const run = await this.graphs.beginRun(record.id);
|
|
937
|
+
this.graphRunsInFlight.add(record.id);
|
|
938
|
+
this.notify();
|
|
939
|
+
void this.executeGraphRun(record, run.id).catch(() => undefined);
|
|
940
|
+
return { run };
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** One task = one fresh session (the schedules rule: never overwrite prior work). */
|
|
944
|
+
private async executeGraphTask(record: GraphRecord, runId: string, taskId: string) {
|
|
945
|
+
const task = record.tasks.find((t) => t.id === taskId);
|
|
946
|
+
if (!task) return;
|
|
947
|
+
await this.graphs.markTask(record.id, runId, taskId, { status: "running" });
|
|
948
|
+
this.notify();
|
|
949
|
+
try {
|
|
950
|
+
const session = await this.create({
|
|
951
|
+
name: `${record.name} · ${task.name}`,
|
|
952
|
+
cwd: record.cwd,
|
|
953
|
+
...(task.model ? { model: task.model } : {}),
|
|
954
|
+
});
|
|
955
|
+
await this.graphs.markTask(record.id, runId, taskId, { sessionId: session.id });
|
|
956
|
+
const row = this.resolveSession(session.id);
|
|
957
|
+
const h = this.harness(row);
|
|
958
|
+
const { c } = await this.resolveAgent(session.id, "main");
|
|
959
|
+
const submission = await this.send(c, {
|
|
960
|
+
content: task.prompt,
|
|
961
|
+
whenBusy: "followUp",
|
|
962
|
+
requestId: `graph-${runId}-${taskId}`,
|
|
963
|
+
});
|
|
964
|
+
const outcome = await this.waitForGraphAnswer(h, submission.id as number);
|
|
965
|
+
await this.graphs.markTask(record.id, runId, taskId, outcome.ok ? { status: "ok" } : { status: "failed", error: outcome.error });
|
|
966
|
+
} catch (e) {
|
|
967
|
+
const error = String(e instanceof Error ? e.message : e).slice(0, 300);
|
|
968
|
+
await this.graphs.markTask(record.id, runId, taskId, { status: "failed", error }).catch(() => undefined);
|
|
969
|
+
}
|
|
970
|
+
this.notify();
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** A task turn gets 30 minutes; `settled` waits ≤5 min a call, so this polls. */
|
|
974
|
+
private async waitForGraphAnswer(h: Harness, submissionId: number): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
975
|
+
const deadline = Date.now() + 30 * 60_000;
|
|
976
|
+
for (;;) {
|
|
977
|
+
try {
|
|
978
|
+
const r = await this.settled(h, submissionId, 60_000);
|
|
979
|
+
if ("answer" in r) return { ok: true };
|
|
980
|
+
if (r.status === "unanswered") return { ok: false, error: `unanswered: ${r.reason}` };
|
|
981
|
+
} catch (e) {
|
|
982
|
+
return { ok: false, error: String(e instanceof Error ? e.message : e).slice(0, 300) };
|
|
983
|
+
}
|
|
984
|
+
if (Date.now() >= deadline) return { ok: false, error: "timed out after 30 minutes" };
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
private async executeGraphRun(record: GraphRecord, runId: string) {
|
|
989
|
+
try {
|
|
990
|
+
const order = topoOrder(record.tasks);
|
|
991
|
+
for (;;) {
|
|
992
|
+
const run = this.graphs.runs(record.id).find((r) => r.id === runId);
|
|
993
|
+
if (!run || run.status !== "running") break;
|
|
994
|
+
const ready = readyTasks(record.tasks, run.tasks).sort((a, b) => order.indexOf(a) - order.indexOf(b));
|
|
995
|
+
if (!ready.length) break; // complete (or fully skipped) — the registry closed it
|
|
996
|
+
await this.executeGraphTask(record, runId, ready[0]!);
|
|
997
|
+
}
|
|
998
|
+
const final = this.graphs.runs(record.id).find((r) => r.id === runId);
|
|
999
|
+
if (final?.status === "ok" || final?.status === "failed")
|
|
1000
|
+
void this.notifyEvent({
|
|
1001
|
+
kind: final.status === "ok" ? "graph.ok" : "graph.failed",
|
|
1002
|
+
title: `Graph ${final.status === "ok" ? "finished" : "failed"}: ${record.name}`,
|
|
1003
|
+
body:
|
|
1004
|
+
final.status === "ok"
|
|
1005
|
+
? `Every task of "${record.name}" finished ok on ${this.name}.`
|
|
1006
|
+
: `A task of "${record.name}" failed on ${this.name}; its dependants were skipped.`,
|
|
1007
|
+
data: { graphId: record.id, runId: final.id },
|
|
1008
|
+
});
|
|
1009
|
+
} finally {
|
|
1010
|
+
this.graphRunsInFlight.delete(record.id);
|
|
1011
|
+
this.notify();
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
845
1015
|
/** `spawnKey` records which tool call created the session, in the same transaction as the session row. */
|
|
846
1016
|
async create(body: CreateSessionBody, spawnKey?: string): Promise<SessionSummary> {
|
|
847
1017
|
if (typeof body?.name !== "string") throw invalid("name is required");
|
|
@@ -2177,6 +2347,8 @@ export class Store {
|
|
|
2177
2347
|
if (this.awakeTimer) clearTimeout(this.awakeTimer);
|
|
2178
2348
|
this.awake.stop();
|
|
2179
2349
|
this.telegram?.stop();
|
|
2350
|
+
// A graceful stop marks an in-flight graph run interrupted (not lost).
|
|
2351
|
+
await this.graphs?.recoverInterrupted().catch(() => undefined);
|
|
2180
2352
|
for (const { harness, unlock, unsubscribe } of this.opened.values()) {
|
|
2181
2353
|
unsubscribe();
|
|
2182
2354
|
try {
|