pi-durable-subagents 1.0.37 → 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 CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.38
4
+
5
+ - An answer to any open question of a call reaches it. A call whose question was interrupted (by a steer) and that
6
+ asked again in other words while waiting no longer orphans the answer to the first question: a waiting subagent
7
+ takes it as the result of its current question, a hibernated one resumes with it (also when the answer was sent
8
+ before it hibernated), and a subagent that is not waiting gets it as a message at its next safe point. Before, an
9
+ answer to a question other than the one the subagent waited on was held until a later ask, usually forever, and
10
+ then retired.
11
+ - One rule for answers: an answer (or the answer a hibernated asker resumes with) to an open question is delivered
12
+ once, at the first chance, never held. A waiting subagent prefers the answer to the question it waits on when
13
+ several are pending. Follow-ups sent before a pending answer still enter ahead of it, notifies after it.
14
+ - An answer to an earlier question that ends the wait on a later one supersedes the later question: the subagent is
15
+ told it was withdrawn and to ask again if it still needs it, its attention item resolves `superseded` (at once when
16
+ the answer is bound to a hibernated call), `status` no longer shows the call `asking`, and a later answer to it is
17
+ refused `stale-rev`.
18
+ - A question revision gets at most one answer receipt. An answer sent before the call hibernated and bound to the
19
+ hibernation is withdrawn from the subagent's inbox; any further envelope for an answered, superseded or stale
20
+ revision is dropped with a receipt, so nothing waits on it. These records survive a crash between their writes: a
21
+ supersession is derived from the binding that made it, an adoption whose withdrawal went out is completed first, and
22
+ a bound answer the session had already closed is settled without waiting for a receipt. An answer bound to a revision
23
+ the subagent has already asked again is not delivered: the call hibernates again and the parent is asked the newer
24
+ revision.
25
+ - A follow-up generation no longer re-opens the questions of the session it continues (its subagent would refuse
26
+ their answers). Items that 1.0.37 re-opened in a running generation are resolved `carried` at orchestrator start.
27
+ - Follow-ups queued while a call waited on its question reach the resumed model before the answer, in send order.
28
+
3
29
  ## 1.0.37
4
30
 
5
31
  - The process table runs `ps` by its absolute path (`/bin/ps`), so an orchestrator started with a minimal PATH keeps
package/README.md CHANGED
@@ -122,7 +122,7 @@ it something. Each verb means one thing, and a refusal says what would work:
122
122
  | `send steer` | a running subagent | Reaches it at its next safe point. To a finished one: refused, use `follow-up`; To one waiting on its question: it interrupts the question, and the subagent usually asks again; `answer` answers it. |
123
123
  | `send notify` | any subagent | Tells it a decision without disturbing it. The reply's `delivery` says how: `steered` (running: it gets the note at its next safe point, like a steer), `held-until-answer` (waiting on its question: never interrupts it; it gets the note at the first safe point after the answer) or `noted` (not running: nothing starts; the note is recorded, and the call's next follow-up opens with it). |
124
124
  | `send follow-up` | any subagent | A finished one continues in the same session as a new generation (`key@2`); the reply names it (`generation`, `call`). A running one gets it after its current turn; the reply says `delivery: forwarded` and names the running generation (`call: <wid>/<key>@<gen>`). With `model` (a model or a pool's name), the generation that takes it runs on it. |
125
- | `send answer` | an open question | Answers it once. |
125
+ | `send answer` | an open question | Answers it once, at the first chance: as the result of the question it waits on, or (when it no longer waits on that question, say after a steer) as a message at its next safe point. An answer to an earlier question while it waits on a later one ends the later one: that question is withdrawn (`superseded`, the subagent is told to ask again if it still needs it) and takes no answer. |
126
126
  | `send model` | any subagent | A running one switches at its next request; one asking, hibernated or waiting for a slot launches on it when it runs again. A pool's name picks its first model that is not used up (and, for a running call, has a free slot); the reply names the model picked, and a call from that pool stays in it. |
127
127
  | `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. |
128
128
  | `drain` / `resume` | existing workflows | A reversible hold; runs started later are not held. |
@@ -3,7 +3,14 @@ import { CT } from "../../types.js";
3
3
  * session of the previous one (P37), but request sequences are per recipient (P5): records addressed to an earlier
4
4
  * generation stay in history and are skipped here: segments opened by another call's execution marker are foreign. */
5
5
  export function recover(entries, call) {
6
- const records = [], questions = new Map(), answered = new Set();
6
+ const records = [], questions = new Map(), answered = new Set(), superseded = new Set();
7
+ // D2: an answer to another question that ended a blocked ask (or resumed a hibernated one) supersedes that question.
8
+ const supersede = (details) => {
9
+ if (Array.isArray(details?.superseded))
10
+ for (const s of details.superseded)
11
+ if (typeof s?.qid === 'string' && typeof s.rev === 'number')
12
+ superseded.add(`${s.qid}@${s.rev}`);
13
+ };
7
14
  let foreign = false;
8
15
  for (const entry of entries) {
9
16
  if (entry.type === 'custom' && entry.customType === CT.exec) {
@@ -33,6 +40,7 @@ export function recover(entries, call) {
33
40
  else if (entry.type === 'custom_message' && entry.customType === CT.msg) {
34
41
  const details = entry.details;
35
42
  records.push({ type: 'applied', rid: details.rid });
43
+ supersede(details);
36
44
  // P28: a hibernation resume delivers the answer as a continue message; its receipt answers qid@rev.
37
45
  if (details.qid && details.rev)
38
46
  answered.add(`${details.qid}@${details.rev}`);
@@ -41,9 +49,10 @@ export function recover(entries, call) {
41
49
  const details = entry.message.details;
42
50
  if (details?.rid)
43
51
  records.push({ type: 'applied', rid: details.rid });
52
+ supersede(details);
44
53
  if (details?.qid && details.rev)
45
54
  answered.add(`${details.qid}@${details.rev}`);
46
55
  }
47
56
  }
48
- return { records, questions, answered };
57
+ return { records, questions, answered, superseded };
49
58
  }
@@ -11,6 +11,17 @@ import { recover } from "./child/history.js";
11
11
  import { validate } from "./child/schema.js";
12
12
  import { registerLive } from "./child/live.js";
13
13
  const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
14
+ /** D2: the questions a bound continue supersedes: the hibernated asker's own question when it resumes with the answer
15
+ * to another one (the orchestrator names it in the body). */
16
+ function supersededOf(req) {
17
+ const list = req.kind === 'continue' ? req.body?.superseded : undefined;
18
+ return Array.isArray(list) ? list.filter((s) => typeof s?.qid === 'string' && typeof s?.rev === 'number').map(s => ({ qid: s.qid, rev: s.rev })) : [];
19
+ }
20
+ /** The question an envelope answers: an `answer`, or a `continue` that resumes a hibernated asker with its answer (P28). */
21
+ export function answers(req) {
22
+ const qid = req.cond?.qid, rev = req.cond?.rev;
23
+ return (req.kind === 'answer' || req.kind === 'continue') && typeof qid === 'string' && typeof rev === 'number' ? { qid, rev } : undefined;
24
+ }
14
25
  /** P31, P33, P37: Usage of this call only — assistant messages in segments opened by this call's executions,
15
26
  * deduplicated by entry id. Context inherited from an earlier generation or a forked origin is not charged. */
16
27
  export function usage(entries, call) {
@@ -78,20 +89,48 @@ export function registerChild(pi) {
78
89
  if (!active || (mode === 'idle' && !ctx.isIdle()))
79
90
  return [];
80
91
  let delivered = false;
92
+ // Revisions answered (taken) or superseded (planned) by a decision of this intake are closed for the rest of it:
93
+ // one delivery each (D3), and no answer to a question an earlier decision of the same intake superseded (D2).
94
+ const taken = new Set(), planned = new Set();
95
+ const closed = () => new Set([...state.answered, ...state.superseded, ...taken, ...planned]);
96
+ const open = (q) => openness({ open: [...state.questions.values()], closed: closed() }, q);
97
+ const pending = (req, view) => view.admitted.has(req.rid) && !view.resolved.has(req.rid) && !view.tombstones.has(req.rid);
98
+ // An answer to an open question (or a bound continue, P28) that waits to be delivered.
99
+ const waiting = (req, view) => {
100
+ const q = answers(req);
101
+ return !!q && pending(req, view) && open(q);
102
+ };
81
103
  const plans = planDecisions(state.records, candidates, (req, view) => {
82
104
  if (req.to !== call)
83
105
  return { action: 'reject', reason: 'wrong-recipient' };
84
106
  if ([...MESSAGES, 'answer'].includes(req.kind) && typeof req.body?.message !== 'string')
85
107
  return { action: 'reject', reason: 'malformed' };
86
- if (req.kind === 'answer') {
87
- const qid = req.cond?.qid, rev = req.cond?.rev, question = qid ? state.questions.get(qid) : undefined;
88
- if (state.answered.has(`${qid}@${rev}`))
108
+ const q = answers(req);
109
+ // D1, D3, V4: one rule for answers (an `answer`, or a bound `continue`): an open question takes its answer at the
110
+ // first opportunity, once; any further envelope for an answered or superseded revision is dropped with a receipt.
111
+ if (q) {
112
+ const key = `${q.qid}@${q.rev}`;
113
+ if (state.answered.has(key) || taken.has(key))
89
114
  return { action: 'reject', reason: 'already-answered' };
90
- if (!question || question.rev !== rev)
115
+ // Not open: superseded, an older revision, or a question this generation did not ask. A bound continue too: the
116
+ // orchestrator binds the latest revision it observed, and the child may have asked again meanwhile (V4).
117
+ if (!open(q))
91
118
  return { action: 'reject', reason: 'stale-rev' };
92
- if (mode !== 'ask' || delivered || !openness({ open: [...state.questions.values()], blocked }, { qid: qid, rev: rev }))
119
+ if (delivered && mode !== 'boundary' && mode !== 'settle')
120
+ return { action: 'defer' };
121
+ // A blocked ask prefers its own answer when answers to several open questions wait.
122
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev) && candidates.some(other => pending(other, view) &&
123
+ answers(other)?.qid === blocked.qid && answers(other)?.rev === blocked.rev))
124
+ return { action: 'defer' };
125
+ // Follow-ups ordered before it enter first (fix C): at a boundary they ride ahead (below); here it waits.
126
+ if (mode !== 'ask' && candidates.some(other => other.kind === 'follow-up' && pending(other, view) && view.order.get(other.rid) < view.order.get(req.rid)))
93
127
  return { action: 'defer' };
94
128
  delivered = true;
129
+ taken.add(key);
130
+ for (const s of supersededOf(req))
131
+ planned.add(`${s.qid}@${s.rev}`);
132
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev))
133
+ planned.add(`${blocked.qid}@${blocked.rev}`);
95
134
  return { action: 'apply' };
96
135
  }
97
136
  if (mode === 'ask' && (req.kind !== 'steer' || delivered))
@@ -103,12 +142,14 @@ export function registerChild(pi) {
103
142
  return body && ctx.modelRegistry.find(body.provider, body.model) ? { action: 'apply' } : { action: 'reject', reason: 'unknown-model' };
104
143
  }
105
144
  if (MESSAGES.includes(req.kind)) {
106
- if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary'))
145
+ // A resumed turn can reach this boundary before an idle intake. Older follow-ups must ride ahead of its
146
+ // bound answer; otherwise continue bypasses them and the model sees stale instructions after the answer.
147
+ const beforeResume = mode === 'boundary' && req.kind === 'follow-up' && candidates.some(other => waiting(other, view) && view.order.get(req.rid) < (view.order.get(other.rid) ?? -1));
148
+ if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary' && !beforeResume))
107
149
  return { action: 'defer' };
108
150
  // A notify never interrupts a question: while an answer waits to be delivered (a hibernated asker resumes with
109
151
  // its answer as a continue) it goes after it, at the next safe point. In ask mode it was deferred above.
110
- if (req.kind === 'notify' && candidates.some(other => !view.resolved.has(other.rid) && !view.tombstones.has(other.rid) &&
111
- (other.kind === 'answer' && !state.answered.has(`${other.cond?.qid}@${other.cond?.rev}`) || other.kind === 'continue' && other.cond?.qid !== undefined)))
152
+ if (req.kind === 'notify' && candidates.some(other => waiting(other, view)))
112
153
  return { action: 'defer' };
113
154
  delivered = true;
114
155
  return { action: 'apply' };
@@ -118,7 +159,7 @@ export function registerChild(pi) {
118
159
  // Idle delivery starts pi immediately. Commit only through that message's receipt;
119
160
  // later decisions must be reconsidered at the next boundary, in history order.
120
161
  if (mode === 'idle') {
121
- const firstMessage = plans.findIndex(d => d.type === 'applied' && MESSAGES.includes(byRid.get(d.rid).kind));
162
+ const firstMessage = plans.findIndex(d => d.type === 'applied' && [...MESSAGES, 'answer'].includes(byRid.get(d.rid).kind));
122
163
  if (firstMessage >= 0)
123
164
  plans.splice(firstMessage + 1);
124
165
  }
@@ -150,19 +191,35 @@ export function registerChild(pi) {
150
191
  record(CT.model, { rid: req.rid, provider: body.provider, model: body.model, ...(body.thinking ? { thinking: body.thinking } : {}) });
151
192
  }
152
193
  else if (mode === 'ask' && waiter) {
153
- const text = req.body.message;
154
- answer = req.kind === 'answer'
155
- ? { content: [{ type: 'text', text }], details: { rid: req.rid, qid: waiter.qid, rev: waiter.rev } }
156
- : { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
157
- if (req.kind === 'answer')
158
- state.answered.add(`${waiter.qid}@${waiter.rev}`);
194
+ const text = req.body.message, q = answers(req);
195
+ if (q) {
196
+ const carried = supersededOf(req);
197
+ // D2: an answer to another open question ends the blocked ask too; the blocked question is superseded (the
198
+ // model is told so), and a later answer to it is rejected.
199
+ const own = q.qid === waiter.qid && q.rev === waiter.rev;
200
+ const note = own ? '' : `${JSON.stringify({ answers_earlier_question: q.qid, withdrawn: waiter.qid })}\n` +
201
+ `Your question "${waiter.question}" is withdrawn: this answers your earlier question instead. Ask again if you still need it answered.\n` +
202
+ (req.kind === 'answer' ? `Question: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ` : '');
203
+ const superseded = [...carried, ...(own ? [] : [{ qid: waiter.qid, rev: waiter.rev }])];
204
+ answer = { content: [{ type: 'text', text: `${note}${text}` }], details: { rid: req.rid, qid: q.qid, rev: q.rev, ...(superseded.length ? { superseded } : {}) } };
205
+ state.answered.add(`${q.qid}@${q.rev}`);
206
+ for (const s of superseded)
207
+ state.superseded.add(`${s.qid}@${s.rev}`);
208
+ }
209
+ else
210
+ answer = { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
159
211
  }
160
212
  else {
161
- // P28: a continue bound to a question (hibernation resume) is that question's answer receipt.
162
- const bound = req.kind === 'continue' && req.cond?.qid && req.cond.rev ? { qid: req.cond.qid, rev: req.cond.rev } : undefined;
163
- if (bound)
164
- state.answered.add(`${bound.qid}@${bound.rev}`);
165
- entries.push({ type: 'custom_message', customType: CT.msg, content: req.body.message, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...bound } });
213
+ // P28: a continue bound to a question (hibernation resume) is that question's answer receipt; D1: so is an
214
+ // answer delivered outside an ask (its ask ended by a steer or a reminder), as a message at this boundary.
215
+ const q = answers(req), body = req.body, superseded = supersededOf(req);
216
+ if (q)
217
+ state.answered.add(`${q.qid}@${q.rev}`);
218
+ for (const s of superseded)
219
+ state.superseded.add(`${s.qid}@${s.rev}`);
220
+ const content = req.kind === 'answer'
221
+ ? `The answer to your earlier question arrived.\nQuestion: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ${body.message}` : body.message;
222
+ entries.push({ type: 'custom_message', customType: CT.msg, content, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...q, ...(superseded.length ? { superseded } : {}) } });
166
223
  }
167
224
  }
168
225
  }
@@ -116,6 +116,13 @@ function applyWait(f, e) {
116
116
  }
117
117
  break;
118
118
  }
119
+ // D6: hibernated again after a bound answer the session had already closed: it waits for a new answer.
120
+ case "hibernated": {
121
+ const c = f.calls.get(String(e.call));
122
+ if (c && c.exec === e.exec)
123
+ delete c.answered;
124
+ break;
125
+ }
119
126
  case "answer-bound": {
120
127
  const c = f.calls.get(String(e.call)), id = `q:${e.call}:${e.qid}`, item = f.items.get(id);
121
128
  if (item?.rev === e.rev)
@@ -10,10 +10,10 @@ export function seal(state, transition) {
10
10
  export function currency(state, transition) {
11
11
  return Object.entries(transition).every(([key, value]) => value === undefined || state[key] === value);
12
12
  }
13
- /** A4, V4, P28: Answers require an open question and matching blocked or hibernated state. */
13
+ /** A4, V4, P28: An answer requires an open question: the current revision of a question the call asked (`open`), not yet
14
+ * answered or superseded (`closed`, keys `qid@rev`). Any open question takes its answer, blocked in an ask or not. */
14
15
  export function openness(state, transition) {
15
- const matches = (q) => q?.qid === transition.qid && q.rev === transition.rev;
16
- return state.open.some(matches) && (matches(state.blocked) || matches(state.hibernated));
16
+ return state.open.some(q => q.qid === transition.qid && q.rev === transition.rev) && !state.closed.has(`${transition.qid}@${transition.rev}`);
17
17
  }
18
18
  /** A4, V5, P5: Dependencies must be earlier admissions, and resolved before application. */
19
19
  export function dependency(state, transition) {
@@ -6,6 +6,10 @@ import { CT } from "../../types.js";
6
6
  import { askOf, cutAskResult, receiptId } from "./session.js";
7
7
  import { messageUsage } from "./usage.js";
8
8
  export const answerKey = (qid, rev) => JSON.stringify([qid, rev]);
9
+ /** D2: the questions an answer receipt superseded (`details.superseded`: the blocked or hibernated asker's question). */
10
+ export function supersededBy(details) {
11
+ return Array.isArray(details?.superseded) ? details.superseded.filter(q => typeof q?.qid === "string" && typeof q?.rev === "number") : [];
12
+ }
9
13
  /** A fold of one session for one call, extended over appended entries. */
10
14
  export class SessionFold {
11
15
  call;
@@ -19,7 +23,7 @@ export class SessionFold {
19
23
  state;
20
24
  constructor(call) { this.call = call; this.state = SessionFold.empty(); }
21
25
  static empty() {
22
- return { usage: [], receipts: new Map(), questions: [], answered: new Set(), lastQuestion: -1, questionAt: new Map(), execAt: new Map(), results: new Map() };
26
+ return { usage: [], receipts: new Map(), questions: [], answered: new Set(), superseded: new Set(), lastQuestion: -1, questionAt: new Map(), execAt: new Map(), results: new Map() };
23
27
  }
24
28
  update(entries) {
25
29
  if (entries === this.entries)
@@ -48,13 +52,16 @@ export class SessionFold {
48
52
  s.questionAt.set(e.data?.qid, i);
49
53
  if (e.type === "custom") {
50
54
  s.lastQuestion = i;
51
- if (e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
55
+ if (this.own && e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
52
56
  s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question });
53
57
  }
54
58
  }
55
59
  const details = e.message?.details ?? e.details;
56
60
  if (details && rid !== undefined)
57
61
  s.answered.add(answerKey(details.qid, details.rev));
62
+ if (rid !== undefined)
63
+ for (const q of supersededBy(details))
64
+ s.superseded.add(answerKey(q.qid, q.rev));
58
65
  const m = e.message;
59
66
  if (m?.role === "toolResult" && typeof m.toolCallId === "string" && !s.results.has(m.toolCallId))
60
67
  s.results.set(m.toolCallId, e);
@@ -70,7 +77,7 @@ export function digestOpenQuestion(entries, s) {
70
77
  const at = s.lastQuestion, q = entries[at]?.data;
71
78
  if (!q || typeof q.qid !== "string" || typeof q.rev !== "number")
72
79
  return;
73
- if (s.answered.has(answerKey(q.qid, q.rev)))
80
+ if (s.answered.has(answerKey(q.qid, q.rev)) || s.superseded.has(answerKey(q.qid, q.rev)))
74
81
  return;
75
82
  const ask = askOf(entries, at);
76
83
  const result = ask === undefined ? undefined : s.results.get(ask);
@@ -1,7 +1,8 @@
1
1
  // Private workflow entries (P28): hibernated{call,qid,rev,exec};
2
2
  // answer-bound{call,qid,rev,rid,rid2,message,hash}; resumed{call,rid,exec}.
3
- import { CT } from "../../types.js";
3
+ import { CT, JT, attentionEntries } from "../../types.js";
4
4
  import { askOf, cutAskResult, receiptId } from "./session.js";
5
+ import { supersededBy } from "./digest.js";
5
6
  /** P28, V4: Find an unanswered question whose native ask tool remains blocked. */
6
7
  export function openQuestion(entries) {
7
8
  const at = entries.findLastIndex(e => e.type === "custom" && e.customType === CT.question), q = entries[at]?.data;
@@ -9,7 +10,8 @@ export function openQuestion(entries) {
9
10
  return;
10
11
  if (entries.some(e => {
11
12
  const details = e.message?.details ?? e.details;
12
- return !!details && details.qid === q.qid && details.rev === q.rev && receiptId(e) !== undefined;
13
+ return !!details && receiptId(e) !== undefined && (details.qid === q.qid && details.rev === q.rev ||
14
+ supersededBy(details).some(s => s.qid === q.qid && s.rev === q.rev));
13
15
  }))
14
16
  return;
15
17
  // Only the ask that wrote this question counts: it is still blocked when it has no result, or only the error it ended
@@ -25,3 +27,24 @@ export function openQuestion(entries) {
25
27
  export function hibernation(journal, call) {
26
28
  return journal.entries().findLast(e => e.type === "hibernated" && e.call === call);
27
29
  }
30
+ /** P28: The question qid@rev of a call is still open: its attention item is its latest revision and is unresolved.
31
+ * A call hibernated on one question takes the answer to any of its open questions (an earlier one stays open when a
32
+ * steer ended its ask, or the child asked a reminder while it waited). */
33
+ export function openAsked(entries, call, qid, rev) {
34
+ if (typeof qid !== "string" || typeof rev !== "number")
35
+ return false;
36
+ const id = `q:${call}:${qid}`, items = attentionEntries(entries, id);
37
+ return items.some(e => e.item.rev === rev) && !items.some(e => e.item.rev > rev) &&
38
+ !entries.some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev) && !supersededByBinding(entries, call, qid, rev);
39
+ }
40
+ /** D2: qid@rev of `call` was superseded by a durable binding: an `answer-bound` names it in `superseded`. The binding is
41
+ * the source of truth; the attention resolution `superseded` is derived from it (and may lag it across a crash). */
42
+ export function supersededByBinding(entries, call, qid, rev) {
43
+ return entries.some(e => e.type === "answer-bound" && e.call === call && Array.isArray(e.superseded) &&
44
+ e.superseded.some(s => s?.qid === qid && s?.rev === rev));
45
+ }
46
+ /** P28: The answer bound to hibernation `sleeping`: to its question, or (bound after it) to another open question. */
47
+ export function boundAnswer(entries, sleeping) {
48
+ return entries.find(e => e.type === "answer-bound" && e.call === sleeping.call &&
49
+ (e.qid === sleeping.qid && e.rev === sleeping.rev || e.seq > sleeping.seq));
50
+ }
@@ -25,7 +25,7 @@ import { parseModel, plainModel, resolveModel } from "../../compat/model.js";
25
25
  import { buildCallResult } from "../../compat/result.js";
26
26
  import createEffects from "./effects/index.js";
27
27
  import { continueSession } from "./generation.js";
28
- import { hibernation, openQuestion } from "./hibernate.js";
28
+ import { boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
29
  import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
30
30
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
31
31
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
@@ -122,6 +122,17 @@ export function continueMessage(dangling) {
122
122
  /** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
123
123
  export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
124
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
+ }
125
136
  /** A launch failure the environment causes (the command or its interpreter is missing or not executable): fixing the
126
137
  * environment, or another orchestrator started from a better one, makes the same launch work. */
127
138
  export const environmentSpawnError = (error) => ["ENOENT", "EACCES"].includes(String(error?.code));
@@ -834,9 +845,36 @@ export default function createExecutor(ledgers, options = {}) {
834
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) } });
835
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))
836
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");
837
850
  }
851
+ await resolveSuperseded(t.journal, t.callId);
852
+ if (entries.length)
853
+ await resolveCarried(t.journal, t.callId, digest.questions);
838
854
  });
839
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
+ }
840
878
  /** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
841
879
  const inUse = new Map();
842
880
  async function switched(exec, journal, event) {
@@ -1038,6 +1076,26 @@ export default function createExecutor(ledgers, options = {}) {
1038
1076
  let entries = await readCall(journal, t.callId);
1039
1077
  let dangling = [];
1040
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
+ };
1041
1099
  const sleeping = hibernation(journal, t.callId);
1042
1100
  if (exec && sleeping?.exec === exec) {
1043
1101
  await fence(journal, exec, { park: a });
@@ -1048,18 +1106,31 @@ export default function createExecutor(ledgers, options = {}) {
1048
1106
  break;
1049
1107
  if (reached(totalUsage(journal.entries(), t.callId), t.spec.budget) || reached(totalUsage(journal.entries()), t.workflowBudget))
1050
1108
  return finish(journal, t.callId, exec, makeResult("budget"));
1051
- bound = journal.entries().find(e => e.type === "answer-bound" && e.call === t.callId && e.qid === sleeping.qid && e.rev === sleeping.rev);
1109
+ bound = boundAnswer(journal.entries(), sleeping);
1052
1110
  if (bound)
1053
1111
  break;
1054
1112
  await new Promise(resolve => { const timer = setTimeout(resolve, config.k?.trackerMs ?? 1000); a.wake = () => { clearTimeout(timer); resolve(); }; });
1055
1113
  }
1056
1114
  }
1057
1115
  const pendingAnswer = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
1058
- if (!bound && pendingAnswer && !entries.some(e => receiptId(e) === pendingAnswer.rid2))
1116
+ await settleClosed(pendingAnswer, entries);
1117
+ if (!bound && pendingAnswer && !answerSettled(pendingAnswer, entries))
1059
1118
  bound = pendingAnswer;
1060
1119
  if (exec) {
1061
1120
  await fence(journal, exec, { park: a });
1062
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
+ }
1063
1134
  await recordUsage(t, sessionUsage(entries, t.callId));
1064
1135
  const ev = evidence(entries, exec);
1065
1136
  dangling = ev.dangling;
@@ -1151,7 +1222,10 @@ export default function createExecutor(ledgers, options = {}) {
1151
1222
  });
1152
1223
  // The answer uses its stable forwarded identity across every recovery incarnation.
1153
1224
  const unresolved = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
1154
- const receipt = unresolved && entries.some(e => receiptId(e) === unresolved.rid2);
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);
1155
1229
  const openingRid = t.opening && contentHash([t.opening.rid, "dispatch"]);
1156
1230
  const openingReceived = openingRid && entries.some(e => receiptId(e) === openingRid);
1157
1231
  // The task has one identity: the dispatch of the call's first execution. A later execution continues only once
@@ -1164,7 +1238,7 @@ export default function createExecutor(ledgers, options = {}) {
1164
1238
  else if (!openingRid && !taskReceived)
1165
1239
  await sender.send(t.callId, "task", { message: t.spec.task }, undefined, { rid: taskRid });
1166
1240
  else if (unresolved && !receipt)
1167
- await sender.send(t.callId, "continue", { message: String(unresolved.message) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
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) });
1168
1242
  else if (previous) {
1169
1243
  // After launches that failed for a reason of the environment, no child received their dispatches: the first
1170
1244
  // execution of that run of failures keeps its dispatch (rid and content), so one is pending, not one per retry.
@@ -1239,29 +1313,49 @@ export default function createExecutor(ledgers, options = {}) {
1239
1313
  */
1240
1314
  async function adoptAnswer(journal, call, sleeping) {
1241
1315
  const entries = await readCall(journal, call);
1242
- await serial(async () => {
1243
- const all = journal.entries();
1244
- if (all.some(e => e.type === "answer-bound" && e.call === call && e.qid === sleeping.qid && e.rev === sleeping.rev))
1245
- return;
1246
- const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1247
- const f = all.find(e => {
1248
- if (e.type !== "forward" || e.dest !== call)
1249
- return false;
1250
- const env = e.envelope;
1251
- return env.kind === "answer" && env.cond?.qid === sleeping.qid && env.cond?.rev === sleeping.rev && !receipts.has(String(e.rid2)) &&
1252
- !all.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered"));
1253
- });
1254
- if (!f)
1255
- return;
1256
- const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1257
- const message = String(f.envelope.body?.message ?? "");
1258
- // A new identity: the stale answer may still sit in the child's inbox under the forward's rid2.
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,
1260
- message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${message}` });
1261
- await resolveBoundAnswer(journal, call, sleeping.qid, sleeping.rev);
1262
- await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1263
- await (await outbox).markResolved(String(f.rid2));
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));
1264
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));
1265
1359
  }
1266
1360
  async function replayForward(e) {
1267
1361
  const envelope = e.envelope;
@@ -1346,17 +1440,32 @@ export default function createExecutor(ledgers, options = {}) {
1346
1440
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1347
1441
  if (req.kind === "send" && req.body.kind === "answer") {
1348
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);
1349
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);
1350
1447
  if (priorAnswer)
1351
1448
  return priorAnswer.rid === req.rid && priorAnswer.hash === hash ? { action: "apply" } : { action: "reject", reason: "already-answered" };
1352
- if (sleeping && current(ctx.journal, dest) === sleeping.exec) {
1353
- if (sleeping.qid !== req.cond?.qid || sleeping.rev !== req.cond?.rev)
1354
- return { action: "reject", reason: "stale-rev" };
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;
1355
1461
  const rid2 = forwardRid(req.rid, ctx.widRev, ctx.key, hash);
1356
- const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1462
+ const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === qid && e.item.rev === rev)?.item;
1357
1463
  // `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);
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");
1360
1469
  active.get(dest)?.wake();
1361
1470
  wake();
1362
1471
  return { action: "apply" };
@@ -1540,6 +1649,11 @@ export default function createExecutor(ledgers, options = {}) {
1540
1649
  await retireAttention(journal, call);
1541
1650
  await unknownAttention(journal, call);
1542
1651
  }
1652
+ else {
1653
+ await resolveSuperseded(journal, call);
1654
+ if (session.length)
1655
+ await resolveCarried(journal, call, digestOf(call, session).questions);
1656
+ }
1543
1657
  });
1544
1658
  if (!active.has(call))
1545
1659
  forgetCall(call);
@@ -162,6 +162,9 @@ function snapshotReducer(wid, entries) {
162
162
  hibernating.set(call.callId, call.exec);
163
163
  if (fenced.has(call.exec))
164
164
  call.hibernated = true;
165
+ // D6: hibernated again after a bound answer the session had already closed: it waits for a new answer.
166
+ if (call.phase !== "sealed")
167
+ delete call.answered;
165
168
  }
166
169
  }
167
170
  else if (e.type === "answer-bound") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.37",
3
+ "version": "1.0.38",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",