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
package/dist/cli/restart.js
CHANGED
|
@@ -10,6 +10,7 @@ import { hostname, userInfo } from "node:os";
|
|
|
10
10
|
import { setTimeout as delay } from "node:timers/promises";
|
|
11
11
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
12
12
|
import { journalPath, orchLedger } from "../paths.js";
|
|
13
|
+
import { PS } from "../platform/proctable.js";
|
|
13
14
|
import { JT } from "../types.js";
|
|
14
15
|
import { restartInputError, restartRefusal } from "../orchestrator/restart.js";
|
|
15
16
|
import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
|
|
@@ -26,7 +27,7 @@ export function cliInitiator(env) {
|
|
|
26
27
|
let parent = "";
|
|
27
28
|
try {
|
|
28
29
|
parent = process.platform === "linux" ? readFileSync(`/proc/${process.ppid}/cmdline`, "utf8").replace(/\0/g, " ").trim()
|
|
29
|
-
: process.platform === "darwin" ? execFileSync(
|
|
30
|
+
: process.platform === "darwin" ? execFileSync(PS, ["-o", "command=", "-p", String(process.ppid)], { encoding: "utf8", timeout: 1000, maxBuffer: 64 * 1024 }).trim() : "";
|
|
30
31
|
}
|
|
31
32
|
catch { /* Parent may have exited or /proc may be unavailable. */ }
|
|
32
33
|
return { cli: { user: userInfo().username, host: hostname(), ppid: process.ppid, parent: parent.slice(0, 200) } };
|
package/dist/cli/service.js
CHANGED
|
@@ -7,17 +7,19 @@ import { syncDirectory } from "../kernel/journal.js";
|
|
|
7
7
|
const name = "pi-durable-subagents";
|
|
8
8
|
const quote = (s, exec = true) => `"${s.replace(/[%$\\"\n\r]/g, c => c === "$" ? exec ? "$$" : "$" : ({ "%": "%%", "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r" })[c])}"`;
|
|
9
9
|
const xml = (s) => s.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
10
|
-
/** P1, K1: Render a login and 30-second starter using absolute runtime paths; it runs `start`, never `resume`.
|
|
11
|
-
|
|
10
|
+
/** P1, K1: Render a login and 30-second starter using absolute runtime paths; it runs `start`, never `resume`. `pi`
|
|
11
|
+
* (resolved when installing) becomes its DSA_PI_BIN: a service manager's PATH rarely has pi, and without one `start`
|
|
12
|
+
* refuses to start an orchestrator. */
|
|
13
|
+
export function serviceFiles(home, dsa, entry, platform = process.platform, node = process.execPath, pi) {
|
|
12
14
|
if (platform === "linux") {
|
|
13
15
|
const dir = join(home, ".config/systemd/user");
|
|
14
16
|
return [
|
|
15
|
-
{ path: join(dir, `${name}.service`), content: `[Unit]\nDescription=Durable subagents starter\n\n[Service]\nType=oneshot\n# Keep the detached orchestrator alive after the starter exits.\nKillMode=process\nEnvironment=${quote(`DSA_HOME=${dsa}`, false)}\
|
|
17
|
+
{ path: join(dir, `${name}.service`), content: `[Unit]\nDescription=Durable subagents starter\n\n[Service]\nType=oneshot\n# Keep the detached orchestrator alive after the starter exits.\nKillMode=process\nEnvironment=${quote(`DSA_HOME=${dsa}`, false)}\n${pi ? `Environment=${quote(`DSA_PI_BIN=${pi}`, false)}\n` : ""}ExecStart=${quote(node)} ${quote(entry)} start\n` },
|
|
16
18
|
{ path: join(dir, `${name}.timer`), content: `[Unit]\nDescription=Durable subagents periodic starter\n\n[Timer]\nOnStartupSec=1s\nOnUnitActiveSec=30s\nAccuracySec=1s\nUnit=${name}.service\n\n[Install]\nWantedBy=timers.target\n` },
|
|
17
19
|
];
|
|
18
20
|
}
|
|
19
21
|
if (platform === "darwin")
|
|
20
|
-
return [{ path: join(home, "Library/LaunchAgents", `${name}.plist`), content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${name}</string>\n<key>ProgramArguments</key><array>${[node, entry, "start"].map(s => `<string>${xml(s)}</string>`).join("")}</array>\n<key>EnvironmentVariables</key><dict><key>DSA_HOME</key><string>${xml(dsa)}</string
|
|
22
|
+
return [{ path: join(home, "Library/LaunchAgents", `${name}.plist`), content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${name}</string>\n<key>ProgramArguments</key><array>${[node, entry, "start"].map(s => `<string>${xml(s)}</string>`).join("")}</array>\n<key>EnvironmentVariables</key><dict><key>DSA_HOME</key><string>${xml(dsa)}</string>${pi ? `<key>DSA_PI_BIN</key><string>${xml(pi)}</string>` : ""}</dict>\n<key>RunAtLoad</key><true/>\n<!-- Keep the detached orchestrator alive after the starter exits. -->\n<key>AbandonProcessGroup</key><true/>\n<key>StartInterval</key><integer>30</integer>\n</dict></plist>\n` }];
|
|
21
23
|
throw new Error(`Starter service unavailable on ${platform}`);
|
|
22
24
|
}
|
|
23
25
|
/** P1: Invoke the platform service manager, surfacing the exact failed command. */
|
package/dist/compat/model.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export const thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
2
|
+
/** The model without scheduling fields, as recorded and launched. */
|
|
3
|
+
export const plainModel = (m) => ({ ...(m.provider !== undefined ? { provider: m.provider } : {}), id: m.id, ...(m.thinking ? { thinking: m.thinking } : {}) });
|
|
2
4
|
/** P35: Parse Pi model identifiers, preserving colons that are not thinking suffixes. */
|
|
3
5
|
export function parseModel(value) {
|
|
4
6
|
let id = value.trim();
|
|
@@ -13,17 +15,21 @@ export function parseModel(value) {
|
|
|
13
15
|
throw new Error(`Invalid model: ${value}`);
|
|
14
16
|
return { ...(slash < 0 ? {} : { provider: id.slice(0, slash) }), id: slash < 0 ? id : id.slice(slash + 1), ...(thinking ? { thinking } : {}) };
|
|
15
17
|
}
|
|
16
|
-
/** P11, P35: Resolve a pool into ordered candidates without making an unrecorded selection.
|
|
18
|
+
/** P11, P35: Resolve a pool into ordered candidates without making an unrecorded selection. An object entry's
|
|
19
|
+
* `afterMs` applies to every model it expands to; nested ones keep the larger value. */
|
|
17
20
|
export function resolveModel(value, pools = {}) {
|
|
18
|
-
const expand = (name, seen) => {
|
|
19
|
-
if (!Object.hasOwn(pools, name))
|
|
20
|
-
|
|
21
|
+
const expand = (name, seen, after) => {
|
|
22
|
+
if (!Object.hasOwn(pools, name)) {
|
|
23
|
+
const m = parseModel(name);
|
|
24
|
+
return [after > 0 ? { ...m, afterMs: after } : m];
|
|
25
|
+
}
|
|
21
26
|
if (seen.has(name))
|
|
22
27
|
throw new Error(`Cyclic model pool: ${name}`);
|
|
23
28
|
const entries = pools[name];
|
|
24
29
|
if (!entries.length)
|
|
25
30
|
throw new Error(`Empty model pool: ${name}`);
|
|
26
|
-
return entries.flatMap(entry => expand(entry, new Set([...seen, name]))
|
|
31
|
+
return entries.flatMap(entry => typeof entry === "string" ? expand(entry, new Set([...seen, name]), after)
|
|
32
|
+
: expand(entry.model, new Set([...seen, name]), Math.max(after, entry.afterMs ?? 0)));
|
|
27
33
|
};
|
|
28
|
-
return expand(value.trim(), new Set());
|
|
34
|
+
return expand(value.trim(), new Set(), 0);
|
|
29
35
|
}
|
package/dist/events/derive.js
CHANGED
|
@@ -104,19 +104,28 @@ export function deriveEntry(wid, entries, i, orch, id) {
|
|
|
104
104
|
const parts = callParts(item.call);
|
|
105
105
|
return [{ ...base("asking"), type: "asking", ...onCall(item.call), qid: item.qid, rev: item.rev, question: item.text, to: `${wid}/${parts?.key ?? ""}` }];
|
|
106
106
|
}
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
// `answered` at the binding of an answer when that `answer-bound` is marked `event: true` (written so from 1.0.36 on);
|
|
108
|
+
// otherwise (an older journal) at the question's `attention-resolved{answered}`, as before, so a rebuilt event log
|
|
109
|
+
// keeps the events (and ids) an older version derived.
|
|
110
|
+
if (e.type === "answer-bound" && e.event === true || isEntry(e, JT.attentionResolved)) {
|
|
111
|
+
const bound = e.type === "answer-bound";
|
|
112
|
+
if (!bound && e.resolution !== "answered")
|
|
109
113
|
return [];
|
|
114
|
+
const questionId = bound ? `q:${e.call}:${e.qid}` : e.id;
|
|
110
115
|
let item;
|
|
111
116
|
for (let j = i - 1; j >= 0 && !item; j--) {
|
|
112
117
|
const a = entries[j];
|
|
113
|
-
if (isEntry(a, JT.attention) && a.item.id ===
|
|
118
|
+
if (isEntry(a, JT.attention) && a.item.id === questionId && a.item.rev === e.rev)
|
|
114
119
|
item = a;
|
|
115
120
|
}
|
|
116
121
|
const q = item?.item;
|
|
117
122
|
if (!q || q.kind !== "question" || !q.call || q.qid === undefined)
|
|
118
123
|
return [];
|
|
119
|
-
|
|
124
|
+
// A marked binding reports answered immediately; the resolution after it, or a duplicate resolution, reports nothing.
|
|
125
|
+
if (entries.slice(0, i).some(a => a.type === "answer-bound" && a.event === true && a.call === q.call && a.qid === q.qid && a.rev === q.rev ||
|
|
126
|
+
a.type === JT.attentionResolved && a.id === q.id && a.rev === q.rev && a.resolution === "answered"))
|
|
127
|
+
return [];
|
|
128
|
+
const answer = answerOf(entries, bound ? i + 1 : i, before(orch, e), q.call, q.qid, q.rev);
|
|
120
129
|
return [{ ...base("answered"), type: "answered", ...onCall(q.call), qid: q.qid, rev: q.rev, ...answeredBy(answer.request),
|
|
121
130
|
digest: createHash("sha256").update(answer.text, "utf8").digest("hex"), length: answer.text.length }];
|
|
122
131
|
}
|
package/dist/events/waiting.js
CHANGED
|
@@ -19,13 +19,12 @@
|
|
|
19
19
|
// silent an open `stall:`/`noprogress:` attention item (kind stall; its text names the running command) of
|
|
20
20
|
// the current execution while it works (selected, not fenced): a drained call is not waiting.
|
|
21
21
|
// An asking call is not waiting, a sealed one never. Asking = an open question raised in the call's current execution
|
|
22
|
-
// (the call's latest `exec` before the question's attention entry is its current one), hibernated or not
|
|
23
|
-
// answer
|
|
24
|
-
// the new execution reads it (describe's `state: "asking"` still follows the open item).
|
|
22
|
+
// (the call's latest `exec` before the question's attention entry is its current one), hibernated or not. Binding an
|
|
23
|
+
// answer closes that question immediately and queues the call; its waits count before its next execution starts.
|
|
25
24
|
import { JT } from "../types.js";
|
|
26
25
|
import { EVENT_SEQ_SKIP, WAIT_REASONS } from "./types.js";
|
|
27
26
|
import { emptyLedger, foldLedger, settingsOf } from "../orchestrator/ledger.js";
|
|
28
|
-
import { exhaustedLine, slotLine } from "../orchestrator/snapshot.js";
|
|
27
|
+
import { exhaustedLine, heldIn, slotLine } from "../orchestrator/snapshot.js";
|
|
29
28
|
import { parseModel, resolveModel } from "../compat/model.js";
|
|
30
29
|
import { leaseCalls, leaseState } from "../platform/lease.js";
|
|
31
30
|
import { requestId } from "../requests.js";
|
|
@@ -86,10 +85,19 @@ function applyWait(f, e) {
|
|
|
86
85
|
case JT.done:
|
|
87
86
|
f.done = true;
|
|
88
87
|
break;
|
|
89
|
-
case "resumed":
|
|
88
|
+
case "resumed": {
|
|
90
89
|
if (!e.call)
|
|
91
90
|
f.done = false;
|
|
91
|
+
else {
|
|
92
|
+
const c = f.calls.get(String(e.call));
|
|
93
|
+
if (c && (!e.exec || c.exec === e.exec)) {
|
|
94
|
+
c.selected = true;
|
|
95
|
+
c.fenced = false;
|
|
96
|
+
delete c.answered;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
92
99
|
break;
|
|
100
|
+
}
|
|
93
101
|
case "call":
|
|
94
102
|
case "generation": {
|
|
95
103
|
const key = String(e.key), gen = Number(e.gen) || 1, call = `${f.wid}@${f.rev}/${key}@${gen}`, spec = e.spec;
|
|
@@ -104,6 +112,24 @@ function applyWait(f, e) {
|
|
|
104
112
|
c.queued = e.ts;
|
|
105
113
|
c.selected = false;
|
|
106
114
|
c.fenced = false;
|
|
115
|
+
delete c.answered;
|
|
116
|
+
}
|
|
117
|
+
break;
|
|
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
|
+
}
|
|
126
|
+
case "answer-bound": {
|
|
127
|
+
const c = f.calls.get(String(e.call)), id = `q:${e.call}:${e.qid}`, item = f.items.get(id);
|
|
128
|
+
if (item?.rev === e.rev)
|
|
129
|
+
f.items.delete(id);
|
|
130
|
+
if (c) {
|
|
131
|
+
c.answered = String(e.qid);
|
|
132
|
+
c.queued = e.ts;
|
|
107
133
|
}
|
|
108
134
|
break;
|
|
109
135
|
}
|
|
@@ -112,8 +138,10 @@ function applyWait(f, e) {
|
|
|
112
138
|
const c = ofExec(f, e.exec), model = modelName(e.model);
|
|
113
139
|
if (c && model)
|
|
114
140
|
c.model = model;
|
|
115
|
-
if (c && e.type === "selected")
|
|
141
|
+
if (c && e.type === "selected") {
|
|
116
142
|
c.selected = true;
|
|
143
|
+
delete c.answered;
|
|
144
|
+
}
|
|
117
145
|
break;
|
|
118
146
|
}
|
|
119
147
|
case JT.fenced: {
|
|
@@ -191,7 +219,9 @@ catch {
|
|
|
191
219
|
} };
|
|
192
220
|
/** The call's state as `whyWaiting` reads it. `agentModel` names the model of a pinned agent (for a call naming none). */
|
|
193
221
|
export function waitInput(f, c, env, agentModel) {
|
|
194
|
-
|
|
222
|
+
// An answered asker is queued (live) although its hibernated execution is fenced, unless a drain holds its workflow.
|
|
223
|
+
const answered = c.answered !== undefined && !env.held?.(f.wid);
|
|
224
|
+
const settings = settingsOf(env.ledger, env.config ?? {}), live = c.exec && (!c.fenced || answered), selected = c.selected && c.answered === undefined;
|
|
195
225
|
const attention = [];
|
|
196
226
|
let asking = false;
|
|
197
227
|
for (const [id, item] of f.items)
|
|
@@ -201,7 +231,7 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
201
231
|
asking = true;
|
|
202
232
|
}
|
|
203
233
|
let providers = [];
|
|
204
|
-
if (live &&
|
|
234
|
+
if (live && selected) {
|
|
205
235
|
const p = providerOf(c.model);
|
|
206
236
|
if (p)
|
|
207
237
|
providers = [p];
|
|
@@ -222,8 +252,8 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
222
252
|
providers = [p];
|
|
223
253
|
}
|
|
224
254
|
}
|
|
225
|
-
let full = live && !
|
|
226
|
-
const slot = live && !
|
|
255
|
+
let full = live && !selected && providers.length > 0;
|
|
256
|
+
const slot = live && !selected && providers.length ? providers.map(p => {
|
|
227
257
|
let held = 0;
|
|
228
258
|
for (const h of env.ledger.held.values())
|
|
229
259
|
if (h.pool === p)
|
|
@@ -233,10 +263,10 @@ export function waitInput(f, c, env, agentModel) {
|
|
|
233
263
|
full = false;
|
|
234
264
|
return slotLine(p, held, limit);
|
|
235
265
|
}).join(", ") : undefined;
|
|
236
|
-
const lease = live &&
|
|
266
|
+
const lease = live && selected ? env.leases?.get(c.call) : undefined;
|
|
237
267
|
return {
|
|
238
268
|
asking,
|
|
239
|
-
...(live ? { exec: { id: c.exec, since: c.queued ?? 0, selected: !!
|
|
269
|
+
...(live ? { exec: { id: c.exec, since: c.queued ?? 0, selected: !!selected } } : {}),
|
|
240
270
|
...(providers.length ? { providers } : {}), exhausted: env.ledger.exhausted,
|
|
241
271
|
...(c.writer ? { writerWait: c.writer } : {}), ...(lease ? { lease } : {}),
|
|
242
272
|
...(attention.length ? { attention } : {}), ...(slot ? { slot } : {}), ...(full ? { full } : {}),
|
|
@@ -385,7 +415,7 @@ export function waitCollector(src) {
|
|
|
385
415
|
foldLedger(ledger, orch);
|
|
386
416
|
foldRuns(orch);
|
|
387
417
|
let leases;
|
|
388
|
-
const env = { now, ledger, ...(src.config ? { config: src.config } : {}), get leases() { return leases ??= leaseWaits((src.leases ?? (() => leaseState(src.home)))(), now); } };
|
|
418
|
+
const env = { now, ledger, held: heldIn(orch), ...(src.config ? { config: src.config } : {}), get leases() { return leases ??= leaseWaits((src.leases ?? (() => leaseState(src.home)))(), now); } };
|
|
389
419
|
const current = new Map(), meta = new Map(), present = new Set();
|
|
390
420
|
for (const wf of src.workflows()) {
|
|
391
421
|
present.add(wf.wid);
|
package/dist/kernel/guards.js
CHANGED
|
@@ -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:
|
|
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
|
-
|
|
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) {
|
package/dist/kernel/mailbox.js
CHANGED
|
@@ -136,6 +136,8 @@ export class Outbox {
|
|
|
136
136
|
return structuredClone(req);
|
|
137
137
|
});
|
|
138
138
|
}
|
|
139
|
+
/** The envelope recorded as sent under `rid`, if any. */
|
|
140
|
+
recorded(rid) { const req = this.sent.get(rid); return req && structuredClone(req); }
|
|
139
141
|
/** P38: Re-publish every unresolved envelope under its original identity. */
|
|
140
142
|
republishPending() { return this.serial(async () => { for (const req of this.pending.values())
|
|
141
143
|
await this.publish(req); }); }
|
|
@@ -32,9 +32,24 @@ export function configProblem(raw) {
|
|
|
32
32
|
if (pools !== undefined) {
|
|
33
33
|
if (!record(pools))
|
|
34
34
|
return "pools must map names to model lists";
|
|
35
|
-
for (const [name, list] of Object.entries(pools))
|
|
36
|
-
if (!Array.isArray(list) || !list.length
|
|
37
|
-
return `pools.${name} must be a nonempty list of "provider/id[:thinking]"`;
|
|
35
|
+
for (const [name, list] of Object.entries(pools)) {
|
|
36
|
+
if (!Array.isArray(list) || !list.length)
|
|
37
|
+
return `pools.${name} must be a nonempty list of "provider/id[:thinking]" or { model, afterMs }`;
|
|
38
|
+
for (const [i, m] of list.entries()) {
|
|
39
|
+
if (typeof m === "string" && m)
|
|
40
|
+
continue;
|
|
41
|
+
const at = `pools.${name}[${i}]`;
|
|
42
|
+
if (!record(m))
|
|
43
|
+
return `${at} must be "provider/id[:thinking]" (or a pool name) or { model, afterMs }`;
|
|
44
|
+
if (typeof m.model !== "string" || !m.model)
|
|
45
|
+
return `${at}.model must be "provider/id[:thinking]" or a pool name`;
|
|
46
|
+
if (m.afterMs !== undefined && !(count(m.afterMs) && Number(m.afterMs) > 0))
|
|
47
|
+
return `${at}.afterMs must be a positive number of milliseconds`;
|
|
48
|
+
const extra = Object.keys(m).find(k => k !== "model" && k !== "afterMs");
|
|
49
|
+
if (extra)
|
|
50
|
+
return `${at}.${extra} is not a pool entry key (model, afterMs)`;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
38
53
|
}
|
|
39
54
|
if (providers !== undefined) {
|
|
40
55
|
if (!record(providers))
|
|
@@ -6,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
|
|
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
|
+
}
|