pi-durable-subagents 1.0.33 → 1.0.35
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 +22 -0
- package/README.md +11 -2
- package/dist/agent/main/tool.js +26 -1
- package/dist/agent/main.js +3 -3
- package/dist/cli/requests.js +7 -8
- package/dist/orchestrator/engine.js +77 -20
- package/dist/orchestrator/executor/index.js +5 -2
- package/dist/orchestrator/notes.js +27 -0
- package/dist/ui/screen.js +2 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.35
|
|
4
|
+
|
|
5
|
+
- Generation openings of one workflow are serialized. The reopen of undelivered follow-ups at orchestrator start, the
|
|
6
|
+
one after each seal and a follow-up sent to a sealed call could each find the same key unopened and open its next
|
|
7
|
+
generation twice (seen after a restart while a reopened generation sealed). A follow-up that finds a generation
|
|
8
|
+
opened meanwhile is deferred and then reaches that generation.
|
|
9
|
+
- Releases publish to npm through trusted publishing (OIDC, no token) from the `npm` environment, with provenance.
|
|
10
|
+
Workflows run with read-only permissions by default.
|
|
11
|
+
|
|
12
|
+
## 1.0.34
|
|
13
|
+
|
|
14
|
+
- A follow-up queued into running work is no longer lost when that generation ends before taking it. The next
|
|
15
|
+
generation opens with it, after any pending notes. A follow-up sent to the finished call in the meantime takes the
|
|
16
|
+
queued ones along, in the order sent (`generation.follows`). Restarts open it once. Only a stop drops it, because
|
|
17
|
+
a stop is final; a withdrawn one is gone too. The executor marks such a forward `forward-retired` with reason
|
|
18
|
+
`undelivered-follow-up`.
|
|
19
|
+
- The send reply says where a follow-up went. One that opened a generation has `generation` and `call`, from the CLI
|
|
20
|
+
and now also from the pi tool. One queued into running work has `delivery: "forwarded"` and
|
|
21
|
+
`call: "<wid>/<key>@<gen>"`. A retry of the same request names the generation it went into.
|
|
22
|
+
- Typing in the watch view to a finished subagent sends a follow-up. Before, it sent a steer, which the orchestrator
|
|
23
|
+
refused with `finished:<status> — use kind "follow-up"`.
|
|
24
|
+
|
|
3
25
|
## 1.0.33
|
|
4
26
|
|
|
5
27
|
- A run copies its origin session branch only when it can use it: its script
|
package/README.md
CHANGED
|
@@ -119,7 +119,7 @@ it something. Each verb means one thing, and a refusal says what would work:
|
|
|
119
119
|
| `run` | — | Start one subagent, `tasks` in parallel, a `chain`, or a workflow script. An unknown agent name is refused before anything starts, with the list of agents. |
|
|
120
120
|
| `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. |
|
|
121
121
|
| `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). |
|
|
122
|
-
| `send follow-up` |
|
|
122
|
+
| `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. |
|
|
123
123
|
| `send answer` | an open question | Answers it once. |
|
|
124
124
|
| `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. |
|
|
125
125
|
| `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. |
|
|
@@ -142,6 +142,14 @@ requests. A notify accepted for a running call that seals before it gets the
|
|
|
142
142
|
note becomes a pending note too. `status` shows them on the call
|
|
143
143
|
(`b@1 ok "..." · 2 notes pending`; JSON `notesPending`).
|
|
144
144
|
|
|
145
|
+
A follow-up queued into running work is not lost when that generation ends
|
|
146
|
+
before taking it: the next generation opens with it, after any pending notes,
|
|
147
|
+
as if it had been sent just after the end. A follow-up sent to the finished call
|
|
148
|
+
in the meantime opens that generation and takes the queued ones along (in the
|
|
149
|
+
order sent, before its own message). A retry of the same request then names the
|
|
150
|
+
generation it went into. Only a stop drops it, because a stop is final; a
|
|
151
|
+
withdrawn follow-up is gone too.
|
|
152
|
+
|
|
145
153
|
`to` may list several calls for `steer`, `notify`, `follow-up` and `model`
|
|
146
154
|
(`answer` takes one). Each call gets its own request and is decided on its
|
|
147
155
|
own: an unknown or refused target does not affect the others, and the reply
|
|
@@ -229,7 +237,8 @@ subagents of one workflow. Scrolling up pauses following; pi's
|
|
|
229
237
|
`↓ Jump to latest message · End` badge (or `End`, or a click) brings you back.
|
|
230
238
|
|
|
231
239
|
Typing steers the subagent you are watching (`Alt+Enter` queues a
|
|
232
|
-
follow-up instead),
|
|
240
|
+
follow-up instead), answers it if it is asking you something, and continues
|
|
241
|
+
it (a follow-up) if it has finished. `/model`
|
|
233
242
|
switches its model. Steers, answers and model switches are journaled as
|
|
234
243
|
coming from you, and the main agent sees a note at its next turn.
|
|
235
244
|
|
package/dist/agent/main/tool.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { restartInputError } from "../../orchestrator/restart.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
2
3
|
import { resolve } from "node:path";
|
|
4
|
+
import { readJournalSnapshot } from "../../kernel/journal.js";
|
|
5
|
+
import { generationRids } from "../../orchestrator/notes.js";
|
|
6
|
+
import { journalPath } from "../../paths.js";
|
|
3
7
|
import { validateCallSpec } from "../../compat/spec.js";
|
|
4
8
|
import { compileFanout } from "../../compat/fanout.js";
|
|
5
9
|
import { checkLabels } from "../../events/labels.js";
|
|
@@ -43,12 +47,33 @@ export function sendReceipt(ledger, rid) {
|
|
|
43
47
|
return { delivery: note.delivery, note: DELIVERY_NOTE[note.delivery] ?? note.delivery };
|
|
44
48
|
return { model: String(note.model), effect: String(note.effect), ...(note.pool ? { pool: String(note.pool) } : {}) };
|
|
45
49
|
}
|
|
50
|
+
/** Where an applied follow-up went. It opened a generation: `generation` and `call` (`<wid>/<key>`), from the workflow
|
|
51
|
+
* journal, under the request's rid or, for one forwarded into running work that sealed first, in `follows` of the
|
|
52
|
+
* generation that took it along. It was queued into unfinished work: `delivery: "forwarded"` and `call`
|
|
53
|
+
* (`<wid>/<key>@<gen>`, the running generation). If that generation ends before taking it, the message opens the next
|
|
54
|
+
* generation (unless a stop ended it), and a retry of the same request then names that generation. */
|
|
55
|
+
export function followUpReceipt(home, rid, body) {
|
|
56
|
+
const send = body;
|
|
57
|
+
if (send?.kind !== "follow-up" || typeof send.to !== "string")
|
|
58
|
+
return {};
|
|
59
|
+
const wid = send.to.split("/")[0].split("@")[0], path = journalPath(home, wid);
|
|
60
|
+
if (!existsSync(path))
|
|
61
|
+
return {};
|
|
62
|
+
const log = readJournalSnapshot(path), opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
|
|
63
|
+
if (opened)
|
|
64
|
+
return { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` };
|
|
65
|
+
const queued = log.find(e => e.type === "forward" && e.rid === rid);
|
|
66
|
+
if (!queued)
|
|
67
|
+
return {};
|
|
68
|
+
const into = `${wid}/${String(queued.dest).slice(String(queued.dest).indexOf("/") + 1)}`;
|
|
69
|
+
return { delivery: "forwarded", call: into, note: `queued into running ${into}; if it ends before taking it, it opens the next generation` };
|
|
70
|
+
}
|
|
46
71
|
/** The internal argument through which a send to several calls passes its `batch` (not a tool parameter). */
|
|
47
72
|
export const BATCH = Symbol("batch");
|
|
48
73
|
/** One line of a reply per target: applied (with how a notify went), rejected with its reason, or not decided yet. */
|
|
49
74
|
export function outcomeLine(r) {
|
|
50
75
|
if (r.applied === true)
|
|
51
|
-
return `applied${r.delivery ? ` (${String(r.delivery)}: ${String(r.note)})` : r.effect ? ` (model ${String(r.model)}, ${String(r.effect)})` : ""}`;
|
|
76
|
+
return `applied${r.generation !== undefined ? ` (follow-up generation ${String(r.generation)} of ${String(r.call)})` : ""}${r.delivery ? ` (${String(r.delivery)}: ${String(r.note)})` : r.effect ? ` (model ${String(r.model)}, ${String(r.effect)})` : ""}`;
|
|
52
77
|
if (r.applied === false)
|
|
53
78
|
return `rejected ${String(r.reason)}`;
|
|
54
79
|
if (r.submitted)
|
package/dist/agent/main.js
CHANGED
|
@@ -13,7 +13,7 @@ import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.j
|
|
|
13
13
|
import { CT, JT } from "../types.js";
|
|
14
14
|
import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
|
|
15
15
|
import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
16
|
-
import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
16
|
+
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
17
17
|
import { parameters } from "./main/schema.js";
|
|
18
18
|
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
|
|
19
19
|
import { discoverAgents } from "../compat/agents.js";
|
|
@@ -413,7 +413,7 @@ export function registerMain(pi, ui) {
|
|
|
413
413
|
if (decision.type === "rejected")
|
|
414
414
|
return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
|
|
415
415
|
if (sent.kind !== "run") {
|
|
416
|
-
return { applied: true, rid: sent.rid, ...sendReceipt(ledger(), sent.rid) };
|
|
416
|
+
return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt(ledger(), sent.rid) };
|
|
417
417
|
}
|
|
418
418
|
}
|
|
419
419
|
if (performance.now() >= deadline || signal?.aborted)
|
|
@@ -435,7 +435,7 @@ export function registerMain(pi, ui) {
|
|
|
435
435
|
"Durable asynchronous subagents; run returns {wid} when created (or {submitted:{rid}} while pending). A finished workflow (its notice carries every agent's result) or a question wakes you, so after starting work end your turn: never poll with sleep or repeated status. Crash recovery resumes sessions, not external side effects. Background helper processes (orchestrator, evaluator) exit by themselves about 10 s after all work ends: never kill processes or delete files to 'clean up'. When the user quits pi, this session's running workflows pause (nothing is spent); resume continues them.",
|
|
436
436
|
"run (action optional for exactly one launch form): agent+task; tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
|
|
437
437
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
438
|
-
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 or queues after a running turn; follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
438
|
+
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
439
439
|
"stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
|
440
440
|
"Control replies are {applied:true,rid} or {applied:false,reason,rid} when decided; otherwise {submitted:{rid}} after 10s.",
|
|
441
441
|
...(agents ? [`Available agents: ${agents}.`] : []),
|
package/dist/cli/requests.js
CHANGED
|
@@ -10,7 +10,7 @@ import { journalPath, orchLedger, pinnedDir } from "../paths.js";
|
|
|
10
10
|
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, SESSION_ID, specDigest } from "../requests.js";
|
|
11
11
|
import { NOTIFY_SINCE, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
12
12
|
import { leaseCalls, leaseState } from "../platform/lease.js";
|
|
13
|
-
import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
13
|
+
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
14
14
|
import { discoverAgents } from "../compat/agents.js";
|
|
15
15
|
import { JT } from "../types.js";
|
|
16
16
|
import { startOrchestrator, submitIdentified } from "./control.js";
|
|
@@ -501,15 +501,14 @@ function decided(ctx, id, done, json) {
|
|
|
501
501
|
ctx.write(json ? JSON.stringify({ request: id, applied: false, reason: done.outcome.reason, spec_digest: done.sent.digest }) : `${id}: rejected ${done.outcome.reason}`);
|
|
502
502
|
return EXIT.rejected;
|
|
503
503
|
}
|
|
504
|
-
// A follow-up
|
|
505
|
-
const
|
|
506
|
-
const
|
|
507
|
-
const opened = done.sent.request.kind === "send" && wid && existsSync(journalPath(ctx.home, wid))
|
|
508
|
-
? readJournalSnapshot(journalPath(ctx.home, wid)).find(e => e.type === "generation" && e.rid === done.sent.request.rid) : undefined;
|
|
504
|
+
// A follow-up opened a generation, or was queued into unfinished work (followUpReceipt).
|
|
505
|
+
const followed = done.sent.request.kind === "send" ? followUpReceipt(ctx.home, done.sent.request.rid, done.sent.request.body) : {};
|
|
506
|
+
const opened = followed.generation !== undefined ? followed : undefined;
|
|
509
507
|
// A notify says how it went (steered, held-until-answer or noted); a model send which model and when it applies.
|
|
510
508
|
const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home), done.sent.request.rid) : {};
|
|
511
|
-
const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
|
|
512
|
-
|
|
509
|
+
const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
|
|
510
|
+
: followed.delivery ? { delivery: followed.delivery, call: followed.call, note: followed.note } : {};
|
|
511
|
+
const reply = { request: id, applied: true, ...(opened ? { generation: opened.generation, call: opened.call } : {}), ...receipt, spec_digest: done.sent.digest };
|
|
513
512
|
ctx.write(json ? JSON.stringify(reply) : `${id}: applied${opened ? ` (follow-up generation ${reply.generation} of ${reply.call})` : ""}${receipt.delivery ? ` (${receipt.delivery}: ${receipt.note})` : ""}`);
|
|
514
513
|
return EXIT.ok;
|
|
515
514
|
}
|
|
@@ -33,7 +33,7 @@ import { WaitTracker, waitCollector, startWaiting } from "../events/waiting.js";
|
|
|
33
33
|
import { readPage } from "../events/log.js";
|
|
34
34
|
import { eventsLog } from "../paths.js";
|
|
35
35
|
import { parseModel } from "../compat/model.js";
|
|
36
|
-
import { PENDING_NOTE, pendingNotes,
|
|
36
|
+
import { PENDING_NOTE, generationRids, openingMessage, pendingFollowUps, pendingNotes, unsettledForward, unsettledNotify } from "./notes.js";
|
|
37
37
|
import { journalAppends } from "../kernel/journal.js";
|
|
38
38
|
import { STATS_EVERY_MS, readBytes, writeStats } from "./stats.js";
|
|
39
39
|
const tail = (text, n) => text.length > n ? `…${text.slice(-(n - 1))}` : text;
|
|
@@ -99,6 +99,10 @@ export function finishedText(wid, entries, call) {
|
|
|
99
99
|
return `${prefix}${lines.join('')}${footer}`;
|
|
100
100
|
}
|
|
101
101
|
/** A1, P2, P10, P11: Serialize decisions while executions run independently. */
|
|
102
|
+
/** A key's latest call in the current revision: its first call or its newest generation. */
|
|
103
|
+
function latestCall(wf, key) {
|
|
104
|
+
return revisionEntries(wf).findLast(e => (e.type === 'call' || e.type === 'generation') && String(e.key) === key);
|
|
105
|
+
}
|
|
102
106
|
export class Engine {
|
|
103
107
|
store;
|
|
104
108
|
/** The cross-workflow event log's writer (derives milestones from the journals; waiting/moving emits through it). */
|
|
@@ -114,6 +118,8 @@ export class Engine {
|
|
|
114
118
|
closed = false;
|
|
115
119
|
restarting = false;
|
|
116
120
|
generations = new Set();
|
|
121
|
+
/** The tail of each workflow's generation openings, see serialOpen. */
|
|
122
|
+
opening = new Map();
|
|
117
123
|
// wid -> executor runs whose follow-up has not run yet (prune never closes a journal they may still append to).
|
|
118
124
|
running = new Map();
|
|
119
125
|
/** Drain: held by a drain that applies to it (all, its session's origin, or itself) and recorded after its creation. */
|
|
@@ -229,6 +235,7 @@ export class Engine {
|
|
|
229
235
|
await this.attention(wf);
|
|
230
236
|
for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
|
|
231
237
|
this.dispatchGeneration(wf, entry);
|
|
238
|
+
await this.reopenForwarded(wf);
|
|
232
239
|
}
|
|
233
240
|
await this.intake();
|
|
234
241
|
for (const wf of this.store.workflows.values())
|
|
@@ -442,7 +449,7 @@ export class Engine {
|
|
|
442
449
|
await this.startWorkflow(wf);
|
|
443
450
|
}
|
|
444
451
|
else if (req.kind === 'send') {
|
|
445
|
-
const existing = [...this.store.workflows.values()].flatMap(wf => wf.journal.entries().filter(e => e.type === 'generation' && e.
|
|
452
|
+
const existing = [...this.store.workflows.values()].flatMap(wf => wf.journal.entries().filter(e => e.type === 'generation' && generationRids(e).includes(req.rid)).map(entry => ({ wf, entry })))[0];
|
|
446
453
|
if (existing) {
|
|
447
454
|
this.dispatchGeneration(existing.wf, existing.entry);
|
|
448
455
|
return { action: 'apply' };
|
|
@@ -468,24 +475,21 @@ export class Engine {
|
|
|
468
475
|
return { action: 'reject', reason: 'unknown-model' };
|
|
469
476
|
}
|
|
470
477
|
}
|
|
471
|
-
if (seal && send.kind === 'follow-up')
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
await this.
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
this.dispatchGeneration(wf, opened);
|
|
487
|
-
return { action: 'apply' };
|
|
488
|
-
}
|
|
478
|
+
if (seal && send.kind === 'follow-up')
|
|
479
|
+
return this.serialOpen(wf.wid, async () => {
|
|
480
|
+
// A generation opened meanwhile (undelivered follow-ups after a seal) is the call this follow-up now reaches.
|
|
481
|
+
if (latestCall(wf, String(entry.key))?.gen !== entry.gen)
|
|
482
|
+
return { action: 'defer' };
|
|
483
|
+
// Pending notes and undelivered follow-ups ride on the opening message, recorded in the same entry (consumed
|
|
484
|
+
// exactly once). A notify or follow-up whose fate the seal has not settled yet may still become one: wait for it.
|
|
485
|
+
if (unsettledForward(revisionEntries(wf), from))
|
|
486
|
+
return { action: 'defer' };
|
|
487
|
+
if (send.model !== undefined)
|
|
488
|
+
await this.note(req.rid, send.model, 'next-generation');
|
|
489
|
+
const opened = await this.openGeneration(wf, entry, from, { rid: req.rid, message: send.message ?? '', ...(send.model !== undefined ? { model: send.model } : {}) });
|
|
490
|
+
this.dispatchGeneration(wf, opened);
|
|
491
|
+
return { action: 'apply' };
|
|
492
|
+
});
|
|
489
493
|
// A follow-up naming a model, queued on unfinished work: the executor records its model request with the message.
|
|
490
494
|
return this.executor.forward(req, this.context(wf, entry));
|
|
491
495
|
}
|
|
@@ -684,6 +688,56 @@ export class Engine {
|
|
|
684
688
|
console.error(`durable-subagents: removal of pruned workflow ${wf.wid} failed, retrying at next start: ${String(error)}`);
|
|
685
689
|
}
|
|
686
690
|
}
|
|
691
|
+
/** Open the next generation of `entry`'s key (its latest call), continuing sealed call `from`. The opening message
|
|
692
|
+
* carries the key's pending notes, then its undelivered follow-ups, then `own` (a follow-up sent to the sealed call;
|
|
693
|
+
* without one the undelivered follow-ups open it by themselves). The latest model named replaces the session's. */
|
|
694
|
+
async openGeneration(wf, entry, from, own) {
|
|
695
|
+
const log = revisionEntries(wf), key = String(entry.key), notes = pendingNotes(log, key), carried = pendingFollowUps(log, key);
|
|
696
|
+
const asked = (rid) => this.ledgers.orch.entries().findLast(e => e.type === 'request' && e.request?.rid === rid)?.request?.body?.model;
|
|
697
|
+
const model = [...carried.map(c => asked(c.rid)), own?.model].filter((m) => typeof m === 'string').at(-1);
|
|
698
|
+
const pools = this.ledgers.config.pools, pool = model !== undefined && pools && Object.hasOwn(pools, model);
|
|
699
|
+
const rid = own?.rid ?? carried[0].rid, follows = carried.map(c => c.rid).filter(r => r !== rid);
|
|
700
|
+
const gen = Math.max(0, ...wf.journal.entries().filter(e => ['call', 'generation'].includes(e.type) && e.key === entry.key).map(e => Number(e.gen))) + 1;
|
|
701
|
+
// A follow-up's model replaces the continued session's for this generation and those continuing it.
|
|
702
|
+
const spec = model !== undefined ? { ...entry.spec, model } : entry.spec;
|
|
703
|
+
const message = openingMessage(notes.map(n => String(n.message)), [...carried.map(c => c.message), own?.message ?? '']);
|
|
704
|
+
return wf.journal.append('generation', { rid, key: entry.key, gen, from, spec, revision: wf.revision, opening: { rid, kind: 'follow-up', message },
|
|
705
|
+
...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(follows.length ? { follows } : {}), ...(model !== undefined && !pool ? { model } : {}) });
|
|
706
|
+
}
|
|
707
|
+
/** Follow-ups forwarded into running work whose call sealed before taking them (`undelivered-follow-up`) open the
|
|
708
|
+
* key's next generation, as a follow-up sent after the seal would: once its latest generation has sealed, unless a
|
|
709
|
+
* later follow-up took them along. Idempotent; run after every seal and at start. */
|
|
710
|
+
reopenForwarded(wf) { return this.serialOpen(wf.wid, () => this.reopenForwardedNow(wf)); }
|
|
711
|
+
async reopenForwardedNow(wf) {
|
|
712
|
+
const log = revisionEntries(wf);
|
|
713
|
+
if (!log.some(e => e.type === 'forward-retired' && e.reason === 'undelivered-follow-up'))
|
|
714
|
+
return;
|
|
715
|
+
for (const key of new Set(log.filter(e => e.type === 'call' || e.type === 'generation').map(e => String(e.key)))) {
|
|
716
|
+
if (!pendingFollowUps(revisionEntries(wf), key).length)
|
|
717
|
+
continue;
|
|
718
|
+
const latest = latestCall(wf, key);
|
|
719
|
+
const from = `${wf.wid}@${wf.revision}/${key}@${latest.gen}`, entries = wf.journal.entries();
|
|
720
|
+
if (!entries.some(e => e.type === JT.sealed && e.call === from) || entries.some(e => e.type === 'retired' && e.call === from))
|
|
721
|
+
continue;
|
|
722
|
+
if (unsettledForward(revisionEntries(wf), from))
|
|
723
|
+
continue;
|
|
724
|
+
this.dispatchGeneration(wf, await this.openGeneration(wf, latest, from));
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/** One generation opening at a time per workflow, so the check that a key's latest call is sealed and unopened and
|
|
728
|
+
* the `generation` it appends are one step. Otherwise the reopen at start, the one after a seal and a follow-up's
|
|
729
|
+
* each see the key unopened and open it twice. */
|
|
730
|
+
async serialOpen(wid, fn) {
|
|
731
|
+
const run = (this.opening.get(wid) ?? Promise.resolve()).then(fn), tail = run.then(() => { }, () => { });
|
|
732
|
+
this.opening.set(wid, tail);
|
|
733
|
+
try {
|
|
734
|
+
return await run;
|
|
735
|
+
}
|
|
736
|
+
finally {
|
|
737
|
+
if (this.opening.get(wid) === tail)
|
|
738
|
+
this.opening.delete(wid);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
687
741
|
dispatchGeneration(wf, entry) {
|
|
688
742
|
const ticket = this.ticket({ wf }, entry), id = ticket.callId;
|
|
689
743
|
if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
|
|
@@ -693,6 +747,7 @@ export class Engine {
|
|
|
693
747
|
void this.executor.run(ticket).then(() => this.background(async () => {
|
|
694
748
|
if (!wf.journal.entries().some(e => e.type === JT.sealed && e.call === id))
|
|
695
749
|
throw new Error(`Generation returned without seal: ${id}`);
|
|
750
|
+
await this.reopenForwarded(wf);
|
|
696
751
|
if (!wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`))
|
|
697
752
|
await wf.journal.append(JT.attention, { item: { id: `finished:${id}`, rev: 1, kind: 'finished', wid: wf.wid, call: id, text: finishedText(wf.wid, wf.journal.entries(), id), origin: wf.origin } });
|
|
698
753
|
this.generations.delete(id);
|
|
@@ -783,6 +838,8 @@ export class Engine {
|
|
|
783
838
|
const release = this.hold(st.wf.wid);
|
|
784
839
|
void this.executor.run(this.ticket(st, entry)).then(() => this.background(async () => {
|
|
785
840
|
try {
|
|
841
|
+
if (this.states.get(st.wf.wid) === st)
|
|
842
|
+
await this.reopenForwarded(st.wf);
|
|
786
843
|
if (this.states.get(st.wf.wid) !== st || this.terminal(st.wf))
|
|
787
844
|
return;
|
|
788
845
|
const result = this.sealed(st, entry);
|
|
@@ -35,7 +35,7 @@ import { reached, sessionUsage, totalUsage } from "./usage.js";
|
|
|
35
35
|
import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
|
|
36
36
|
import { gateRetired } from "./effects/gate.js";
|
|
37
37
|
import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
|
|
38
|
-
import { PENDING_NOTE } from "../notes.js";
|
|
38
|
+
import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
|
|
39
39
|
const MEM_RECORD_MS = 30000;
|
|
40
40
|
/** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
|
|
41
41
|
const MEM_WARMUP_MS = 30000;
|
|
@@ -352,7 +352,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
352
352
|
const withdrawn = all.some(r => r.type === "forward" && r.dest === call && r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
|
|
353
353
|
if (envelope.kind === "notify" && !withdrawn && !all.some(r => r.type === PENDING_NOTE && r.rid === e.rid))
|
|
354
354
|
await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
|
|
355
|
-
|
|
355
|
+
// A follow-up the call never took is not lost either: the orchestrator opens the next generation with it (or a
|
|
356
|
+
// later follow-up takes it along). A stop is final and drops it; a withdrawn one is gone.
|
|
357
|
+
const reopen = envelope.kind === "follow-up" && !withdrawn && sealed(journal, call)?.status !== "stopped";
|
|
358
|
+
await journal.append("forward-retired", { rid: e.rid, rid2: e.rid2, reason: reopen ? UNDELIVERED_FOLLOW_UP : "retired-without-child-receipt" });
|
|
356
359
|
}
|
|
357
360
|
await (await outbox).markResolved(String(e.rid2));
|
|
358
361
|
}
|
|
@@ -11,6 +11,33 @@ export function unsettledNotify(log, call) {
|
|
|
11
11
|
return log.some(e => e.type === "forward" && e.dest === call && e.envelope?.kind === "notify" &&
|
|
12
12
|
!log.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered")));
|
|
13
13
|
}
|
|
14
|
+
/** The `forward-retired` reason of a follow-up forwarded into running work that sealed before taking it (not stopped,
|
|
15
|
+
* not withdrawn): it is pending, like a note, and opens the next generation (by itself, or with a later follow-up). */
|
|
16
|
+
export const UNDELIVERED_FOLLOW_UP = "undelivered-follow-up";
|
|
17
|
+
/** The request rids a generation entry carries: the follow-up that opened it and the undelivered ones it took along. */
|
|
18
|
+
export function generationRids(e) {
|
|
19
|
+
return [String(e.rid), ...(Array.isArray(e.follows) ? e.follows.map(String) : [])];
|
|
20
|
+
}
|
|
21
|
+
/** The undelivered follow-ups of a call key in one revision's entries, in the order they were forwarded: each one's
|
|
22
|
+
* request rid and message, while no generation names its rid. */
|
|
23
|
+
export function pendingFollowUps(log, key) {
|
|
24
|
+
const taken = new Set(log.filter(e => e.type === "generation").flatMap(generationRids));
|
|
25
|
+
const retired = new Set(log.filter(e => e.type === "forward-retired" && e.reason === UNDELIVERED_FOLLOW_UP).map(e => String(e.rid2)));
|
|
26
|
+
const keyOf = (call) => call.slice(call.indexOf("/") + 1, call.lastIndexOf("@"));
|
|
27
|
+
return log.filter(e => e.type === "forward" && retired.has(String(e.rid2)) && keyOf(String(e.dest)) === key && !taken.has(String(e.rid)))
|
|
28
|
+
.map(e => ({ rid: String(e.rid), from: String(e.dest), message: String((e.envelope?.body?.message) ?? "") }));
|
|
29
|
+
}
|
|
30
|
+
/** A notify or follow-up forwarded to `call` whose fate is not known yet: at its seal the executor may still turn it into
|
|
31
|
+
* a pending note or an undelivered follow-up, so a follow-up waits for that first. */
|
|
32
|
+
export function unsettledForward(log, call) {
|
|
33
|
+
return log.some(e => e.type === "forward" && e.dest === call && ["notify", "follow-up"].includes(String(e.envelope?.kind)) &&
|
|
34
|
+
!log.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered")));
|
|
35
|
+
}
|
|
36
|
+
/** The opening message of a follow-up that also takes undelivered follow-ups along: notes first, then each message in
|
|
37
|
+
* the order sent, separated by a blank line. */
|
|
38
|
+
export function openingMessage(notes, messages) {
|
|
39
|
+
return withNotes(notes, messages.filter(m => m !== "").join("\n\n"));
|
|
40
|
+
}
|
|
14
41
|
/** The opening message of a follow-up that carries pending notes: every note in order, then the follow-up's own message. */
|
|
15
42
|
export function withNotes(notes, message) {
|
|
16
43
|
if (!notes.length)
|
package/dist/ui/screen.js
CHANGED
|
@@ -258,7 +258,8 @@ export class SubagentScreen {
|
|
|
258
258
|
return;
|
|
259
259
|
}
|
|
260
260
|
const q = w.attention.find(a => a.kind === "question" && a.call === c.callId);
|
|
261
|
-
|
|
261
|
+
// A finished call cannot be steered: typing to it continues it (a follow-up), as the note says.
|
|
262
|
+
const kind = followUp || c.phase === "sealed" ? "follow-up" : q ? "answer" : "steer";
|
|
262
263
|
void this.send({ action: "send", to: c.callId, kind, message, ...(kind === "answer" ? { qid: q.qid, rev: q.rev } : {}) }, `${kind === "answer" ? "replied to" : followUp ? "queued follow-up for" : c.phase === "sealed" ? "continued" : "steered"} ${callName(w, c)}: ${JSON.stringify(message)}`);
|
|
263
264
|
}
|
|
264
265
|
handleInput(key) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-durable-subagents",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.35",
|
|
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",
|