pi-durable-subagents 1.0.41 → 1.0.43
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/CHANGELOG.md +43 -0
- package/README.md +29 -1
- package/dist/agent/main/snapshots.js +24 -1
- package/dist/agent/main/tool.js +3 -2
- package/dist/agent/main.js +5 -11
- package/dist/cli/control.js +20 -10
- package/dist/cli/main.js +13 -3
- package/dist/cli/requests.js +51 -32
- package/dist/events/fence.js +2 -0
- package/dist/events/pump.js +6 -2
- package/dist/events/waiting.js +12 -2
- package/dist/kernel/journal.js +294 -52
- package/dist/kernel/lifecycle.js +66 -23
- package/dist/kernel/mailbox.js +51 -32
- package/dist/kernel/overlay.js +47 -0
- package/dist/orchestrator/engine.js +228 -35
- package/dist/orchestrator/executor/effects/gate.js +10 -3
- package/dist/orchestrator/executor/effects/index.js +2 -1
- package/dist/orchestrator/executor/index.js +114 -40
- package/dist/orchestrator/executor/indexes.js +34 -0
- package/dist/orchestrator/executor/recovered.js +85 -0
- package/dist/orchestrator/executor/session.js +4 -0
- package/dist/orchestrator/executor/sweep.js +41 -9
- package/dist/orchestrator/ledger.js +12 -4
- package/dist/orchestrator/main.js +5 -2
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/settled.js +142 -0
- package/dist/orchestrator/snapshot.js +91 -11
- package/dist/orchestrator/store.js +248 -39
- package/dist/requests.js +41 -5
- package/dist/ui/tool.js +5 -3
- package/dist/ui/view.js +20 -8
- package/package.json +1 -1
|
@@ -13,10 +13,24 @@ import { discoverAgents } from "../compat/agents.js";
|
|
|
13
13
|
import { parseFrontmatter } from "../compat/frontmatter.js";
|
|
14
14
|
import { compileFanout } from "../compat/fanout.js";
|
|
15
15
|
import { contentHash, ulid } from "../kernel/ids.js";
|
|
16
|
-
import { openJournal, syncDirectory } from "../kernel/journal.js";
|
|
16
|
+
import { openJournal, openLazyJournal, syncDirectory } from "../kernel/journal.js";
|
|
17
|
+
import { readSettled, settledPath } from "./settled.js";
|
|
17
18
|
import { publishFile } from "../kernel/mailbox.js";
|
|
18
19
|
import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
19
20
|
import { JT } from "../types.js";
|
|
21
|
+
/** The same record checks for asynchronous verification and a synchronous released-pins reload. */
|
|
22
|
+
function pinRecordFiles(dir, hash, record, verify) {
|
|
23
|
+
const { digest, ...body } = record;
|
|
24
|
+
if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
|
|
25
|
+
return undefined;
|
|
26
|
+
if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
|
|
27
|
+
return undefined;
|
|
28
|
+
const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
|
|
29
|
+
if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
|
|
30
|
+
return undefined;
|
|
31
|
+
return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
|
|
32
|
+
originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
|
|
33
|
+
}
|
|
20
34
|
/** Every file publishPins writes for one revision, relative to its directory (inputs given relative too). */
|
|
21
35
|
function publishedFiles(inputs, origin) {
|
|
22
36
|
return [...new Set(['script.js', 'args.json', 'agents.json', 'inputs.json', ...inputs, ...(origin ? ['origin.jsonl'] : [])])];
|
|
@@ -185,7 +199,61 @@ export class Store {
|
|
|
185
199
|
/** Called after each append to a workflow journal (the event pump derives from it). */
|
|
186
200
|
appended;
|
|
187
201
|
ledgers;
|
|
202
|
+
/** Terminal workflows awaiting file verification; reuse their immutable revision intent instead of a wrapper. */
|
|
203
|
+
unverified = new Map();
|
|
204
|
+
verifying = new Map();
|
|
205
|
+
/** A request can verify pins and then be refused before live work starts. Release those pins after the request. */
|
|
206
|
+
pinRest = new Map();
|
|
207
|
+
/** Share one accessor pair per store, so released history carries no per-workflow getter/setter closures. */
|
|
208
|
+
pinAccessors = (() => {
|
|
209
|
+
const store = this;
|
|
210
|
+
return { enumerable: true, configurable: true,
|
|
211
|
+
get() { const pins = store.releasedPins(this); this.pins = pins; store.restPins(this); return pins; },
|
|
212
|
+
set(pins) { Object.defineProperty(this, 'pins', { value: pins, enumerable: true, configurable: true, writable: true }); } };
|
|
213
|
+
})();
|
|
214
|
+
restPins(wf) {
|
|
215
|
+
if (wf.journal.closed || !wf.journal.resting || !Object.hasOwn(Object.getOwnPropertyDescriptor(wf, 'pins') ?? {}, 'value'))
|
|
216
|
+
return;
|
|
217
|
+
clearTimeout(this.pinRest.get(wf.wid));
|
|
218
|
+
const revision = wf.revision;
|
|
219
|
+
const timer = setTimeout(() => {
|
|
220
|
+
this.pinRest.delete(wf.wid);
|
|
221
|
+
if (this.workflows.get(wf.wid) === wf && wf.revision === revision && wf.journal.resting && !wf.journal.closed && !this.verifying.has(wf.wid))
|
|
222
|
+
this.releasePins(wf);
|
|
223
|
+
}, 1000);
|
|
224
|
+
timer.unref();
|
|
225
|
+
this.pinRest.set(wf.wid, timer);
|
|
226
|
+
}
|
|
227
|
+
/** What the store looks up in the orchestrator ledger, folded over appended entries only (first entry wins, as find). */
|
|
228
|
+
ix = { seen: 0, pruned: new Set(), created: new Set(), createIntents: [], createByRid: new Map(),
|
|
229
|
+
createByWid: new Map(), reviseByRid: new Map(), rids: new Map() };
|
|
188
230
|
constructor(ledgers) { this.ledgers = ledgers; }
|
|
231
|
+
index() {
|
|
232
|
+
const ix = this.ix, entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
|
|
233
|
+
while (ix.seen < entries.length) {
|
|
234
|
+
const e = entries[ix.seen++];
|
|
235
|
+
if (e.type === 'pruned')
|
|
236
|
+
ix.pruned.add(String(e.wid));
|
|
237
|
+
else if (e.type === JT.created)
|
|
238
|
+
ix.created.add(String(e.rid));
|
|
239
|
+
else if (e.type === 'create-intent' || e.type === 'revise-intent') {
|
|
240
|
+
const byRid = e.type === 'create-intent' ? ix.createByRid : ix.reviseByRid, rid = String(e.rid), wid = String(e.wid);
|
|
241
|
+
if (e.type === 'create-intent') {
|
|
242
|
+
ix.createIntents.push(e);
|
|
243
|
+
if (!ix.createByWid.has(wid))
|
|
244
|
+
ix.createByWid.set(wid, e);
|
|
245
|
+
}
|
|
246
|
+
if (!byRid.has(rid))
|
|
247
|
+
byRid.set(rid, e);
|
|
248
|
+
const rids = ix.rids.get(wid);
|
|
249
|
+
if (rids)
|
|
250
|
+
rids.push(rid);
|
|
251
|
+
else
|
|
252
|
+
ix.rids.set(wid, [rid]);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return ix;
|
|
256
|
+
}
|
|
189
257
|
stagePath(rid) {
|
|
190
258
|
if (!rid || rid === '.' || rid === '..')
|
|
191
259
|
throw new Error('Invalid staging identity');
|
|
@@ -215,6 +283,7 @@ export class Store {
|
|
|
215
283
|
const change = req.body, wf = this.workflows.get(change?.wid);
|
|
216
284
|
if (!wf)
|
|
217
285
|
throw new Error('unknown-workflow');
|
|
286
|
+
await this.ready(wf);
|
|
218
287
|
body = { cwd: wf.cwd, ...(change.workflow !== undefined ? { workflow: change.workflow } : { source: change.source ?? wf.pins.source }),
|
|
219
288
|
args: Object.hasOwn(change, 'args') ? change.args : wf.pins.args, inputs: wf.pins.inputSources,
|
|
220
289
|
usageBudget: wf.pins.usageBudget, maxCalls: wf.pins.maxCalls };
|
|
@@ -295,7 +364,8 @@ export class Store {
|
|
|
295
364
|
}
|
|
296
365
|
/** P3, P6: Remove staging only after a durable rejection or withdrawal without a committed intent. */
|
|
297
366
|
async discardStage(rid) {
|
|
298
|
-
|
|
367
|
+
const ix = this.index();
|
|
368
|
+
if (ix.createByRid.has(rid) || ix.reviseByRid.has(rid))
|
|
299
369
|
return;
|
|
300
370
|
await rm(this.stagePath(rid), { recursive: true, force: true });
|
|
301
371
|
await syncDirectory(join(this.ledgers.home, 'staging')).catch(error => { if (error.code !== 'ENOENT')
|
|
@@ -303,14 +373,14 @@ export class Store {
|
|
|
303
373
|
}
|
|
304
374
|
/** A5: Fix the workflow identity and snapshot reference before filesystem effects. */
|
|
305
375
|
async create(req) {
|
|
306
|
-
let intent = this.
|
|
376
|
+
let intent = this.index().createByRid.get(req.rid);
|
|
307
377
|
intent ??= await this.ledgers.orch.append('create-intent', { rid: req.rid, wid: ulid(), origin: req.from, cwd: req.body.cwd,
|
|
308
378
|
...(req.body.name !== undefined ? { name: req.body.name } : {}), snapshot: await this.reference(req.rid) });
|
|
309
379
|
return this.materialize(intent);
|
|
310
380
|
}
|
|
311
381
|
/** P14, A5: Bind the next revision before retiring any old authority. */
|
|
312
382
|
async revisionIntent(req, wf) {
|
|
313
|
-
return this.
|
|
383
|
+
return this.index().reviseByRid.get(req.rid) ??
|
|
314
384
|
await this.ledgers.orch.append('revise-intent', { rid: req.rid, wid: wf.wid, revision: wf.revision + 1, snapshot: await this.reference(req.rid) });
|
|
315
385
|
}
|
|
316
386
|
async publishPins(wid, revision, pins) {
|
|
@@ -344,41 +414,36 @@ export class Store {
|
|
|
344
414
|
* workflow), and use it only when it is well formed, names this snapshot, its pins hash to its digest and every file
|
|
345
415
|
* hashes as recorded — otherwise they take the snapshot path, whose byte comparison reports a changed file as a
|
|
346
416
|
* conflict, and record it again. */
|
|
347
|
-
async pinnedFiles(wid, revision, intent) {
|
|
417
|
+
async pinnedFiles(wid, revision, intent, verify = true) {
|
|
348
418
|
const dir = revision === 1 ? pinnedDir(this.ledgers.home, wid) : join(pinnedDir(this.ledgers.home, wid), `r${revision}`);
|
|
349
419
|
const ref = intent.pins ? undefined : intent.snapshot;
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
}
|
|
420
|
+
const hash = ref?.hash ?? contentHash(intent.pins);
|
|
421
|
+
const recorded = await this.recorded(dir, hash, verify).catch(() => undefined);
|
|
422
|
+
if (recorded)
|
|
423
|
+
return recorded;
|
|
355
424
|
const files = await this.publishPins(wid, revision, await this.pinned(intent));
|
|
356
|
-
|
|
425
|
+
{
|
|
357
426
|
const hashes = {};
|
|
358
427
|
for (const name of publishedFiles(Object.values(files.inputs).map(path => relative(dir, path)), files.originPath !== undefined))
|
|
359
428
|
hashes[name] = await fileHash(join(dir, name));
|
|
360
|
-
const body = { snapshot:
|
|
429
|
+
const body = { snapshot: hash, pins: files.pins,
|
|
361
430
|
inputs: Object.fromEntries(Object.entries(files.inputs).map(([name, path]) => [name, relative(dir, path)])), origin: files.originPath !== undefined, files: hashes };
|
|
362
431
|
await replaceFile(dir, 'pins.json', JSON.stringify({ ...body, digest: contentHash(body) }));
|
|
363
432
|
}
|
|
364
433
|
return files;
|
|
365
434
|
}
|
|
366
|
-
/** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
|
|
373
|
-
return undefined;
|
|
374
|
-
const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
|
|
375
|
-
if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
|
|
435
|
+
/** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
|
|
436
|
+
* Without `verify`, only the record's form is checked (its digest and the file hashes are left to `ready`). */
|
|
437
|
+
async recorded(dir, hash, verify = true) {
|
|
438
|
+
const record = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
|
|
439
|
+
const files = pinRecordFiles(dir, hash, record, verify !== false);
|
|
440
|
+
if (!files)
|
|
376
441
|
return undefined;
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
442
|
+
if (verify === true)
|
|
443
|
+
for (const name of Object.keys(record.files))
|
|
444
|
+
if (record.files[name] !== await fileHash(join(dir, name)))
|
|
445
|
+
return undefined;
|
|
446
|
+
return files;
|
|
382
447
|
}
|
|
383
448
|
/** P14, A2: Publish a new revision only after the engine has retired its predecessor. */
|
|
384
449
|
async revise(intent) {
|
|
@@ -388,20 +453,112 @@ export class Store {
|
|
|
388
453
|
const revision = Number(intent.revision), files = await this.pinnedFiles(wf.wid, revision, intent);
|
|
389
454
|
await wf.journal.append('revised', { rid: intent.rid, revision, snapshot: intent.snapshot });
|
|
390
455
|
Object.assign(wf, files, { revision });
|
|
456
|
+
this.unverified.delete(wf.wid);
|
|
457
|
+
}
|
|
458
|
+
pinIntent(wf) {
|
|
459
|
+
const intent = wf.revision === 1 ? this.index().createByWid.get(wf.wid)
|
|
460
|
+
: wf.journal.loaded === false ? wf.settled?.revised : wf.journal.entries().findLast(e => e.type === 'revised');
|
|
461
|
+
if (!intent)
|
|
462
|
+
throw new Error(`Missing pinned revision: ${wf.wid}@${wf.revision}`);
|
|
463
|
+
return intent;
|
|
464
|
+
}
|
|
465
|
+
/** Reload metadata with ready's form/digest checks and immutable-snapshot fallback, without rechecking file bytes. */
|
|
466
|
+
releasedPins(wf) {
|
|
467
|
+
const intent = this.pinIntent(wf), hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
|
|
468
|
+
const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
|
|
469
|
+
try {
|
|
470
|
+
const recorded = pinRecordFiles(dir, hash, JSON.parse(readFileSync(join(dir, 'pins.json'), 'utf8')), true);
|
|
471
|
+
if (recorded)
|
|
472
|
+
return recorded.pins;
|
|
473
|
+
}
|
|
474
|
+
catch { /* The same immutable fallback as ready's asynchronous reload. */ }
|
|
475
|
+
let source = intent.pins;
|
|
476
|
+
if (!source) {
|
|
477
|
+
const ref = intent.snapshot;
|
|
478
|
+
if (!ref)
|
|
479
|
+
throw new Error('Missing pinned snapshot');
|
|
480
|
+
const snapshot = JSON.parse(readFileSync(join(this.ledgers.home, ref.path), 'utf8'));
|
|
481
|
+
if (contentHash(snapshot) !== ref.hash || !snapshot.pins)
|
|
482
|
+
throw new Error('Staged snapshot hash mismatch');
|
|
483
|
+
source = snapshot.pins;
|
|
484
|
+
}
|
|
485
|
+
const { origin: _origin, inputs: _inputs, ...pins } = source;
|
|
486
|
+
return { ...pins, inputs: {} };
|
|
391
487
|
}
|
|
488
|
+
/** Whether the workflow's pins are in memory (not released behind the lazy accessor). */
|
|
489
|
+
pinsResident(wf) { return !Object.getOwnPropertyDescriptor(wf, 'pins')?.get; }
|
|
490
|
+
/** Release terminal pins. The next read caches checked metadata until the same idle release runs again. */
|
|
491
|
+
releasePins(wf) {
|
|
492
|
+
clearTimeout(this.pinRest.get(wf.wid));
|
|
493
|
+
this.pinRest.delete(wf.wid);
|
|
494
|
+
if (Object.getOwnPropertyDescriptor(wf, 'pins')?.get)
|
|
495
|
+
return;
|
|
496
|
+
Object.defineProperty(wf, 'pins', this.pinAccessors);
|
|
497
|
+
}
|
|
498
|
+
/** A1: Verify the pinned files of a workflow materialized unverified (a terminal one) before its script, inputs, origin
|
|
499
|
+
* or pins are used again: the record's digest and every file's hash, else the snapshot path (which republishes a
|
|
500
|
+
* missing file and refuses a changed one). Nothing evaluates from a file that does not hash as recorded. Idempotent;
|
|
501
|
+
* a refusal is raised again by every later call. */
|
|
502
|
+
async ready(wf) {
|
|
503
|
+
if (!this.unverified.has(wf.wid)) {
|
|
504
|
+
const revision = wf.revision, unloaded = Object.getOwnPropertyDescriptor(wf, 'pins')?.get;
|
|
505
|
+
if (unloaded) {
|
|
506
|
+
const intent = this.pinIntent(wf);
|
|
507
|
+
const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
|
|
508
|
+
const hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
|
|
509
|
+
const recorded = await this.recorded(dir, hash, 'record').catch(() => undefined);
|
|
510
|
+
// These files were verified in this process. If their cache record changed, recover the same pins from the
|
|
511
|
+
// immutable snapshot, without changing when file verification is required.
|
|
512
|
+
const pins = recorded?.pins ?? await (async () => {
|
|
513
|
+
const { origin: _origin, inputs: _inputs, ...kept } = await this.pinned(intent);
|
|
514
|
+
return { ...kept, inputs: {} };
|
|
515
|
+
})();
|
|
516
|
+
if (wf.revision === revision && Object.getOwnPropertyDescriptor(wf, 'pins')?.get === unloaded)
|
|
517
|
+
wf.pins = pins;
|
|
518
|
+
}
|
|
519
|
+
this.restPins(wf);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
let run = this.verifying.get(wf.wid);
|
|
523
|
+
if (!run) {
|
|
524
|
+
run = (async () => {
|
|
525
|
+
const pending = this.unverified.get(wf.wid);
|
|
526
|
+
if (!pending)
|
|
527
|
+
return;
|
|
528
|
+
const revision = wf.revision, files = await this.pinnedFiles(wf.wid, revision, pending);
|
|
529
|
+
if (this.workflows.get(wf.wid) !== wf || this.unverified.get(wf.wid) !== pending)
|
|
530
|
+
return; // A revision or owner changed meanwhile.
|
|
531
|
+
if (revision === wf.revision)
|
|
532
|
+
Object.assign(wf, files);
|
|
533
|
+
this.unverified.delete(wf.wid);
|
|
534
|
+
})().finally(() => this.verifying.delete(wf.wid));
|
|
535
|
+
this.verifying.set(wf.wid, run);
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
await run;
|
|
539
|
+
}
|
|
540
|
+
finally {
|
|
541
|
+
this.restPins(wf);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
/** Whether a workflow's pinned files were verified in this process (see ready). */
|
|
545
|
+
verified(wid) { return !this.unverified.has(wid); }
|
|
392
546
|
/** P32: Rebuild a historical ticket from that revision's immutable snapshot. */
|
|
393
547
|
async atRevision(wf, revision) {
|
|
394
|
-
if (revision === wf.revision)
|
|
548
|
+
if (revision === wf.revision) {
|
|
549
|
+
await this.ready(wf);
|
|
395
550
|
return wf;
|
|
551
|
+
}
|
|
396
552
|
const intent = revision === 1
|
|
397
|
-
? this.
|
|
553
|
+
? this.index().createByWid.get(wf.wid)
|
|
398
554
|
: wf.journal.entries().find(e => e.type === 'revised' && e.revision === revision);
|
|
399
555
|
if (!intent)
|
|
400
556
|
throw new Error(`Missing pinned revision: ${wf.wid}@${revision}`);
|
|
401
|
-
|
|
557
|
+
const { wid, origin, cwd, journal, settled } = wf;
|
|
558
|
+
return { wid, origin, cwd, journal, ...(settled ? { settled } : {}), revision, ...await this.pinnedFiles(wid, revision, intent) };
|
|
402
559
|
}
|
|
403
560
|
/** A1, housekeeping: Wids with a committed pruned entry; they are gone and never materialize again. */
|
|
404
|
-
pruned() { return
|
|
561
|
+
pruned() { return this.index().pruned; }
|
|
405
562
|
/** Housekeeping: Bytes a prune of `wid` frees: its workflow directory and the staging dirs of its requests. */
|
|
406
563
|
async footprint(wid) {
|
|
407
564
|
let total = await diskUsage(workflowDir(this.ledgers.home, wid));
|
|
@@ -410,10 +567,12 @@ export class Store {
|
|
|
410
567
|
return total;
|
|
411
568
|
}
|
|
412
569
|
stagedRids(wid) {
|
|
413
|
-
return this.
|
|
570
|
+
return [...this.index().rids.get(wid) ?? []];
|
|
414
571
|
}
|
|
415
572
|
/** A1, A2: Retire a pruned workflow's handle after its pruned entry is committed; nothing appends to it again. */
|
|
416
573
|
async drop(wid) {
|
|
574
|
+
clearTimeout(this.pinRest.get(wid));
|
|
575
|
+
this.pinRest.delete(wid);
|
|
417
576
|
const wf = this.workflows.get(wid);
|
|
418
577
|
this.workflows.delete(wid);
|
|
419
578
|
await wf?.journal.close();
|
|
@@ -429,6 +588,7 @@ export class Store {
|
|
|
429
588
|
throw error; });
|
|
430
589
|
// Readers' caches of it (derived, never authoritative: no sync needed).
|
|
431
590
|
await rm(join(digestDir(this.ledgers.home), `${wid}.json`), { force: true });
|
|
591
|
+
await rm(settledPath(this.ledgers.home, wid), { force: true });
|
|
432
592
|
const cached = await readdir(digestDir(this.ledgers.home)).catch(error => { if (error.code !== 'ENOENT')
|
|
433
593
|
throw error; return []; });
|
|
434
594
|
for (const name of cached)
|
|
@@ -448,31 +608,80 @@ export class Store {
|
|
|
448
608
|
console.error(`durable-subagents: removal of pruned workflow ${wid} failed, retrying at next start: ${String(error)}`);
|
|
449
609
|
}
|
|
450
610
|
}
|
|
451
|
-
for (const intent of this.
|
|
611
|
+
for (const intent of [...this.index().createIntents])
|
|
452
612
|
if (!pruned.has(String(intent.wid)))
|
|
453
613
|
await this.materialize(intent);
|
|
454
614
|
}
|
|
615
|
+
/** A1: A workflow that already ended (its journal's current revision is terminal) is materialized from its pinned
|
|
616
|
+
* files' record without verifying them (see ready): a start does not hash the pinned files of finished history. */
|
|
455
617
|
async materialize(intent) {
|
|
456
618
|
const wid = intent.wid, existing = this.workflows.get(wid);
|
|
457
619
|
if (existing)
|
|
458
620
|
return existing;
|
|
459
621
|
if (this.pruned().has(wid))
|
|
460
622
|
throw new Error(`Workflow ${wid} was pruned`);
|
|
461
|
-
const
|
|
462
|
-
|
|
623
|
+
const path = journalPath(this.ledgers.home, wid);
|
|
624
|
+
// A settled workflow (settled.ts) whose journal is still what its record describes opens without decoding it.
|
|
625
|
+
const settled = readSettled(this.ledgers.home, wid), lazy = settled && await openLazyJournal(path, settled.journal);
|
|
626
|
+
if (settled && lazy) {
|
|
627
|
+
try {
|
|
628
|
+
const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
|
|
629
|
+
const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
|
|
630
|
+
const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
|
|
631
|
+
this.releasePins(wf);
|
|
632
|
+
this.unverified.set(wid, current);
|
|
633
|
+
lazy.onAppend = () => this.appended?.(wid);
|
|
634
|
+
this.workflows.set(wid, wf);
|
|
635
|
+
if (!this.index().created.has(String(intent.rid)))
|
|
636
|
+
await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
|
|
637
|
+
return wf;
|
|
638
|
+
}
|
|
639
|
+
catch (error) {
|
|
640
|
+
this.workflows.delete(wid);
|
|
641
|
+
this.unverified.delete(wid);
|
|
642
|
+
await lazy.close();
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
// A new workflow publishes its pins before its journal exists (a failed publication leaves no journal).
|
|
647
|
+
const fresh = await stat(path).then(() => false, error => { if (error.code === 'ENOENT')
|
|
648
|
+
return true; throw error; });
|
|
649
|
+
const first = fresh ? await this.pinnedFiles(wid, 1, intent) : undefined;
|
|
650
|
+
const journal = await openJournal(path);
|
|
651
|
+
let wf;
|
|
652
|
+
try {
|
|
653
|
+
const entries = journal.entries(), revised = entries.findLast(e => e.type === 'revised');
|
|
654
|
+
const revision = revised ? Number(revised.revision) : 1, current = revised ?? intent;
|
|
655
|
+
// terminalEntry over the whole journal: a `revised` after the last done supersedes it, as in the revision's view.
|
|
656
|
+
const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
|
|
657
|
+
const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
|
|
658
|
+
wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
|
|
659
|
+
if (ended) {
|
|
660
|
+
this.releasePins(wf);
|
|
661
|
+
this.unverified.set(wid, current);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
await journal.close();
|
|
666
|
+
throw error;
|
|
667
|
+
}
|
|
463
668
|
journal.onAppend = () => this.appended?.(wid);
|
|
464
|
-
const wf = { wid, revision: 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
|
|
465
669
|
this.workflows.set(wid, wf);
|
|
466
670
|
if (!journal.entries().length)
|
|
467
671
|
await journal.append('wf-created', { rid: intent.rid, origin: intent.origin, cwd: intent.cwd, revision: 1,
|
|
468
672
|
...(intent.name !== undefined ? { name: intent.name } : {}) });
|
|
469
673
|
const revised = journal.entries().findLast(e => e.type === 'revised');
|
|
470
|
-
if (revised)
|
|
674
|
+
if (revised && wf.revision !== Number(revised.revision))
|
|
471
675
|
Object.assign(wf, await this.pinnedFiles(wid, Number(revised.revision), revised), { revision: Number(revised.revision) });
|
|
472
|
-
if (!this.
|
|
676
|
+
if (!this.index().created.has(String(intent.rid)))
|
|
473
677
|
await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
|
|
474
678
|
return wf;
|
|
475
679
|
}
|
|
476
680
|
/** A1: Close shared journals only after engine and executor activity retires. */
|
|
477
|
-
async close() {
|
|
681
|
+
async close() {
|
|
682
|
+
for (const timer of this.pinRest.values())
|
|
683
|
+
clearTimeout(timer);
|
|
684
|
+
this.pinRest.clear();
|
|
685
|
+
await Promise.all([...this.workflows.values()].map(w => w.journal.close()));
|
|
686
|
+
}
|
|
478
687
|
}
|
package/dist/requests.js
CHANGED
|
@@ -7,7 +7,7 @@ import { readdir } from 'node:fs/promises';
|
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
9
|
import { contentHash } from "./kernel/ids.js";
|
|
10
|
-
import {
|
|
10
|
+
import { readJournalFold } from "./kernel/journal.js";
|
|
11
11
|
import { publishRequest } from "./kernel/mailbox.js";
|
|
12
12
|
import { OsLock } from "./platform/lock.js";
|
|
13
13
|
import { orchInbox, orchLedger, outboxRoot } from "./paths.js";
|
|
@@ -65,17 +65,53 @@ export function specDigest(req) {
|
|
|
65
65
|
}
|
|
66
66
|
return contentHash({ kind: req.kind, body, cond: req.cond });
|
|
67
67
|
}
|
|
68
|
+
// Repeated request checks verify the same immutable prefixes, including on either side of a lock. Retain only
|
|
69
|
+
// negative positions, never envelopes: every check still stats the file and folds fresh appended bytes. The bound
|
|
70
|
+
// counts files, not hinted IDs: one hinted lookup cannot evict its earlier files within the file budget.
|
|
71
|
+
const misses = new Map(), MISS_FILES = 1024, MISS_IDS = 64;
|
|
72
|
+
function requestIn(path, rid, type, related, touched) {
|
|
73
|
+
const probes = [...new Set([rid, ...related])].slice(0, MISS_IDS), key = JSON.stringify([path, type]);
|
|
74
|
+
touched.add(key);
|
|
75
|
+
const known = misses.get(key);
|
|
76
|
+
misses.delete(key); // A failed read must not retain a partially extended prefix or absence set.
|
|
77
|
+
const reusable = known && probes.every(id => known.state.has(id));
|
|
78
|
+
// Watch every cached absent ID while extending: otherwise an appended envelope could invalidate an older hint.
|
|
79
|
+
const watched = new Set(reusable ? known.state : probes);
|
|
80
|
+
let found;
|
|
81
|
+
const record = readJournalFold(path, reusable ? { ...known, state: watched } : undefined, () => watched, (absent, entry) => {
|
|
82
|
+
if (entry.type !== type)
|
|
83
|
+
return;
|
|
84
|
+
const id = entry.request.rid;
|
|
85
|
+
absent.delete(id);
|
|
86
|
+
if (!found && id === rid)
|
|
87
|
+
found = entry;
|
|
88
|
+
}, { needles: [...watched].map(id => JSON.stringify(id)) });
|
|
89
|
+
// Keep positions and absent IDs only, never the found envelope. Torn tails cannot be cached: a repair may
|
|
90
|
+
// commit a line at the same inode/size. Each future check still stats and folds freshly appended bytes.
|
|
91
|
+
if (record && record.length === record.size && record.state.size) {
|
|
92
|
+
if (misses.size >= MISS_FILES) {
|
|
93
|
+
// More files than the budget: omit later positions rather than evict this lookup's earliest files.
|
|
94
|
+
const evict = [...misses.keys()].find(candidate => !touched.has(candidate));
|
|
95
|
+
if (evict !== undefined)
|
|
96
|
+
misses.delete(evict);
|
|
97
|
+
}
|
|
98
|
+
if (misses.size < MISS_FILES)
|
|
99
|
+
misses.set(key, record);
|
|
100
|
+
}
|
|
101
|
+
return found;
|
|
102
|
+
}
|
|
68
103
|
/** The envelope recorded for `rid`: the orchestrator's admitted copy (ledger `request`, kept after prune), else any
|
|
69
|
-
* sender's outbox `sent` entry (published or about to be). Read-only.
|
|
70
|
-
|
|
71
|
-
|
|
104
|
+
* sender's outbox `sent` entry (published or about to be). Read-only. Related IDs are only hints for sharing a
|
|
105
|
+
* verified negative prefix; their eventual lookups still read fresh state and preserve first-match/file order. */
|
|
106
|
+
export async function findRequest(home, rid, related = []) {
|
|
107
|
+
const touched = new Set(), admitted = requestIn(orchLedger(home), rid, 'request', related, touched);
|
|
72
108
|
if (admitted)
|
|
73
109
|
return { request: admitted.request, admitted: true };
|
|
74
110
|
const dir = join(outboxRoot(home), 'outbox');
|
|
75
111
|
const names = await readdir(dir).catch(error => { if (error.code === 'ENOENT')
|
|
76
112
|
return []; throw error; });
|
|
77
113
|
for (const name of names.filter(n => n.endsWith('.jsonl')).sort()) {
|
|
78
|
-
const sent =
|
|
114
|
+
const sent = requestIn(join(dir, name), rid, 'sent', related, touched);
|
|
79
115
|
if (sent)
|
|
80
116
|
return { request: sent.request, admitted: false };
|
|
81
117
|
}
|
package/dist/ui/tool.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Text } from "@earendil-works/pi-tui";
|
|
2
|
-
import { plainReason } from "./view.js";
|
|
2
|
+
import { plainReason, queuedPhrase } from "./view.js";
|
|
3
3
|
const short = (id) => typeof id === "string" ? (id.length > 12 ? `${id.slice(0, 10)}…` : id) : "";
|
|
4
4
|
const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
|
|
5
5
|
/** UI §5: One line per tool call: what was asked, never the raw arguments (scripts and task prompts stay out of the transcript). */
|
|
@@ -32,7 +32,7 @@ export function resultLines(details) {
|
|
|
32
32
|
const d = (details ?? {});
|
|
33
33
|
if (typeof d.wid === "string" && typeof d.key === "string" && typeof d.phase === "string") {
|
|
34
34
|
const r = d.result;
|
|
35
|
-
return [`${d.key} · ${r?.status ?? (d.phase === "queued"
|
|
35
|
+
return [`${d.key} · ${r?.status ?? (d.phase === "queued" ? queuedPhrase(d, Date.now()) : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
|
|
36
36
|
}
|
|
37
37
|
if (typeof d.wid === "string" && !Array.isArray(d.calls))
|
|
38
38
|
return [`started workflow ${d.wid}`, ...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : [])];
|
|
@@ -53,7 +53,9 @@ export function resultLines(details) {
|
|
|
53
53
|
return `${w.name ?? short(w.wid)} · ${w.paused ? "paused" : w.followUps ? `follow-up running (run ${w.status})` : w.status} · ${w.progress} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}${alerts ? ` · ${alerts} alert${alerts > 1 ? "s" : ""}` : ""}`;
|
|
54
54
|
});
|
|
55
55
|
const finished = Array.isArray(d.finished) ? d.finished.length + Number(d.olderFinished ?? 0) : 0;
|
|
56
|
-
|
|
56
|
+
// The orchestrator line ("1.0.42 (pid 7, starting 12s)") while it recovers: nothing queued starts until then.
|
|
57
|
+
const starting = typeof d.orchestrator === "string" ? /^[^(]*\(pid \d+, starting ([^)]+)\)/.exec(d.orchestrator)?.[1] : undefined;
|
|
58
|
+
return [...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : []), ...(starting ? [`orchestrator starting (${starting})`] : []), ...(rows.length ? rows.slice(0, 6) : ["nothing running"]),
|
|
57
59
|
...(rows.length > 6 ? [`… ${rows.length - 6} more`] : []), ...(finished ? [`${finished} finished`] : [])];
|
|
58
60
|
}
|
|
59
61
|
if (Array.isArray(d.workflows)) {
|
package/dist/ui/view.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
-
import { answerForwardedNote, isLive, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
|
|
2
|
+
import { answerForwardedNote, isLive, queuedText, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
|
|
3
3
|
import { oneLine } from "./frame.js";
|
|
4
4
|
/** UI §2: Render compact wall-clock durations; never present these as charged active time. */
|
|
5
5
|
export function duration(ms) {
|
|
@@ -129,7 +129,7 @@ export function statusPhrase(call, workflow, facts, now) {
|
|
|
129
129
|
if (workflow.attention.some(a => a.kind === "stall" && a.call === call.callId))
|
|
130
130
|
return `no activity for ${duration(now - Math.max(call.lastActivity ?? call.startedAt ?? now, facts?.lastActivity ?? 0))}`;
|
|
131
131
|
if (call.phase === "queued")
|
|
132
|
-
return workflow.paused ? "paused · r resumes" : call
|
|
132
|
+
return workflow.paused ? "paused · r resumes" : queuedPhrase(call, now);
|
|
133
133
|
// Liveness (UI §2): the age of the newest evidence ticks, and resets whenever the agent does anything.
|
|
134
134
|
const since = duration(Math.max(0, now - Math.max(call.lastActivity ?? 0, facts?.lastActivity ?? 0, call.startedAt ?? 0)));
|
|
135
135
|
if (facts?.activity)
|
|
@@ -142,6 +142,16 @@ export function statusPhrase(call, workflow, facts, now) {
|
|
|
142
142
|
return live.tool ? `writing a ${live.tool} call · ${age}` : live.text ? `writing · ${age}` : `thinking · ${age}`;
|
|
143
143
|
return `thinking · ${since}`;
|
|
144
144
|
}
|
|
145
|
+
/** Why a queued call does not start, only as far as the orchestrator ledger says (CallSnapshot.queuedFor): a call is
|
|
146
|
+
* never said to wait for a slot without a full provider, an answered asker neither ("queued (answered)"). */
|
|
147
|
+
export function queuedPhrase(call, now) {
|
|
148
|
+
const why = call.queuedFor;
|
|
149
|
+
if (why?.reason === "starting")
|
|
150
|
+
return `queued: ${queuedText(why, now, duration)}`;
|
|
151
|
+
if (call.answered)
|
|
152
|
+
return why ? `queued (answered): ${why.detail}` : "queued (answered)";
|
|
153
|
+
return why ? `queued: ${queuedText(why, now, duration)}` : "queued";
|
|
154
|
+
}
|
|
145
155
|
function failed(c) { return c.phase === "sealed" && c.result && !c.result.ok && c.result.status !== "skipped"; }
|
|
146
156
|
/** UI §2, P37: Calls are named by key; later generations of a key carry their generation. */
|
|
147
157
|
export const label = (c) => c.gen > 1 ? `${c.key}@${c.gen}` : c.key;
|
|
@@ -183,19 +193,21 @@ export function summary(workflows) {
|
|
|
183
193
|
done: progress.reduce((n, p) => n + p.done, 0), total: progress.reduce((n, p) => n + p.total, 0), plus: progress.some(p => p.plus) };
|
|
184
194
|
}
|
|
185
195
|
/** UI §1, v12 §4: What needs you first, then what is running, then progress — e.g. "1 asking · 3 working · 12/40 done". */
|
|
186
|
-
export function summaryText(workflows) {
|
|
196
|
+
export function summaryText(workflows, now = Date.now()) {
|
|
187
197
|
const s = summary(workflows), finished = workflows.filter(w => !isLive(w)).length;
|
|
188
198
|
if (!s.total)
|
|
189
199
|
return finished ? `${finished} finished` : "nothing running";
|
|
190
|
-
|
|
200
|
+
// While the orchestrator recovers, nothing queued starts: say so once, rather than suggest a slot shortage.
|
|
201
|
+
const starting = s.queued ? workflows.filter(w => isLive(w) && !w.paused).flatMap(liveCalls).find(c => c.phase === "queued" && c.queuedFor?.reason === "starting")?.queuedFor : undefined;
|
|
202
|
+
return [s.asking ? `${s.asking} asking` : "", s.working ? `${s.working} working` : "", s.queued ? `${s.queued} queued${starting ? `: ${queuedText(starting, now, duration)}` : ""}` : "", s.paused ? `${s.paused} paused` : "", `${s.done}/${s.total}${s.plus ? "+" : ""} done`].filter(Boolean).join(" · ");
|
|
191
203
|
}
|
|
192
|
-
export function mainLine(workflows) {
|
|
204
|
+
export function mainLine(workflows, now = Date.now()) {
|
|
193
205
|
if (!workflows.length)
|
|
194
206
|
return undefined;
|
|
195
207
|
const s = summary(workflows);
|
|
196
208
|
// The key that opens the list is spelled out: a bare arrow is easy to miss.
|
|
197
209
|
if (s.working || s.asking || s.queued || s.paused)
|
|
198
|
-
return `${summaryText(workflows)} · ↓ subagents`;
|
|
210
|
+
return `${summaryText(workflows, now)} · ↓ subagents`;
|
|
199
211
|
const w = workflows.filter(w => !isLive(w)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))[0];
|
|
200
212
|
if (!w)
|
|
201
213
|
return undefined;
|
|
@@ -225,7 +237,7 @@ export function dockLines(workflows, facts, name, width, now = Date.now(), rows
|
|
|
225
237
|
}).sort((a, b) => Number(b.asking) - Number(a.asking));
|
|
226
238
|
if (!active.length) {
|
|
227
239
|
const ended = workflows.filter(w => !isLive(w)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))[0];
|
|
228
|
-
const line = ended && now - (ended.endedAt ?? 0) < 10 * 60_000 ? mainLine(workflows) : undefined;
|
|
240
|
+
const line = ended && now - (ended.endedAt ?? 0) < 10 * 60_000 ? mainLine(workflows, now) : undefined;
|
|
229
241
|
return line ? [truncateToWidth(line, Math.max(1, width))] : [];
|
|
230
242
|
}
|
|
231
243
|
const cols = { key: Math.min(20, Math.max(...active.map(a => visibleWidth(callName(a.w, a.c))))), model: Math.min(20, Math.max(...active.map(a => visibleWidth(name(facts.get(a.c.callId)?.model ?? a.c.model))))) };
|
|
@@ -238,7 +250,7 @@ export function dockLines(workflows, facts, name, width, now = Date.now(), rows
|
|
|
238
250
|
return rowText(`${mark} `, callName(w, c), name(f?.model ?? c.model), phrase, [], width, cols);
|
|
239
251
|
});
|
|
240
252
|
const more = active.length - shown.length;
|
|
241
|
-
lines.push(truncateToWidth(`${more ? `+${more} more · ` : ""}${summaryText(workflows)} · ↓ subagents`, Math.max(1, width)));
|
|
253
|
+
lines.push(truncateToWidth(`${more ? `+${more} more · ` : ""}${summaryText(workflows, now)} · ↓ subagents`, Math.max(1, width)));
|
|
242
254
|
return lines;
|
|
243
255
|
}
|
|
244
256
|
/** UI §2, v12 §5: Group workflows (finished ones stay listed, dimmed and expandable — never hidden behind a toggle),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-durable-subagents",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.43",
|
|
4
4
|
"description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|