pi-durable-subagents 1.0.43 → 1.1.0
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 +106 -0
- package/README.md +254 -27
- package/dist/agent/main/schema.js +6 -2
- package/dist/agent/main/snapshots.js +50 -4
- package/dist/agent/main/tool.js +18 -6
- package/dist/agent/main.js +6 -2
- package/dist/cli/hold.js +85 -80
- package/dist/cli/main.js +11 -4
- package/dist/cli/requests.js +70 -17
- package/dist/compat/fanout.js +13 -5
- package/dist/compat/spec.js +46 -1
- package/dist/events/waiting.js +16 -1
- package/dist/orchestrator/engine.js +200 -16
- package/dist/orchestrator/executor/command.js +61 -0
- package/dist/orchestrator/executor/ended.js +23 -0
- package/dist/orchestrator/executor/index.js +377 -11
- package/dist/orchestrator/executor/sweep.js +5 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/reader-ledger.js +65 -5
- package/dist/orchestrator/restart.js +4 -1
- package/dist/orchestrator/settled.js +6 -0
- package/dist/orchestrator/snapshot.js +104 -11
- package/dist/orchestrator/store.js +4 -4
- package/dist/platform/cmdline.js +16 -0
- package/dist/platform/command.js +98 -0
- package/dist/platform/containment.js +34 -0
- package/dist/platform/launch.js +13 -3
- package/dist/platform/lease.js +91 -44
- package/dist/platform/proctable.js +43 -5
- package/dist/requests.js +1 -1
- 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
|
@@ -21,7 +21,7 @@ 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;
|
|
@@ -56,7 +57,7 @@ export function unknownAgent(name, agents) {
|
|
|
56
57
|
return `unknown agent ${JSON.stringify(name)}; available agents: ${agents.map(a => a.name).sort().join(", ") || "none"}`;
|
|
57
58
|
}
|
|
58
59
|
/** v12 §3: Wake with bounded latest-per-key results, preferring structured reports and preserving clipped tails. */
|
|
59
|
-
export function finishedText(wid, entries, call) {
|
|
60
|
+
export function finishedText(wid, entries, call, commandOutput = false) {
|
|
60
61
|
const snap = snapshotFromEntries(wid, entries), label = snap.name ?? wid;
|
|
61
62
|
const latest = new Map(snap.calls.map(c => [c.key, c]));
|
|
62
63
|
const calls = call ? snap.calls.filter(c => c.callId === call) : [...latest.values()];
|
|
@@ -73,7 +74,7 @@ export function finishedText(wid, entries, call) {
|
|
|
73
74
|
// Share the space fairly: short results take what they need and the rest goes to longer ones (one agent may use it
|
|
74
75
|
// all), so a notice is cut only when the results really exceed it; usage and the full-output hint are never lost.
|
|
75
76
|
const want = calls.map(c => {
|
|
76
|
-
const message = c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
|
|
77
|
+
const message = commandOutput && c.command !== undefined ? c.result?.output : c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
|
|
77
78
|
return 120 + (message?.length ?? 0) + Math.min(320, c.result?.error?.length ?? 0);
|
|
78
79
|
});
|
|
79
80
|
const shares = new Array(calls.length).fill(0);
|
|
@@ -94,12 +95,25 @@ export function finishedText(wid, entries, call) {
|
|
|
94
95
|
const title = `\n${tail(name, allowance - 1)}`;
|
|
95
96
|
const error = result?.error && allowance - title.length > 10 ? `\n Error: ${tail(result.error, Math.min(300, allowance - title.length - 9))}` : '';
|
|
96
97
|
const space = allowance - title.length - error.length;
|
|
97
|
-
const message = result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
|
|
98
|
+
const message = commandOutput && c.command !== undefined ? result?.output : result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
|
|
98
99
|
const line = title + (message && space > 4 ? `\n ${tail(message.trimEnd(), space - 3)}` : '') + error;
|
|
99
100
|
lines.push(line);
|
|
100
101
|
}
|
|
101
102
|
return `${prefix}${lines.join('')}${footer}`;
|
|
102
103
|
}
|
|
104
|
+
export function wakeText(rid, wid, done, entries) {
|
|
105
|
+
const calls = [...new Map(snapshotFromEntries(wid, entries).calls.map(c => [c.key, c])).values()];
|
|
106
|
+
const lines = calls.slice(0, 20).map(c => {
|
|
107
|
+
const data = c.command !== undefined ? c.result?.data : undefined;
|
|
108
|
+
const ms = data?.durationMs ?? (c.endedAt !== undefined && c.startedAt !== undefined ? c.endedAt - c.startedAt : 0);
|
|
109
|
+
return `${c.key}: ${callStatus(c)}${data?.exitCode != null ? ` exit ${data.exitCode}` : ''}${data?.signal ? ` signal ${data.signal}` : ''} (${Math.max(0, Math.round(ms))}ms)`;
|
|
110
|
+
});
|
|
111
|
+
if (calls.length > 20)
|
|
112
|
+
lines.push(`… ${calls.length - 20} more`);
|
|
113
|
+
const head = `Durable run ${rid} (${wid}) that you started with --wake caller finished: ${done.status}.\n${lines.join('\n')}\n`;
|
|
114
|
+
const prefix = head.slice(0, 4000), space = 4000 - prefix.length;
|
|
115
|
+
return prefix + (space > 0 ? tail(finishedText(wid, entries, undefined, true), space) : '');
|
|
116
|
+
}
|
|
103
117
|
/** A1, P2, P10, P11: Serialize decisions while executions run independently. */
|
|
104
118
|
/** A key's latest call in the current revision: its first call or its newest generation. */
|
|
105
119
|
function latestCall(wf, key) {
|
|
@@ -171,7 +185,7 @@ export class Engine {
|
|
|
171
185
|
}
|
|
172
186
|
/** Nothing of the workflow is live: it ended (or parked), no script runs, no executor run or follow-up is open. */
|
|
173
187
|
quiescent(wf) {
|
|
174
|
-
if (!this.terminal(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
|
|
188
|
+
if (!this.terminal(wf) || this.wakePending(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
|
|
175
189
|
return false;
|
|
176
190
|
for (const id of this.generations)
|
|
177
191
|
if (id.startsWith(`${wf.wid}@`))
|
|
@@ -329,12 +343,60 @@ export class Engine {
|
|
|
329
343
|
this.dispatchGeneration(wf, entry);
|
|
330
344
|
await this.reopenForwarded(wf);
|
|
331
345
|
}
|
|
346
|
+
// Command calls outlive the orchestrator: each with an attempt and no seal is adopted, also in a held or ended
|
|
347
|
+
// workflow (whose replay dispatches nothing), and watched until it seals.
|
|
348
|
+
for (const wf of this.store.workflows.values())
|
|
349
|
+
if (!lazy(wf))
|
|
350
|
+
this.adoptCommands(wf);
|
|
332
351
|
await this.intake();
|
|
333
352
|
for (const wf of this.store.workflows.values())
|
|
334
353
|
this.settle(wf);
|
|
335
354
|
this.startWaiting();
|
|
336
355
|
return { workflows: this.store.workflows.size, calls, skipped };
|
|
337
356
|
}
|
|
357
|
+
/** Watch every unsealed command call of the current revision (Executor.run is idempotent per call: a replay's
|
|
358
|
+
* dispatch of the same call joins the same run). */
|
|
359
|
+
adoptCommands(wf) {
|
|
360
|
+
for (const call of unsealedCommandCalls(wf.journal.entries())) {
|
|
361
|
+
const m = /^(.*)@(\d+)\/(.*)@(\d+)$/.exec(call);
|
|
362
|
+
if (!m || Number(m[2]) !== wf.revision)
|
|
363
|
+
continue;
|
|
364
|
+
const entry = revisionEntries(wf).find(e => (e.type === 'call' || e.type === 'generation') && String(e.key) === m[3] && Number(e.gen) === Number(m[4]));
|
|
365
|
+
if (!entry)
|
|
366
|
+
continue;
|
|
367
|
+
const release = this.hold(wf.wid);
|
|
368
|
+
wf.journal.resting = false;
|
|
369
|
+
void this.executor.run(this.unpinnedTicket(wf, entry)).then(() => this.background(async () => {
|
|
370
|
+
try {
|
|
371
|
+
await this.deliverAdopted(wf, entry);
|
|
372
|
+
}
|
|
373
|
+
finally {
|
|
374
|
+
release();
|
|
375
|
+
}
|
|
376
|
+
}), error => {
|
|
377
|
+
release();
|
|
378
|
+
if (!(error instanceof Error && error.name === 'ExecutorShutdown'))
|
|
379
|
+
console.error(`durable-subagents: adopted command ${call}: ${String(error)}`);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** An adopted command call sealed: its result reaches the workflow as a dispatched call's does. The replay proposed
|
|
384
|
+
* it without dispatching (a held workflow dispatches nothing): it is ready now, and the script goes on (a new call
|
|
385
|
+
* it makes stays queued under the hold; a workflow that ends records done and its finished notice). One the replay
|
|
386
|
+
* has not reached yet is found sealed when it gets there; one a dispatch runs is delivered by that dispatch. */
|
|
387
|
+
async deliverAdopted(wf, entry) {
|
|
388
|
+
const st = this.states.get(wf.wid);
|
|
389
|
+
if (!st || st.wf !== wf || this.terminal(wf) || entry.type !== 'call')
|
|
390
|
+
return;
|
|
391
|
+
const pos = entry.pos, own = st.calls.get(pos);
|
|
392
|
+
if (!own || !st.proposed.has(pos) || st.running.has(pos) || st.ready.has(pos))
|
|
393
|
+
return;
|
|
394
|
+
const result = this.sealed(st, own);
|
|
395
|
+
if (!result)
|
|
396
|
+
return;
|
|
397
|
+
st.ready.set(pos, result);
|
|
398
|
+
await this.flush(st);
|
|
399
|
+
}
|
|
338
400
|
/** A successful call with a worktree whose removal (or keeping) is not recorded yet: its post-seal effect is due. */
|
|
339
401
|
worktreeUnsettled(wf, call) {
|
|
340
402
|
const log = callEntries(wf.journal, call), result = log.find(e => e.type === JT.sealed)?.result;
|
|
@@ -399,7 +461,7 @@ export class Engine {
|
|
|
399
461
|
const ev = Math.max(0, ...wf.journal.entries().filter(e => e.type === 'ev').map(e => e.n)) + 1;
|
|
400
462
|
await wf.journal.append('ev', { n: ev });
|
|
401
463
|
const calls = new Map(log.filter(e => ['call', 'refused', 'reused'].includes(e.type)).map(e => [e.pos, e]));
|
|
402
|
-
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 };
|
|
464
|
+
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 };
|
|
403
465
|
this.states.set(wf.wid, st);
|
|
404
466
|
this.evaluator.send({ t: 'start', wid: wf.wid, ev, scriptPath: wf.scriptPath, args: wf.pins.args, inputs: wf.inputs });
|
|
405
467
|
}
|
|
@@ -468,7 +530,8 @@ export class Engine {
|
|
|
468
530
|
throw error; });
|
|
469
531
|
}
|
|
470
532
|
}
|
|
471
|
-
|
|
533
|
+
await this.deliverWakes();
|
|
534
|
+
this.consumed = { length: this.intakeSeen, pending: this.lifecycle().open.size > 0 };
|
|
472
535
|
}
|
|
473
536
|
findCall(to, bareWid = false) {
|
|
474
537
|
for (const wf of this.store.workflows.values()) {
|
|
@@ -522,6 +585,23 @@ export class Engine {
|
|
|
522
585
|
}
|
|
523
586
|
if (req.kind === 'run') {
|
|
524
587
|
const created = this.ledgers.orch.entries().find(e => e.type === JT.created && e.rid === req.rid);
|
|
588
|
+
if (!created && req.body?.wake !== undefined) {
|
|
589
|
+
const { wake, caller } = req.body;
|
|
590
|
+
const match = typeof caller === 'string' && /^([^@/]+)@(\d+)\/(.+)@(\d+)$/.exec(caller);
|
|
591
|
+
const parent = match ? this.store.workflows.get(match[1]) : undefined;
|
|
592
|
+
const refuse = (reason) => ({ action: 'reject', reason: `wake caller: ${reason}` });
|
|
593
|
+
if (!match || !wake || wake.to !== `${match[1]}/${match[3]}`)
|
|
594
|
+
return refuse('invalid caller');
|
|
595
|
+
if (!parent || this.store.pruned().has(parent.wid))
|
|
596
|
+
return refuse('workflow missing or pruned');
|
|
597
|
+
if (parent.revision !== Number(match[2]))
|
|
598
|
+
return refuse('stale-revision');
|
|
599
|
+
const entry = latestCall(parent, match[3]);
|
|
600
|
+
if (!entry)
|
|
601
|
+
return refuse('unknown key');
|
|
602
|
+
if (isCommandCall(entry.spec))
|
|
603
|
+
return refuse('command call');
|
|
604
|
+
}
|
|
525
605
|
// Senders validate labels; a hand-written request must not bypass that.
|
|
526
606
|
const labels = req.body?.labels, invalid = !created && labels !== undefined ? labelsProblem(labels) : undefined;
|
|
527
607
|
if (invalid)
|
|
@@ -570,6 +650,9 @@ export class Engine {
|
|
|
570
650
|
if (!target)
|
|
571
651
|
return { action: 'reject', reason: this.unknownCall(req.body?.to) };
|
|
572
652
|
const { wf, entry } = target, send = req.body;
|
|
653
|
+
// A command call runs a process, not an agent: nothing receives a message or switches a model (stop ends it).
|
|
654
|
+
if (isCommandCall(entry.spec))
|
|
655
|
+
return { action: 'reject', reason: `command call: ${String(send.kind)} is not supported (stop it, or start a new call)` };
|
|
573
656
|
const from = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
|
|
574
657
|
const seal = wf.journal.entries().find(e => e.type === JT.sealed && e.call === from);
|
|
575
658
|
if (seal && send.kind === 'steer')
|
|
@@ -704,9 +787,14 @@ export class Engine {
|
|
|
704
787
|
}
|
|
705
788
|
else if (req.kind === 'drain') {
|
|
706
789
|
const { fence, origin, wid } = req.body ?? {}, scoped = Boolean(origin || wid);
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
790
|
+
// Recorded in one step of the executor's serial queue (F2): a command call's intent is either before the drain
|
|
791
|
+
// (it started; the hold never stops it) or after it (its start decision sees the hold and records none).
|
|
792
|
+
const record = async () => {
|
|
793
|
+
if (!this.ledgers.orch.entries().some(e => e.type === 'drain' && e.rid === req.rid)) {
|
|
794
|
+
await this.ledgers.orch.append('drain', { rid: req.rid, fence: fence === true, ...(wid ? { wid } : origin ? { origin } : {}) });
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
await (this.executor.exclusive ? this.executor.exclusive(record) : record());
|
|
710
798
|
if (fence === true) {
|
|
711
799
|
await this.executor.suspend(scoped ? w => this.held(w) : undefined);
|
|
712
800
|
for (const st of this.states.values())
|
|
@@ -722,7 +810,7 @@ export class Engine {
|
|
|
722
810
|
// A claimed subagent call only restricts (it cannot force); otherwise the main session's sender is authoritative.
|
|
723
811
|
const initiator = body.initiator && 'call' in body.initiator ? body.initiator : req.from.startsWith('main:') ? { origin: req.from } : body.initiator ?? { origin: req.from };
|
|
724
812
|
const gate = this.executor.quiesce?.() ?? { live: [], resume() { } };
|
|
725
|
-
const reason = restartRefusal(this.ledgers.home, gate.live.map(l => ({ ...l, origin: this.store.workflows.get(l.wid)?.origin })), body, req.from.startsWith('main:'));
|
|
813
|
+
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);
|
|
726
814
|
if (reason) {
|
|
727
815
|
gate.resume();
|
|
728
816
|
return { action: 'reject', reason };
|
|
@@ -781,6 +869,8 @@ export class Engine {
|
|
|
781
869
|
/** Housekeeping: Why a workflow cannot be pruned: not final (parked or running), open executor work, an unresolved
|
|
782
870
|
* fence failure, or ended after the cutoff. */
|
|
783
871
|
unprunable(wf, cutoff) {
|
|
872
|
+
if (this.wakePending(wf))
|
|
873
|
+
return 'wake pending';
|
|
784
874
|
const done = this.terminal(wf), status = done ? String(done.status) : 'running';
|
|
785
875
|
if (!['done', 'failed', 'stopped'].includes(status))
|
|
786
876
|
return `not-finished:${status}`;
|
|
@@ -793,6 +883,8 @@ export class Engine {
|
|
|
793
883
|
const log = wf.journal.entries(), has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
|
|
794
884
|
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}`));
|
|
795
885
|
const liveExec = log.some(e => e.type === JT.exec && !has(JT.fenced, 'exec', e.exec) && !has(JT.sealed, 'call', e.call));
|
|
886
|
+
if (unsealedCommandCalls(log).length)
|
|
887
|
+
return 'running-command';
|
|
796
888
|
if (openGeneration || liveExec || this.running.has(wf.wid) || [...this.generations].some(id => id.startsWith(`${wf.wid}@`)))
|
|
797
889
|
return 'open-generation';
|
|
798
890
|
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) ||
|
|
@@ -818,7 +910,9 @@ export class Engine {
|
|
|
818
910
|
catch (error) {
|
|
819
911
|
return `event-log: ${error instanceof Error ? error.message : String(error)}`;
|
|
820
912
|
}
|
|
821
|
-
|
|
913
|
+
const wake = wf.wake && wf.journal.entries().findLast(e => e.type === 'wake-outcome');
|
|
914
|
+
const wakeReceipt = wake ? { wake: { to: wf.wake.to, state: wake.state, rev: wake.rev, ...(wake.generation !== undefined ? { generation: wake.generation } : {}), ...(wake.reason !== undefined ? { reason: wake.reason } : {}) } } : {};
|
|
915
|
+
await this.ledgers.orch.append('pruned', { rid, wid: wf.wid, endedAt: done.ts, bytes, status: String(done.status), ...identity, ...wakeReceipt });
|
|
822
916
|
this.states.delete(wf.wid);
|
|
823
917
|
await this.store.drop(wf.wid);
|
|
824
918
|
try {
|
|
@@ -986,7 +1080,11 @@ export class Engine {
|
|
|
986
1080
|
await this.ledgers.orch.append('send-note', { rid, model, effect });
|
|
987
1081
|
}
|
|
988
1082
|
ticket(st, entry) {
|
|
989
|
-
const spec = entry.spec
|
|
1083
|
+
const spec = entry.spec;
|
|
1084
|
+
// A command call runs no agent: its ticket carries the placeholder agent of an unpinned ticket.
|
|
1085
|
+
if (isCommandCall(spec))
|
|
1086
|
+
return this.unpinnedTicket(st.wf, entry);
|
|
1087
|
+
const agent = st.wf.pins.agents.find(a => a.name === spec.agent);
|
|
990
1088
|
if (!agent)
|
|
991
1089
|
throw new Error(`Unknown pinned agent: ${spec.agent}`);
|
|
992
1090
|
return { wid: st.wf.wid, widRev: `${st.wf.wid}@${st.wf.revision}`, key: entry.key, gen: entry.gen,
|
|
@@ -1074,8 +1172,21 @@ export class Engine {
|
|
|
1074
1172
|
}
|
|
1075
1173
|
if (st.replaying)
|
|
1076
1174
|
return;
|
|
1175
|
+
// A position is exposed at most once per workflow state (F1): two observers of one seal (an adopted command's watch
|
|
1176
|
+
// and a dispatch of the same call) may both deliver it; the first one wins, a later one is dropped.
|
|
1077
1177
|
for (const [pos, result] of st.ready) {
|
|
1078
|
-
|
|
1178
|
+
if (st.exposed.has(pos)) {
|
|
1179
|
+
st.ready.delete(pos);
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
st.exposed.add(pos);
|
|
1183
|
+
try {
|
|
1184
|
+
await st.wf.journal.append('exposed', { pos });
|
|
1185
|
+
}
|
|
1186
|
+
catch (error) {
|
|
1187
|
+
st.exposed.delete(pos);
|
|
1188
|
+
throw error;
|
|
1189
|
+
}
|
|
1079
1190
|
this.evaluator.send({ t: 'expose', wid: st.wf.wid, ev: st.ev, pos, result });
|
|
1080
1191
|
st.ready.delete(pos);
|
|
1081
1192
|
}
|
|
@@ -1087,7 +1198,8 @@ export class Engine {
|
|
|
1087
1198
|
const park = (error) => this.finish(st.wf, 'parked', undefined, error);
|
|
1088
1199
|
if (message.t === 'call') {
|
|
1089
1200
|
// An unknown agent name refuses that call (the script gets a failed result naming the available agents), like an invalid spec.
|
|
1090
|
-
|
|
1201
|
+
// A command call names no agent (its fingerprint pins agent null).
|
|
1202
|
+
const command = isCommandCall(message.spec), agent = command ? null : st.wf.pins.agents.find(a => a.name === message.spec.agent) ?? null;
|
|
1091
1203
|
const fingerprint = contentHash({ spec: message.spec, agent }), old = st.outputs.get(message.pos);
|
|
1092
1204
|
if (st.proposed.has(message.pos) || (old && (!['call', 'refused', 'reused'].includes(old.type) || old.key !== message.key || old.fingerprint !== fingerprint)))
|
|
1093
1205
|
return park(`Replay mismatch at ${message.pos}`);
|
|
@@ -1107,7 +1219,7 @@ export class Engine {
|
|
|
1107
1219
|
const reused = history.findLast(e => e.type === JT.sealed && matching.includes(String(e.call)));
|
|
1108
1220
|
const fields = { pos: message.pos, key: message.key, spec: message.spec, fingerprint };
|
|
1109
1221
|
const problems = validateCallSpec(message.spec);
|
|
1110
|
-
if (!problems.length && !agent)
|
|
1222
|
+
if (!problems.length && !agent && !command)
|
|
1111
1223
|
problems.push(unknownAgent(message.spec.agent, st.wf.pins.agents));
|
|
1112
1224
|
// A malformed spec from a script never runs: the script gets a failed result naming every problem.
|
|
1113
1225
|
if (problems.length)
|
|
@@ -1167,6 +1279,78 @@ export class Engine {
|
|
|
1167
1279
|
if (done && !wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${wf.wid}` && e.item.rev === rev)) {
|
|
1168
1280
|
await wf.journal.append(JT.attention, { item: { id: `finished:${wf.wid}`, rev, kind: 'finished', wid: wf.wid, text: finishedText(wf.wid, wf.journal.entries()) } });
|
|
1169
1281
|
}
|
|
1282
|
+
await this.deliverWake(wf);
|
|
1283
|
+
}
|
|
1284
|
+
/** A pending wake keeps the journal decoded and unprunable until its durable outcome is recorded. */
|
|
1285
|
+
wakePending(wf) {
|
|
1286
|
+
if (!wf.wake || lazy(wf))
|
|
1287
|
+
return false;
|
|
1288
|
+
const log = wf.journal.entries(), rev = log.filter(e => e.type === JT.done).length;
|
|
1289
|
+
return !rev || !log.some(e => e.type === 'wake-outcome' && e.rev === rev);
|
|
1290
|
+
}
|
|
1291
|
+
async deliverWakes() {
|
|
1292
|
+
for (const wf of this.store.workflows.values())
|
|
1293
|
+
if (wf.wake && !lazy(wf)) {
|
|
1294
|
+
await this.deliverWake(wf);
|
|
1295
|
+
this.settle(wf);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
/** The intent pins the message before admission. Lifecycle resolution and send's existing generation/forward
|
|
1299
|
+
* receipts make every crash cut replayable, including a crash between the send effect and its decision. */
|
|
1300
|
+
waking = new Map();
|
|
1301
|
+
deliverWake(wf) {
|
|
1302
|
+
const pending = this.waking.get(wf.wid);
|
|
1303
|
+
if (pending)
|
|
1304
|
+
return pending;
|
|
1305
|
+
const run = this.deliverWakeNow(wf).finally(() => { if (this.waking.get(wf.wid) === run)
|
|
1306
|
+
this.waking.delete(wf.wid); });
|
|
1307
|
+
this.waking.set(wf.wid, run);
|
|
1308
|
+
return run;
|
|
1309
|
+
}
|
|
1310
|
+
async deliverWakeNow(wf) {
|
|
1311
|
+
if (!wf.wake || lazy(wf))
|
|
1312
|
+
return;
|
|
1313
|
+
const { rid, to, caller } = wf.wake;
|
|
1314
|
+
const dones = wf.journal.entries().filter(e => e.type === JT.done);
|
|
1315
|
+
for (const [n, done] of dones.entries()) {
|
|
1316
|
+
const rev = n + 1;
|
|
1317
|
+
if (wf.journal.entries().some(e => e.type === 'wake-outcome' && e.rev === rev))
|
|
1318
|
+
continue;
|
|
1319
|
+
let intent = wf.journal.entries().find(e => e.type === 'wake-request' && e.rev === rev);
|
|
1320
|
+
if (!intent) {
|
|
1321
|
+
const target = this.findCall(to), id = target && `${target.wf.wid}@${target.wf.revision}/${target.entry.key}@${target.entry.gen}`;
|
|
1322
|
+
const seal = target?.wf.journal.entries().find(e => e.type === JT.sealed && e.call === id);
|
|
1323
|
+
if (target && `${target.wf.wid}@${target.wf.revision}` === caller.slice(0, caller.indexOf('/')) && seal?.result?.status === 'stopped') {
|
|
1324
|
+
await wf.journal.append('wake-outcome', { rev, state: 'skipped', reason: 'caller stopped' });
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
const request = { rid: `wake-${contentHash([rid, rev]).slice(0, 32)}`, from: `wake:${rid}:${rev}`, to: 'orch', sseq: 1,
|
|
1328
|
+
kind: 'send', cond: { epoch: caller.slice(0, caller.indexOf('/')) }, body: { to, kind: 'follow-up', message: wakeText(requestId(rid) ?? rid, wf.wid, done, wf.journal.entries().filter(e => e.seq <= done.seq)) } };
|
|
1329
|
+
intent = await wf.journal.append('wake-request', { rev, request });
|
|
1330
|
+
}
|
|
1331
|
+
const request = intent.request;
|
|
1332
|
+
for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => ({ action: 'defer' }))) {
|
|
1333
|
+
if (type === 'admitted')
|
|
1334
|
+
await this.ledgers.orch.append('request', { request });
|
|
1335
|
+
await this.ledgers.orch.append(type, fields);
|
|
1336
|
+
}
|
|
1337
|
+
let resolution = this.lifecycle().resolved.get(request.rid);
|
|
1338
|
+
if (!resolution) {
|
|
1339
|
+
const decision = await this.decide(request);
|
|
1340
|
+
if (decision.action === 'defer')
|
|
1341
|
+
return;
|
|
1342
|
+
for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => decision))
|
|
1343
|
+
await this.ledgers.orch.append(type, fields);
|
|
1344
|
+
resolution = this.lifecycle().resolved.get(request.rid);
|
|
1345
|
+
}
|
|
1346
|
+
if (!resolution)
|
|
1347
|
+
continue;
|
|
1348
|
+
const target = this.findCall(to), opened = target && revisionEntries(target.wf).find(e => e.type === 'generation' && generationRids(e).includes(request.rid));
|
|
1349
|
+
const forward = target && target.wf.journal.entries().find(e => e.type === 'forward' && e.rid === request.rid);
|
|
1350
|
+
const generation = opened ? Number(opened.gen) : forward ? Number(String(forward.dest).match(/@(\d+)$/)?.[1]) : undefined;
|
|
1351
|
+
await wf.journal.append('wake-outcome', { rev, state: resolution.type === 'applied' ? 'applied' : 'rejected',
|
|
1352
|
+
...(resolution.type === 'rejected' ? { reason: resolution.reason } : {}), ...(generation !== undefined ? { generation } : {}) });
|
|
1353
|
+
}
|
|
1170
1354
|
}
|
|
1171
1355
|
async resolveFinished(wf) {
|
|
1172
1356
|
for (const { item } of attentionEntries(wf.journal.entries())) {
|
|
@@ -0,0 +1,61 @@
|
|
|
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 { delimiter } from "node:path";
|
|
4
|
+
import { binDir } from "../../paths.js";
|
|
5
|
+
import { JT } from "../../types.js";
|
|
6
|
+
/** EX3: Custom/inherited tools win; the orchestrator's shim is the last PATH entry, never an empty entry. */
|
|
7
|
+
export function commandEnvironment(home, id, call, env) {
|
|
8
|
+
const bin = binDir(home), PATH = [...(env?.PATH ?? process.env.PATH ?? "").split(delimiter).filter(p => p && p !== bin), bin].join(delimiter);
|
|
9
|
+
return { ...process.env, ...env, PATH, DSA_EXEC: id, DSA_CALL: call, DSA_HOME: home };
|
|
10
|
+
}
|
|
11
|
+
export const COMMAND_INTENT = "command-intent";
|
|
12
|
+
export const COMMAND_STARTED = "command-started";
|
|
13
|
+
export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
|
|
14
|
+
export const COMMAND_TIMEOUT = "command-timeout";
|
|
15
|
+
export const COMMAND_WITHDRAWN = "command-withdrawn";
|
|
16
|
+
/** The attempt id (and process tag DSA_EXEC) of attempt `n` of a command call. */
|
|
17
|
+
export const commandId = (call, n) => `command:${call}#${n}`;
|
|
18
|
+
/** The attempt directory name (under the call dir) of attempt `n`. */
|
|
19
|
+
export const commandDirName = (n) => `command-${n}`;
|
|
20
|
+
/** Command calls with an attempt and no seal, not retired: a command that may run (the orchestrator adopts it). */
|
|
21
|
+
export function unsealedCommandCalls(entries) {
|
|
22
|
+
const calls = new Set();
|
|
23
|
+
for (const e of entries)
|
|
24
|
+
if (e.type === COMMAND_INTENT)
|
|
25
|
+
calls.add(String(e.call));
|
|
26
|
+
if (!calls.size)
|
|
27
|
+
return [];
|
|
28
|
+
for (const e of entries)
|
|
29
|
+
if ((e.type === JT.sealed || e.type === "retired") && calls.has(String(e.call)))
|
|
30
|
+
calls.delete(String(e.call));
|
|
31
|
+
return [...calls];
|
|
32
|
+
}
|
|
33
|
+
/** F4: Command calls with a live attempt: the call's latest `command-intent` has no later `command-withdrawn` with the
|
|
34
|
+
* same id (a process was, or may be being, started for it), and the call has neither `sealed` nor `retired`. Leftover
|
|
35
|
+
* processes of a retired call are ended by the next start's sweep; they do not make a call live. */
|
|
36
|
+
export function liveCommandCalls(entries) {
|
|
37
|
+
const latest = new Map(), withdrawn = new Set(), ended = new Set();
|
|
38
|
+
for (const e of entries) {
|
|
39
|
+
if (e.type === COMMAND_INTENT) {
|
|
40
|
+
latest.set(String(e.call), String(e.id));
|
|
41
|
+
withdrawn.delete(String(e.id));
|
|
42
|
+
}
|
|
43
|
+
else if (e.type === COMMAND_WITHDRAWN)
|
|
44
|
+
withdrawn.add(String(e.id));
|
|
45
|
+
else if (e.type === JT.sealed || e.type === "retired")
|
|
46
|
+
ended.add(String(e.call));
|
|
47
|
+
}
|
|
48
|
+
return [...latest].filter(([call, id]) => !ended.has(call) && !withdrawn.has(id)).map(([call]) => call);
|
|
49
|
+
}
|
|
50
|
+
/** Retired command calls without a seal: their processes, if any still run, are ended at the next start. */
|
|
51
|
+
export function retiredCommandAttempts(entries) {
|
|
52
|
+
const retired = new Set(entries.filter(e => e.type === "retired").map(e => String(e.call)));
|
|
53
|
+
const sealed = new Set(entries.filter(e => e.type === JT.sealed).map(e => String(e.call)));
|
|
54
|
+
const result = [];
|
|
55
|
+
for (const e of entries)
|
|
56
|
+
if (e.type === COMMAND_INTENT && retired.has(String(e.call)) && !sealed.has(String(e.call))) {
|
|
57
|
+
const started = entries.findLast(s => s.type === COMMAND_STARTED && s.id === e.id);
|
|
58
|
+
result.push({ call: String(e.call), id: String(e.id), ...(started ? { pid: Number(started.pid), start: String(started.start) } : {}) });
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { commandLine } from "../../platform/cmdline.js";
|
|
2
|
+
/** EX1 / WK8: Agent fences only. The direct child's tracked identity is retained across recovery (old journals: first tracked). */
|
|
3
|
+
export async function fenceAgent(containment, journal, exec, tracked, child) {
|
|
4
|
+
const options = { beforeKill: async (targets, signal) => {
|
|
5
|
+
const identities = journal.entries().filter(e => e.type === "tracked" && e.exec === exec);
|
|
6
|
+
const direct = child ?? identities.find(e => e.child === true) ?? identities[0];
|
|
7
|
+
// R-11-3: a crash after spawn but before tracked leaves no provable direct identity. Roots of the target
|
|
8
|
+
// forest may be pi or orphaned descendants: omit all roots rather than ever reporting the direct child.
|
|
9
|
+
const pids = new Set(targets.map(p => p.pid));
|
|
10
|
+
const others = direct ? targets.filter(p => p.pid !== direct.pid || p.start !== direct.start)
|
|
11
|
+
: targets.filter(p => pids.has(p.ppid));
|
|
12
|
+
if (!others.length || signal.aborted)
|
|
13
|
+
return;
|
|
14
|
+
const commands = await Promise.all(others.map(async (p) => ({ pid: p.pid, command: await commandLine(p.pid, signal) })));
|
|
15
|
+
const procs = commands.slice(0, 20);
|
|
16
|
+
// The timeout cancels command reads and prevents an outstanding read from appending after the kill/seal.
|
|
17
|
+
if (signal.aborted)
|
|
18
|
+
return;
|
|
19
|
+
await journal.append("ended", { exec, call: exec.slice(0, exec.lastIndexOf("#")), procs,
|
|
20
|
+
...(others.length > procs.length ? { more: others.length - procs.length } : {}) });
|
|
21
|
+
} };
|
|
22
|
+
await containment.fence(exec, tracked, options);
|
|
23
|
+
}
|