pi-durable-subagents 1.0.35 → 1.0.38
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 +58 -0
- package/README.md +87 -7
- package/dist/agent/child/history.js +11 -2
- package/dist/agent/child.js +77 -20
- package/dist/agent/main.js +3 -5
- 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 +2 -2
- 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 +43 -13
- package/dist/kernel/guards.js +3 -3
- package/dist/kernel/mailbox.js +2 -0
- package/dist/orchestrator/config.js +18 -3
- package/dist/orchestrator/executor/digest.js +10 -3
- package/dist/orchestrator/executor/hibernate.js +25 -2
- package/dist/orchestrator/executor/index.js +386 -93
- package/dist/orchestrator/ledger.js +6 -3
- package/dist/orchestrator/main.js +24 -9
- package/dist/orchestrator/snapshot.js +70 -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 +2 -2
- 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,11 +21,11 @@ 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";
|
|
26
|
-
import { hibernation, openQuestion } from "./hibernate.js";
|
|
28
|
+
import { boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
|
|
27
29
|
import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
|
|
28
30
|
import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
|
|
29
31
|
import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.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,28 @@ 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
|
+
/** D2: an answer bound to another question than the one its call hibernated on supersedes that one. */
|
|
126
|
+
function supersedes(sleeping, qid, rev) {
|
|
127
|
+
return qid === sleeping.qid && rev === sleeping.rev ? {} : { superseded: [{ qid: String(sleeping.qid), rev: Number(sleeping.rev) }] };
|
|
128
|
+
}
|
|
129
|
+
/** D2: what the resumed asker is told of the question it hibernated on, when the answer it resumes with is another's. */
|
|
130
|
+
function withdrawn(entries, call, sleeping, qid, rev) {
|
|
131
|
+
if (qid === sleeping.qid && rev === sleeping.rev)
|
|
132
|
+
return "";
|
|
133
|
+
const text = attentionEntries(entries).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item.text;
|
|
134
|
+
return ` Your later question "${text ?? String(sleeping.qid)}" is withdrawn: the answer below is to your earlier question. Ask again if you still need it answered.`;
|
|
135
|
+
}
|
|
136
|
+
/** A launch failure the environment causes (the command or its interpreter is missing or not executable): fixing the
|
|
137
|
+
* environment, or another orchestrator started from a better one, makes the same launch work. */
|
|
138
|
+
export const environmentSpawnError = (error) => ["ENOENT", "EACCES"].includes(String(error?.code));
|
|
139
|
+
/** The default wait before an environment launch failure is retried (an orchestrator restart retries at once). */
|
|
140
|
+
export const SPAWN_RETRY_MS = 60_000;
|
|
141
|
+
/** A call's environment launch failures print one console line at the first, then at most one per this interval. */
|
|
142
|
+
export const SPAWN_CONSOLE_MS = 600_000;
|
|
110
143
|
export default function createExecutor(ledgers, options = {}) {
|
|
111
144
|
const { home, config, orch } = ledgers;
|
|
112
145
|
const containment = options.containment ?? serialContainment(), effects = options.effects ?? createEffects(ledgers);
|
|
146
|
+
const piCommand = options.pi ?? "pi";
|
|
113
147
|
const active = new Map(), completed = new Map(), journals = new Map();
|
|
114
148
|
let queue = Promise.resolve(), closed = false;
|
|
115
149
|
let suspending;
|
|
@@ -609,63 +643,148 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
609
643
|
});
|
|
610
644
|
wake();
|
|
611
645
|
}
|
|
646
|
+
/** The origin of a workflow (its `wf-created` entry, else the orchestrator ledger's `created`), cached once known. */
|
|
647
|
+
const origins = new Map();
|
|
648
|
+
function originOf(wid) {
|
|
649
|
+
let o = origins.get(wid);
|
|
650
|
+
if (o === undefined) {
|
|
651
|
+
const journal = journals.get(wid);
|
|
652
|
+
const value = journal?.entries().find(e => e.type === "wf-created")?.origin ?? orch.entries().find(e => e.type === JT.created && e.wid === wid)?.origin;
|
|
653
|
+
if (typeof value === "string")
|
|
654
|
+
origins.set(wid, o = value);
|
|
655
|
+
}
|
|
656
|
+
return o;
|
|
657
|
+
}
|
|
658
|
+
const widOf = (exec) => exec.slice(0, exec.indexOf("@"));
|
|
659
|
+
/** Slot precedence: every acquisition waiting now. `blockedOn`: the providers its latest attempt (at `at`) found full. */
|
|
660
|
+
const acquiring = new Map();
|
|
661
|
+
/** Whether another waiter with precedence for `provider` found it full on a recent attempt: then `exec` leaves the
|
|
662
|
+
* free slot to it. Precedence: a call that ran before (its session, cache and worktree are ready; a parent waits on it)
|
|
663
|
+
* before a fresh one; then the workflow origin holding fewer of the provider's slots; then the longer wait; then call id. */
|
|
664
|
+
function yields(exec, provider) {
|
|
665
|
+
const me = acquiring.get(exec);
|
|
666
|
+
if (!me)
|
|
667
|
+
return false;
|
|
668
|
+
const recent = 3 * (config.k?.trackerMs ?? 1000), now = Date.now();
|
|
669
|
+
let held;
|
|
670
|
+
const heldBy = (origin) => {
|
|
671
|
+
if (!held) {
|
|
672
|
+
held = new Map();
|
|
673
|
+
for (const h of holdings())
|
|
674
|
+
if (h.pool === provider) {
|
|
675
|
+
const o = originOf(widOf(h.exec));
|
|
676
|
+
held.set(o, (held.get(o) ?? 0) + 1);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return held.get(origin) ?? 0;
|
|
680
|
+
};
|
|
681
|
+
for (const [other, w] of acquiring) {
|
|
682
|
+
if (other === exec || !w.blockedOn.has(provider) || now - w.at >= recent || interrupted(w.a))
|
|
683
|
+
continue;
|
|
684
|
+
if (w.resume !== me.resume) {
|
|
685
|
+
if (w.resume)
|
|
686
|
+
return true;
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
const mine = heldBy(me.origin), theirs = heldBy(w.origin);
|
|
690
|
+
if (theirs !== mine) {
|
|
691
|
+
if (theirs < mine)
|
|
692
|
+
return true;
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
if (w.since !== me.since ? w.since < me.since : w.call < me.call)
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
612
700
|
/** Wait for a slot. The candidates are decided again on every attempt, inside the serial section that also applies
|
|
613
701
|
* config.json changes: a queued call follows a reloaded defaultModel, pool or limit, never a mix of two versions. */
|
|
614
702
|
async function acquire(a, exec, decide, writer) {
|
|
703
|
+
const t = a.ticket, since = Date.now();
|
|
704
|
+
// An execution that never started (its launch failed for a reason of the environment) does not make a resume.
|
|
705
|
+
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)));
|
|
706
|
+
const mine = { a, call: t.callId, origin: originOf(t.wid), since, resume, blockedOn: new Set(), at: since };
|
|
707
|
+
acquiring.set(exec, mine);
|
|
708
|
+
try {
|
|
709
|
+
return await acquireLoop(a, exec, decide, mine, writer);
|
|
710
|
+
}
|
|
711
|
+
finally {
|
|
712
|
+
acquiring.delete(exec);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
async function acquireLoop(a, exec, decide, mine, writer) {
|
|
615
716
|
let continuation = false;
|
|
616
717
|
for (;;) {
|
|
617
718
|
let signal;
|
|
618
719
|
const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
|
|
720
|
+
const blocked = new Set();
|
|
619
721
|
const chosen = await serial(async () => {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
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)
|
|
722
|
+
try {
|
|
723
|
+
if (interrupted(a) || await workflowReached(a.ticket))
|
|
724
|
+
return;
|
|
725
|
+
if (writer && !await writerAdmit(a, writer))
|
|
649
726
|
return;
|
|
650
|
-
const
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
727
|
+
const decision = await decide(), models = decision.candidates, pool = decision.pool;
|
|
728
|
+
continuation = decision.continuation;
|
|
729
|
+
for (const model of models) {
|
|
730
|
+
if (!continuation && pool && models.length > 1 && skipped(pool, model))
|
|
731
|
+
continue;
|
|
732
|
+
// A pool entry with afterMs waits its turn: it is taken only once this acquisition has waited that long.
|
|
733
|
+
if (model.afterMs !== undefined && Date.now() - mine.since < model.afterMs)
|
|
734
|
+
continue;
|
|
735
|
+
const provider = model.provider;
|
|
736
|
+
if (unavailable(provider))
|
|
737
|
+
continue;
|
|
738
|
+
const probe = provider !== undefined && folded().exhausted.has(provider);
|
|
739
|
+
const holders = holdings().filter(e => e.pool === provider);
|
|
740
|
+
const limit = settings().providers?.[provider ?? ""]?.slots ?? Infinity;
|
|
741
|
+
if (!capacity({ kind: "provider", holders: holders.length, capacity: limit })) {
|
|
742
|
+
if (provider)
|
|
743
|
+
blocked.add(provider);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (provider && yields(exec, provider))
|
|
747
|
+
continue;
|
|
748
|
+
// A burst of dispatches all read the same MemAvailable before any child has grown: subtract the children
|
|
749
|
+
// admitted in the last 30 s (their memory is not visible yet), so a burst cannot over-commit the headroom.
|
|
750
|
+
const perChild = settings().memory?.perChildMb ?? 300;
|
|
751
|
+
const warming = holdings().filter(e => e.pool === "memory" && Date.now() - e.ts < MEM_WARMUP_MS).length;
|
|
752
|
+
const measured = await (options.memory ?? availableMemory)(), available = measured - warming * perChild;
|
|
753
|
+
const admitted = capacity({ kind: "memory", available, reserve: settings().memory?.reserveMb ?? 2048, perChild });
|
|
754
|
+
// F3: every admitted dispatch is recorded; repeated refusals at most once per 30 s per call.
|
|
755
|
+
if (admitted || a.refusedAt === undefined || Date.now() - a.refusedAt >= MEM_RECORD_MS) {
|
|
756
|
+
await orch.append("mem", { available, admitted, exec, ...(warming ? { measured, warming } : {}) });
|
|
757
|
+
a.refusedAt = admitted ? undefined : Date.now();
|
|
758
|
+
}
|
|
759
|
+
if (!admitted)
|
|
760
|
+
return;
|
|
761
|
+
const memory = holdings().filter(e => e.pool === "memory");
|
|
762
|
+
let memorySlot = 0;
|
|
763
|
+
while (memory.some(e => e.slot === memorySlot))
|
|
764
|
+
memorySlot++;
|
|
765
|
+
await orch.append("hold", { pool: "memory", slot: memorySlot, exec });
|
|
766
|
+
if (provider) {
|
|
767
|
+
let slot = 0;
|
|
768
|
+
while (holders.some(e => e.slot === slot))
|
|
769
|
+
slot++;
|
|
770
|
+
await orch.append("hold", { pool: provider, slot, exec });
|
|
771
|
+
// After its next try, the first call admitted to a used-up provider is its probe: its first request
|
|
772
|
+
// either goes through (the provider is available again) or is refused, which uses no quota.
|
|
773
|
+
if (probe)
|
|
774
|
+
await orch.append("provider-probe", { provider, exec });
|
|
775
|
+
}
|
|
776
|
+
const plain = plainModel(model);
|
|
777
|
+
await a.ticket.journal.append("selected", { exec, model: plain, ...(pool ? { pool } : {}) });
|
|
778
|
+
return plain;
|
|
664
779
|
}
|
|
665
|
-
|
|
666
|
-
|
|
780
|
+
}
|
|
781
|
+
finally {
|
|
782
|
+
mine.blockedOn = blocked;
|
|
783
|
+
mine.at = Date.now();
|
|
667
784
|
}
|
|
668
785
|
});
|
|
786
|
+
if (!chosen)
|
|
787
|
+
options.attempted?.(exec, [...blocked]);
|
|
669
788
|
if (chosen || interrupted(a) || reached(totalUsage(a.ticket.journal.entries()), a.ticket.workflowBudget)) {
|
|
670
789
|
waiters.delete(signal);
|
|
671
790
|
return { model: chosen, continuation };
|
|
@@ -709,6 +828,12 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
709
828
|
return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
|
|
710
829
|
return { candidates, continuation: false, pool };
|
|
711
830
|
}
|
|
831
|
+
/** Resolve a bound answer before it waits for admission; also repairs an interrupted append pair. Called serially. */
|
|
832
|
+
async function resolveBoundAnswer(journal, call, qid, rev) {
|
|
833
|
+
const id = `q:${call}:${qid}`;
|
|
834
|
+
if (!journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev))
|
|
835
|
+
await journal.append(JT.attentionResolved, { id, rev, resolution: "answered" });
|
|
836
|
+
}
|
|
712
837
|
async function questions(t, entries) {
|
|
713
838
|
await collectReceipts(t.callId, entries).catch(error => console.error(`durable-subagents: inbox cleanup of ${t.callId} failed: ${String(error)}`));
|
|
714
839
|
await serial(async () => {
|
|
@@ -718,11 +843,38 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
718
843
|
const id = `q:${t.callId}:${qid}`;
|
|
719
844
|
if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
|
|
720
845
|
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))
|
|
722
|
-
await t.journal.
|
|
846
|
+
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))
|
|
847
|
+
await resolveBoundAnswer(t.journal, t.callId, qid, rev);
|
|
848
|
+
else if (digest.superseded.has(answerKey(qid, rev)) || supersededByBinding(t.journal.entries(), t.callId, qid, rev))
|
|
849
|
+
await resolveQuestion(t.journal, t.callId, qid, rev, "superseded");
|
|
723
850
|
}
|
|
851
|
+
await resolveSuperseded(t.journal, t.callId);
|
|
852
|
+
if (entries.length)
|
|
853
|
+
await resolveCarried(t.journal, t.callId, digest.questions);
|
|
724
854
|
});
|
|
725
855
|
}
|
|
856
|
+
/** D2, D4: close a question's attention item once (superseded, carried) unless already resolved. Called serially. */
|
|
857
|
+
async function resolveQuestion(journal, call, qid, rev, resolution) {
|
|
858
|
+
const id = `q:${call}:${qid}`;
|
|
859
|
+
if (attentionEntries(journal.entries(), id).some(e => e.item.rev === rev) && !journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev))
|
|
860
|
+
await journal.append(JT.attentionResolved, { id, rev, resolution });
|
|
861
|
+
}
|
|
862
|
+
/** D2: the questions durable bindings superseded (answer-bound.superseded, the source of truth) resolve `superseded`:
|
|
863
|
+
* after a crash between the binding and its resolution, recovery and observation derive it. Called serially. */
|
|
864
|
+
async function resolveSuperseded(journal, call) {
|
|
865
|
+
for (const b of journal.entries().filter(e => e.type === "answer-bound" && e.call === call && Array.isArray(e.superseded)))
|
|
866
|
+
for (const s of b.superseded)
|
|
867
|
+
await resolveQuestion(journal, call, s.qid, s.rev, "superseded");
|
|
868
|
+
}
|
|
869
|
+
/** D4: a question item of `call` that none of its executions asked (1.0.37 re-opened the questions of the session a
|
|
870
|
+
* generation continues) is resolved `carried`. `own`: the questions the call's executions asked. Called serially. */
|
|
871
|
+
async function resolveCarried(journal, call, own) {
|
|
872
|
+
for (const { item } of attentionEntries(journal.entries())) {
|
|
873
|
+
if (item.kind !== "question" || item.call !== call || own.some(q => q.qid === item.qid && q.rev === item.rev))
|
|
874
|
+
continue;
|
|
875
|
+
await resolveQuestion(journal, call, item.qid, item.rev, "carried");
|
|
876
|
+
}
|
|
877
|
+
}
|
|
726
878
|
/** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
|
|
727
879
|
const inUse = new Map();
|
|
728
880
|
async function switched(exec, journal, event) {
|
|
@@ -790,8 +942,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
790
942
|
wake();
|
|
791
943
|
}
|
|
792
944
|
/** 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
|
|
794
|
-
* the call waits for the provider once they end. */
|
|
945
|
+
* neither used up nor full and has no afterMs (such an entry is for calls that waited for a slot), reserving that
|
|
946
|
+
* slot as a requested switch does. Without one, pi's retries go on and the call waits for the provider once they end. */
|
|
795
947
|
async function failover(t, exec, provider) {
|
|
796
948
|
if (pendingSwitch(exec))
|
|
797
949
|
return;
|
|
@@ -806,7 +958,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
806
958
|
return;
|
|
807
959
|
}
|
|
808
960
|
for (const m of models) {
|
|
809
|
-
if (!m.provider || m.provider === provider || unavailable(m.provider) || skipped(pool, m))
|
|
961
|
+
if (!m.provider || m.provider === provider || m.afterMs !== undefined || unavailable(m.provider) || skipped(pool, m))
|
|
810
962
|
continue;
|
|
811
963
|
const rid = contentHash([exec, "failover", provider]);
|
|
812
964
|
if (t.journal.entries().some(e => e.type === "forward" && e.rid === rid))
|
|
@@ -855,6 +1007,44 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
855
1007
|
function pendingSwitch(exec) {
|
|
856
1008
|
return holdings().find(h => h.exec === exec && h.reserved && !folded().observed.has(`${exec}\n${h.rid}`));
|
|
857
1009
|
}
|
|
1010
|
+
/** When each call in environment retries last printed its console line. */
|
|
1011
|
+
const spawnConsoleAt = new Map();
|
|
1012
|
+
/** Serial sections only: record an environment launch failure (before its execution is fenced: recovery after a crash
|
|
1013
|
+
* in between finds an execution that never started, not a loss). */
|
|
1014
|
+
async function spawnEnvRecord(t, exec, error) {
|
|
1015
|
+
if (!has(t.journal, "spawn-env-failed", exec))
|
|
1016
|
+
await t.journal.append("spawn-env-failed", { exec, call: t.callId, command: piCommand, error: String(error).slice(0, 300) });
|
|
1017
|
+
}
|
|
1018
|
+
/** Serial sections only: raise one `environment` alert for the call (a new revision only after an earlier one was
|
|
1019
|
+
* resolved by a launch that worked); one console line at the first failure, then at most one per SPAWN_CONSOLE_MS. */
|
|
1020
|
+
async function spawnEnvFailed(t, exec, cwd, error) {
|
|
1021
|
+
const message = String(error).slice(0, 300), printed = spawnConsoleAt.get(t.callId);
|
|
1022
|
+
if (printed === undefined || Date.now() - printed >= SPAWN_CONSOLE_MS) {
|
|
1023
|
+
console.error(`durable-subagents: launching ${exec} failed: ${message}; retrying`);
|
|
1024
|
+
spawnConsoleAt.set(t.callId, Date.now());
|
|
1025
|
+
}
|
|
1026
|
+
const id = `environment:${t.callId}`, items = attentionEntries(t.journal.entries(), id), last = items.at(-1)?.item;
|
|
1027
|
+
if (last && !t.journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === last.rev))
|
|
1028
|
+
return;
|
|
1029
|
+
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)"
|
|
1030
|
+
: `${piCommand} (DSA_PI_BIN / the PATH the orchestrator started with)`;
|
|
1031
|
+
const text = `${worktreeLabel(t.callId)} could not start: ${message}. It runs ${pi} in ${cwd}. ` +
|
|
1032
|
+
`The call retries every minute (and at once when the orchestrator restarts); stop it to give up`;
|
|
1033
|
+
await t.journal.append(JT.attention, { item: { id, rev: (last?.rev ?? 0) + 1, kind: "environment", text, wid: t.wid, call: t.callId } });
|
|
1034
|
+
}
|
|
1035
|
+
/** Serial sections only: a launch worked, so the call's open environment alert is resolved. */
|
|
1036
|
+
async function spawnEnvResolved(t) {
|
|
1037
|
+
spawnConsoleAt.delete(t.callId);
|
|
1038
|
+
const id = `environment:${t.callId}`, last = attentionEntries(t.journal.entries(), id).at(-1)?.item;
|
|
1039
|
+
if (last && !t.journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === last.rev))
|
|
1040
|
+
await t.journal.append(JT.attentionResolved, { id, rev: last.rev, resolution: "launched" });
|
|
1041
|
+
}
|
|
1042
|
+
/** Wait before launching again after an environment failure; a stop, retirement, suspension or shutdown ends it early. */
|
|
1043
|
+
async function retryWait(a) {
|
|
1044
|
+
const until = Date.now() + (options.spawnRetryMs ?? SPAWN_RETRY_MS);
|
|
1045
|
+
while (!interrupted(a) && Date.now() < until)
|
|
1046
|
+
await new Promise(resolve => { const timer = setTimeout(resolve, Math.min(until - Date.now(), config.k?.trackerMs ?? 1000)); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
1047
|
+
}
|
|
858
1048
|
async function execute(a) {
|
|
859
1049
|
const t = a.ticket, journal = t.journal;
|
|
860
1050
|
const session = callSession(home, t.wid, t.key, t.gen), dir = callDir(home, t.wid, t.key, t.gen);
|
|
@@ -886,6 +1076,26 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
886
1076
|
let entries = await readCall(journal, t.callId);
|
|
887
1077
|
let dangling = [];
|
|
888
1078
|
let bound;
|
|
1079
|
+
// D3: a bound answer is settled by its receipt in the session, or by one durable `answer-settled{rid2}` when the
|
|
1080
|
+
// session closed its question revision without it (the child took that answer, or superseded the question, before
|
|
1081
|
+
// it was fenced): the resume never waits for a receipt the child would not give.
|
|
1082
|
+
const answerSettled = (u, session) => session.some(e => receiptId(e) === u.rid2) ||
|
|
1083
|
+
journal.entries().some(e => e.type === "answer-settled" && e.call === t.callId && e.rid2 === u.rid2);
|
|
1084
|
+
const settleClosed = async (u, session) => {
|
|
1085
|
+
if (!u || answerSettled(u, session))
|
|
1086
|
+
return;
|
|
1087
|
+
const d = digestOf(t.callId, session), key = answerKey(u.qid, u.rev);
|
|
1088
|
+
// D6: a newer revision of the question (the child asked it again, a steer having ended the ask, before the fence)
|
|
1089
|
+
// closes the bound one too: the child would refuse it as stale.
|
|
1090
|
+
const reason = d.answered.has(key) ? "answered-in-session" : d.superseded.has(key) ? "superseded-in-session" :
|
|
1091
|
+
d.questions.some(q => q.qid === u.qid && q.rev > Number(u.rev)) ? "newer-revision" : undefined;
|
|
1092
|
+
if (!reason)
|
|
1093
|
+
return;
|
|
1094
|
+
await serial(async () => {
|
|
1095
|
+
if (!journal.entries().some(e => e.type === "answer-settled" && e.call === t.callId && e.rid2 === u.rid2))
|
|
1096
|
+
await journal.append("answer-settled", { call: t.callId, rid2: u.rid2, qid: u.qid, rev: u.rev, reason });
|
|
1097
|
+
});
|
|
1098
|
+
};
|
|
889
1099
|
const sleeping = hibernation(journal, t.callId);
|
|
890
1100
|
if (exec && sleeping?.exec === exec) {
|
|
891
1101
|
await fence(journal, exec, { park: a });
|
|
@@ -896,18 +1106,31 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
896
1106
|
break;
|
|
897
1107
|
if (reached(totalUsage(journal.entries(), t.callId), t.spec.budget) || reached(totalUsage(journal.entries()), t.workflowBudget))
|
|
898
1108
|
return finish(journal, t.callId, exec, makeResult("budget"));
|
|
899
|
-
bound = journal.entries()
|
|
1109
|
+
bound = boundAnswer(journal.entries(), sleeping);
|
|
900
1110
|
if (bound)
|
|
901
1111
|
break;
|
|
902
1112
|
await new Promise(resolve => { const timer = setTimeout(resolve, config.k?.trackerMs ?? 1000); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
903
1113
|
}
|
|
904
1114
|
}
|
|
905
1115
|
const pendingAnswer = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
|
|
906
|
-
|
|
1116
|
+
await settleClosed(pendingAnswer, entries);
|
|
1117
|
+
if (!bound && pendingAnswer && !answerSettled(pendingAnswer, entries))
|
|
907
1118
|
bound = pendingAnswer;
|
|
908
1119
|
if (exec) {
|
|
909
1120
|
await fence(journal, exec, { park: a });
|
|
910
1121
|
await questions(t, entries = await readCall(journal, t.callId));
|
|
1122
|
+
// D6: after the fence the session is final. A bound answer it closed (answered, superseded, or re-asked as a newer
|
|
1123
|
+
// revision) is settled; if the session still has an open question of this call, the call does not launch: it
|
|
1124
|
+
// hibernates again on that question (its attention is open, so the parent is asked), and resumes only on a new
|
|
1125
|
+
// binding. Otherwise it launches with the plain continue. Each step is idempotent across a crash between them.
|
|
1126
|
+
if (bound) {
|
|
1127
|
+
await settleClosed(bound, entries);
|
|
1128
|
+
const asking = answerSettled(bound, entries) ? digestOpenQuestion(entries, digestOf(t.callId, entries)) : undefined;
|
|
1129
|
+
if (asking && !journal.entries().some(e => e.type === "hibernated" && e.call === t.callId && e.seq > bound.seq)) {
|
|
1130
|
+
await serial(() => journal.append("hibernated", { call: t.callId, exec, qid: asking.qid, rev: asking.rev, reason: "rebound-settled" }));
|
|
1131
|
+
continue;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
911
1134
|
await recordUsage(t, sessionUsage(entries, t.callId));
|
|
912
1135
|
const ev = evidence(entries, exec);
|
|
913
1136
|
dangling = ev.dangling;
|
|
@@ -919,7 +1142,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
919
1142
|
return finish(journal, t.callId, exec, makeResult("timeout"));
|
|
920
1143
|
if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
|
|
921
1144
|
return finish(journal, t.callId, exec, makeResult("budget"));
|
|
922
|
-
|
|
1145
|
+
// A child that never started (its launch failed for a reason of the environment) lost nothing: launch again.
|
|
1146
|
+
if (!bound && !has(journal, "spawn-env-failed", exec)) {
|
|
923
1147
|
// P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
|
|
924
1148
|
// hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
|
|
925
1149
|
// hibernation; it is neither a loss nor, for `once`, an unknown outcome.
|
|
@@ -998,7 +1222,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
998
1222
|
});
|
|
999
1223
|
// The answer uses its stable forwarded identity across every recovery incarnation.
|
|
1000
1224
|
const unresolved = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
|
|
1001
|
-
|
|
1225
|
+
// D3: the child takes one answer per question revision; a bound answer to one the session already closed (answered
|
|
1226
|
+
// or superseded) is settled durably instead of sent (it would be dropped), and the execution continues.
|
|
1227
|
+
await settleClosed(unresolved, entries);
|
|
1228
|
+
const receipt = unresolved && answerSettled(unresolved, entries);
|
|
1002
1229
|
const openingRid = t.opening && contentHash([t.opening.rid, "dispatch"]);
|
|
1003
1230
|
const openingReceived = openingRid && entries.some(e => receiptId(e) === openingRid);
|
|
1004
1231
|
// The task has one identity: the dispatch of the call's first execution. A later execution continues only once
|
|
@@ -1011,9 +1238,17 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1011
1238
|
else if (!openingRid && !taskReceived)
|
|
1012
1239
|
await sender.send(t.callId, "task", { message: t.spec.task }, undefined, { rid: taskRid });
|
|
1013
1240
|
else if (unresolved && !receipt)
|
|
1014
|
-
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
|
-
|
|
1241
|
+
await sender.send(t.callId, "continue", { message: String(unresolved.message), ...(Array.isArray(unresolved.superseded) ? { superseded: unresolved.superseded } : {}) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
|
|
1242
|
+
else if (previous) {
|
|
1243
|
+
// After launches that failed for a reason of the environment, no child received their dispatches: the first
|
|
1244
|
+
// execution of that run of failures keeps its dispatch (rid and content), so one is pending, not one per retry.
|
|
1245
|
+
const chain = envFailedChain(journal, t.callId, previous);
|
|
1246
|
+
const prior = chain && sender.recorded(contentHash([chain.first, "dispatch"]));
|
|
1247
|
+
if (prior)
|
|
1248
|
+
await sender.send(t.callId, prior.kind, prior.body, prior.cond, { rid: prior.rid });
|
|
1249
|
+
else
|
|
1250
|
+
await sender.send(t.callId, "continue", { message: continueMessage(chain?.before ? evidence(entries, chain.before).dangling : dangling) }, undefined, { rid: contentHash([chain?.first ?? exec, "dispatch"]) });
|
|
1251
|
+
}
|
|
1017
1252
|
else
|
|
1018
1253
|
await sender.send(t.callId, "task", { message: t.opening?.message ?? t.spec.task }, undefined, { rid: contentHash([exec, "dispatch"]) });
|
|
1019
1254
|
await launchGate(a, exec, "child");
|
|
@@ -1023,14 +1258,24 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1023
1258
|
}
|
|
1024
1259
|
let child;
|
|
1025
1260
|
try {
|
|
1026
|
-
child = await containment.spawn({ exec, command:
|
|
1027
|
-
|
|
1261
|
+
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,
|
|
1262
|
+
// The orchestrator's node follows binDir: a `#!/usr/bin/env node` pi runs under a PATH without node (a service's).
|
|
1263
|
+
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
1264
|
}
|
|
1029
1265
|
catch (error) {
|
|
1266
|
+
const environment = environmentSpawnError(error);
|
|
1267
|
+
if (environment)
|
|
1268
|
+
await serial(() => spawnEnvRecord(t, exec, error));
|
|
1030
1269
|
await fence(journal, exec, { park: a });
|
|
1031
1270
|
a.live = undefined;
|
|
1032
|
-
|
|
1271
|
+
if (!environment)
|
|
1272
|
+
return finish(journal, t.callId, exec, makeResult("failed", "", `Spawn failed: ${String(error)}`));
|
|
1273
|
+
await release(exec);
|
|
1274
|
+
await serial(() => spawnEnvFailed(t, exec, cwd, error));
|
|
1275
|
+
await retryWait(a);
|
|
1276
|
+
continue;
|
|
1033
1277
|
}
|
|
1278
|
+
await serial(() => spawnEnvResolved(t));
|
|
1034
1279
|
try {
|
|
1035
1280
|
await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
|
|
1036
1281
|
await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
|
|
@@ -1068,28 +1313,49 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1068
1313
|
*/
|
|
1069
1314
|
async function adoptAnswer(journal, call, sleeping) {
|
|
1070
1315
|
const entries = await readCall(journal, call);
|
|
1071
|
-
await serial(
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1316
|
+
await serial(() => adopt(journal, call, sleeping, entries));
|
|
1317
|
+
}
|
|
1318
|
+
/** The forward whose adoption was begun (its envelope withdrawn from the child's inbox) and not yet bound. */
|
|
1319
|
+
async function adoptionBegun(journal, call) {
|
|
1320
|
+
const sender = await outbox, all = journal.entries();
|
|
1321
|
+
return all.find(e => e.type === "forward" && e.dest === call && e.envelope.kind === "answer" &&
|
|
1322
|
+
!all.some(r => r.rid2 === e.rid2 && r.type === "forward-retired") && !!sender.recorded(contentHash([String(e.rid2), "withdraw-adopted"])));
|
|
1323
|
+
}
|
|
1324
|
+
/** P28, D3: bind a pending answer forward to hibernation `sleeping` (see adoptAnswer). `onlyBegun`: only one whose
|
|
1325
|
+
* adoption was begun before a crash (its envelope is withdrawn, so it can reach the child only through this binding).
|
|
1326
|
+
* Called serially. */
|
|
1327
|
+
async function adopt(journal, call, sleeping, entries, onlyBegun = false) {
|
|
1328
|
+
const all = journal.entries();
|
|
1329
|
+
if (boundAnswer(all, sleeping))
|
|
1330
|
+
return;
|
|
1331
|
+
const begun = await adoptionBegun(journal, call);
|
|
1332
|
+
const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
|
|
1333
|
+
// The answer to the question it hibernated on, else to another of its questions still open (an earlier one).
|
|
1334
|
+
const pending = all.filter(e => {
|
|
1335
|
+
if (e.type !== "forward" || e.dest !== call)
|
|
1336
|
+
return false;
|
|
1337
|
+
const env = e.envelope;
|
|
1338
|
+
return env.kind === "answer" && !receipts.has(String(e.rid2)) && !all.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered")) &&
|
|
1339
|
+
(env.cond?.qid === sleeping.qid && env.cond?.rev === sleeping.rev || openAsked(all, call, env.cond?.qid, env.cond?.rev));
|
|
1092
1340
|
});
|
|
1341
|
+
// An adoption begun before a crash is completed first: its envelope is already withdrawn.
|
|
1342
|
+
const f = pending.find(e => e.rid2 === begun?.rid2) ?? (onlyBegun ? undefined : pending.find(e => e.envelope.cond?.qid === sleeping.qid) ?? pending[0]);
|
|
1343
|
+
if (!f)
|
|
1344
|
+
return;
|
|
1345
|
+
const { qid, rev } = f.envelope.cond;
|
|
1346
|
+
const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === qid && e.item.rev === rev)?.item;
|
|
1347
|
+
const message = String(f.envelope.body?.message ?? "");
|
|
1348
|
+
// A new identity: the stale answer may still sit in the child's inbox under the forward's rid2. It is withdrawn
|
|
1349
|
+
// there (D3; before the bound continue is sent, so the resumed child drops it first): the continue carries the
|
|
1350
|
+
// answer and what it supersedes. Idempotent by rid, so a crash before the binding sends it once.
|
|
1351
|
+
await (await outbox).send(call, "withdraw", { rids: [String(f.rid2)] }, undefined, { rid: contentHash([String(f.rid2), "withdraw-adopted"]) });
|
|
1352
|
+
await journal.append("answer-bound", { event: true, call, qid, rev, rid: f.rid, rid2: contentHash([String(f.rid2), "hibernated"]), hash: f.hash,
|
|
1353
|
+
message: `${HIBERNATED_NOTE}${withdrawn(all, call, sleeping, qid, rev)}\n\nQuestion: ${item?.text ?? qid}\nAnswer: ${message}`, ...supersedes(sleeping, qid, rev) });
|
|
1354
|
+
await resolveBoundAnswer(journal, call, qid, rev);
|
|
1355
|
+
if (qid !== sleeping.qid || rev !== sleeping.rev)
|
|
1356
|
+
await resolveQuestion(journal, call, sleeping.qid, sleeping.rev, "superseded");
|
|
1357
|
+
await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
|
|
1358
|
+
await (await outbox).markResolved(String(f.rid2));
|
|
1093
1359
|
}
|
|
1094
1360
|
async function replayForward(e) {
|
|
1095
1361
|
const envelope = e.envelope;
|
|
@@ -1164,21 +1430,42 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1164
1430
|
return { action: "apply" };
|
|
1165
1431
|
}
|
|
1166
1432
|
const boundRetry = ctx.journal.entries().find(e => e.type === "answer-bound" && e.call === dest && e.rid === req.rid);
|
|
1167
|
-
if (boundRetry)
|
|
1168
|
-
|
|
1433
|
+
if (boundRetry) {
|
|
1434
|
+
if (boundRetry.hash !== hash)
|
|
1435
|
+
return { action: "reject", reason: "identity-conflict" };
|
|
1436
|
+
await resolveBoundAnswer(ctx.journal, dest, boundRetry.qid, boundRetry.rev);
|
|
1437
|
+
return { action: "apply" };
|
|
1438
|
+
}
|
|
1169
1439
|
if (sealed(ctx.journal, dest))
|
|
1170
1440
|
return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
|
|
1171
1441
|
if (req.kind === "send" && req.body.kind === "answer") {
|
|
1172
1442
|
const sleeping = hibernation(ctx.journal, dest);
|
|
1443
|
+
// An adoption begun before a crash (the earlier answer withdrawn from the inbox, not yet bound) binds first.
|
|
1444
|
+
if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping) && await adoptionBegun(ctx.journal, dest))
|
|
1445
|
+
await adopt(ctx.journal, dest, sleeping, await readCall(ctx.journal, dest), true);
|
|
1173
1446
|
const priorAnswer = ctx.journal.entries().find(e => e.type === "answer-bound" && e.call === dest && e.qid === req.cond?.qid && e.rev === req.cond?.rev);
|
|
1174
1447
|
if (priorAnswer)
|
|
1175
1448
|
return priorAnswer.rid === req.rid && priorAnswer.hash === hash ? { action: "apply" } : { action: "reject", reason: "already-answered" };
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1449
|
+
// D2, D4: a superseded or carried question takes no answer.
|
|
1450
|
+
if (supersededByBinding(ctx.journal.entries(), dest, req.cond?.qid, req.cond?.rev) ||
|
|
1451
|
+
ctx.journal.entries().some(e => e.type === JT.attentionResolved && e.id === `q:${dest}:${req.cond?.qid}` && e.rev === req.cond?.rev && (e.resolution === "superseded" || e.resolution === "carried")))
|
|
1452
|
+
return { action: "reject", reason: "stale-rev" };
|
|
1453
|
+
// A hibernated call takes one answer: to the question it hibernated on, or to another of its open questions (an
|
|
1454
|
+
// earlier one, still open while the child asked a reminder). Once one is bound, a further answer to another
|
|
1455
|
+
// open question is forwarded like any other: the resumed child takes it at its next ask.
|
|
1456
|
+
if (sleeping && current(ctx.journal, dest) === sleeping.exec &&
|
|
1457
|
+
!(sleeping.qid === req.cond?.qid && sleeping.rev === req.cond?.rev) && !openAsked(ctx.journal.entries(), dest, req.cond?.qid, req.cond?.rev))
|
|
1458
|
+
return { action: "reject", reason: "stale-rev" };
|
|
1459
|
+
if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping)) {
|
|
1460
|
+
const { qid, rev } = req.cond;
|
|
1179
1461
|
const rid2 = forwardRid(req.rid, ctx.widRev, ctx.key, hash);
|
|
1180
|
-
const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid ===
|
|
1181
|
-
|
|
1462
|
+
const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === qid && e.item.rev === rev)?.item;
|
|
1463
|
+
// `event`: the `answered` event derives from this entry (an unmarked older one: from its resolution).
|
|
1464
|
+
await ctx.journal.append("answer-bound", { event: true, call: dest, qid, rev, rid: req.rid, rid2, hash,
|
|
1465
|
+
message: `${HIBERNATED_NOTE}${withdrawn(ctx.journal.entries(), dest, sleeping, qid, rev)}\n\nQuestion: ${item?.text ?? qid}\nAnswer: ${req.body.message ?? ""}`, ...supersedes(sleeping, qid, rev) });
|
|
1466
|
+
await resolveBoundAnswer(ctx.journal, dest, qid, rev);
|
|
1467
|
+
if (qid !== sleeping.qid || rev !== sleeping.rev)
|
|
1468
|
+
await resolveQuestion(ctx.journal, dest, sleeping.qid, sleeping.rev, "superseded");
|
|
1182
1469
|
active.get(dest)?.wake();
|
|
1183
1470
|
wake();
|
|
1184
1471
|
return { action: "apply" };
|
|
@@ -1192,7 +1479,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1192
1479
|
// recorded and the next execution launches on it (`requestedModel`); its slot is acquired then, as for any launch.
|
|
1193
1480
|
const idle = !exec || has(ctx.journal, JT.fenced, exec) || !has(ctx.journal, "selected", exec);
|
|
1194
1481
|
// 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
|
|
1482
|
+
// call) a free slot; an entry with afterMs is skipped (it is for calls that waited for a slot), as failover
|
|
1483
|
+
// skips it. The call's own pool stays, so a used-up window later moves it on as before.
|
|
1196
1484
|
const pools = settings().pools, pool = pools && Object.hasOwn(pools, model) ? model : undefined;
|
|
1197
1485
|
if (pool) {
|
|
1198
1486
|
let models;
|
|
@@ -1204,7 +1492,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1204
1492
|
}
|
|
1205
1493
|
const free = (p) => idle || holdings().some(h => h.exec === exec && h.pool === p) ||
|
|
1206
1494
|
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));
|
|
1495
|
+
const m = models.find(m => m.provider && m.afterMs === undefined && !unavailable(m.provider) && free(m.provider));
|
|
1208
1496
|
if (!m)
|
|
1209
1497
|
return { action: "reject", reason: "pool-unavailable" };
|
|
1210
1498
|
model = `${m.provider}/${m.id}${m.thinking ? `:${m.thinking}` : ""}`;
|
|
@@ -1361,6 +1649,11 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1361
1649
|
await retireAttention(journal, call);
|
|
1362
1650
|
await unknownAttention(journal, call);
|
|
1363
1651
|
}
|
|
1652
|
+
else {
|
|
1653
|
+
await resolveSuperseded(journal, call);
|
|
1654
|
+
if (session.length)
|
|
1655
|
+
await resolveCarried(journal, call, digestOf(call, session).questions);
|
|
1656
|
+
}
|
|
1364
1657
|
});
|
|
1365
1658
|
if (!active.has(call))
|
|
1366
1659
|
forgetCall(call);
|