pi-durable-subagents 1.0.33 → 1.0.37
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 +54 -0
- package/README.md +97 -8
- package/dist/agent/main/tool.js +26 -1
- package/dist/agent/main.js +6 -8
- package/dist/cli/control.js +6 -6
- package/dist/cli/doctor.js +20 -1
- package/dist/cli/main.js +15 -9
- package/dist/cli/requests.js +9 -10
- package/dist/cli/restart.js +2 -1
- package/dist/cli/service.js +6 -4
- package/dist/compat/model.js +12 -6
- package/dist/events/derive.js +13 -4
- package/dist/events/waiting.js +36 -13
- package/dist/kernel/mailbox.js +2 -0
- package/dist/orchestrator/config.js +18 -3
- package/dist/orchestrator/engine.js +77 -20
- package/dist/orchestrator/executor/index.js +248 -66
- package/dist/orchestrator/ledger.js +6 -3
- package/dist/orchestrator/main.js +24 -9
- package/dist/orchestrator/notes.js +27 -0
- package/dist/orchestrator/snapshot.js +67 -17
- package/dist/platform/launch.js +127 -0
- package/dist/platform/lease.js +58 -14
- package/dist/platform/proctable.js +6 -3
- package/dist/ui/cards.js +1 -0
- package/dist/ui/screen.js +4 -3
- package/dist/ui/tool.js +3 -3
- package/dist/ui/view.js +1 -1
- package/package.json +1 -1
|
@@ -6,11 +6,13 @@
|
|
|
6
6
|
// observation{exec,event}; selected{exec,model}; switch-observed{exec,rid,pool}.
|
|
7
7
|
// P28 entries are documented in hibernate.ts; generation session publication in generation.ts.
|
|
8
8
|
// session-corrupt{call,line}: a malformed native session line was skipped (once per line, E4).
|
|
9
|
+
// spawn-env-failed{exec,call,command,error}: launching the child failed for a reason of the environment (ENOENT, EACCES:
|
|
10
|
+
// pi or its interpreter missing or not executable); the call stays queued and launches again after a backoff.
|
|
9
11
|
// fence-failed{exec,error} is documented in sweep.ts. The orchestrator ledger owns hold/release{pool,slot,exec}
|
|
10
12
|
// and mem{available,admitted,exec} (every admission; a repeated refusal at most every 30 s per call). All transitions are serialized before publication.
|
|
11
13
|
import { mkdir, open, readdir, readFile, realpath, rm, unlink, writeFile } from "node:fs/promises";
|
|
12
14
|
import { homedir } from "node:os";
|
|
13
|
-
import { delimiter, join } from "node:path";
|
|
15
|
+
import { delimiter, dirname, join } from "node:path";
|
|
14
16
|
import { fileURLToPath } from "node:url";
|
|
15
17
|
import { CT, JT, attentionEntries, isEntry } from "../../types.js";
|
|
16
18
|
import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
|
|
@@ -19,7 +21,7 @@ import { Outbox } from "../../kernel/mailbox.js";
|
|
|
19
21
|
import { contentHash, forwardRid } from "../../kernel/ids.js";
|
|
20
22
|
import { capacity, seal } from "../../kernel/guards.js";
|
|
21
23
|
import { buildPiArgs } from "../../compat/pi-args.js";
|
|
22
|
-
import { parseModel, resolveModel } from "../../compat/model.js";
|
|
24
|
+
import { parseModel, plainModel, resolveModel } from "../../compat/model.js";
|
|
23
25
|
import { buildCallResult } from "../../compat/result.js";
|
|
24
26
|
import createEffects from "./effects/index.js";
|
|
25
27
|
import { continueSession } from "./generation.js";
|
|
@@ -35,7 +37,7 @@ import { reached, sessionUsage, totalUsage } from "./usage.js";
|
|
|
35
37
|
import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
|
|
36
38
|
import { gateRetired } from "./effects/gate.js";
|
|
37
39
|
import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
|
|
38
|
-
import { PENDING_NOTE } from "../notes.js";
|
|
40
|
+
import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
|
|
39
41
|
const MEM_RECORD_MS = 30000;
|
|
40
42
|
/** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
|
|
41
43
|
const MEM_WARMUP_MS = 30000;
|
|
@@ -50,6 +52,19 @@ const entriesFor = (journal, call) => journal.entries().filter(e => e.call === c
|
|
|
50
52
|
const current = (journal, call) => entriesFor(journal, call).findLast(e => e.type === JT.exec)?.exec;
|
|
51
53
|
const sealed = (journal, call) => entriesFor(journal, call).find(e => e.type === JT.sealed)?.result;
|
|
52
54
|
const has = (journal, type, exec) => entriesOf(journal, type, exec).length > 0;
|
|
55
|
+
/** The run of executions of `call` whose launches failed for a reason of the environment, ending at `exec`: its first
|
|
56
|
+
* execution and the one before it (absent for the call's first). Undefined when `exec` did not fail so. */
|
|
57
|
+
function envFailedChain(journal, call, exec) {
|
|
58
|
+
if (!has(journal, "spawn-env-failed", exec))
|
|
59
|
+
return undefined;
|
|
60
|
+
const execs = entriesFor(journal, call).filter(e => e.type === JT.exec).map(e => String(e.exec));
|
|
61
|
+
let i = execs.lastIndexOf(exec);
|
|
62
|
+
if (i < 0)
|
|
63
|
+
return undefined;
|
|
64
|
+
while (i > 0 && has(journal, "spawn-env-failed", execs[i - 1]))
|
|
65
|
+
i--;
|
|
66
|
+
return { first: execs[i], ...(i > 0 ? { before: execs[i - 1] } : {}) };
|
|
67
|
+
}
|
|
53
68
|
/** The rid of the model request a follow-up naming a model makes (P12): derived, so withdrawing or replacing the
|
|
54
69
|
* follow-up withdraws its model request too. */
|
|
55
70
|
export const modelRid = (rid) => contentHash([rid, "model"]);
|
|
@@ -107,9 +122,17 @@ export function continueMessage(dangling) {
|
|
|
107
122
|
/** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
|
|
108
123
|
export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
|
|
109
124
|
"started (background ones included) were stopped with it. Check them before relying on them.";
|
|
125
|
+
/** A launch failure the environment causes (the command or its interpreter is missing or not executable): fixing the
|
|
126
|
+
* environment, or another orchestrator started from a better one, makes the same launch work. */
|
|
127
|
+
export const environmentSpawnError = (error) => ["ENOENT", "EACCES"].includes(String(error?.code));
|
|
128
|
+
/** The default wait before an environment launch failure is retried (an orchestrator restart retries at once). */
|
|
129
|
+
export const SPAWN_RETRY_MS = 60_000;
|
|
130
|
+
/** A call's environment launch failures print one console line at the first, then at most one per this interval. */
|
|
131
|
+
export const SPAWN_CONSOLE_MS = 600_000;
|
|
110
132
|
export default function createExecutor(ledgers, options = {}) {
|
|
111
133
|
const { home, config, orch } = ledgers;
|
|
112
134
|
const containment = options.containment ?? serialContainment(), effects = options.effects ?? createEffects(ledgers);
|
|
135
|
+
const piCommand = options.pi ?? "pi";
|
|
113
136
|
const active = new Map(), completed = new Map(), journals = new Map();
|
|
114
137
|
let queue = Promise.resolve(), closed = false;
|
|
115
138
|
let suspending;
|
|
@@ -352,7 +375,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
352
375
|
const withdrawn = all.some(r => r.type === "forward" && r.dest === call && r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
|
|
353
376
|
if (envelope.kind === "notify" && !withdrawn && !all.some(r => r.type === PENDING_NOTE && r.rid === e.rid))
|
|
354
377
|
await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
|
|
355
|
-
|
|
378
|
+
// A follow-up the call never took is not lost either: the orchestrator opens the next generation with it (or a
|
|
379
|
+
// later follow-up takes it along). A stop is final and drops it; a withdrawn one is gone.
|
|
380
|
+
const reopen = envelope.kind === "follow-up" && !withdrawn && sealed(journal, call)?.status !== "stopped";
|
|
381
|
+
await journal.append("forward-retired", { rid: e.rid, rid2: e.rid2, reason: reopen ? UNDELIVERED_FOLLOW_UP : "retired-without-child-receipt" });
|
|
356
382
|
}
|
|
357
383
|
await (await outbox).markResolved(String(e.rid2));
|
|
358
384
|
}
|
|
@@ -606,63 +632,148 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
606
632
|
});
|
|
607
633
|
wake();
|
|
608
634
|
}
|
|
635
|
+
/** The origin of a workflow (its `wf-created` entry, else the orchestrator ledger's `created`), cached once known. */
|
|
636
|
+
const origins = new Map();
|
|
637
|
+
function originOf(wid) {
|
|
638
|
+
let o = origins.get(wid);
|
|
639
|
+
if (o === undefined) {
|
|
640
|
+
const journal = journals.get(wid);
|
|
641
|
+
const value = journal?.entries().find(e => e.type === "wf-created")?.origin ?? orch.entries().find(e => e.type === JT.created && e.wid === wid)?.origin;
|
|
642
|
+
if (typeof value === "string")
|
|
643
|
+
origins.set(wid, o = value);
|
|
644
|
+
}
|
|
645
|
+
return o;
|
|
646
|
+
}
|
|
647
|
+
const widOf = (exec) => exec.slice(0, exec.indexOf("@"));
|
|
648
|
+
/** Slot precedence: every acquisition waiting now. `blockedOn`: the providers its latest attempt (at `at`) found full. */
|
|
649
|
+
const acquiring = new Map();
|
|
650
|
+
/** Whether another waiter with precedence for `provider` found it full on a recent attempt: then `exec` leaves the
|
|
651
|
+
* free slot to it. Precedence: a call that ran before (its session, cache and worktree are ready; a parent waits on it)
|
|
652
|
+
* before a fresh one; then the workflow origin holding fewer of the provider's slots; then the longer wait; then call id. */
|
|
653
|
+
function yields(exec, provider) {
|
|
654
|
+
const me = acquiring.get(exec);
|
|
655
|
+
if (!me)
|
|
656
|
+
return false;
|
|
657
|
+
const recent = 3 * (config.k?.trackerMs ?? 1000), now = Date.now();
|
|
658
|
+
let held;
|
|
659
|
+
const heldBy = (origin) => {
|
|
660
|
+
if (!held) {
|
|
661
|
+
held = new Map();
|
|
662
|
+
for (const h of holdings())
|
|
663
|
+
if (h.pool === provider) {
|
|
664
|
+
const o = originOf(widOf(h.exec));
|
|
665
|
+
held.set(o, (held.get(o) ?? 0) + 1);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
return held.get(origin) ?? 0;
|
|
669
|
+
};
|
|
670
|
+
for (const [other, w] of acquiring) {
|
|
671
|
+
if (other === exec || !w.blockedOn.has(provider) || now - w.at >= recent || interrupted(w.a))
|
|
672
|
+
continue;
|
|
673
|
+
if (w.resume !== me.resume) {
|
|
674
|
+
if (w.resume)
|
|
675
|
+
return true;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const mine = heldBy(me.origin), theirs = heldBy(w.origin);
|
|
679
|
+
if (theirs !== mine) {
|
|
680
|
+
if (theirs < mine)
|
|
681
|
+
return true;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (w.since !== me.since ? w.since < me.since : w.call < me.call)
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
609
689
|
/** Wait for a slot. The candidates are decided again on every attempt, inside the serial section that also applies
|
|
610
690
|
* config.json changes: a queued call follows a reloaded defaultModel, pool or limit, never a mix of two versions. */
|
|
611
691
|
async function acquire(a, exec, decide, writer) {
|
|
692
|
+
const t = a.ticket, since = Date.now();
|
|
693
|
+
// An execution that never started (its launch failed for a reason of the environment) does not make a resume.
|
|
694
|
+
const resume = !!t.continueFrom || t.journal.entries().some(e => e.type === JT.exec && e.call === t.callId && e.exec !== exec && !has(t.journal, "spawn-env-failed", String(e.exec)));
|
|
695
|
+
const mine = { a, call: t.callId, origin: originOf(t.wid), since, resume, blockedOn: new Set(), at: since };
|
|
696
|
+
acquiring.set(exec, mine);
|
|
697
|
+
try {
|
|
698
|
+
return await acquireLoop(a, exec, decide, mine, writer);
|
|
699
|
+
}
|
|
700
|
+
finally {
|
|
701
|
+
acquiring.delete(exec);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
async function acquireLoop(a, exec, decide, mine, writer) {
|
|
612
705
|
let continuation = false;
|
|
613
706
|
for (;;) {
|
|
614
707
|
let signal;
|
|
615
708
|
const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
|
|
709
|
+
const blocked = new Set();
|
|
616
710
|
const chosen = await serial(async () => {
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
const decision = await decide(), models = decision.candidates, pool = decision.pool;
|
|
622
|
-
continuation = decision.continuation;
|
|
623
|
-
for (const model of models) {
|
|
624
|
-
if (!continuation && pool && models.length > 1 && skipped(pool, model))
|
|
625
|
-
continue;
|
|
626
|
-
const provider = model.provider;
|
|
627
|
-
if (unavailable(provider))
|
|
628
|
-
continue;
|
|
629
|
-
const probe = provider !== undefined && folded().exhausted.has(provider);
|
|
630
|
-
const holders = holdings().filter(e => e.pool === provider);
|
|
631
|
-
const limit = settings().providers?.[provider ?? ""]?.slots ?? Infinity;
|
|
632
|
-
if (!capacity({ kind: "provider", holders: holders.length, capacity: limit }))
|
|
633
|
-
continue;
|
|
634
|
-
// A burst of dispatches all read the same MemAvailable before any child has grown: subtract the children
|
|
635
|
-
// admitted in the last 30 s (their memory is not visible yet), so a burst cannot over-commit the headroom.
|
|
636
|
-
const perChild = settings().memory?.perChildMb ?? 300;
|
|
637
|
-
const warming = holdings().filter(e => e.pool === "memory" && Date.now() - e.ts < MEM_WARMUP_MS).length;
|
|
638
|
-
const measured = await (options.memory ?? availableMemory)(), available = measured - warming * perChild;
|
|
639
|
-
const admitted = capacity({ kind: "memory", available, reserve: settings().memory?.reserveMb ?? 2048, perChild });
|
|
640
|
-
// F3: every admitted dispatch is recorded; repeated refusals at most once per 30 s per call.
|
|
641
|
-
if (admitted || a.refusedAt === undefined || Date.now() - a.refusedAt >= MEM_RECORD_MS) {
|
|
642
|
-
await orch.append("mem", { available, admitted, exec, ...(warming ? { measured, warming } : {}) });
|
|
643
|
-
a.refusedAt = admitted ? undefined : Date.now();
|
|
644
|
-
}
|
|
645
|
-
if (!admitted)
|
|
711
|
+
try {
|
|
712
|
+
if (interrupted(a) || await workflowReached(a.ticket))
|
|
713
|
+
return;
|
|
714
|
+
if (writer && !await writerAdmit(a, writer))
|
|
646
715
|
return;
|
|
647
|
-
const
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
716
|
+
const decision = await decide(), models = decision.candidates, pool = decision.pool;
|
|
717
|
+
continuation = decision.continuation;
|
|
718
|
+
for (const model of models) {
|
|
719
|
+
if (!continuation && pool && models.length > 1 && skipped(pool, model))
|
|
720
|
+
continue;
|
|
721
|
+
// A pool entry with afterMs waits its turn: it is taken only once this acquisition has waited that long.
|
|
722
|
+
if (model.afterMs !== undefined && Date.now() - mine.since < model.afterMs)
|
|
723
|
+
continue;
|
|
724
|
+
const provider = model.provider;
|
|
725
|
+
if (unavailable(provider))
|
|
726
|
+
continue;
|
|
727
|
+
const probe = provider !== undefined && folded().exhausted.has(provider);
|
|
728
|
+
const holders = holdings().filter(e => e.pool === provider);
|
|
729
|
+
const limit = settings().providers?.[provider ?? ""]?.slots ?? Infinity;
|
|
730
|
+
if (!capacity({ kind: "provider", holders: holders.length, capacity: limit })) {
|
|
731
|
+
if (provider)
|
|
732
|
+
blocked.add(provider);
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (provider && yields(exec, provider))
|
|
736
|
+
continue;
|
|
737
|
+
// A burst of dispatches all read the same MemAvailable before any child has grown: subtract the children
|
|
738
|
+
// admitted in the last 30 s (their memory is not visible yet), so a burst cannot over-commit the headroom.
|
|
739
|
+
const perChild = settings().memory?.perChildMb ?? 300;
|
|
740
|
+
const warming = holdings().filter(e => e.pool === "memory" && Date.now() - e.ts < MEM_WARMUP_MS).length;
|
|
741
|
+
const measured = await (options.memory ?? availableMemory)(), available = measured - warming * perChild;
|
|
742
|
+
const admitted = capacity({ kind: "memory", available, reserve: settings().memory?.reserveMb ?? 2048, perChild });
|
|
743
|
+
// F3: every admitted dispatch is recorded; repeated refusals at most once per 30 s per call.
|
|
744
|
+
if (admitted || a.refusedAt === undefined || Date.now() - a.refusedAt >= MEM_RECORD_MS) {
|
|
745
|
+
await orch.append("mem", { available, admitted, exec, ...(warming ? { measured, warming } : {}) });
|
|
746
|
+
a.refusedAt = admitted ? undefined : Date.now();
|
|
747
|
+
}
|
|
748
|
+
if (!admitted)
|
|
749
|
+
return;
|
|
750
|
+
const memory = holdings().filter(e => e.pool === "memory");
|
|
751
|
+
let memorySlot = 0;
|
|
752
|
+
while (memory.some(e => e.slot === memorySlot))
|
|
753
|
+
memorySlot++;
|
|
754
|
+
await orch.append("hold", { pool: "memory", slot: memorySlot, exec });
|
|
755
|
+
if (provider) {
|
|
756
|
+
let slot = 0;
|
|
757
|
+
while (holders.some(e => e.slot === slot))
|
|
758
|
+
slot++;
|
|
759
|
+
await orch.append("hold", { pool: provider, slot, exec });
|
|
760
|
+
// After its next try, the first call admitted to a used-up provider is its probe: its first request
|
|
761
|
+
// either goes through (the provider is available again) or is refused, which uses no quota.
|
|
762
|
+
if (probe)
|
|
763
|
+
await orch.append("provider-probe", { provider, exec });
|
|
764
|
+
}
|
|
765
|
+
const plain = plainModel(model);
|
|
766
|
+
await a.ticket.journal.append("selected", { exec, model: plain, ...(pool ? { pool } : {}) });
|
|
767
|
+
return plain;
|
|
661
768
|
}
|
|
662
|
-
|
|
663
|
-
|
|
769
|
+
}
|
|
770
|
+
finally {
|
|
771
|
+
mine.blockedOn = blocked;
|
|
772
|
+
mine.at = Date.now();
|
|
664
773
|
}
|
|
665
774
|
});
|
|
775
|
+
if (!chosen)
|
|
776
|
+
options.attempted?.(exec, [...blocked]);
|
|
666
777
|
if (chosen || interrupted(a) || reached(totalUsage(a.ticket.journal.entries()), a.ticket.workflowBudget)) {
|
|
667
778
|
waiters.delete(signal);
|
|
668
779
|
return { model: chosen, continuation };
|
|
@@ -706,6 +817,12 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
706
817
|
return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
|
|
707
818
|
return { candidates, continuation: false, pool };
|
|
708
819
|
}
|
|
820
|
+
/** Resolve a bound answer before it waits for admission; also repairs an interrupted append pair. Called serially. */
|
|
821
|
+
async function resolveBoundAnswer(journal, call, qid, rev) {
|
|
822
|
+
const id = `q:${call}:${qid}`;
|
|
823
|
+
if (!journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev))
|
|
824
|
+
await journal.append(JT.attentionResolved, { id, rev, resolution: "answered" });
|
|
825
|
+
}
|
|
709
826
|
async function questions(t, entries) {
|
|
710
827
|
await collectReceipts(t.callId, entries).catch(error => console.error(`durable-subagents: inbox cleanup of ${t.callId} failed: ${String(error)}`));
|
|
711
828
|
await serial(async () => {
|
|
@@ -715,8 +832,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
715
832
|
const id = `q:${t.callId}:${qid}`;
|
|
716
833
|
if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
|
|
717
834
|
await t.journal.append(JT.attention, { item: { id, rev, kind: "question", text: String(question), wid: t.wid, call: t.callId, qid, session: callSession(home, t.wid, t.key, t.gen) } });
|
|
718
|
-
if (digest.answered.has(answerKey(qid, rev))
|
|
719
|
-
await t.journal.
|
|
835
|
+
if (digest.answered.has(answerKey(qid, rev)) || t.journal.entries().some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === qid && e.rev === rev))
|
|
836
|
+
await resolveBoundAnswer(t.journal, t.callId, qid, rev);
|
|
720
837
|
}
|
|
721
838
|
});
|
|
722
839
|
}
|
|
@@ -787,8 +904,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
787
904
|
wake();
|
|
788
905
|
}
|
|
789
906
|
/** Switch a running execution off a used-up provider: to the first model of its pool on another provider that is
|
|
790
|
-
* neither used up nor full
|
|
791
|
-
* the call waits for the provider once they end. */
|
|
907
|
+
* neither used up nor full and has no afterMs (such an entry is for calls that waited for a slot), reserving that
|
|
908
|
+
* slot as a requested switch does. Without one, pi's retries go on and the call waits for the provider once they end. */
|
|
792
909
|
async function failover(t, exec, provider) {
|
|
793
910
|
if (pendingSwitch(exec))
|
|
794
911
|
return;
|
|
@@ -803,7 +920,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
803
920
|
return;
|
|
804
921
|
}
|
|
805
922
|
for (const m of models) {
|
|
806
|
-
if (!m.provider || m.provider === provider || unavailable(m.provider) || skipped(pool, m))
|
|
923
|
+
if (!m.provider || m.provider === provider || m.afterMs !== undefined || unavailable(m.provider) || skipped(pool, m))
|
|
807
924
|
continue;
|
|
808
925
|
const rid = contentHash([exec, "failover", provider]);
|
|
809
926
|
if (t.journal.entries().some(e => e.type === "forward" && e.rid === rid))
|
|
@@ -852,6 +969,44 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
852
969
|
function pendingSwitch(exec) {
|
|
853
970
|
return holdings().find(h => h.exec === exec && h.reserved && !folded().observed.has(`${exec}\n${h.rid}`));
|
|
854
971
|
}
|
|
972
|
+
/** When each call in environment retries last printed its console line. */
|
|
973
|
+
const spawnConsoleAt = new Map();
|
|
974
|
+
/** Serial sections only: record an environment launch failure (before its execution is fenced: recovery after a crash
|
|
975
|
+
* in between finds an execution that never started, not a loss). */
|
|
976
|
+
async function spawnEnvRecord(t, exec, error) {
|
|
977
|
+
if (!has(t.journal, "spawn-env-failed", exec))
|
|
978
|
+
await t.journal.append("spawn-env-failed", { exec, call: t.callId, command: piCommand, error: String(error).slice(0, 300) });
|
|
979
|
+
}
|
|
980
|
+
/** Serial sections only: raise one `environment` alert for the call (a new revision only after an earlier one was
|
|
981
|
+
* resolved by a launch that worked); one console line at the first failure, then at most one per SPAWN_CONSOLE_MS. */
|
|
982
|
+
async function spawnEnvFailed(t, exec, cwd, error) {
|
|
983
|
+
const message = String(error).slice(0, 300), printed = spawnConsoleAt.get(t.callId);
|
|
984
|
+
if (printed === undefined || Date.now() - printed >= SPAWN_CONSOLE_MS) {
|
|
985
|
+
console.error(`durable-subagents: launching ${exec} failed: ${message}; retrying`);
|
|
986
|
+
spawnConsoleAt.set(t.callId, Date.now());
|
|
987
|
+
}
|
|
988
|
+
const id = `environment:${t.callId}`, items = attentionEntries(t.journal.entries(), id), last = items.at(-1)?.item;
|
|
989
|
+
if (last && !t.journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === last.rev))
|
|
990
|
+
return;
|
|
991
|
+
const pi = piCommand === "pi" ? "`pi` from the orchestrator's PATH (no absolute pi was resolved; set DSA_PI_BIN, or start the orchestrator from an environment whose PATH has pi)"
|
|
992
|
+
: `${piCommand} (DSA_PI_BIN / the PATH the orchestrator started with)`;
|
|
993
|
+
const text = `${worktreeLabel(t.callId)} could not start: ${message}. It runs ${pi} in ${cwd}. ` +
|
|
994
|
+
`The call retries every minute (and at once when the orchestrator restarts); stop it to give up`;
|
|
995
|
+
await t.journal.append(JT.attention, { item: { id, rev: (last?.rev ?? 0) + 1, kind: "environment", text, wid: t.wid, call: t.callId } });
|
|
996
|
+
}
|
|
997
|
+
/** Serial sections only: a launch worked, so the call's open environment alert is resolved. */
|
|
998
|
+
async function spawnEnvResolved(t) {
|
|
999
|
+
spawnConsoleAt.delete(t.callId);
|
|
1000
|
+
const id = `environment:${t.callId}`, last = attentionEntries(t.journal.entries(), id).at(-1)?.item;
|
|
1001
|
+
if (last && !t.journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === last.rev))
|
|
1002
|
+
await t.journal.append(JT.attentionResolved, { id, rev: last.rev, resolution: "launched" });
|
|
1003
|
+
}
|
|
1004
|
+
/** Wait before launching again after an environment failure; a stop, retirement, suspension or shutdown ends it early. */
|
|
1005
|
+
async function retryWait(a) {
|
|
1006
|
+
const until = Date.now() + (options.spawnRetryMs ?? SPAWN_RETRY_MS);
|
|
1007
|
+
while (!interrupted(a) && Date.now() < until)
|
|
1008
|
+
await new Promise(resolve => { const timer = setTimeout(resolve, Math.min(until - Date.now(), config.k?.trackerMs ?? 1000)); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
1009
|
+
}
|
|
855
1010
|
async function execute(a) {
|
|
856
1011
|
const t = a.ticket, journal = t.journal;
|
|
857
1012
|
const session = callSession(home, t.wid, t.key, t.gen), dir = callDir(home, t.wid, t.key, t.gen);
|
|
@@ -916,7 +1071,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
916
1071
|
return finish(journal, t.callId, exec, makeResult("timeout"));
|
|
917
1072
|
if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
|
|
918
1073
|
return finish(journal, t.callId, exec, makeResult("budget"));
|
|
919
|
-
|
|
1074
|
+
// A child that never started (its launch failed for a reason of the environment) lost nothing: launch again.
|
|
1075
|
+
if (!bound && !has(journal, "spawn-env-failed", exec)) {
|
|
920
1076
|
// P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
|
|
921
1077
|
// hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
|
|
922
1078
|
// hibernation; it is neither a loss nor, for `once`, an unknown outcome.
|
|
@@ -1009,8 +1165,16 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1009
1165
|
await sender.send(t.callId, "task", { message: t.spec.task }, undefined, { rid: taskRid });
|
|
1010
1166
|
else if (unresolved && !receipt)
|
|
1011
1167
|
await sender.send(t.callId, "continue", { message: String(unresolved.message) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
|
|
1012
|
-
else if (previous)
|
|
1013
|
-
|
|
1168
|
+
else if (previous) {
|
|
1169
|
+
// After launches that failed for a reason of the environment, no child received their dispatches: the first
|
|
1170
|
+
// execution of that run of failures keeps its dispatch (rid and content), so one is pending, not one per retry.
|
|
1171
|
+
const chain = envFailedChain(journal, t.callId, previous);
|
|
1172
|
+
const prior = chain && sender.recorded(contentHash([chain.first, "dispatch"]));
|
|
1173
|
+
if (prior)
|
|
1174
|
+
await sender.send(t.callId, prior.kind, prior.body, prior.cond, { rid: prior.rid });
|
|
1175
|
+
else
|
|
1176
|
+
await sender.send(t.callId, "continue", { message: continueMessage(chain?.before ? evidence(entries, chain.before).dangling : dangling) }, undefined, { rid: contentHash([chain?.first ?? exec, "dispatch"]) });
|
|
1177
|
+
}
|
|
1014
1178
|
else
|
|
1015
1179
|
await sender.send(t.callId, "task", { message: t.opening?.message ?? t.spec.task }, undefined, { rid: contentHash([exec, "dispatch"]) });
|
|
1016
1180
|
await launchGate(a, exec, "child");
|
|
@@ -1020,14 +1184,24 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1020
1184
|
}
|
|
1021
1185
|
let child;
|
|
1022
1186
|
try {
|
|
1023
|
-
child = await containment.spawn({ exec, command:
|
|
1024
|
-
|
|
1187
|
+
child = await containment.spawn({ exec, command: piCommand, args: [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}) }), "-e", extension], cwd,
|
|
1188
|
+
// The orchestrator's node follows binDir: a `#!/usr/bin/env node` pi runs under a PATH without node (a service's).
|
|
1189
|
+
env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}) } });
|
|
1025
1190
|
}
|
|
1026
1191
|
catch (error) {
|
|
1192
|
+
const environment = environmentSpawnError(error);
|
|
1193
|
+
if (environment)
|
|
1194
|
+
await serial(() => spawnEnvRecord(t, exec, error));
|
|
1027
1195
|
await fence(journal, exec, { park: a });
|
|
1028
1196
|
a.live = undefined;
|
|
1029
|
-
|
|
1197
|
+
if (!environment)
|
|
1198
|
+
return finish(journal, t.callId, exec, makeResult("failed", "", `Spawn failed: ${String(error)}`));
|
|
1199
|
+
await release(exec);
|
|
1200
|
+
await serial(() => spawnEnvFailed(t, exec, cwd, error));
|
|
1201
|
+
await retryWait(a);
|
|
1202
|
+
continue;
|
|
1030
1203
|
}
|
|
1204
|
+
await serial(() => spawnEnvResolved(t));
|
|
1031
1205
|
try {
|
|
1032
1206
|
await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
|
|
1033
1207
|
await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
|
|
@@ -1082,8 +1256,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1082
1256
|
const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
|
|
1083
1257
|
const message = String(f.envelope.body?.message ?? "");
|
|
1084
1258
|
// A new identity: the stale answer may still sit in the child's inbox under the forward's rid2.
|
|
1085
|
-
await journal.append("answer-bound", { call, qid: sleeping.qid, rev: sleeping.rev, rid: f.rid, rid2: contentHash([String(f.rid2), "hibernated"]), hash: f.hash,
|
|
1259
|
+
await journal.append("answer-bound", { event: true, call, qid: sleeping.qid, rev: sleeping.rev, rid: f.rid, rid2: contentHash([String(f.rid2), "hibernated"]), hash: f.hash,
|
|
1086
1260
|
message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${message}` });
|
|
1261
|
+
await resolveBoundAnswer(journal, call, sleeping.qid, sleeping.rev);
|
|
1087
1262
|
await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
|
|
1088
1263
|
await (await outbox).markResolved(String(f.rid2));
|
|
1089
1264
|
});
|
|
@@ -1161,8 +1336,12 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1161
1336
|
return { action: "apply" };
|
|
1162
1337
|
}
|
|
1163
1338
|
const boundRetry = ctx.journal.entries().find(e => e.type === "answer-bound" && e.call === dest && e.rid === req.rid);
|
|
1164
|
-
if (boundRetry)
|
|
1165
|
-
|
|
1339
|
+
if (boundRetry) {
|
|
1340
|
+
if (boundRetry.hash !== hash)
|
|
1341
|
+
return { action: "reject", reason: "identity-conflict" };
|
|
1342
|
+
await resolveBoundAnswer(ctx.journal, dest, boundRetry.qid, boundRetry.rev);
|
|
1343
|
+
return { action: "apply" };
|
|
1344
|
+
}
|
|
1166
1345
|
if (sealed(ctx.journal, dest))
|
|
1167
1346
|
return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
|
|
1168
1347
|
if (req.kind === "send" && req.body.kind === "answer") {
|
|
@@ -1175,7 +1354,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1175
1354
|
return { action: "reject", reason: "stale-rev" };
|
|
1176
1355
|
const rid2 = forwardRid(req.rid, ctx.widRev, ctx.key, hash);
|
|
1177
1356
|
const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
|
|
1178
|
-
|
|
1357
|
+
// `event`: the `answered` event derives from this entry (an unmarked older one: from its resolution).
|
|
1358
|
+
await ctx.journal.append("answer-bound", { event: true, call: dest, qid: sleeping.qid, rev: sleeping.rev, rid: req.rid, rid2, hash, message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${req.body.message ?? ""}` });
|
|
1359
|
+
await resolveBoundAnswer(ctx.journal, dest, sleeping.qid, sleeping.rev);
|
|
1179
1360
|
active.get(dest)?.wake();
|
|
1180
1361
|
wake();
|
|
1181
1362
|
return { action: "apply" };
|
|
@@ -1189,7 +1370,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1189
1370
|
// recorded and the next execution launches on it (`requestedModel`); its slot is acquired then, as for any launch.
|
|
1190
1371
|
const idle = !exec || has(ctx.journal, JT.fenced, exec) || !has(ctx.journal, "selected", exec);
|
|
1191
1372
|
// A pool's name asks for its first model that can take the call now: provider not used up, and (for a running
|
|
1192
|
-
// call) a free slot
|
|
1373
|
+
// call) a free slot; an entry with afterMs is skipped (it is for calls that waited for a slot), as failover
|
|
1374
|
+
// skips it. The call's own pool stays, so a used-up window later moves it on as before.
|
|
1193
1375
|
const pools = settings().pools, pool = pools && Object.hasOwn(pools, model) ? model : undefined;
|
|
1194
1376
|
if (pool) {
|
|
1195
1377
|
let models;
|
|
@@ -1201,7 +1383,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1201
1383
|
}
|
|
1202
1384
|
const free = (p) => idle || holdings().some(h => h.exec === exec && h.pool === p) ||
|
|
1203
1385
|
capacity({ kind: "provider", holders: holdings().filter(h => h.pool === p).length, capacity: settings().providers?.[p]?.slots ?? Infinity });
|
|
1204
|
-
const m = models.find(m => m.provider && !unavailable(m.provider) && free(m.provider));
|
|
1386
|
+
const m = models.find(m => m.provider && m.afterMs === undefined && !unavailable(m.provider) && free(m.provider));
|
|
1205
1387
|
if (!m)
|
|
1206
1388
|
return { action: "reject", reason: "pool-unavailable" };
|
|
1207
1389
|
model = `${m.provider}/${m.id}${m.thinking ? `:${m.thinking}` : ""}`;
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
// provider-*: used-up usage windows (providers.ts).
|
|
6
6
|
// config{hash,config}: the orchestrator settings in effect from here; config-rejected{error,hash?}: a change of
|
|
7
7
|
// config.json refused, while the earlier settings stay (cleared by the next config record).
|
|
8
|
-
// orchestrator{version,pid} / orchestrator-exit{pid}: the orchestrator running (its package
|
|
8
|
+
// orchestrator{version,pid,pi?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its package
|
|
9
|
+
// version, the pi it launches) and its exit (why: idle, restart, signal, error).
|
|
9
10
|
// restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
|
|
10
11
|
// Old records lack reason/initiator/from and remain readable (A1).
|
|
11
12
|
// writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
|
|
@@ -36,7 +37,7 @@ export function applyLedger(state, e) {
|
|
|
36
37
|
else if (e.type === "restart")
|
|
37
38
|
state.pendingRestart = e.force === true ? { ts: e.ts, reason: e.reason, initiator: e.initiator, from: e.from } : undefined;
|
|
38
39
|
else if (isEntry(e, "orchestrator")) {
|
|
39
|
-
state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
|
|
40
|
+
state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
|
|
40
41
|
delete state.pendingRestart;
|
|
41
42
|
}
|
|
42
43
|
else if (e.type === "writer-hold") {
|
|
@@ -50,6 +51,8 @@ export function applyLedger(state, e) {
|
|
|
50
51
|
else if (isEntry(e, "orchestrator-exit")) {
|
|
51
52
|
if (state.orchestrator?.pid === e.pid)
|
|
52
53
|
state.orchestrator.exited = true;
|
|
54
|
+
if (e.reason)
|
|
55
|
+
state.lastExit = { pid: e.pid, ts: e.ts, reason: e.reason, ...(e.signal ? { signal: e.signal } : {}), ...(e.error ? { error: e.error } : {}) };
|
|
53
56
|
}
|
|
54
57
|
foldExhaustion(state.exhausted, e);
|
|
55
58
|
}
|
|
@@ -58,7 +61,7 @@ export function applyLedger(state, e) {
|
|
|
58
61
|
export function foldLedger(state, entries) {
|
|
59
62
|
// Journal readers keep the entry objects of a ledger as it grows (kernel/journal.ts), so identity tells them apart.
|
|
60
63
|
if (state.seen && entries[state.seen - 1] !== state.last)
|
|
61
|
-
Object.assign(state, emptyLedger(), { config: undefined, rejected: undefined, orchestrator: undefined, pendingRestart: undefined, last: undefined });
|
|
64
|
+
Object.assign(state, emptyLedger(), { config: undefined, rejected: undefined, orchestrator: undefined, pendingRestart: undefined, last: undefined, lastExit: undefined });
|
|
62
65
|
for (; state.seen < entries.length; state.seen++)
|
|
63
66
|
applyLedger(state, entries[state.seen]);
|
|
64
67
|
state.last = entries[state.seen - 1];
|
|
@@ -6,13 +6,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
6
6
|
}
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
|
-
import { spawn } from 'node:child_process';
|
|
10
9
|
import { mkdir } from 'node:fs/promises';
|
|
11
10
|
import { fileURLToPath } from 'node:url';
|
|
12
11
|
import { realpathSync } from 'node:fs';
|
|
13
12
|
import { join, resolve } from 'node:path';
|
|
14
13
|
import { binDir, dsaHome, orchLedger, orchLock } from "../paths.js";
|
|
15
|
-
import { writeShim } from "../platform/lease.js";
|
|
14
|
+
import { removeStaleTemps, writeShim } from "../platform/lease.js";
|
|
15
|
+
import { launchOrchestrator, resolvePi } from "../platform/launch.js";
|
|
16
16
|
import { openJournal } from "../kernel/journal.js";
|
|
17
17
|
import { OsLock } from "../platform/lock.js";
|
|
18
18
|
import { captureStart } from "../platform/proctable.js";
|
|
@@ -30,6 +30,7 @@ export async function main(options = {}) {
|
|
|
30
30
|
if (!lock)
|
|
31
31
|
return {};
|
|
32
32
|
let engine, ledgers, watcher;
|
|
33
|
+
let exit = { reason: 'error', error: 'ended before its loop' };
|
|
33
34
|
try {
|
|
34
35
|
let config = options.config, stamp;
|
|
35
36
|
if (!config) {
|
|
@@ -46,6 +47,8 @@ export async function main(options = {}) {
|
|
|
46
47
|
// Which version runs is visible to every pi session (status; a notice when it differs from the one pi loaded).
|
|
47
48
|
// `start` (Linux) tells this process from a later one given the same pid after a crash.
|
|
48
49
|
const start = await captureStart(process.pid).catch(() => '');
|
|
50
|
+
// Partial writes of earlier starts (a full disk, say): best effort, never fails the start.
|
|
51
|
+
removeStaleTemps(binDir(home), 10 * 60_000);
|
|
49
52
|
// Subagents reach `pi-durable-subagents hold …` through this shim, written before the start is recorded (executor puts its directory first on PATH).
|
|
50
53
|
try {
|
|
51
54
|
writeShim(binDir(home), process.execPath, fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../cli/main.ts' : '../cli/main.js', import.meta.url)));
|
|
@@ -53,9 +56,14 @@ export async function main(options = {}) {
|
|
|
53
56
|
catch (error) {
|
|
54
57
|
console.error(`durable-subagents: cannot write ${binDir(home)}: ${String(error)}`);
|
|
55
58
|
}
|
|
56
|
-
|
|
59
|
+
// The pi subagents run: resolved once (an executable DSA_PI_BIN from the starter, else this PATH), not per launch from an inherited
|
|
60
|
+
// PATH; null when there is none (each launch then runs a bare `pi`, and fails as an environment error until it works).
|
|
61
|
+
const pi = resolvePi(process.env).path ?? resolvePi({ PATH: process.env.PATH }).path;
|
|
62
|
+
if (!pi)
|
|
63
|
+
console.error('durable-subagents: pi not found (DSA_PI_BIN unset or not executable, not on PATH); subagents launch `pi` from PATH');
|
|
64
|
+
await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null });
|
|
57
65
|
const factory = options.executor ?? (await import(__rewriteRelativeImportExtension(new URL(import.meta.url.endsWith('.ts') ? './executor/index.ts' : './executor/index.js', import.meta.url).href))).default;
|
|
58
|
-
const executor = factory(ledgers);
|
|
66
|
+
const executor = factory(ledgers, pi ? { pi } : {});
|
|
59
67
|
engine = new Engine(ledgers, executor, options);
|
|
60
68
|
// A4: admission reads the settings recorded last, so the ones this run starts with are recorded (given ones too).
|
|
61
69
|
await recordConfig(ledgers.orch, config);
|
|
@@ -66,8 +74,15 @@ export async function main(options = {}) {
|
|
|
66
74
|
}
|
|
67
75
|
await engine.recover();
|
|
68
76
|
await engine.loop(options.signal);
|
|
77
|
+
const reason = options.signal?.reason;
|
|
78
|
+
exit = engine.restartRequested ? { reason: 'restart' }
|
|
79
|
+
: options.signal?.aborted ? { reason: 'signal', ...(typeof reason === 'string' ? { signal: reason } : {}) } : { reason: 'idle' };
|
|
69
80
|
return engine.restartRequested ? { restart: true } : {};
|
|
70
81
|
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
exit = { reason: 'error', error: String(error).slice(0, 300) };
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
71
86
|
finally {
|
|
72
87
|
try {
|
|
73
88
|
await watcher?.stop();
|
|
@@ -75,7 +90,7 @@ export async function main(options = {}) {
|
|
|
75
90
|
}
|
|
76
91
|
finally {
|
|
77
92
|
try {
|
|
78
|
-
await ledgers?.orch.append('orchestrator-exit', { pid: process.pid }).catch(() => { });
|
|
93
|
+
await ledgers?.orch.append('orchestrator-exit', { pid: process.pid, ...exit }).catch(() => { });
|
|
79
94
|
await ledgers?.orch.close();
|
|
80
95
|
}
|
|
81
96
|
finally {
|
|
@@ -88,12 +103,12 @@ export async function main(options = {}) {
|
|
|
88
103
|
// import.meta.url is the real file: compare real paths, as the CLI does.
|
|
89
104
|
if (process.argv[1] && realpathSync(resolve(process.argv[1])) === fileURLToPath(import.meta.url)) {
|
|
90
105
|
const controller = new AbortController();
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
main({ signal: controller.signal }).then(({ restart }) => {
|
|
106
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'])
|
|
107
|
+
process.once(signal, () => controller.abort(signal));
|
|
108
|
+
main({ signal: controller.signal }).then(async ({ restart }) => {
|
|
94
109
|
// Restart: the successor runs this same entry, which an update replaced in place; any pi session or CLI would start
|
|
95
110
|
// it too (whoever takes the lock first wins, the others exit at once).
|
|
96
111
|
if (restart)
|
|
97
|
-
|
|
112
|
+
await launchOrchestrator(process.argv[1], process.env, { home: dsaHome() });
|
|
98
113
|
}).catch(error => { console.error(error); process.exitCode = 1; });
|
|
99
114
|
}
|