pi-durable-subagents 1.0.42 → 1.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.
- package/CHANGELOG.md +61 -0
- package/README.md +90 -8
- package/dist/agent/main/schema.js +6 -2
- package/dist/agent/main/snapshots.js +74 -5
- package/dist/agent/main/tool.js +21 -8
- package/dist/agent/main.js +10 -12
- package/dist/cli/control.js +20 -10
- package/dist/cli/main.js +5 -3
- package/dist/cli/requests.js +70 -34
- package/dist/compat/fanout.js +13 -5
- package/dist/compat/spec.js +46 -1
- package/dist/events/fence.js +2 -0
- package/dist/events/waiting.js +25 -3
- package/dist/kernel/journal.js +114 -25
- package/dist/kernel/lifecycle.js +66 -23
- package/dist/kernel/mailbox.js +49 -32
- package/dist/kernel/overlay.js +47 -0
- package/dist/orchestrator/engine.js +175 -41
- package/dist/orchestrator/executor/command.js +54 -0
- package/dist/orchestrator/executor/index.js +360 -8
- package/dist/orchestrator/executor/sweep.js +40 -24
- package/dist/orchestrator/ledger.js +4 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/restart.js +4 -1
- package/dist/orchestrator/settled.js +14 -2
- package/dist/orchestrator/snapshot.js +88 -9
- package/dist/orchestrator/store.js +133 -33
- package/dist/platform/command.js +98 -0
- package/dist/platform/launch.js +13 -3
- package/dist/requests.js +41 -5
- package/dist/types.js +2 -0
- package/dist/ui/screen.js +62 -13
- package/dist/ui/tool.js +8 -4
- package/dist/ui/view.js +18 -7
- package/package.json +1 -1
|
@@ -17,11 +17,11 @@ import { mkdir, readdir, unlink } from 'node:fs/promises';
|
|
|
17
17
|
import { resolve, join } from 'node:path';
|
|
18
18
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
19
19
|
import { contentHash } from "../kernel/ids.js";
|
|
20
|
-
import {
|
|
20
|
+
import { LifecycleFold, planDecisions } from "../kernel/lifecycle.js";
|
|
21
21
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
22
22
|
import { orchInbox, pinnedDir } from "../paths.js";
|
|
23
23
|
import { SESSION_ID, requestId, specDigest } from "../requests.js";
|
|
24
|
-
import { JT, attentionEntries, isEntry } from "../types.js";
|
|
24
|
+
import { JT, attentionEntries, isCommandCall, isEntry } from "../types.js";
|
|
25
25
|
import { isForceRestart, restartRefusal } from "./restart.js";
|
|
26
26
|
import { EvaluatorClient } from "./evaluator-client.js";
|
|
27
27
|
import { Store, revisionEntries, terminalEntry } from "./store.js";
|
|
@@ -36,6 +36,7 @@ import { parseModel } from "../compat/model.js";
|
|
|
36
36
|
import { PENDING_NOTE, generationRids, openingMessage, pendingFollowUps, pendingNotes, unsettledForward, unsettledNotify } from "./notes.js";
|
|
37
37
|
import { journalAppends } from "../kernel/journal.js";
|
|
38
38
|
import { callEntries, entriesOf } from "./executor/indexes.js";
|
|
39
|
+
import { unsealedCommandCalls } from "./executor/command.js";
|
|
39
40
|
import { lazy, writeSettled } from "./settled.js";
|
|
40
41
|
import { STATS_EVERY_MS, readBytes, writeStats } from "./stats.js";
|
|
41
42
|
const tail = (text, n) => text.length > n ? `…${text.slice(-(n - 1))}` : text;
|
|
@@ -185,8 +186,10 @@ export class Engine {
|
|
|
185
186
|
if (wf.journal.closed)
|
|
186
187
|
return;
|
|
187
188
|
const quiet = wf.journal.resting = this.quiescent(wf);
|
|
188
|
-
if (quiet)
|
|
189
|
+
if (quiet) {
|
|
189
190
|
this.recordSettled(wf);
|
|
191
|
+
this.store.releasePins(wf);
|
|
192
|
+
}
|
|
190
193
|
}
|
|
191
194
|
/** Journal lengths of the workflows whose settled record (settled.ts) was last written or found not due. */
|
|
192
195
|
settledAt = new Map();
|
|
@@ -221,7 +224,53 @@ export class Engine {
|
|
|
221
224
|
}
|
|
222
225
|
started = Date.now();
|
|
223
226
|
terminal(wf) { return lazy(wf) ? wf.settled.done : terminalEntry(revisionEntries(wf)); }
|
|
224
|
-
|
|
227
|
+
intakeFold = new LifecycleFold();
|
|
228
|
+
intakeSeen = 0;
|
|
229
|
+
/** Journal positions preserve retained-envelope order, even for repeated request entries. */
|
|
230
|
+
retained = new Map();
|
|
231
|
+
retainedAt = new Map();
|
|
232
|
+
sends = new Map();
|
|
233
|
+
rejectedStages = new Set();
|
|
234
|
+
withdrawnStages = new Set();
|
|
235
|
+
/** One writer appends committed entries; folds never advance past an uncommitted append or an awaited decision. */
|
|
236
|
+
lifecycle() {
|
|
237
|
+
const entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
|
|
238
|
+
for (; this.intakeSeen < entries.length; this.intakeSeen++) {
|
|
239
|
+
const entry = entries[this.intakeSeen];
|
|
240
|
+
if (entry.type === 'request') {
|
|
241
|
+
const request = entry.request;
|
|
242
|
+
if (request.kind === 'send') {
|
|
243
|
+
const sent = this.sends.get(request.rid) ?? [];
|
|
244
|
+
sent.push({ at: this.intakeSeen, request });
|
|
245
|
+
this.sends.set(request.rid, sent);
|
|
246
|
+
}
|
|
247
|
+
if (!this.intakeFold.resolved.has(request.rid)) {
|
|
248
|
+
this.retained.set(this.intakeSeen, request);
|
|
249
|
+
const positions = this.retainedAt.get(request.rid) ?? new Set();
|
|
250
|
+
positions.add(this.intakeSeen);
|
|
251
|
+
this.retainedAt.set(request.rid, positions);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
else if (['admitted', 'applied', 'rejected', 'withdrawn'].includes(entry.type)) {
|
|
255
|
+
const record = entry;
|
|
256
|
+
this.intakeFold.apply(record);
|
|
257
|
+
if (record.type === 'withdrawn')
|
|
258
|
+
for (const rid of record.rids)
|
|
259
|
+
this.withdrawnStages.add(rid);
|
|
260
|
+
else {
|
|
261
|
+
const resolution = this.intakeFold.resolved.get(record.rid);
|
|
262
|
+
if (resolution) {
|
|
263
|
+
for (const at of this.retainedAt.get(record.rid) ?? [])
|
|
264
|
+
this.retained.delete(at);
|
|
265
|
+
this.retainedAt.delete(record.rid);
|
|
266
|
+
if (resolution.type === 'rejected' && ['run', 'revise'].includes(this.intakeFold.admitted.get(record.rid)?.kind ?? ''))
|
|
267
|
+
this.rejectedStages.add(record.rid);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return this.intakeFold;
|
|
273
|
+
}
|
|
225
274
|
/** A2, P10: Recover executor authority before replaying each unfinished workflow. Returns what it recovered: the
|
|
226
275
|
* workflows, the calls the executor read and repaired, and those it skipped as already recovered. */
|
|
227
276
|
async recover() {
|
|
@@ -281,12 +330,60 @@ export class Engine {
|
|
|
281
330
|
this.dispatchGeneration(wf, entry);
|
|
282
331
|
await this.reopenForwarded(wf);
|
|
283
332
|
}
|
|
333
|
+
// Command calls outlive the orchestrator: each with an attempt and no seal is adopted, also in a held or ended
|
|
334
|
+
// workflow (whose replay dispatches nothing), and watched until it seals.
|
|
335
|
+
for (const wf of this.store.workflows.values())
|
|
336
|
+
if (!lazy(wf))
|
|
337
|
+
this.adoptCommands(wf);
|
|
284
338
|
await this.intake();
|
|
285
339
|
for (const wf of this.store.workflows.values())
|
|
286
340
|
this.settle(wf);
|
|
287
341
|
this.startWaiting();
|
|
288
342
|
return { workflows: this.store.workflows.size, calls, skipped };
|
|
289
343
|
}
|
|
344
|
+
/** Watch every unsealed command call of the current revision (Executor.run is idempotent per call: a replay's
|
|
345
|
+
* dispatch of the same call joins the same run). */
|
|
346
|
+
adoptCommands(wf) {
|
|
347
|
+
for (const call of unsealedCommandCalls(wf.journal.entries())) {
|
|
348
|
+
const m = /^(.*)@(\d+)\/(.*)@(\d+)$/.exec(call);
|
|
349
|
+
if (!m || Number(m[2]) !== wf.revision)
|
|
350
|
+
continue;
|
|
351
|
+
const entry = revisionEntries(wf).find(e => (e.type === 'call' || e.type === 'generation') && String(e.key) === m[3] && Number(e.gen) === Number(m[4]));
|
|
352
|
+
if (!entry)
|
|
353
|
+
continue;
|
|
354
|
+
const release = this.hold(wf.wid);
|
|
355
|
+
wf.journal.resting = false;
|
|
356
|
+
void this.executor.run(this.unpinnedTicket(wf, entry)).then(() => this.background(async () => {
|
|
357
|
+
try {
|
|
358
|
+
await this.deliverAdopted(wf, entry);
|
|
359
|
+
}
|
|
360
|
+
finally {
|
|
361
|
+
release();
|
|
362
|
+
}
|
|
363
|
+
}), error => {
|
|
364
|
+
release();
|
|
365
|
+
if (!(error instanceof Error && error.name === 'ExecutorShutdown'))
|
|
366
|
+
console.error(`durable-subagents: adopted command ${call}: ${String(error)}`);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/** An adopted command call sealed: its result reaches the workflow as a dispatched call's does. The replay proposed
|
|
371
|
+
* it without dispatching (a held workflow dispatches nothing): it is ready now, and the script goes on (a new call
|
|
372
|
+
* it makes stays queued under the hold; a workflow that ends records done and its finished notice). One the replay
|
|
373
|
+
* has not reached yet is found sealed when it gets there; one a dispatch runs is delivered by that dispatch. */
|
|
374
|
+
async deliverAdopted(wf, entry) {
|
|
375
|
+
const st = this.states.get(wf.wid);
|
|
376
|
+
if (!st || st.wf !== wf || this.terminal(wf) || entry.type !== 'call')
|
|
377
|
+
return;
|
|
378
|
+
const pos = entry.pos, own = st.calls.get(pos);
|
|
379
|
+
if (!own || !st.proposed.has(pos) || st.running.has(pos) || st.ready.has(pos))
|
|
380
|
+
return;
|
|
381
|
+
const result = this.sealed(st, own);
|
|
382
|
+
if (!result)
|
|
383
|
+
return;
|
|
384
|
+
st.ready.set(pos, result);
|
|
385
|
+
await this.flush(st);
|
|
386
|
+
}
|
|
290
387
|
/** A successful call with a worktree whose removal (or keeping) is not recorded yet: its post-seal effect is due. */
|
|
291
388
|
worktreeUnsettled(wf, call) {
|
|
292
389
|
const log = callEntries(wf.journal, call), result = log.find(e => e.type === JT.sealed)?.result;
|
|
@@ -342,18 +439,16 @@ export class Engine {
|
|
|
342
439
|
async startWorkflow(wf) {
|
|
343
440
|
if (this.terminal(wf))
|
|
344
441
|
return;
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
442
|
+
await this.store.ready(wf);
|
|
443
|
+
if (this.terminal(wf))
|
|
444
|
+
return;
|
|
350
445
|
wf.journal.resting = false;
|
|
351
446
|
await this.resolveFinished(wf);
|
|
352
447
|
const log = revisionEntries(wf);
|
|
353
448
|
const ev = Math.max(0, ...wf.journal.entries().filter(e => e.type === 'ev').map(e => e.n)) + 1;
|
|
354
449
|
await wf.journal.append('ev', { n: ev });
|
|
355
450
|
const calls = new Map(log.filter(e => ['call', 'refused', 'reused'].includes(e.type)).map(e => [e.pos, e]));
|
|
356
|
-
const st = { wf, ev, calls, proposed: new Set(), exposures: log.filter(e => e.type === 'exposed'), sent: 0, replaying: true, ready: new Map(), running: new Set(), outputs: new Map(log.filter(e => ['call', 'refused', 'reused', 'emit'].includes(e.type)).map(e => [e.pos, e])), values: log.filter(e => e.type === 'value'), needs: 0 };
|
|
451
|
+
const st = { wf, ev, calls, proposed: new Set(), exposures: log.filter(e => e.type === 'exposed'), exposed: new Set(log.filter(e => e.type === 'exposed').map(e => e.pos)), sent: 0, replaying: true, ready: new Map(), running: new Set(), outputs: new Map(log.filter(e => ['call', 'refused', 'reused', 'emit'].includes(e.type)).map(e => [e.pos, e])), values: log.filter(e => e.type === 'value'), needs: 0 };
|
|
357
452
|
this.states.set(wf.wid, st);
|
|
358
453
|
this.evaluator.send({ t: 'start', wid: wf.wid, ev, scriptPath: wf.scriptPath, args: wf.pins.args, inputs: wf.inputs });
|
|
359
454
|
}
|
|
@@ -365,18 +460,17 @@ export class Engine {
|
|
|
365
460
|
const files = await readdir(orchInbox(this.ledgers.home)).catch(error => { if (error.code === 'ENOENT')
|
|
366
461
|
return []; throw error; });
|
|
367
462
|
const last = this.consumed;
|
|
368
|
-
|
|
463
|
+
const length = this.ledgers.orch.count?.() ?? (this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries()).length;
|
|
464
|
+
if (!files.length && last && !last.pending && last.length === length)
|
|
369
465
|
return;
|
|
370
466
|
await this.consume();
|
|
371
467
|
}
|
|
372
468
|
async consume() {
|
|
373
469
|
this.passes.push(Date.now());
|
|
374
470
|
const scanned = (await scanInbox(orchInbox(this.ledgers.home))).filter(r => r.to === 'orch');
|
|
375
|
-
const before =
|
|
376
|
-
//
|
|
377
|
-
|
|
378
|
-
const retained = this.ledgers.orch.entries().filter(e => e.type === 'request' && !before.resolved.has(e.request.rid)).map(e => e.request);
|
|
379
|
-
const candidates = [...retained, ...scanned];
|
|
471
|
+
const before = this.lifecycle(), staged = new Set();
|
|
472
|
+
// The watermark index removes envelopes only after a committed terminal resolution.
|
|
473
|
+
const candidates = [...this.retained.values(), ...scanned];
|
|
380
474
|
for (const request of candidates) {
|
|
381
475
|
if (!['run', 'revise'].includes(request.kind) || before.admitted.has(request.rid) || before.tombstones.has(request.rid) || staged.has(request.rid))
|
|
382
476
|
continue;
|
|
@@ -410,21 +504,20 @@ export class Engine {
|
|
|
410
504
|
for (const { type, ...fields } of resolution)
|
|
411
505
|
await this.ledgers.orch.append(type, fields);
|
|
412
506
|
}
|
|
413
|
-
const view =
|
|
414
|
-
for (const [
|
|
415
|
-
|
|
507
|
+
const view = this.lifecycle();
|
|
508
|
+
for (const pending of [this.rejectedStages, this.withdrawnStages]) {
|
|
509
|
+
for (const rid of pending) {
|
|
416
510
|
await this.store.discardStage(rid);
|
|
511
|
+
pending.delete(rid);
|
|
512
|
+
}
|
|
417
513
|
}
|
|
418
|
-
for (const rid of view.tombstones)
|
|
419
|
-
await this.store.discardStage(rid);
|
|
420
514
|
for (const req of scanned) {
|
|
421
515
|
if (view.resolved.has(req.rid) || (view.admitted.has(req.rid) && view.admitted.get(req.rid).hash !== contentHash(req))) {
|
|
422
516
|
await unlink(join(orchInbox(this.ledgers.home), `${req.rid}.json`)).catch(error => { if (error.code !== 'ENOENT')
|
|
423
517
|
throw error; });
|
|
424
518
|
}
|
|
425
519
|
}
|
|
426
|
-
|
|
427
|
-
this.consumed = { length: this.ledgers.orch.entries().length, pending: [...after.admitted.keys()].some(rid => !after.resolved.has(rid)) };
|
|
520
|
+
this.consumed = { length: this.intakeSeen, pending: view.open.size > 0 };
|
|
428
521
|
}
|
|
429
522
|
findCall(to, bareWid = false) {
|
|
430
523
|
for (const wf of this.store.workflows.values()) {
|
|
@@ -451,9 +544,9 @@ export class Engine {
|
|
|
451
544
|
context(wf, entry) { return { journal: wf.journal, widRev: `${wf.wid}@${wf.revision}`, key: entry.key, gen: entry.gen }; }
|
|
452
545
|
async withdraw(req) {
|
|
453
546
|
const rids = req.body.rids;
|
|
547
|
+
this.lifecycle();
|
|
548
|
+
const sent = [...new Set(rids)].flatMap(rid => this.sends.get(rid) ?? []).sort((a, b) => a.at - b.at).map(item => item.request);
|
|
454
549
|
for (const wf of this.store.workflows.values()) {
|
|
455
|
-
const requests = this.ledgers.orch.entries().filter(e => e.type === 'request').map(e => e.request);
|
|
456
|
-
const sent = requests.filter(r => r.kind === 'send' && rids.includes(r.rid));
|
|
457
550
|
const visited = new Set();
|
|
458
551
|
for (const target of sent) {
|
|
459
552
|
const found = this.findCall(target.body.to, true);
|
|
@@ -526,6 +619,9 @@ export class Engine {
|
|
|
526
619
|
if (!target)
|
|
527
620
|
return { action: 'reject', reason: this.unknownCall(req.body?.to) };
|
|
528
621
|
const { wf, entry } = target, send = req.body;
|
|
622
|
+
// A command call runs a process, not an agent: nothing receives a message or switches a model (stop ends it).
|
|
623
|
+
if (isCommandCall(entry.spec))
|
|
624
|
+
return { action: 'reject', reason: `command call: ${String(send.kind)} is not supported (stop it, or start a new call)` };
|
|
529
625
|
const from = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
|
|
530
626
|
const seal = wf.journal.entries().find(e => e.type === JT.sealed && e.call === from);
|
|
531
627
|
if (seal && send.kind === 'steer')
|
|
@@ -623,7 +719,7 @@ export class Engine {
|
|
|
623
719
|
// them): a changed file refuses the resume before anything is recorded.
|
|
624
720
|
for (const wf of this.store.workflows.values()) {
|
|
625
721
|
const done = this.terminal(wf);
|
|
626
|
-
if (!inScope(wf) ||
|
|
722
|
+
if (!inScope(wf) || !(done?.status === 'parked' || (releasing && !done)))
|
|
627
723
|
continue;
|
|
628
724
|
try {
|
|
629
725
|
await this.store.ready(wf);
|
|
@@ -660,9 +756,14 @@ export class Engine {
|
|
|
660
756
|
}
|
|
661
757
|
else if (req.kind === 'drain') {
|
|
662
758
|
const { fence, origin, wid } = req.body ?? {}, scoped = Boolean(origin || wid);
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
759
|
+
// Recorded in one step of the executor's serial queue (F2): a command call's intent is either before the drain
|
|
760
|
+
// (it started; the hold never stops it) or after it (its start decision sees the hold and records none).
|
|
761
|
+
const record = async () => {
|
|
762
|
+
if (!this.ledgers.orch.entries().some(e => e.type === 'drain' && e.rid === req.rid)) {
|
|
763
|
+
await this.ledgers.orch.append('drain', { rid: req.rid, fence: fence === true, ...(wid ? { wid } : origin ? { origin } : {}) });
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
await (this.executor.exclusive ? this.executor.exclusive(record) : record());
|
|
666
767
|
if (fence === true) {
|
|
667
768
|
await this.executor.suspend(scoped ? w => this.held(w) : undefined);
|
|
668
769
|
for (const st of this.states.values())
|
|
@@ -678,7 +779,7 @@ export class Engine {
|
|
|
678
779
|
// A claimed subagent call only restricts (it cannot force); otherwise the main session's sender is authoritative.
|
|
679
780
|
const initiator = body.initiator && 'call' in body.initiator ? body.initiator : req.from.startsWith('main:') ? { origin: req.from } : body.initiator ?? { origin: req.from };
|
|
680
781
|
const gate = this.executor.quiesce?.() ?? { live: [], resume() { } };
|
|
681
|
-
const reason = restartRefusal(this.ledgers.home, gate.live.map(l => ({ ...l, origin: this.store.workflows.get(l.wid)?.origin })), body, req.from.startsWith('main:'));
|
|
782
|
+
const reason = restartRefusal(this.ledgers.home, gate.live.map(l => ({ ...l, origin: this.store.workflows.get(l.wid)?.origin })), body, req.from.startsWith('main:'), Date.now(), gate.commands ?? 0);
|
|
682
783
|
if (reason) {
|
|
683
784
|
gate.resume();
|
|
684
785
|
return { action: 'reject', reason };
|
|
@@ -749,6 +850,8 @@ export class Engine {
|
|
|
749
850
|
const log = wf.journal.entries(), has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
|
|
750
851
|
const openGeneration = log.some(e => e.type === 'generation' && !has(JT.sealed, 'call', `${wf.wid}@${e.revision}/${e.key}@${e.gen}`) && !has('retired', 'call', `${wf.wid}@${e.revision}/${e.key}@${e.gen}`));
|
|
751
852
|
const liveExec = log.some(e => e.type === JT.exec && !has(JT.fenced, 'exec', e.exec) && !has(JT.sealed, 'call', e.call));
|
|
853
|
+
if (unsealedCommandCalls(log).length)
|
|
854
|
+
return 'running-command';
|
|
752
855
|
if (openGeneration || liveExec || this.running.has(wf.wid) || [...this.generations].some(id => id.startsWith(`${wf.wid}@`)))
|
|
753
856
|
return 'open-generation';
|
|
754
857
|
if (log.some(e => e.type === 'fence-failed' && !log.some(r => r.seq > e.seq && ((r.type === JT.fenced && r.exec === e.exec) || (r.type === 'gate' && r.id === e.exec) ||
|
|
@@ -834,15 +937,19 @@ export class Engine {
|
|
|
834
937
|
this.opening.delete(wid);
|
|
835
938
|
}
|
|
836
939
|
}
|
|
837
|
-
dispatchGeneration(wf, entry, refusal) {
|
|
940
|
+
dispatchGeneration(wf, entry, refusal, checked = false) {
|
|
941
|
+
const id = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
|
|
942
|
+
if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
|
|
943
|
+
return;
|
|
838
944
|
// A finished workflow's pinned files are verified before a generation of it runs (the ticket names its origin); a
|
|
839
945
|
// sealed generation's run only repeats post-seal steps, which read no pinned file. When they do not verify, the
|
|
840
946
|
// generation is sealed failed (`pin-failed: …`) without a child, like any call that cannot be prepared: the engine
|
|
841
947
|
// goes on, the workflow ends again, and a later follow-up verifies the files again.
|
|
842
|
-
|
|
948
|
+
// Released pins (not resident) take the same asynchronous path: a getter must never throw out of this method.
|
|
949
|
+
if (refusal === undefined && !checked && !(this.store.verified(wf.wid) && this.store.pinsResident(wf)) && !callEntries(wf.journal, `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`).some(e => e.type === JT.sealed)) {
|
|
843
950
|
const revision = wf.revision, current = () => wf.revision === revision && this.store.workflows.get(wf.wid) === wf && !this.closed;
|
|
844
951
|
void this.store.ready(wf).then(() => { if (current())
|
|
845
|
-
this.dispatchGeneration(wf, entry); }, error => {
|
|
952
|
+
this.dispatchGeneration(wf, entry, undefined, true); }, error => {
|
|
846
953
|
if (!current())
|
|
847
954
|
return;
|
|
848
955
|
const reason = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
@@ -857,10 +964,19 @@ export class Engine {
|
|
|
857
964
|
}
|
|
858
965
|
// Pins not verified (a refusal, or the post-seal steps of a sealed generation): the ticket comes from the journal's
|
|
859
966
|
// entry alone, so a damaged pinned record cannot keep the call from sealing.
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
967
|
+
// After ready, pins released again before this dispatch reload through the checked getter; a load that fails
|
|
968
|
+
// seals this generation alone (`pin-failed: …`), so no getter error escapes and ready is not retried in a loop.
|
|
969
|
+
let ticket;
|
|
970
|
+
if (refusal !== undefined || !this.store.verified(wf.wid))
|
|
971
|
+
ticket = { ...this.unpinnedTicket(wf, entry), ...(refusal !== undefined ? { refusal } : {}) };
|
|
972
|
+
else
|
|
973
|
+
try {
|
|
974
|
+
ticket = this.ticket({ wf }, entry);
|
|
975
|
+
}
|
|
976
|
+
catch (error) {
|
|
977
|
+
refusal = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
978
|
+
ticket = { ...this.unpinnedTicket(wf, entry), refusal };
|
|
979
|
+
}
|
|
864
980
|
this.generations.add(id);
|
|
865
981
|
wf.journal.resting = false;
|
|
866
982
|
void this.executor.run(ticket).then(result => this.background(async () => {
|
|
@@ -929,7 +1045,11 @@ export class Engine {
|
|
|
929
1045
|
await this.ledgers.orch.append('send-note', { rid, model, effect });
|
|
930
1046
|
}
|
|
931
1047
|
ticket(st, entry) {
|
|
932
|
-
const spec = entry.spec
|
|
1048
|
+
const spec = entry.spec;
|
|
1049
|
+
// A command call runs no agent: its ticket carries the placeholder agent of an unpinned ticket.
|
|
1050
|
+
if (isCommandCall(spec))
|
|
1051
|
+
return this.unpinnedTicket(st.wf, entry);
|
|
1052
|
+
const agent = st.wf.pins.agents.find(a => a.name === spec.agent);
|
|
933
1053
|
if (!agent)
|
|
934
1054
|
throw new Error(`Unknown pinned agent: ${spec.agent}`);
|
|
935
1055
|
return { wid: st.wf.wid, widRev: `${st.wf.wid}@${st.wf.revision}`, key: entry.key, gen: entry.gen,
|
|
@@ -1017,8 +1137,21 @@ export class Engine {
|
|
|
1017
1137
|
}
|
|
1018
1138
|
if (st.replaying)
|
|
1019
1139
|
return;
|
|
1140
|
+
// A position is exposed at most once per workflow state (F1): two observers of one seal (an adopted command's watch
|
|
1141
|
+
// and a dispatch of the same call) may both deliver it; the first one wins, a later one is dropped.
|
|
1020
1142
|
for (const [pos, result] of st.ready) {
|
|
1021
|
-
|
|
1143
|
+
if (st.exposed.has(pos)) {
|
|
1144
|
+
st.ready.delete(pos);
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
st.exposed.add(pos);
|
|
1148
|
+
try {
|
|
1149
|
+
await st.wf.journal.append('exposed', { pos });
|
|
1150
|
+
}
|
|
1151
|
+
catch (error) {
|
|
1152
|
+
st.exposed.delete(pos);
|
|
1153
|
+
throw error;
|
|
1154
|
+
}
|
|
1022
1155
|
this.evaluator.send({ t: 'expose', wid: st.wf.wid, ev: st.ev, pos, result });
|
|
1023
1156
|
st.ready.delete(pos);
|
|
1024
1157
|
}
|
|
@@ -1030,7 +1163,8 @@ export class Engine {
|
|
|
1030
1163
|
const park = (error) => this.finish(st.wf, 'parked', undefined, error);
|
|
1031
1164
|
if (message.t === 'call') {
|
|
1032
1165
|
// An unknown agent name refuses that call (the script gets a failed result naming the available agents), like an invalid spec.
|
|
1033
|
-
|
|
1166
|
+
// A command call names no agent (its fingerprint pins agent null).
|
|
1167
|
+
const command = isCommandCall(message.spec), agent = command ? null : st.wf.pins.agents.find(a => a.name === message.spec.agent) ?? null;
|
|
1034
1168
|
const fingerprint = contentHash({ spec: message.spec, agent }), old = st.outputs.get(message.pos);
|
|
1035
1169
|
if (st.proposed.has(message.pos) || (old && (!['call', 'refused', 'reused'].includes(old.type) || old.key !== message.key || old.fingerprint !== fingerprint)))
|
|
1036
1170
|
return park(`Replay mismatch at ${message.pos}`);
|
|
@@ -1050,7 +1184,7 @@ export class Engine {
|
|
|
1050
1184
|
const reused = history.findLast(e => e.type === JT.sealed && matching.includes(String(e.call)));
|
|
1051
1185
|
const fields = { pos: message.pos, key: message.key, spec: message.spec, fingerprint };
|
|
1052
1186
|
const problems = validateCallSpec(message.spec);
|
|
1053
|
-
if (!problems.length && !agent)
|
|
1187
|
+
if (!problems.length && !agent && !command)
|
|
1054
1188
|
problems.push(unknownAgent(message.spec.agent, st.wf.pins.agents));
|
|
1055
1189
|
// A malformed spec from a script never runs: the script gets a failed result naming every problem.
|
|
1056
1190
|
if (problems.length)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Command calls: the workflow journal records the executor writes for them (documented in index.ts) and the questions
|
|
2
|
+
// the engine and recovery ask of them. Pure functions of the journal's entries.
|
|
3
|
+
import { JT } from "../../types.js";
|
|
4
|
+
export const COMMAND_INTENT = "command-intent";
|
|
5
|
+
export const COMMAND_STARTED = "command-started";
|
|
6
|
+
export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
|
|
7
|
+
export const COMMAND_TIMEOUT = "command-timeout";
|
|
8
|
+
export const COMMAND_WITHDRAWN = "command-withdrawn";
|
|
9
|
+
/** The attempt id (and process tag DSA_EXEC) of attempt `n` of a command call. */
|
|
10
|
+
export const commandId = (call, n) => `command:${call}#${n}`;
|
|
11
|
+
/** The attempt directory name (under the call dir) of attempt `n`. */
|
|
12
|
+
export const commandDirName = (n) => `command-${n}`;
|
|
13
|
+
/** Command calls with an attempt and no seal, not retired: a command that may run (the orchestrator adopts it). */
|
|
14
|
+
export function unsealedCommandCalls(entries) {
|
|
15
|
+
const calls = new Set();
|
|
16
|
+
for (const e of entries)
|
|
17
|
+
if (e.type === COMMAND_INTENT)
|
|
18
|
+
calls.add(String(e.call));
|
|
19
|
+
if (!calls.size)
|
|
20
|
+
return [];
|
|
21
|
+
for (const e of entries)
|
|
22
|
+
if ((e.type === JT.sealed || e.type === "retired") && calls.has(String(e.call)))
|
|
23
|
+
calls.delete(String(e.call));
|
|
24
|
+
return [...calls];
|
|
25
|
+
}
|
|
26
|
+
/** F4: Command calls with a live attempt: the call's latest `command-intent` has no later `command-withdrawn` with the
|
|
27
|
+
* same id (a process was, or may be being, started for it), and the call has neither `sealed` nor `retired`. Leftover
|
|
28
|
+
* processes of a retired call are ended by the next start's sweep; they do not make a call live. */
|
|
29
|
+
export function liveCommandCalls(entries) {
|
|
30
|
+
const latest = new Map(), withdrawn = new Set(), ended = new Set();
|
|
31
|
+
for (const e of entries) {
|
|
32
|
+
if (e.type === COMMAND_INTENT) {
|
|
33
|
+
latest.set(String(e.call), String(e.id));
|
|
34
|
+
withdrawn.delete(String(e.id));
|
|
35
|
+
}
|
|
36
|
+
else if (e.type === COMMAND_WITHDRAWN)
|
|
37
|
+
withdrawn.add(String(e.id));
|
|
38
|
+
else if (e.type === JT.sealed || e.type === "retired")
|
|
39
|
+
ended.add(String(e.call));
|
|
40
|
+
}
|
|
41
|
+
return [...latest].filter(([call, id]) => !ended.has(call) && !withdrawn.has(id)).map(([call]) => call);
|
|
42
|
+
}
|
|
43
|
+
/** Retired command calls without a seal: their processes, if any still run, are ended at the next start. */
|
|
44
|
+
export function retiredCommandAttempts(entries) {
|
|
45
|
+
const retired = new Set(entries.filter(e => e.type === "retired").map(e => String(e.call)));
|
|
46
|
+
const sealed = new Set(entries.filter(e => e.type === JT.sealed).map(e => String(e.call)));
|
|
47
|
+
const result = [];
|
|
48
|
+
for (const e of entries)
|
|
49
|
+
if (e.type === COMMAND_INTENT && retired.has(String(e.call)) && !sealed.has(String(e.call))) {
|
|
50
|
+
const started = entries.findLast(s => s.type === COMMAND_STARTED && s.id === e.id);
|
|
51
|
+
result.push({ call: String(e.call), id: String(e.id), ...(started ? { pid: Number(started.pid), start: String(started.start) } : {}) });
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|