pi-durable-subagents 1.0.35 → 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.
@@ -136,6 +136,8 @@ export class Outbox {
136
136
  return structuredClone(req);
137
137
  });
138
138
  }
139
+ /** The envelope recorded as sent under `rid`, if any. */
140
+ recorded(rid) { const req = this.sent.get(rid); return req && structuredClone(req); }
139
141
  /** P38: Re-publish every unresolved envelope under its original identity. */
140
142
  republishPending() { return this.serial(async () => { for (const req of this.pending.values())
141
143
  await this.publish(req); }); }
@@ -32,9 +32,24 @@ export function configProblem(raw) {
32
32
  if (pools !== undefined) {
33
33
  if (!record(pools))
34
34
  return "pools must map names to model lists";
35
- for (const [name, list] of Object.entries(pools))
36
- if (!Array.isArray(list) || !list.length || !list.every(m => typeof m === "string" && m))
37
- return `pools.${name} must be a nonempty list of "provider/id[:thinking]"`;
35
+ for (const [name, list] of Object.entries(pools)) {
36
+ if (!Array.isArray(list) || !list.length)
37
+ return `pools.${name} must be a nonempty list of "provider/id[:thinking]" or { model, afterMs }`;
38
+ for (const [i, m] of list.entries()) {
39
+ if (typeof m === "string" && m)
40
+ continue;
41
+ const at = `pools.${name}[${i}]`;
42
+ if (!record(m))
43
+ return `${at} must be "provider/id[:thinking]" (or a pool name) or { model, afterMs }`;
44
+ if (typeof m.model !== "string" || !m.model)
45
+ return `${at}.model must be "provider/id[:thinking]" or a pool name`;
46
+ if (m.afterMs !== undefined && !(count(m.afterMs) && Number(m.afterMs) > 0))
47
+ return `${at}.afterMs must be a positive number of milliseconds`;
48
+ const extra = Object.keys(m).find(k => k !== "model" && k !== "afterMs");
49
+ if (extra)
50
+ return `${at}.${extra} is not a pool entry key (model, afterMs)`;
51
+ }
52
+ }
38
53
  }
39
54
  if (providers !== undefined) {
40
55
  if (!record(providers))
@@ -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";
@@ -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;
@@ -609,63 +632,148 @@ export default function createExecutor(ledgers, options = {}) {
609
632
  });
610
633
  wake();
611
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
+ }
612
689
  /** Wait for a slot. The candidates are decided again on every attempt, inside the serial section that also applies
613
690
  * config.json changes: a queued call follows a reloaded defaultModel, pool or limit, never a mix of two versions. */
614
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) {
615
705
  let continuation = false;
616
706
  for (;;) {
617
707
  let signal;
618
708
  const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
709
+ const blocked = new Set();
619
710
  const chosen = await serial(async () => {
620
- if (interrupted(a) || await workflowReached(a.ticket))
621
- return;
622
- if (writer && !await writerAdmit(a, writer))
623
- return;
624
- const decision = await decide(), models = decision.candidates, pool = decision.pool;
625
- continuation = decision.continuation;
626
- for (const model of models) {
627
- if (!continuation && pool && models.length > 1 && skipped(pool, model))
628
- continue;
629
- const provider = model.provider;
630
- if (unavailable(provider))
631
- continue;
632
- const probe = provider !== undefined && folded().exhausted.has(provider);
633
- const holders = holdings().filter(e => e.pool === provider);
634
- const limit = settings().providers?.[provider ?? ""]?.slots ?? Infinity;
635
- if (!capacity({ kind: "provider", holders: holders.length, capacity: limit }))
636
- continue;
637
- // A burst of dispatches all read the same MemAvailable before any child has grown: subtract the children
638
- // admitted in the last 30 s (their memory is not visible yet), so a burst cannot over-commit the headroom.
639
- const perChild = settings().memory?.perChildMb ?? 300;
640
- const warming = holdings().filter(e => e.pool === "memory" && Date.now() - e.ts < MEM_WARMUP_MS).length;
641
- const measured = await (options.memory ?? availableMemory)(), available = measured - warming * perChild;
642
- const admitted = capacity({ kind: "memory", available, reserve: settings().memory?.reserveMb ?? 2048, perChild });
643
- // F3: every admitted dispatch is recorded; repeated refusals at most once per 30 s per call.
644
- if (admitted || a.refusedAt === undefined || Date.now() - a.refusedAt >= MEM_RECORD_MS) {
645
- await orch.append("mem", { available, admitted, exec, ...(warming ? { measured, warming } : {}) });
646
- a.refusedAt = admitted ? undefined : Date.now();
647
- }
648
- if (!admitted)
711
+ try {
712
+ if (interrupted(a) || await workflowReached(a.ticket))
713
+ return;
714
+ if (writer && !await writerAdmit(a, writer))
649
715
  return;
650
- const memory = holdings().filter(e => e.pool === "memory");
651
- let memorySlot = 0;
652
- while (memory.some(e => e.slot === memorySlot))
653
- memorySlot++;
654
- await orch.append("hold", { pool: "memory", slot: memorySlot, exec });
655
- if (provider) {
656
- let slot = 0;
657
- while (holders.some(e => e.slot === slot))
658
- slot++;
659
- await orch.append("hold", { pool: provider, slot, exec });
660
- // After its next try, the first call admitted to a used-up provider is its probe: its first request
661
- // either goes through (the provider is available again) or is refused, which uses no quota.
662
- if (probe)
663
- await orch.append("provider-probe", { provider, exec });
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;
664
768
  }
665
- await a.ticket.journal.append("selected", { exec, model, ...(pool ? { pool } : {}) });
666
- return model;
769
+ }
770
+ finally {
771
+ mine.blockedOn = blocked;
772
+ mine.at = Date.now();
667
773
  }
668
774
  });
775
+ if (!chosen)
776
+ options.attempted?.(exec, [...blocked]);
669
777
  if (chosen || interrupted(a) || reached(totalUsage(a.ticket.journal.entries()), a.ticket.workflowBudget)) {
670
778
  waiters.delete(signal);
671
779
  return { model: chosen, continuation };
@@ -709,6 +817,12 @@ export default function createExecutor(ledgers, options = {}) {
709
817
  return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
710
818
  return { candidates, continuation: false, pool };
711
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
+ }
712
826
  async function questions(t, entries) {
713
827
  await collectReceipts(t.callId, entries).catch(error => console.error(`durable-subagents: inbox cleanup of ${t.callId} failed: ${String(error)}`));
714
828
  await serial(async () => {
@@ -718,8 +832,8 @@ export default function createExecutor(ledgers, options = {}) {
718
832
  const id = `q:${t.callId}:${qid}`;
719
833
  if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
720
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) } });
721
- if (digest.answered.has(answerKey(qid, rev)) && !entriesOf(t.journal, JT.attentionResolved).some(r => r.id === id && r.rev === rev))
722
- await t.journal.append(JT.attentionResolved, { id, rev, resolution: "answered" });
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);
723
837
  }
724
838
  });
725
839
  }
@@ -790,8 +904,8 @@ export default function createExecutor(ledgers, options = {}) {
790
904
  wake();
791
905
  }
792
906
  /** Switch a running execution off a used-up provider: to the first model of its pool on another provider that is
793
- * neither used up nor full, reserving that slot as a requested switch does. Without one, pi's retries go on and
794
- * 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. */
795
909
  async function failover(t, exec, provider) {
796
910
  if (pendingSwitch(exec))
797
911
  return;
@@ -806,7 +920,7 @@ export default function createExecutor(ledgers, options = {}) {
806
920
  return;
807
921
  }
808
922
  for (const m of models) {
809
- 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))
810
924
  continue;
811
925
  const rid = contentHash([exec, "failover", provider]);
812
926
  if (t.journal.entries().some(e => e.type === "forward" && e.rid === rid))
@@ -855,6 +969,44 @@ export default function createExecutor(ledgers, options = {}) {
855
969
  function pendingSwitch(exec) {
856
970
  return holdings().find(h => h.exec === exec && h.reserved && !folded().observed.has(`${exec}\n${h.rid}`));
857
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
+ }
858
1010
  async function execute(a) {
859
1011
  const t = a.ticket, journal = t.journal;
860
1012
  const session = callSession(home, t.wid, t.key, t.gen), dir = callDir(home, t.wid, t.key, t.gen);
@@ -919,7 +1071,8 @@ export default function createExecutor(ledgers, options = {}) {
919
1071
  return finish(journal, t.callId, exec, makeResult("timeout"));
920
1072
  if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
921
1073
  return finish(journal, t.callId, exec, makeResult("budget"));
922
- if (!bound) {
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)) {
923
1076
  // P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
924
1077
  // hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
925
1078
  // hibernation; it is neither a loss nor, for `once`, an unknown outcome.
@@ -1012,8 +1165,16 @@ export default function createExecutor(ledgers, options = {}) {
1012
1165
  await sender.send(t.callId, "task", { message: t.spec.task }, undefined, { rid: taskRid });
1013
1166
  else if (unresolved && !receipt)
1014
1167
  await sender.send(t.callId, "continue", { message: String(unresolved.message) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
1015
- else if (previous)
1016
- await sender.send(t.callId, "continue", { message: continueMessage(dangling) }, undefined, { rid: contentHash([exec, "dispatch"]) });
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
+ }
1017
1178
  else
1018
1179
  await sender.send(t.callId, "task", { message: t.opening?.message ?? t.spec.task }, undefined, { rid: contentHash([exec, "dispatch"]) });
1019
1180
  await launchGate(a, exec, "child");
@@ -1023,14 +1184,24 @@ export default function createExecutor(ledgers, options = {}) {
1023
1184
  }
1024
1185
  let child;
1025
1186
  try {
1026
- child = await containment.spawn({ exec, command: "pi", 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,
1027
- env: { DSA_HOME: home, PATH: [binDir(home), 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}` } : {}) } });
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}` } : {}) } });
1028
1190
  }
1029
1191
  catch (error) {
1192
+ const environment = environmentSpawnError(error);
1193
+ if (environment)
1194
+ await serial(() => spawnEnvRecord(t, exec, error));
1030
1195
  await fence(journal, exec, { park: a });
1031
1196
  a.live = undefined;
1032
- return finish(journal, t.callId, exec, makeResult("failed", "", `Spawn failed: ${String(error)}`));
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;
1033
1203
  }
1204
+ await serial(() => spawnEnvResolved(t));
1034
1205
  try {
1035
1206
  await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
1036
1207
  await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
@@ -1085,8 +1256,9 @@ export default function createExecutor(ledgers, options = {}) {
1085
1256
  const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1086
1257
  const message = String(f.envelope.body?.message ?? "");
1087
1258
  // A new identity: the stale answer may still sit in the child's inbox under the forward's rid2.
1088
- 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,
1089
1260
  message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${message}` });
1261
+ await resolveBoundAnswer(journal, call, sleeping.qid, sleeping.rev);
1090
1262
  await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1091
1263
  await (await outbox).markResolved(String(f.rid2));
1092
1264
  });
@@ -1164,8 +1336,12 @@ export default function createExecutor(ledgers, options = {}) {
1164
1336
  return { action: "apply" };
1165
1337
  }
1166
1338
  const boundRetry = ctx.journal.entries().find(e => e.type === "answer-bound" && e.call === dest && e.rid === req.rid);
1167
- if (boundRetry)
1168
- return boundRetry.hash === hash ? { action: "apply" } : { action: "reject", reason: "identity-conflict" };
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
+ }
1169
1345
  if (sealed(ctx.journal, dest))
1170
1346
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1171
1347
  if (req.kind === "send" && req.body.kind === "answer") {
@@ -1178,7 +1354,9 @@ export default function createExecutor(ledgers, options = {}) {
1178
1354
  return { action: "reject", reason: "stale-rev" };
1179
1355
  const rid2 = forwardRid(req.rid, ctx.widRev, ctx.key, hash);
1180
1356
  const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1181
- await ctx.journal.append("answer-bound", { 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 ?? ""}` });
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);
1182
1360
  active.get(dest)?.wake();
1183
1361
  wake();
1184
1362
  return { action: "apply" };
@@ -1192,7 +1370,8 @@ export default function createExecutor(ledgers, options = {}) {
1192
1370
  // recorded and the next execution launches on it (`requestedModel`); its slot is acquired then, as for any launch.
1193
1371
  const idle = !exec || has(ctx.journal, JT.fenced, exec) || !has(ctx.journal, "selected", exec);
1194
1372
  // A pool's name asks for its first model that can take the call now: provider not used up, and (for a running
1195
- // call) a free slot. The call's own pool stays, so a used-up window later moves it on as before.
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.
1196
1375
  const pools = settings().pools, pool = pools && Object.hasOwn(pools, model) ? model : undefined;
1197
1376
  if (pool) {
1198
1377
  let models;
@@ -1204,7 +1383,7 @@ export default function createExecutor(ledgers, options = {}) {
1204
1383
  }
1205
1384
  const free = (p) => idle || holdings().some(h => h.exec === exec && h.pool === p) ||
1206
1385
  capacity({ kind: "provider", holders: holdings().filter(h => h.pool === p).length, capacity: settings().providers?.[p]?.slots ?? Infinity });
1207
- 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));
1208
1387
  if (!m)
1209
1388
  return { action: "reject", reason: "pool-unavailable" };
1210
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 version) and its exit.
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
- await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true });
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
- process.once('SIGTERM', () => controller.abort());
92
- process.once('SIGINT', () => controller.abort());
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
- spawn(process.execPath, [process.argv[1]], { detached: true, stdio: 'ignore', env: process.env }).unref();
112
+ await launchOrchestrator(process.argv[1], process.env, { home: dsaHome() });
98
113
  }).catch(error => { console.error(error); process.exitCode = 1; });
99
114
  }