pi-durable-subagents 1.0.43 → 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 +40 -0
- package/README.md +90 -8
- 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/main.js +5 -3
- package/dist/cli/requests.js +20 -3
- 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 +87 -10
- package/dist/orchestrator/executor/command.js +54 -0
- package/dist/orchestrator/executor/index.js +360 -8
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/restart.js +4 -1
- package/dist/orchestrator/settled.js +4 -0
- package/dist/orchestrator/snapshot.js +86 -9
- package/dist/platform/command.js +98 -0
- package/dist/platform/launch.js +13 -3
- 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
package/dist/compat/spec.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { schemaProblems } from "../agent/child/schema.js";
|
|
2
|
-
const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer"]);
|
|
2
|
+
const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun"]);
|
|
3
|
+
/** Fields a command call takes; every other known field belongs to agent calls. */
|
|
4
|
+
export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key"];
|
|
5
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
3
6
|
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
4
7
|
const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
5
8
|
const text = (v) => typeof v === "string" && v.trim() !== "";
|
|
@@ -46,6 +49,11 @@ export function validateCallSpec(spec, options = {}) {
|
|
|
46
49
|
else if (k === "key" && !options.fanout)
|
|
47
50
|
errors.push("key is only allowed in tasks/chain steps");
|
|
48
51
|
}
|
|
52
|
+
if (has("command"))
|
|
53
|
+
return [...errors, ...commandProblems(s, options)];
|
|
54
|
+
for (const k of ["env", "rerun"])
|
|
55
|
+
if (has(k))
|
|
56
|
+
errors.push(`${k} is only allowed in a command call`);
|
|
49
57
|
if (!text(s.agent))
|
|
50
58
|
errors.push(`agent must be a non-empty string${has("agent") ? got(s.agent) : ""}`);
|
|
51
59
|
if (!text(s.task))
|
|
@@ -76,3 +84,40 @@ export function validateCallSpec(spec, options = {}) {
|
|
|
76
84
|
errors.push("key must be a non-empty string");
|
|
77
85
|
return errors;
|
|
78
86
|
}
|
|
87
|
+
/** A command call: command (argv array or sh string) plus cwd, timeoutMs, env, rerun, writer, key; nothing else. */
|
|
88
|
+
function commandProblems(s, options) {
|
|
89
|
+
const errors = [], has = (k) => s[k] !== undefined;
|
|
90
|
+
for (const k of Object.keys(s))
|
|
91
|
+
if (has(k) && fields.has(k) && !COMMAND_FIELDS.includes(k))
|
|
92
|
+
errors.push(`${k} is not allowed in a command call`);
|
|
93
|
+
const c = s.command;
|
|
94
|
+
if (Array.isArray(c)) {
|
|
95
|
+
if (!c.length || !c.every(v => typeof v === "string") || !text(c[0]))
|
|
96
|
+
errors.push(`command must be a non-empty string or an array of strings with a non-empty first element${got(c)}`);
|
|
97
|
+
}
|
|
98
|
+
else if (!text(c))
|
|
99
|
+
errors.push(`command must be a non-empty string or an array of strings with a non-empty first element${got(c)}`);
|
|
100
|
+
if (has("cwd") && typeof s.cwd !== "string")
|
|
101
|
+
errors.push(`cwd must be a string${got(s.cwd)}`);
|
|
102
|
+
if (has("timeoutMs") && !positive(s.timeoutMs))
|
|
103
|
+
errors.push(`timeoutMs must be a positive number (milliseconds)${got(s.timeoutMs)}`);
|
|
104
|
+
if (has("env")) {
|
|
105
|
+
if (!isObject(s.env))
|
|
106
|
+
errors.push(`env must be an object of strings${got(s.env)}`);
|
|
107
|
+
else
|
|
108
|
+
for (const [k, v] of Object.entries(s.env)) {
|
|
109
|
+
if (!ENV_NAME.test(k))
|
|
110
|
+
errors.push(`env name ${JSON.stringify(k)} is not a valid variable name`);
|
|
111
|
+
else if (k.startsWith("DSA_"))
|
|
112
|
+
errors.push(`env name ${k} is reserved (DSA_*)`);
|
|
113
|
+
if (typeof v !== "string")
|
|
114
|
+
errors.push(`env.${k} must be a string${got(v)}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
for (const k of ["rerun", "writer"])
|
|
118
|
+
if (has(k) && typeof s[k] !== "boolean")
|
|
119
|
+
errors.push(`${k} must be a boolean${got(s[k])}`);
|
|
120
|
+
if (options.fanout && has("key") && !text(s.key))
|
|
121
|
+
errors.push("key must be a non-empty string");
|
|
122
|
+
return errors;
|
|
123
|
+
}
|
package/dist/events/waiting.js
CHANGED
|
@@ -102,7 +102,19 @@ function applyWait(f, e) {
|
|
|
102
102
|
case "generation": {
|
|
103
103
|
const key = String(e.key), gen = Number(e.gen) || 1, call = `${f.wid}@${f.rev}/${key}@${gen}`, spec = e.spec;
|
|
104
104
|
const wanted = typeof e.model === "string" && e.model ? e.model : typeof spec?.model === "string" && spec.model ? spec.model : undefined;
|
|
105
|
-
f.calls.set(call, { call, key, gen, generation: e.type === "generation", ...(typeof spec?.agent === "string" ? { agent: spec.agent } : {}), ...(wanted ? { wanted } : {})
|
|
105
|
+
f.calls.set(call, { call, key, gen, generation: e.type === "generation", ...(typeof spec?.agent === "string" ? { agent: spec.agent } : {}), ...(wanted ? { wanted } : {}),
|
|
106
|
+
...(spec?.command !== undefined ? { command: true } : {}) });
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
case "command-intent": {
|
|
110
|
+
const c = f.calls.get(String(e.call));
|
|
111
|
+
if (c?.command) {
|
|
112
|
+
c.exec = String(e.id);
|
|
113
|
+
c.queued = e.ts;
|
|
114
|
+
c.selected = true;
|
|
115
|
+
c.fenced = false;
|
|
116
|
+
delete c.writer;
|
|
117
|
+
}
|
|
106
118
|
break;
|
|
107
119
|
}
|
|
108
120
|
case JT.exec: {
|
|
@@ -221,6 +233,9 @@ catch {
|
|
|
221
233
|
export function waitInput(f, c, env, agentModel) {
|
|
222
234
|
// An answered asker is queued (live) although its hibernated execution is fenced, unless a drain holds its workflow.
|
|
223
235
|
const answered = c.answered !== undefined && !env.held?.(f.wid);
|
|
236
|
+
// A command call queued behind a writer lock has no attempt yet: the lock is its wait (it takes no slot).
|
|
237
|
+
if (c.command && !c.exec)
|
|
238
|
+
return c.writer ? { asking: false, exec: { id: "", since: c.writer.since, selected: false }, writerWait: c.writer } : { asking: false };
|
|
224
239
|
const settings = settingsOf(env.ledger, env.config ?? {}), live = c.exec && (!c.fenced || answered), selected = c.selected && c.answered === undefined;
|
|
225
240
|
const attention = [];
|
|
226
241
|
let asking = false;
|
|
@@ -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;
|
|
@@ -329,12 +330,60 @@ export class Engine {
|
|
|
329
330
|
this.dispatchGeneration(wf, entry);
|
|
330
331
|
await this.reopenForwarded(wf);
|
|
331
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);
|
|
332
338
|
await this.intake();
|
|
333
339
|
for (const wf of this.store.workflows.values())
|
|
334
340
|
this.settle(wf);
|
|
335
341
|
this.startWaiting();
|
|
336
342
|
return { workflows: this.store.workflows.size, calls, skipped };
|
|
337
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
|
+
}
|
|
338
387
|
/** A successful call with a worktree whose removal (or keeping) is not recorded yet: its post-seal effect is due. */
|
|
339
388
|
worktreeUnsettled(wf, call) {
|
|
340
389
|
const log = callEntries(wf.journal, call), result = log.find(e => e.type === JT.sealed)?.result;
|
|
@@ -399,7 +448,7 @@ export class Engine {
|
|
|
399
448
|
const ev = Math.max(0, ...wf.journal.entries().filter(e => e.type === 'ev').map(e => e.n)) + 1;
|
|
400
449
|
await wf.journal.append('ev', { n: ev });
|
|
401
450
|
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 };
|
|
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 };
|
|
403
452
|
this.states.set(wf.wid, st);
|
|
404
453
|
this.evaluator.send({ t: 'start', wid: wf.wid, ev, scriptPath: wf.scriptPath, args: wf.pins.args, inputs: wf.inputs });
|
|
405
454
|
}
|
|
@@ -570,6 +619,9 @@ export class Engine {
|
|
|
570
619
|
if (!target)
|
|
571
620
|
return { action: 'reject', reason: this.unknownCall(req.body?.to) };
|
|
572
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)` };
|
|
573
625
|
const from = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
|
|
574
626
|
const seal = wf.journal.entries().find(e => e.type === JT.sealed && e.call === from);
|
|
575
627
|
if (seal && send.kind === 'steer')
|
|
@@ -704,9 +756,14 @@ export class Engine {
|
|
|
704
756
|
}
|
|
705
757
|
else if (req.kind === 'drain') {
|
|
706
758
|
const { fence, origin, wid } = req.body ?? {}, scoped = Boolean(origin || wid);
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
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());
|
|
710
767
|
if (fence === true) {
|
|
711
768
|
await this.executor.suspend(scoped ? w => this.held(w) : undefined);
|
|
712
769
|
for (const st of this.states.values())
|
|
@@ -722,7 +779,7 @@ export class Engine {
|
|
|
722
779
|
// A claimed subagent call only restricts (it cannot force); otherwise the main session's sender is authoritative.
|
|
723
780
|
const initiator = body.initiator && 'call' in body.initiator ? body.initiator : req.from.startsWith('main:') ? { origin: req.from } : body.initiator ?? { origin: req.from };
|
|
724
781
|
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:'));
|
|
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);
|
|
726
783
|
if (reason) {
|
|
727
784
|
gate.resume();
|
|
728
785
|
return { action: 'reject', reason };
|
|
@@ -793,6 +850,8 @@ export class Engine {
|
|
|
793
850
|
const log = wf.journal.entries(), has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
|
|
794
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}`));
|
|
795
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';
|
|
796
855
|
if (openGeneration || liveExec || this.running.has(wf.wid) || [...this.generations].some(id => id.startsWith(`${wf.wid}@`)))
|
|
797
856
|
return 'open-generation';
|
|
798
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) ||
|
|
@@ -986,7 +1045,11 @@ export class Engine {
|
|
|
986
1045
|
await this.ledgers.orch.append('send-note', { rid, model, effect });
|
|
987
1046
|
}
|
|
988
1047
|
ticket(st, entry) {
|
|
989
|
-
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);
|
|
990
1053
|
if (!agent)
|
|
991
1054
|
throw new Error(`Unknown pinned agent: ${spec.agent}`);
|
|
992
1055
|
return { wid: st.wf.wid, widRev: `${st.wf.wid}@${st.wf.revision}`, key: entry.key, gen: entry.gen,
|
|
@@ -1074,8 +1137,21 @@ export class Engine {
|
|
|
1074
1137
|
}
|
|
1075
1138
|
if (st.replaying)
|
|
1076
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.
|
|
1077
1142
|
for (const [pos, result] of st.ready) {
|
|
1078
|
-
|
|
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
|
+
}
|
|
1079
1155
|
this.evaluator.send({ t: 'expose', wid: st.wf.wid, ev: st.ev, pos, result });
|
|
1080
1156
|
st.ready.delete(pos);
|
|
1081
1157
|
}
|
|
@@ -1087,7 +1163,8 @@ export class Engine {
|
|
|
1087
1163
|
const park = (error) => this.finish(st.wf, 'parked', undefined, error);
|
|
1088
1164
|
if (message.t === 'call') {
|
|
1089
1165
|
// An unknown agent name refuses that call (the script gets a failed result naming the available agents), like an invalid spec.
|
|
1090
|
-
|
|
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;
|
|
1091
1168
|
const fingerprint = contentHash({ spec: message.spec, agent }), old = st.outputs.get(message.pos);
|
|
1092
1169
|
if (st.proposed.has(message.pos) || (old && (!['call', 'refused', 'reused'].includes(old.type) || old.key !== message.key || old.fingerprint !== fingerprint)))
|
|
1093
1170
|
return park(`Replay mismatch at ${message.pos}`);
|
|
@@ -1107,7 +1184,7 @@ export class Engine {
|
|
|
1107
1184
|
const reused = history.findLast(e => e.type === JT.sealed && matching.includes(String(e.call)));
|
|
1108
1185
|
const fields = { pos: message.pos, key: message.key, spec: message.spec, fingerprint };
|
|
1109
1186
|
const problems = validateCallSpec(message.spec);
|
|
1110
|
-
if (!problems.length && !agent)
|
|
1187
|
+
if (!problems.length && !agent && !command)
|
|
1111
1188
|
problems.push(unknownAgent(message.spec.agent, st.wf.pins.agents));
|
|
1112
1189
|
// A malformed spec from a script never runs: the script gets a failed result naming every problem.
|
|
1113
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
|
+
}
|