pi-durable-subagents 1.1.0 → 1.2.0
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 +50 -0
- package/README.md +132 -6
- package/dist/agent/child/schema.js +53 -0
- package/dist/agent/child.js +23 -6
- package/dist/agent/main/snapshots.js +2 -2
- package/dist/agent/main.js +2 -2
- package/dist/cli/main.js +3 -2
- package/dist/cli/requests.js +3 -3
- package/dist/orchestrator/config.js +4 -2
- package/dist/orchestrator/engine.js +47 -7
- package/dist/orchestrator/executor/digest.js +3 -3
- package/dist/orchestrator/executor/index.js +8 -6
- package/dist/orchestrator/model-choice.js +17 -0
- package/dist/orchestrator/snapshot.js +44 -4
- package/dist/types.js +12 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,55 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.2.0
|
|
4
|
+
|
|
5
|
+
- Structured asks: the child `ask` tool keeps required `question: string` and adds optional `decision_needed` (one
|
|
6
|
+
sentence naming the decision), `options: [{label, scope?, cost?, risk?, preferred?}]`, `facts: string[]`,
|
|
7
|
+
`tried: string[]` and `classification_candidates: [{label, evidence?: string[], unproven?: string[]}]`.
|
|
8
|
+
Option scope/cost/risk and candidate evidence/unproven distinguish costs, evidence and explanations not yet proved.
|
|
9
|
+
Parent-facing asking notices, agent-tool status and CLI status/describe text show the decision first, numbered
|
|
10
|
+
option labels second (preferred marked), then the original question. Plain questions display as before.
|
|
11
|
+
- Ask limits and refusal: any supplied structured field requires a nonblank `decision_needed`. Structured asks limit
|
|
12
|
+
every string, including `question`, to 2000 characters; options and classification candidates to 9 items each;
|
|
13
|
+
facts and tried to 20 each. At most one option may be preferred. Nested evidence/unproven arrays have no additional
|
|
14
|
+
item-count limit. Empty arrays are allowed; text is preserved, not trimmed or coerced; omitted fields stay absent.
|
|
15
|
+
Wrong types, exceeded limits, multiple preferred options or a missing decision produce `ask refused:` before any
|
|
16
|
+
question entry, attention item, waiter or revision is created, and the child can correct it and ask again. The
|
|
17
|
+
missing-decision text is `ask refused: decision_needed is required (one sentence naming the decision you need), then options`.
|
|
18
|
+
Under default settings, question-only asks keep their 1.1.0 behaviour, including no new question-length limit.
|
|
19
|
+
- Ask configuration: `askRequireDecision` is a boolean `config.json` key, default false, validated and included in the
|
|
20
|
+
orchestrator config hash. True requires a decision on every ask and applies structured-ask string limits. The
|
|
21
|
+
setting reaches a child when its execution starts: a live config change affects executions started afterwards,
|
|
22
|
+
not a child already running; a resumed execution receives the current setting.
|
|
23
|
+
- Ask storage and JSON: supplied fields survive session entries, digests, attention and orchestrator restarts.
|
|
24
|
+
`describe --key <request> --json`, `describe <wid> --json` and the program `describe()` API add them to each
|
|
25
|
+
`questions[]` item alongside `qid`, `rev`, `to`, `call` and `text`; text stays the original question. Full status
|
|
26
|
+
JSON attention retains metadata; compact status clips the decision like question text. Agent-tool brief `asking[]`
|
|
27
|
+
adds clipped `decision_needed` and `rev` only for structured entries, including mixed lists. Plain-question JSON
|
|
28
|
+
keeps its previous shape and serialization, without defaults. The qid formula, answer, steer and hibernation
|
|
29
|
+
semantics are unchanged; machine JSON stays separate from rendered text.
|
|
30
|
+
- Sticky model switches: an accepted manual `send kind:model` becomes the logical call's choice for later follow-up
|
|
31
|
+
generations (g+1, g+2, …), including calls initially launched from a pool. Another accepted manual switch or a
|
|
32
|
+
follow-up specifying `model` replaces it. Refused, withdrawn or replaced requests never become choices; automatic
|
|
33
|
+
failover never becomes one. A concrete `provider/id[:thinking]` remains concrete; a pool choice remains a pool,
|
|
34
|
+
resolved again at each generation launch using current configuration and existing availability, slot, skip and
|
|
35
|
+
failover rules. Concrete choices keep the 1.1 explicit-model path: an exhausted provider waits for availability,
|
|
36
|
+
probing and slots, with no fallback pool invented. Live-switch admission and reservations are unchanged.
|
|
37
|
+
- Sealed model switches: `send kind:model` records a sealed call's choice with `effect: "next-generation"`, creating
|
|
38
|
+
no generation, starting no child and reserving no slot. A follow-up continues it. Status keeps the last actual
|
|
39
|
+
`model` and shows the unused choice as `switching`; opening the next generation consumes the indicator, not the
|
|
40
|
+
persistent choice. The existing sealed follow-up acceptance path applies, including done and stopped workflows;
|
|
41
|
+
address, stale-revision, command-call and pin-validation refusals remain. A model send alone does not resume work.
|
|
42
|
+
- Model durability and upgrade: choices persist before the applied reply and survive restarts; retried request ids
|
|
43
|
+
return their first outcome. New live manual `forward` records have optional `choice` retaining the original model
|
|
44
|
+
or pool; sealed choices use `model-choice {rid, call, model}`; new `generation` records carry optional `choice` and
|
|
45
|
+
write it into `spec.model` (concrete choices also use the existing generation model override). Call/revision scope
|
|
46
|
+
prevents leakage. Existing forwards without `choice` retain their 1.1 execution-only semantics; old journals,
|
|
47
|
+
request digests and decisions keep their meaning. Restart the orchestrator on 1.2.0 and start a new pi session to
|
|
48
|
+
load the new extension before relying on the new behaviour; an already running child's ask setting is unchanged.
|
|
49
|
+
- Test-tail repair: the three live-session helpers in `test/pi/executor/executor.test.ts` parse only complete JSONL
|
|
50
|
+
lines (`revisions()` in reaskedBeforeFence, `rows()` in P28, `receipts()` in P7). An incomplete final write waits for
|
|
51
|
+
its newline; a malformed complete line still throws. Settled-session assertions are unchanged.
|
|
52
|
+
|
|
3
53
|
## 1.1.0
|
|
4
54
|
|
|
5
55
|
- Caller wakes: a subagent can run `run --request <id> --wake caller -- <program> [args…]`, then end its turn. The
|
package/README.md
CHANGED
|
@@ -126,7 +126,7 @@ it something. Each verb means one thing, and a refusal says what would work:
|
|
|
126
126
|
| `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). |
|
|
127
127
|
| `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. |
|
|
128
128
|
| `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. |
|
|
129
|
-
| `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
|
|
129
|
+
| `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 sealed one records a choice for its next follow-up, without starting anything or reserving a slot. An accepted manual choice persists across later generations until another manual choice replaces it (see [Model switching](#model-switching)). |
|
|
130
130
|
| `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. A command call's whole process tree ends. |
|
|
131
131
|
| `drain` / `resume` | existing workflows | A reversible hold; runs started later are not held. |
|
|
132
132
|
|
|
@@ -172,6 +172,96 @@ or the retry is a conflict too.
|
|
|
172
172
|
While an older orchestrator runs, a notify is refused with that advice and
|
|
173
173
|
nothing is sent (an older orchestrator would accept it and drop it).
|
|
174
174
|
|
|
175
|
+
### Asking the parent
|
|
176
|
+
|
|
177
|
+
A child uses `ask` to ask its parent a question and wait for an answer or
|
|
178
|
+
steering message. `{question: string}` still works by default. For a decision
|
|
179
|
+
that the parent can act on, name the decision, options and evidence:
|
|
180
|
+
|
|
181
|
+
```json
|
|
182
|
+
{
|
|
183
|
+
"question": "The local repair is verified; should I keep this scope?",
|
|
184
|
+
"decision_needed": "Choose the repair scope.",
|
|
185
|
+
"options": [
|
|
186
|
+
{"label": "Local fix", "scope": "ask projection", "cost": "one verification run", "risk": "low", "preferred": true},
|
|
187
|
+
{"label": "Defer the repair"}
|
|
188
|
+
],
|
|
189
|
+
"facts": ["commit 5ad9ee3", "run AK", "log sha abc"],
|
|
190
|
+
"tried": ["reproduced the projection loss"],
|
|
191
|
+
"classification_candidates": [
|
|
192
|
+
{"label": "projection loss", "evidence": ["digest drops fields"], "unproven": ["restart path"]}
|
|
193
|
+
]
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`question` is always required and must be a string. The optional fields are:
|
|
198
|
+
|
|
199
|
+
- `decision_needed`: one sentence naming the decision you need; required and
|
|
200
|
+
nonblank whenever any structured field is present.
|
|
201
|
+
- `options`: at most 9 objects with required `label` and optional `scope`,
|
|
202
|
+
`cost`, `risk` (strings) and `preferred` (boolean). At most one may be
|
|
203
|
+
preferred; the parent sees numbered labels, with `(preferred)` on that one.
|
|
204
|
+
- `facts` and `tried`: at most 20 strings each; give durable evidence (commit,
|
|
205
|
+
run id, log sha) and what you have already tried.
|
|
206
|
+
- `classification_candidates`: at most 9 objects with required `label` and
|
|
207
|
+
optional `evidence` and `unproven` arrays of strings, separating evidence
|
|
208
|
+
from explanations not yet proved. These nested arrays have no additional
|
|
209
|
+
item-count limit.
|
|
210
|
+
|
|
211
|
+
Every string in a structured ask, including `question`, is at most 2000
|
|
212
|
+
characters. An ask is structured when any optional field above is present,
|
|
213
|
+
or when `askRequireDecision` is true (see [Configuration](#configuration)).
|
|
214
|
+
Default question-only asks keep the 1.1.0 behaviour, including no new
|
|
215
|
+
question-length limit. Empty arrays are allowed; omitted fields stay absent,
|
|
216
|
+
and text is preserved, not trimmed or coerced.
|
|
217
|
+
|
|
218
|
+
Wrong types, exceeded limits, multiple preferred options or a missing decision
|
|
219
|
+
produce a tool error starting `ask refused:` before any question entry,
|
|
220
|
+
attention item, waiter or revision is created. A missing decision says exactly:
|
|
221
|
+
|
|
222
|
+
```text
|
|
223
|
+
ask refused: decision_needed is required (one sentence naming the decision you need), then options
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The child can correct it and ask again. Parent-facing asking notices, the
|
|
227
|
+
agent tool's status text, and CLI status/describe text show the decision first,
|
|
228
|
+
then numbered option labels, then the original question. Plain questions still
|
|
229
|
+
display as before. The supplied fields survive sessions, digests, attention
|
|
230
|
+
and orchestrator restarts; question identity (`qid`, based on execution and
|
|
231
|
+
question text), answer, steer and hibernation semantics are unchanged. JSON
|
|
232
|
+
fields are described under [Driving dsa from a program](#driving-dsa-from-a-program).
|
|
233
|
+
|
|
234
|
+
### Model switching
|
|
235
|
+
|
|
236
|
+
In 1.2.0, an accepted manual `send kind:model` becomes the logical call's
|
|
237
|
+
choice for every later follow-up generation (g+1, g+2, …), including calls
|
|
238
|
+
initially launched from a pool. Another accepted manual model switch, or a
|
|
239
|
+
follow-up specifying `model`, replaces it. Refused, withdrawn or replaced
|
|
240
|
+
requests never become choices; automatic failover never becomes a choice.
|
|
241
|
+
|
|
242
|
+
A concrete `provider/id[:thinking]` remains concrete. A pool name remains a
|
|
243
|
+
pool choice, resolved again at each generation's launch using the current pool
|
|
244
|
+
configuration. Pool availability, slot, skip and failover rules still apply.
|
|
245
|
+
A concrete choice follows the existing 1.1 explicit-model launch path: it has
|
|
246
|
+
no pool to widen into, so an exhausted provider waits for availability/probing
|
|
247
|
+
and provider slots, not an invented fallback pool. Live-switch capacity
|
|
248
|
+
admission and reservations are unchanged.
|
|
249
|
+
|
|
250
|
+
To a sealed call, `send kind:model` records the choice and replies with
|
|
251
|
+
`model` and `effect: "next-generation"`; it creates no generation, starts no
|
|
252
|
+
child and reserves no slot. Send a follow-up to continue. Until then, `status`
|
|
253
|
+
retains the last actual `model` and shows the pending choice as `switching`.
|
|
254
|
+
Opening the next generation consumes the pending indicator, not the choice.
|
|
255
|
+
Sealed model requests use the existing sealed follow-up acceptance path,
|
|
256
|
+
including done and stopped workflows; address, stale-revision, command-call
|
|
257
|
+
and pin-validation refusals still apply. This does not resume a stopped
|
|
258
|
+
workflow by itself.
|
|
259
|
+
|
|
260
|
+
The choice is persisted before the applied reply and survives orchestrator
|
|
261
|
+
restarts; a retry with the same request id returns the first outcome. Legacy
|
|
262
|
+
model forwards without the new optional `choice` retain their 1.1
|
|
263
|
+
execution-only semantics; upgrading does not make an old switch sticky.
|
|
264
|
+
|
|
175
265
|
### Workflow scripts
|
|
176
266
|
|
|
177
267
|
A workflow is a plain script. These are the globals it can use:
|
|
@@ -562,6 +652,17 @@ is. The reason is a best-effort reading of the journals: `restart-force` when a
|
|
|
562
652
|
`orchestrator-crash` when the orchestrator died uncleanly while it ran, else
|
|
563
653
|
`process-died`.
|
|
564
654
|
|
|
655
|
+
For structured asks, each `describe` `questions[]` item adds the supplied
|
|
656
|
+
`decision_needed`, `options`, `facts`, `tried` and `classification_candidates`
|
|
657
|
+
alongside `qid`, `rev`, `to`, `call` and `text`; `text` remains the original
|
|
658
|
+
question, not a rendered summary. This applies to both CLI describe forms
|
|
659
|
+
and the program `describe()` API. Full `status <wid> --json` attention items
|
|
660
|
+
retain the metadata; compact status clips `decision_needed` like question
|
|
661
|
+
text. The agent tool's brief `asking[]` adds clipped `decision_needed` and
|
|
662
|
+
`rev` only for structured questions, even in a mixed list. Plain-question JSON
|
|
663
|
+
keeps its 1.1.0 shape and serialization, without inserted defaults. Machine
|
|
664
|
+
JSON stays separate from the decision-first text rendering.
|
|
665
|
+
|
|
565
666
|
A wake run's `describe` adds `wake: {to, state, rev?, generation?, reason?}`:
|
|
566
667
|
`state` is `pending`, `applied`, `skipped` or `rejected`; `rev` counts workflow
|
|
567
668
|
completions and `generation` names the delivery generation when known. A
|
|
@@ -952,7 +1053,8 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
952
1053
|
"pools": { "fast": ["anthropic/claude-haiku-4-5", "openai/gpt-5-mini"] },
|
|
953
1054
|
"providers": { "anthropic": { "slots": 4 } },
|
|
954
1055
|
"memory": { "reserveMb": 2048, "perChildMb": 300 },
|
|
955
|
-
"writerLock": "queue"
|
|
1056
|
+
"writerLock": "queue",
|
|
1057
|
+
"askRequireDecision": false
|
|
956
1058
|
}
|
|
957
1059
|
```
|
|
958
1060
|
|
|
@@ -993,8 +1095,11 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
993
1095
|
after it last refused (`"k": { "probeMs": 900000 }`). Then one call at a
|
|
994
1096
|
time goes to it, so finding out costs no extra request. A call that moved to
|
|
995
1097
|
another provider stays there for the rest of its generation (switching back
|
|
996
|
-
mid-task would lose the prompt cache)
|
|
997
|
-
|
|
1098
|
+
mid-task would lose the prompt cache). Automatic failover is not a sticky
|
|
1099
|
+
choice: a follow-up starts from pool order again unless a manual choice
|
|
1100
|
+
stands. A manual pool choice resolves that pool again; a concrete choice
|
|
1101
|
+
has no fallback pool and waits for its provider. `status` lists each used-up
|
|
1102
|
+
provider with its next try,
|
|
998
1103
|
and `events <wid>` shows the move as a model `forward` naming the target
|
|
999
1104
|
(`model=<provider>/<id>`) and the provider it left (`failover=<provider>`);
|
|
1000
1105
|
a model you send shows only its target.
|
|
@@ -1032,11 +1137,19 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
1032
1137
|
`"off"` lets them run together and only reminds you of edits seen in the same
|
|
1033
1138
|
worktree. Writes that do not go through a writing call (your own, or a
|
|
1034
1139
|
`writer: false` call's bash) are not constrained.
|
|
1140
|
+
- **Required ask decisions:** `"askRequireDecision": true` requires a nonblank
|
|
1141
|
+
`decision_needed` on every child ask and applies the structured-ask string
|
|
1142
|
+
limits, even when no other metadata is given. This boolean key defaults to
|
|
1143
|
+
false, is validated and participates in the orchestrator config hash.
|
|
1144
|
+
It is snapshotted when each child execution starts: changing it affects
|
|
1145
|
+
executions started afterwards, not a child already running; a resumed
|
|
1146
|
+
execution receives the current setting. False keeps question-only asks valid.
|
|
1035
1147
|
- **onQuit:** `"pause"` (default) pauses a session's running workflows when
|
|
1036
1148
|
you quit that pi; `"continue"` lets them run on in the background.
|
|
1037
1149
|
- **Changes apply without a restart:** the orchestrator re-reads the file
|
|
1038
|
-
when it changes
|
|
1039
|
-
|
|
1150
|
+
when it changes (`askRequireDecision` reaches a child at execution start,
|
|
1151
|
+
not mid-execution). A new slot limit, pool or default model applies to the
|
|
1152
|
+
next slot acquisition; slots already held are kept when a limit drops. An
|
|
1040
1153
|
invalid change is not applied, and `status` reports it next to the settings
|
|
1041
1154
|
still in effect (`config: <hash> since …`) and the slots held per provider.
|
|
1042
1155
|
|
|
@@ -1153,6 +1266,19 @@ SIGTERM, which is not atomic: a call launched in between is fenced and resumes.
|
|
|
1153
1266
|
The old orchestrator cannot record the new audit fields. A pi session started before the update still
|
|
1154
1267
|
loads the old extension; start a new one.
|
|
1155
1268
|
|
|
1269
|
+
### Upgrading to 1.2.0
|
|
1270
|
+
|
|
1271
|
+
Restart the orchestrator on 1.2.0 and start a new pi session to load the new
|
|
1272
|
+
extension before relying on structured asks or sticky model choices; an
|
|
1273
|
+
already running child keeps its execution-start ask setting. Existing
|
|
1274
|
+
journals, request digests and decisions keep their meaning. Plain asks keep
|
|
1275
|
+
their JSON unchanged, and old model forwards remain execution-only. New live
|
|
1276
|
+
manual model forwards carry optional `choice` (the original model or pool
|
|
1277
|
+
name); sealed choices use `model-choice {rid, call, model}` entries. New
|
|
1278
|
+
generation records carry optional `choice` and put it in `spec.model` (a
|
|
1279
|
+
concrete choice also uses the existing generation `model` override). These
|
|
1280
|
+
records are scoped to the call and revision, not another key or revision.
|
|
1281
|
+
|
|
1156
1282
|
## What we do not promise
|
|
1157
1283
|
|
|
1158
1284
|
- Call specs are checked strictly when a call is first proposed: an unknown or
|
|
@@ -1,7 +1,60 @@
|
|
|
1
|
+
import { ASK_FIELDS } from "../../types.js";
|
|
1
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
3
|
const keywords = new Set(['type', 'enum', 'items', 'properties', 'required', 'additionalProperties', 'description', 'title']);
|
|
3
4
|
const types = new Set(['null', 'boolean', 'object', 'array', 'number', 'integer', 'string']);
|
|
4
5
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
6
|
+
/** AK2: validate before creating a question, revision or waiter. No coercion. */
|
|
7
|
+
export function askProblem(value, requireDecision = false) {
|
|
8
|
+
if (!isObject(value))
|
|
9
|
+
return 'ask refused: arguments must be an object';
|
|
10
|
+
const structured = ASK_FIELDS.some(key => Object.hasOwn(value, key));
|
|
11
|
+
if ((structured || requireDecision) && (value.decision_needed === undefined || typeof value.decision_needed === 'string' && !value.decision_needed.trim()))
|
|
12
|
+
return 'ask refused: decision_needed is required (one sentence naming the decision you need), then options';
|
|
13
|
+
const string = (v, at) => typeof v !== 'string' ? `${at} must be a string` : v.length > 2000 ? `${at} exceeds 2000 characters` : undefined;
|
|
14
|
+
const list = (v, at, max, item) => {
|
|
15
|
+
if (!Array.isArray(v))
|
|
16
|
+
return `${at} must be an array`;
|
|
17
|
+
if (v.length > max)
|
|
18
|
+
return `${at} exceeds ${max} items`;
|
|
19
|
+
for (const [i, entry] of v.entries()) {
|
|
20
|
+
const problem = item(entry, `${at}[${i}]`);
|
|
21
|
+
if (problem)
|
|
22
|
+
return problem;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
let problem = typeof value.question !== 'string' || structured || requireDecision ? string(value.question, 'question') : undefined;
|
|
26
|
+
if (!problem && Object.hasOwn(value, 'decision_needed'))
|
|
27
|
+
problem = string(value.decision_needed, 'decision_needed');
|
|
28
|
+
for (const key of ['facts', 'tried'])
|
|
29
|
+
if (!problem && Object.hasOwn(value, key))
|
|
30
|
+
problem = list(value[key], key, 20, string);
|
|
31
|
+
if (!problem && Object.hasOwn(value, 'options')) {
|
|
32
|
+
problem = list(value.options, 'options', 9, (v, at) => {
|
|
33
|
+
if (!isObject(v))
|
|
34
|
+
return `${at} must be an object`;
|
|
35
|
+
let p = string(v.label, `${at}.label`);
|
|
36
|
+
for (const key of ['scope', 'cost', 'risk'])
|
|
37
|
+
if (!p && Object.hasOwn(v, key))
|
|
38
|
+
p = string(v[key], `${at}.${key}`);
|
|
39
|
+
if (!p && Object.hasOwn(v, 'preferred') && typeof v.preferred !== 'boolean')
|
|
40
|
+
p = `${at}.preferred must be a boolean`;
|
|
41
|
+
return p;
|
|
42
|
+
});
|
|
43
|
+
if (!problem && value.options.filter(o => o.preferred).length > 1)
|
|
44
|
+
problem = 'at most one option may be preferred';
|
|
45
|
+
}
|
|
46
|
+
if (!problem && Object.hasOwn(value, 'classification_candidates'))
|
|
47
|
+
problem = list(value.classification_candidates, 'classification_candidates', 9, (v, at) => {
|
|
48
|
+
if (!isObject(v))
|
|
49
|
+
return `${at} must be an object`;
|
|
50
|
+
let p = string(v.label, `${at}.label`);
|
|
51
|
+
for (const key of ['evidence', 'unproven'])
|
|
52
|
+
if (!p && Object.hasOwn(v, key))
|
|
53
|
+
p = list(v[key], `${at}.${key}`, Infinity, string);
|
|
54
|
+
return p;
|
|
55
|
+
});
|
|
56
|
+
return problem ? `ask refused: ${problem}` : undefined;
|
|
57
|
+
}
|
|
5
58
|
/** P24, T4: List unsupported keywords and malformed shapes so a schema that would not constrain fails loudly. */
|
|
6
59
|
export function schemaProblems(schema, path = '$') {
|
|
7
60
|
if (typeof schema === 'boolean')
|
package/dist/agent/child.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import fs, { watch } from 'node:fs';
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { Type } from '@earendil-works/pi-ai';
|
|
4
|
-
import { ASK_CUT, CT, ENV, JT } from "../types.js";
|
|
4
|
+
import { ASK_CUT, CT, ENV, JT, askFields } from "../types.js";
|
|
5
5
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
6
6
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
7
7
|
import { contentHash } from "../kernel/ids.js";
|
|
8
8
|
import { planDecisions } from "../kernel/lifecycle.js";
|
|
9
9
|
import { openness } from "../kernel/guards.js";
|
|
10
10
|
import { recover } from "./child/history.js";
|
|
11
|
-
import { validate } from "./child/schema.js";
|
|
11
|
+
import { askProblem, validate } from "./child/schema.js";
|
|
12
12
|
import { catalogModel, parseModel, sameModel } from "../compat/model.js";
|
|
13
13
|
import { registerLive } from "./child/live.js";
|
|
14
14
|
const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
|
|
@@ -45,6 +45,7 @@ export function usage(entries, call) {
|
|
|
45
45
|
}
|
|
46
46
|
/** P4, P8, P23, P24: Consume the child mailbox at serialized pi boundaries, retaining native session receipts. */
|
|
47
47
|
export function registerChild(pi) {
|
|
48
|
+
const requireDecision = process.env[ENV.askRequireDecision] === 'true';
|
|
48
49
|
let target = process.env[ENV.model];
|
|
49
50
|
const exec = process.env[ENV.exec], call = process.env[ENV.call], inbox = process.env[ENV.inbox], journal = process.env[ENV.journal];
|
|
50
51
|
let active = false, watcher, queue = Promise.resolve();
|
|
@@ -360,9 +361,25 @@ export function registerChild(pi) {
|
|
|
360
361
|
await queue;
|
|
361
362
|
});
|
|
362
363
|
pi.registerTool({
|
|
363
|
-
name: 'ask', label: 'Ask supervisor', description: 'Ask a question and wait for an answer or steering message.',
|
|
364
|
-
parameters: Type.Object({
|
|
365
|
-
|
|
364
|
+
name: 'ask', label: 'Ask supervisor', description: 'Ask a question and wait for an answer or steering message. State the decision you need (one sentence) in decision_needed, list numbered options with scope/cost/risk and at most one preferred option. Give facts (commit, run id, log sha), what you tried, and candidate explanations with evidence and what is unproven. Every string is at most 2000 characters; options and classification_candidates at most 9, facts and tried at most 20.',
|
|
365
|
+
parameters: Type.Object({
|
|
366
|
+
question: Type.String(), decision_needed: Type.Optional(Type.String()),
|
|
367
|
+
options: Type.Optional(Type.Array(Type.Object({ label: Type.String(), scope: Type.Optional(Type.String()), cost: Type.Optional(Type.String()), risk: Type.Optional(Type.String()), preferred: Type.Optional(Type.Boolean()) }))),
|
|
368
|
+
facts: Type.Optional(Type.Array(Type.String())), tried: Type.Optional(Type.Array(Type.String())),
|
|
369
|
+
classification_candidates: Type.Optional(Type.Array(Type.Object({ label: Type.String(), evidence: Type.Optional(Type.Array(Type.String())), unproven: Type.Optional(Type.Array(Type.String())) }))),
|
|
370
|
+
}), executionMode: 'sequential', exposure: 'model-only',
|
|
371
|
+
// pi validates the schema before execute; reject raw malformed arguments here without coercion as well.
|
|
372
|
+
prepareArguments(args) {
|
|
373
|
+
const problem = askProblem(args, requireDecision);
|
|
374
|
+
if (problem)
|
|
375
|
+
throw new Error(problem);
|
|
376
|
+
return args;
|
|
377
|
+
},
|
|
378
|
+
async execute(_id, args, signal, _update, ctx) {
|
|
379
|
+
const problem = askProblem(args, requireDecision);
|
|
380
|
+
if (problem)
|
|
381
|
+
throw new Error(problem);
|
|
382
|
+
const { question } = args;
|
|
366
383
|
let resolve, reject;
|
|
367
384
|
const result = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
368
385
|
// Attach immediately so abort during the queued intake never produces an unhandled rejection.
|
|
@@ -377,7 +394,7 @@ export function registerChild(pi) {
|
|
|
377
394
|
if (blocked)
|
|
378
395
|
throw new Error('Another question is already blocked');
|
|
379
396
|
const qid = contentHash({ exec, question }), rev = (state.questions.get(qid)?.rev ?? 0) + 1;
|
|
380
|
-
const q = { qid, rev, question };
|
|
397
|
+
const q = { qid, rev, question, ...askFields(args) };
|
|
381
398
|
state.questions.set(qid, q);
|
|
382
399
|
pi.appendEntry(CT.question, q);
|
|
383
400
|
blocked = { ...q, resolve, reject };
|
|
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import { liveCommandCalls } from "../../orchestrator/executor/command.js";
|
|
5
5
|
import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
|
|
6
6
|
import { journalPath } from "../../paths.js";
|
|
7
|
-
import { CT, JT } from "../../types.js";
|
|
7
|
+
import { CT, JT, askText } from "../../types.js";
|
|
8
8
|
import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
|
|
9
9
|
import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
|
|
10
10
|
/** Session-outbox reader: retain only pending identities and a verified position, not sent envelopes/history. */
|
|
@@ -212,7 +212,7 @@ export function attention(home, sender, seen, fresh = false) {
|
|
|
212
212
|
export function presentText(item) {
|
|
213
213
|
const call = item.call ? item.call.replace(/@\d+\/([^@/]+)@\d+$/, "/$1") : undefined, where = call ?? item.wid;
|
|
214
214
|
if (item.kind === "question" && call)
|
|
215
|
-
return `Question from ${call}${item.qid ? ` (qid ${item.qid})` : ""}; reply with send kind:"answer" to:"${call}": ${item.text}`;
|
|
215
|
+
return `Question from ${call}${item.qid ? ` (qid ${item.qid})` : ""}; reply with send kind:"answer" to:"${call}": ${askText(item, item.text)}`;
|
|
216
216
|
return item.text.includes(item.wid) ? item.text : `${where}: ${item.text}`;
|
|
217
217
|
}
|
|
218
218
|
/** Resolutions recorded in one immutable journal snapshot, keyed by id and rev. */
|
package/dist/agent/main.js
CHANGED
|
@@ -11,7 +11,7 @@ import { launchOrchestrator } from "../platform/launch.js";
|
|
|
11
11
|
import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
|
|
12
12
|
import { CT, JT } from "../types.js";
|
|
13
13
|
import { PendingOutboxReader, attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
|
|
14
|
-
import { NOTIFY_SINCE, commandSendRefusal, isCommandTarget, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
14
|
+
import { NOTIFY_SINCE, commandSendRefusal, isCommandTarget, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusText, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
|
|
15
15
|
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
|
|
16
16
|
import { parameters } from "./main/schema.js";
|
|
17
17
|
import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
|
|
@@ -444,7 +444,7 @@ export function registerMain(pi, ui) {
|
|
|
444
444
|
].join("\n"), parameters,
|
|
445
445
|
async execute(_id, args, signal, _update, context) {
|
|
446
446
|
const value = await submit(args, context.cwd, signal);
|
|
447
|
-
return { content: [{ type: "text", text: JSON.stringify(value) }], details: value };
|
|
447
|
+
return { content: [{ type: "text", text: args.action === 'status' ? statusText(home, value) : JSON.stringify(value) }], details: value };
|
|
448
448
|
},
|
|
449
449
|
}));
|
|
450
450
|
}
|
package/dist/cli/main.js
CHANGED
|
@@ -18,6 +18,7 @@ import { resolvePi } from "../platform/launch.js";
|
|
|
18
18
|
import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
|
|
19
19
|
import { restartInputError } from "../orchestrator/restart.js";
|
|
20
20
|
import { packageVersion } from "../version.js";
|
|
21
|
+
import { askText } from "../types.js";
|
|
21
22
|
const commands = ["smoke", "tail", "status", "events", "start", "resume", "drain", "stop", "stop-all", "prune", "restart", "leases", "doctor", "install-service", "uninstall-service", "help"];
|
|
22
23
|
/** P25: Reject ambiguous CLI arguments before any durable action. */
|
|
23
24
|
export function parseArgs(args) {
|
|
@@ -127,7 +128,7 @@ export function renderStatus(wf) {
|
|
|
127
128
|
const last = c.result?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1), err = c.result?.error;
|
|
128
129
|
return ` ${c.key}@${c.gen} ${c.result?.status ?? c.phase}${answeredNote(c, wf.paused)}${commandSuffix(commandStatus(c))}${c.model ? ` ${c.model}` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage && (c.usage.input || c.usage.output) ? ` ${formatUsage(c.usage)}` : ""}${last ? ` ${JSON.stringify(clip(last, 160))}` : err ? ` (${clip(err, 160)})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && !c.result && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`;
|
|
129
130
|
}),
|
|
130
|
-
...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(clip(a.text, 300))}`),
|
|
131
|
+
...wf.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.decision_needed === undefined ? clip(a.text, 300) : askText(a, a.text))}`),
|
|
131
132
|
...(wf.scriptLog ? [` script log: ${wf.scriptLog}`] : [])].join("\n");
|
|
132
133
|
}
|
|
133
134
|
/** `status <wid> --tail/--grep`: the workflow line, then each call with its selected output lines. */
|
|
@@ -139,7 +140,7 @@ export function renderSelected(wf) {
|
|
|
139
140
|
export function renderView(view) {
|
|
140
141
|
const lines = view.workflows.map(w => [`${w.wid}@${w.rev}${w.labels ? ` ${labelsText(w.labels)}` : ""}${w.name ? ` ${w.name}` : ""}: ${w.followUps ? `follow-up running (run ${w.status})` : w.status}${w.error ? ` (${clip(w.error, 200)})` : ""} · ${w.done}/${w.planned ?? w.calls.length}${w.planned === undefined && w.status === "running" ? "+" : ""} done${w.usage.input || w.usage.output || w.usage.costUsd ? ` · ${formatUsage(w.usage)}` : ""}`,
|
|
141
142
|
...w.calls.map(c => ` ${c.key}@${c.gen} ${c.status ?? c.phase}${answeredNote(c, w.paused)}${commandSuffix(c)}${c.hibernated ? " (hibernated, no slot)" : ""}${c.model ? ` ${c.model}` : ""}${c.switching ? ` \u2192 ${c.switching} (requested)` : ""}${c.switchFailed ? ` (switch refused: ${c.switchFailed})` : ""}${c.tools ? ` tools:${c.tools}` : ""}${c.usage ? ` ${formatUsage(c.usage)}` : ""}${c.lastLine ? ` ${JSON.stringify(c.lastLine)}` : c.error ? ` (${c.error})` : ""}${c.sharedWorktree ? ` (shares worktree with ${c.sharedWorktree.join(", ")})` : ""}${c.writerWait && c.phase !== "sealed" ? ` (waiting for writer lock: ${c.writerWait.root} held by ${c.writerWait.holder})` : ""}${c.lease && c.phase !== "sealed" ? ` (${c.lease})` : ""}${notesLine(c.notesPending)}${modelStatusText(c)}`),
|
|
142
|
-
...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.text.split("\n")[0])}`)].join("\n"));
|
|
143
|
+
...w.attention.map(a => ` ${a.kind}: ${JSON.stringify(a.decision_needed === undefined ? a.text.split("\n")[0] : askText(a, a.text))}`)].join("\n"));
|
|
143
144
|
if (view.paused)
|
|
144
145
|
lines.unshift(`${view.paused} (pi-durable-subagents resume)`);
|
|
145
146
|
if (view.olderFinished)
|
package/dist/cli/requests.js
CHANGED
|
@@ -12,7 +12,7 @@ import { NOTIFY_SINCE, WAKE_SINCE, HOLD_ENTRY_TYPES, commandLine, commandSendRef
|
|
|
12
12
|
import { leaseCalls, leaseState, callAddress } from "../platform/lease.js";
|
|
13
13
|
import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
|
|
14
14
|
import { discoverAgents } from "../compat/agents.js";
|
|
15
|
-
import { JT } from "../types.js";
|
|
15
|
+
import { JT, askFields, askText } from "../types.js";
|
|
16
16
|
import { startOrchestrator, submitIdentified } from "./control.js";
|
|
17
17
|
import { FENCE_LEDGER_TYPES, endedExecs, fenceReason } from "../events/fence.js";
|
|
18
18
|
import { parseLabels } from "../events/labels.js";
|
|
@@ -156,7 +156,7 @@ function describeWorkflow(home, wid, entries, now) {
|
|
|
156
156
|
...(waiting && Object.keys(waiting).length ? { waiting } : {}) };
|
|
157
157
|
});
|
|
158
158
|
const keyOf = (call) => call?.replace(/^[^/]*\//, "").replace(/@\d+$/, "");
|
|
159
|
-
const questions = wf.attention.filter(a => a.kind === "question").map(a => ({ ...(a.qid ? { qid: a.qid } : {}), rev: a.rev, to: `${wid}/${keyOf(a.call)}`, ...(a.call ? { call: a.call } : {}), text: a.text }));
|
|
159
|
+
const questions = wf.attention.filter(a => a.kind === "question").map(a => ({ ...(a.qid ? { qid: a.qid } : {}), rev: a.rev, to: `${wid}/${keyOf(a.call)}`, ...(a.call ? { call: a.call } : {}), text: a.text, ...askFields(a) }));
|
|
160
160
|
const attention = wf.attention.filter(a => a.kind !== "question").map(a => ({ id: a.id, rev: a.rev, kind: a.kind, ...(a.call ? { call: a.call } : {}), text: a.text }));
|
|
161
161
|
const state = questions.length ? "asking" : isLive(wf) || wf.status === "parked" ? "running" : "sealed";
|
|
162
162
|
const fence = lastFence(journal, entries);
|
|
@@ -205,7 +205,7 @@ export function renderDescription(d) {
|
|
|
205
205
|
lines.push(...c.output.split("\n").map(l => ` | ${l}`));
|
|
206
206
|
}
|
|
207
207
|
for (const q of d.questions ?? [])
|
|
208
|
-
lines.push(` question ${q.to} qid=${q.qid} rev=${q.rev}:`, ...q.text.split("\n").map(l => ` ${l}`));
|
|
208
|
+
lines.push(` question ${q.to} qid=${q.qid} rev=${q.rev}:`, ...askText(q, q.text).split("\n").map(l => ` ${l}`));
|
|
209
209
|
for (const a of d.attention ?? [])
|
|
210
210
|
lines.push(` ${a.kind}${a.call ? ` ${a.call}` : ""}: ${a.text}`);
|
|
211
211
|
if (d.lastFence)
|
|
@@ -9,7 +9,7 @@ import { readFile } from "node:fs/promises";
|
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { contentHash } from "../kernel/ids.js";
|
|
11
11
|
/** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
|
|
12
|
-
const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "k"];
|
|
12
|
+
const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "askRequireDecision", "k"];
|
|
13
13
|
const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
|
|
14
14
|
export const configPath = (home) => join(home, "config.json");
|
|
15
15
|
/** The orchestrator's part of a parsed config.json. */
|
|
@@ -24,7 +24,9 @@ const count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
|
24
24
|
export function configProblem(raw) {
|
|
25
25
|
if (!record(raw))
|
|
26
26
|
return "config.json must be a JSON object";
|
|
27
|
-
const { defaultModel, pools, providers, memory, writerLock, k } = raw;
|
|
27
|
+
const { defaultModel, pools, providers, memory, writerLock, askRequireDecision, k } = raw;
|
|
28
|
+
if (askRequireDecision !== undefined && typeof askRequireDecision !== "boolean")
|
|
29
|
+
return 'askRequireDecision must be a boolean';
|
|
28
30
|
if (writerLock !== undefined && writerLock !== "queue" && writerLock !== "off")
|
|
29
31
|
return 'writerLock must be "queue" or "off"';
|
|
30
32
|
if (defaultModel !== undefined && typeof defaultModel !== "string")
|
|
@@ -32,7 +32,8 @@ import { labelsProblem } from "../events/labels.js";
|
|
|
32
32
|
import { WaitTracker, waitCollector, startWaiting } from "../events/waiting.js";
|
|
33
33
|
import { readPage } from "../events/log.js";
|
|
34
34
|
import { eventsLog } from "../paths.js";
|
|
35
|
-
import { parseModel } from "../compat/model.js";
|
|
35
|
+
import { parseModel, resolveModel } from "../compat/model.js";
|
|
36
|
+
import { generationModel } from "./model-choice.js";
|
|
36
37
|
import { PENDING_NOTE, generationRids, openingMessage, pendingFollowUps, pendingNotes, unsettledForward, unsettledNotify } from "./notes.js";
|
|
37
38
|
import { journalAppends } from "../kernel/journal.js";
|
|
38
39
|
import { callEntries, entriesOf } from "./executor/indexes.js";
|
|
@@ -646,6 +647,28 @@ export class Engine {
|
|
|
646
647
|
this.dispatchGeneration(existing.wf, existing.entry);
|
|
647
648
|
return { action: 'apply' };
|
|
648
649
|
}
|
|
650
|
+
// A sealed choice was committed before its reply. Replay it even if another request has since opened a generation.
|
|
651
|
+
const chosen = [...this.store.workflows.values()].filter(wf => wf.journal.loaded !== false || to.startsWith(wf.wid))
|
|
652
|
+
.flatMap(wf => revisionEntries(wf).filter(e => e.type === 'model-choice' && e.rid === req.rid))[0];
|
|
653
|
+
if (chosen) {
|
|
654
|
+
await this.note(req.rid, String(chosen.model), 'next-generation');
|
|
655
|
+
return { action: 'apply' };
|
|
656
|
+
}
|
|
657
|
+
if (req.body?.kind === 'model') {
|
|
658
|
+
// A live forward may have committed just before a crash, then been refused or superseded before replay.
|
|
659
|
+
// Keep its original outcome; never turn it into a fresh sealed choice or send it to a newer generation.
|
|
660
|
+
for (const wf of this.store.workflows.values()) {
|
|
661
|
+
if (wf.journal.loaded === false && !to.startsWith(wf.wid))
|
|
662
|
+
continue;
|
|
663
|
+
const log = revisionEntries(wf), prior = log.find(e => e.type === 'forward' && e.rid === req.rid && e.envelope?.kind === 'model');
|
|
664
|
+
if (!prior)
|
|
665
|
+
continue;
|
|
666
|
+
const entry = log.find(e => (e.type === 'call' || e.type === 'generation') && `${wf.wid}@${wf.revision}/${e.key}@${e.gen}` === prior.dest);
|
|
667
|
+
if (entry && !log.some(e => (e.type === JT.sealed || e.type === 'retired') && e.call === prior.dest))
|
|
668
|
+
return this.executor.forward(req, this.context(wf, entry));
|
|
669
|
+
return { action: 'apply' };
|
|
670
|
+
}
|
|
671
|
+
}
|
|
649
672
|
const target = this.findCall(req.body?.to, true);
|
|
650
673
|
if (!target)
|
|
651
674
|
return { action: 'reject', reason: this.unknownCall(req.body?.to) };
|
|
@@ -661,7 +684,7 @@ export class Engine {
|
|
|
661
684
|
return this.notify(req, wf, entry, from, seal !== undefined);
|
|
662
685
|
// A pool's name is a model too: the call keeps the pool, and its order and failover apply to the new generation.
|
|
663
686
|
const pools = this.ledgers.config.pools, pool = send.model !== undefined && pools && Object.hasOwn(pools, send.model);
|
|
664
|
-
if (send.kind === 'follow-up' && send.model !== undefined && !pool) {
|
|
687
|
+
if ((send.kind === 'follow-up' || send.kind === 'model') && send.model !== undefined && !pool) {
|
|
665
688
|
try {
|
|
666
689
|
if (!parseModel(send.model).provider)
|
|
667
690
|
throw new Error('missing provider');
|
|
@@ -670,7 +693,7 @@ export class Engine {
|
|
|
670
693
|
return { action: 'reject', reason: 'unknown-model' };
|
|
671
694
|
}
|
|
672
695
|
}
|
|
673
|
-
if (seal && send.kind === 'follow-up')
|
|
696
|
+
if (seal && (send.kind === 'follow-up' || send.kind === 'model'))
|
|
674
697
|
return this.serialOpen(wf.wid, async () => {
|
|
675
698
|
// A generation opened meanwhile (undelivered follow-ups after a seal) is the call this follow-up now reaches.
|
|
676
699
|
if (latestCall(wf, String(entry.key))?.gen !== entry.gen)
|
|
@@ -686,6 +709,20 @@ export class Engine {
|
|
|
686
709
|
catch (error) {
|
|
687
710
|
return { action: 'reject', reason: `pin-failed: ${String(error)}` };
|
|
688
711
|
}
|
|
712
|
+
if (send.kind === 'model') {
|
|
713
|
+
if (!send.model)
|
|
714
|
+
return { action: 'reject', reason: 'unknown-model' };
|
|
715
|
+
// Record only intent. No execution, generation, mailbox delivery or provider reservation is created here.
|
|
716
|
+
try {
|
|
717
|
+
resolveModel(send.model, pools);
|
|
718
|
+
}
|
|
719
|
+
catch {
|
|
720
|
+
return { action: 'reject', reason: 'unknown-model' };
|
|
721
|
+
}
|
|
722
|
+
await wf.journal.append('model-choice', { rid: req.rid, call: from, model: send.model });
|
|
723
|
+
await this.note(req.rid, send.model, 'next-generation');
|
|
724
|
+
return { action: 'apply' };
|
|
725
|
+
}
|
|
689
726
|
if (send.model !== undefined)
|
|
690
727
|
await this.note(req.rid, send.model, 'next-generation');
|
|
691
728
|
const opened = await this.openGeneration(wf, entry, from, { rid: req.rid, message: send.message ?? '', ...(send.model !== undefined ? { model: send.model } : {}) });
|
|
@@ -693,7 +730,9 @@ export class Engine {
|
|
|
693
730
|
return { action: 'apply' };
|
|
694
731
|
});
|
|
695
732
|
// A follow-up naming a model, queued on unfinished work: the executor records its model request with the message.
|
|
696
|
-
|
|
733
|
+
const forwarded = await this.executor.forward(req, this.context(wf, entry));
|
|
734
|
+
// The executor's serial queue may have sealed the call after our lookup; retry through the same sealed branch.
|
|
735
|
+
return send.kind === 'model' && forwarded.action === 'reject' && forwarded.reason === 'call-sealed' ? { action: 'defer' } : forwarded;
|
|
697
736
|
}
|
|
698
737
|
else if (req.kind === 'stop') {
|
|
699
738
|
const target = req.body?.target;
|
|
@@ -928,15 +967,16 @@ export class Engine {
|
|
|
928
967
|
async openGeneration(wf, entry, from, own) {
|
|
929
968
|
const log = revisionEntries(wf), key = String(entry.key), notes = pendingNotes(log, key), carried = pendingFollowUps(log, key);
|
|
930
969
|
const asked = (rid) => this.ledgers.orch.entries().findLast(e => e.type === 'request' && e.request?.rid === rid)?.request?.body?.model;
|
|
931
|
-
const model =
|
|
970
|
+
const model = own?.model ?? generationModel(log, from) ?? carried.map(c => asked(c.rid)).filter((m) => typeof m === 'string').at(-1) ??
|
|
971
|
+
(typeof entry.choice === 'string' ? entry.choice : undefined);
|
|
932
972
|
const pools = this.ledgers.config.pools, pool = model !== undefined && pools && Object.hasOwn(pools, model);
|
|
933
973
|
const rid = own?.rid ?? carried[0].rid, follows = carried.map(c => c.rid).filter(r => r !== rid);
|
|
934
974
|
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;
|
|
935
|
-
// A follow-up's model
|
|
975
|
+
// A follow-up's explicit model or a new manual choice persists in the spec of every later generation.
|
|
936
976
|
const spec = model !== undefined ? { ...entry.spec, model } : entry.spec;
|
|
937
977
|
const message = openingMessage(notes.map(n => String(n.message)), [...carried.map(c => c.message), own?.message ?? '']);
|
|
938
978
|
return wf.journal.append('generation', { rid, key: entry.key, gen, from, spec, revision: wf.revision, opening: { rid, kind: 'follow-up', message },
|
|
939
|
-
...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(follows.length ? { follows } : {}), ...(model !== undefined && !pool ? { model } : {}) });
|
|
979
|
+
...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(follows.length ? { follows } : {}), ...(model !== undefined ? { choice: model } : {}), ...(model !== undefined && !pool ? { model } : {}) });
|
|
940
980
|
}
|
|
941
981
|
/** Follow-ups forwarded into running work whose call sealed before taking them (`undelivered-follow-up`) open the
|
|
942
982
|
* key's next generation, as a follow-up sent after the seal would: once its latest generation has sealed, unless a
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// extends its entries array with the same entry objects when the file grew, so a fold over a prefix is reused and
|
|
3
3
|
// only appended entries are visited. A session read from scratch (rewritten, replaced) restarts the fold. Each fold
|
|
4
4
|
// equals what the whole-array function it replaces computes over the same entries (see the tests).
|
|
5
|
-
import { CT } from "../../types.js";
|
|
5
|
+
import { CT, askFields } 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]);
|
|
@@ -53,7 +53,7 @@ export class SessionFold {
|
|
|
53
53
|
if (e.type === "custom") {
|
|
54
54
|
s.lastQuestion = i;
|
|
55
55
|
if (this.own && e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
|
|
56
|
-
s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question });
|
|
56
|
+
s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question, ...askFields(e.data) });
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
const details = e.message?.details ?? e.details;
|
|
@@ -83,5 +83,5 @@ export function digestOpenQuestion(entries, s) {
|
|
|
83
83
|
const result = ask === undefined ? undefined : s.results.get(ask);
|
|
84
84
|
if (ask === undefined || result && !cutAskResult(result.message))
|
|
85
85
|
return;
|
|
86
|
-
return { qid: q.qid, rev: q.rev, question: String(q.question) };
|
|
86
|
+
return { qid: q.qid, rev: q.rev, question: String(q.question), ...askFields(q) };
|
|
87
87
|
}
|
|
@@ -26,7 +26,7 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
26
26
|
import { homedir } from "node:os";
|
|
27
27
|
import { delimiter, dirname, join } from "node:path";
|
|
28
28
|
import { fileURLToPath } from "node:url";
|
|
29
|
-
import { CT, JT, attentionEntries, isCommandCall, isEntry } from "../../types.js";
|
|
29
|
+
import { CT, JT, askFields, attentionEntries, isCommandCall, isEntry } from "../../types.js";
|
|
30
30
|
import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
|
|
31
31
|
import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
|
|
32
32
|
import { Outbox } from "../../kernel/mailbox.js";
|
|
@@ -932,10 +932,11 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
932
932
|
await serial(async () => {
|
|
933
933
|
await forwardsDelivered(t.journal, t.callId, entries);
|
|
934
934
|
const digest = digestOf(t.callId, entries);
|
|
935
|
-
for (const
|
|
935
|
+
for (const q of digest.questions) {
|
|
936
|
+
const { qid, rev, question } = q;
|
|
936
937
|
const id = `q:${t.callId}:${qid}`;
|
|
937
938
|
if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
|
|
938
|
-
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) } });
|
|
939
|
+
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), ...askFields(q) } });
|
|
939
940
|
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))
|
|
940
941
|
await resolveBoundAnswer(t.journal, t.callId, qid, rev);
|
|
941
942
|
else if (digest.superseded.has(answerKey(qid, rev)) || supersededByBinding(t.journal.entries(), t.callId, qid, rev))
|
|
@@ -1732,7 +1733,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1732
1733
|
try {
|
|
1733
1734
|
child = await containment.spawn({ exec, command: piCommand, args: [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}) }), "-e", extension], cwd,
|
|
1734
1735
|
// The orchestrator's node follows binDir: a `#!/usr/bin/env node` pi runs under a PATH without node (a service's).
|
|
1735
|
-
env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}) } });
|
|
1736
|
+
env: { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}) } });
|
|
1736
1737
|
}
|
|
1737
1738
|
catch (error) {
|
|
1738
1739
|
const environment = environmentSpawnError(error);
|
|
@@ -2023,7 +2024,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2023
2024
|
}
|
|
2024
2025
|
}
|
|
2025
2026
|
/** P12: a model request to this call, recorded with the rid given; a reject has no effect. */
|
|
2026
|
-
const requestModel = async (rid,
|
|
2027
|
+
const requestModel = async (rid, choice, hash, cond) => {
|
|
2028
|
+
let model = choice;
|
|
2027
2029
|
let body;
|
|
2028
2030
|
const exec = current(ctx.journal, dest);
|
|
2029
2031
|
// P28: with no live execution (not started yet, between executions, hibernated while asking) the model is
|
|
@@ -2067,7 +2069,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2067
2069
|
if (!idle && !await reserveSwitch(exec, body.provider, rid))
|
|
2068
2070
|
return { action: "reject", reason: "provider-full" };
|
|
2069
2071
|
await note(req.rid, model, idle ? "next-execution" : "next-request", pool);
|
|
2070
|
-
const entry = await ctx.journal.append("forward", { rid, rid2, dest, hash, envelope });
|
|
2072
|
+
const entry = await ctx.journal.append("forward", { rid, rid2, dest, hash, envelope, choice });
|
|
2071
2073
|
await replayForward(entry);
|
|
2072
2074
|
if (idle) {
|
|
2073
2075
|
active.get(dest)?.wake();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Latest surviving manual choice in this generation. Earlier generations already carried theirs into the spec.
|
|
2
|
+
* Delivery consumes the live request, not the choice; a refusal or withdrawal disqualifies the request. Failover
|
|
3
|
+
* never contributes intent, even if its selected model later answers. A revision's entries scope the call identity. */
|
|
4
|
+
export function generationModel(log, call) {
|
|
5
|
+
const refused = new Set(log.filter(e => e.type === "forward-delivered" && e.reason !== undefined).map(e => String(e.rid2)));
|
|
6
|
+
const withdrawn = new Set(log.filter(e => e.type === "forward" && e.dest === call && e.envelope?.kind === "withdraw")
|
|
7
|
+
.flatMap(e => e.envelope.body?.rids ?? []));
|
|
8
|
+
for (let i = log.length - 1; i >= 0; i--) {
|
|
9
|
+
const e = log[i];
|
|
10
|
+
if (e.type === "model-choice" && e.call === call && typeof e.model === "string")
|
|
11
|
+
return e.model;
|
|
12
|
+
if (e.type === "forward" && e.dest === call && typeof e.choice === "string" && !e.failover &&
|
|
13
|
+
e.envelope?.kind === "model" && !refused.has(String(e.rid2)) && !withdrawn.has(String(e.rid2)))
|
|
14
|
+
return e.choice;
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
@@ -7,7 +7,7 @@ import { FANOUT_BODIES } from "../compat/fanout.js";
|
|
|
7
7
|
import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
|
|
8
8
|
import { readCache, writeCache } from "../kernel/cache.js";
|
|
9
9
|
import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
|
|
10
|
-
import { JT, attentionEntries, isEntry } from "../types.js";
|
|
10
|
+
import { JT, askText, attentionEntries, isEntry } from "../types.js";
|
|
11
11
|
import { parseModel, resolveModel } from "../compat/model.js";
|
|
12
12
|
import {} from "./ledger.js";
|
|
13
13
|
import { awaitingRuns, readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
|
|
@@ -153,6 +153,7 @@ function snapshotReducer(wid, entries) {
|
|
|
153
153
|
const sends = new Map(), byRid2 = new Map();
|
|
154
154
|
// Pending notes of the current revision by key (notes.ts): recorded rids, and those a generation carried.
|
|
155
155
|
const notes = new Map(), carried = new Set();
|
|
156
|
+
const choices = new Map();
|
|
156
157
|
function apply(batch, from = 0) {
|
|
157
158
|
for (let i = from; i < batch.length; i++) {
|
|
158
159
|
const e = batch[i];
|
|
@@ -167,6 +168,7 @@ function snapshotReducer(wid, entries) {
|
|
|
167
168
|
const callId = e.type === "reused" ? String(e.from) : `${wid}@${rev}/${key}@${gen}`;
|
|
168
169
|
if (e.type === "generation") {
|
|
169
170
|
generations.add(callId);
|
|
171
|
+
choices.delete(String(e.from));
|
|
170
172
|
for (const rid of Array.isArray(e.notes) ? e.notes : [])
|
|
171
173
|
carried.add(String(rid));
|
|
172
174
|
}
|
|
@@ -181,6 +183,10 @@ function snapshotReducer(wid, entries) {
|
|
|
181
183
|
phase: result ? "sealed" : "queued", ...(result ? { result, endedAt: e.ts } : {}),
|
|
182
184
|
...(e.type === "refused" ? { refused: String(e.reason) } : {}), ...(e.type === "reused" ? { reused: String(e.from) } : {}) });
|
|
183
185
|
}
|
|
186
|
+
else if (e.type === "model-choice") {
|
|
187
|
+
if (typeof e.model === "string" && calls.has(String(e.call)))
|
|
188
|
+
choices.set(String(e.call), e.model);
|
|
189
|
+
}
|
|
184
190
|
else if (e.type === PENDING_NOTE) {
|
|
185
191
|
if (boundary >= 0 && e.seq < entries[boundary].seq)
|
|
186
192
|
continue;
|
|
@@ -457,7 +463,10 @@ function snapshotReducer(wid, entries) {
|
|
|
457
463
|
else if (last && last.state !== "retired" && last.model !== (c.virtualModel ? c.selectedModel : c.model)?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
|
|
458
464
|
c.switching = last.model;
|
|
459
465
|
}
|
|
460
|
-
|
|
466
|
+
// A sealed choice has not been used yet; retain the last actual model and expose the intent separately.
|
|
467
|
+
if (choices.has(c.callId) && !retired.has(c.callId))
|
|
468
|
+
c.switching = choices.get(c.callId);
|
|
469
|
+
const selected = c.phase === "sealed" ? c.selectedModel : c.switching ?? c.selectedModel;
|
|
461
470
|
if (c.usedModel && c.virtualModel)
|
|
462
471
|
c.routedModel = c.usedModel;
|
|
463
472
|
else if (c.usedModel && selected && c.usedModel.toLowerCase() !== selected.toLowerCase())
|
|
@@ -1183,7 +1192,7 @@ export function compactWorkflow(wf, leases) {
|
|
|
1183
1192
|
...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
|
|
1184
1193
|
...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}) };
|
|
1185
1194
|
}),
|
|
1186
|
-
attention: wf.attention.map(a => ({ id: a.id, rev: a.rev, kind: a.kind, text: clip(a.text, 300), ...(a.call ? { call: a.call } : {}), ...(a.qid ? { qid: a.qid } : {}) })),
|
|
1195
|
+
attention: wf.attention.map(a => ({ id: a.id, rev: a.rev, kind: a.kind, text: clip(a.text, 300), ...(a.call ? { call: a.call } : {}), ...(a.qid ? { qid: a.qid } : {}), ...(a.decision_needed !== undefined ? { decision_needed: clip(a.decision_needed, 300), ...(a.options !== undefined ? { options: a.options } : {}) } : {}) })),
|
|
1187
1196
|
...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}), ...(wf.labels ? { labels: wf.labels } : {}),
|
|
1188
1197
|
};
|
|
1189
1198
|
}
|
|
@@ -1379,7 +1388,7 @@ export function statusBrief(home, options = {}) {
|
|
|
1379
1388
|
...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(live && c.queuedFor && !w.paused ? { queued: queuedText(c.queuedFor, now) } : {}) };
|
|
1380
1389
|
});
|
|
1381
1390
|
const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
|
|
1382
|
-
...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
|
|
1391
|
+
...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300), ...(a.decision_needed !== undefined ? { rev: a.rev, decision_needed: clip(a.decision_needed, 300) } : {}) }));
|
|
1383
1392
|
const alerts = open.filter(a => a.kind !== "question").map(a => `${a.kind}${a.call ? ` ${w.wid}/${callKey(a.call)}` : ""}: ${clip(a.text, 200)}`);
|
|
1384
1393
|
return { wid: w.wid, ...(w.labels ? { labels: labelsText(w.labels) } : {}), ...(w.name ? { name: w.name } : {}), status: w.status, ...(w.active ? { active: true } : {}), ...(w.paused ? { paused: true } : {}), ...(w.followUps ? { followUps: w.followUps } : {}),
|
|
1385
1394
|
progress: `${p.done}/${p.total}${p.plus ? "+" : ""}`, tokens: tokens(w.usage), calls,
|
|
@@ -1398,6 +1407,34 @@ export function statusBrief(home, options = {}) {
|
|
|
1398
1407
|
hint: "status wid=<wid> shows one workflow (outputs clipped); add key=<key> for one call's full result, or full:true for everything",
|
|
1399
1408
|
};
|
|
1400
1409
|
}
|
|
1410
|
+
/** AK4/R-12-AK-3: render only the projection's own question entries, never business result/data/output. */
|
|
1411
|
+
export function statusText(home, value) {
|
|
1412
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
1413
|
+
const workflow = (v) => {
|
|
1414
|
+
if (!object(v) || typeof v.wid !== 'string')
|
|
1415
|
+
return v;
|
|
1416
|
+
const wid = v.wid;
|
|
1417
|
+
let questions;
|
|
1418
|
+
const items = (list, brief) => !Array.isArray(list) ? list : list.map(item => {
|
|
1419
|
+
if (!object(item) || item.decision_needed === undefined || (!brief && item.kind !== 'question'))
|
|
1420
|
+
return item;
|
|
1421
|
+
// Brief drops the attention id/call; its address, qid and revision still identify the original question.
|
|
1422
|
+
const q = (questions ??= workflowSnapshot(home, wid).attention).find(q => q.kind === 'question' && q.decision_needed !== undefined &&
|
|
1423
|
+
q.qid === item.qid && q.rev === item.rev && (brief
|
|
1424
|
+
? q.call !== undefined && item.to === `${wid}/${callKey(q.call)}`
|
|
1425
|
+
: q.id === item.id && q.call === item.call));
|
|
1426
|
+
return q ? { ...item, [brief ? 'question' : 'text']: askText(q, q.text) } : item;
|
|
1427
|
+
});
|
|
1428
|
+
return { ...v, ...(Array.isArray(v.attention) ? { attention: items(v.attention, false) } : {}),
|
|
1429
|
+
...(Array.isArray(v.asking) ? { asking: items(v.asking, true) } : {}) };
|
|
1430
|
+
};
|
|
1431
|
+
if (!object(value))
|
|
1432
|
+
return JSON.stringify(value);
|
|
1433
|
+
// These are the only workflow containers produced by status. Do not walk calls, result or arbitrary nesting.
|
|
1434
|
+
return JSON.stringify({ ...workflow(value),
|
|
1435
|
+
...(Array.isArray(value.active) ? { active: value.active.map(workflow) } : {}),
|
|
1436
|
+
...(Array.isArray(value.workflows) ? { workflows: value.workflows.map(workflow) } : {}) });
|
|
1437
|
+
}
|
|
1401
1438
|
/** Running workflows of other sessions that a pause holds, as "wid" or "wid (name)": a session's own resume skips them. */
|
|
1402
1439
|
export function pausedElsewhere(home, origin) {
|
|
1403
1440
|
return snapshots(home, origin).all.filter(w => w.paused && w.origin !== origin && !settled(w)).map(w => w.name ? `${w.wid} (${w.name})` : w.wid);
|
|
@@ -1545,6 +1582,9 @@ export function eventsFromEntries(entries) {
|
|
|
1545
1582
|
case "hibernated":
|
|
1546
1583
|
add(e, "hibernated", { call: e.call, qid: e.qid });
|
|
1547
1584
|
break;
|
|
1585
|
+
case "model-choice":
|
|
1586
|
+
add(e, "model-choice", { rid: e.rid, call: e.call, model: e.model, effect: "next-generation" });
|
|
1587
|
+
break;
|
|
1548
1588
|
case "forward": {
|
|
1549
1589
|
forwards.set(String(e.rid2), e);
|
|
1550
1590
|
// A model switch names its target, and a failover (the executor moved the call off a used-up provider) its source.
|
package/dist/types.js
CHANGED
|
@@ -56,6 +56,17 @@ export const JT = {
|
|
|
56
56
|
rejected: "rejected",
|
|
57
57
|
withdrawn: "withdrawn",
|
|
58
58
|
};
|
|
59
|
+
export const ASK_FIELDS = ['decision_needed', 'options', 'facts', 'tried', 'classification_candidates'];
|
|
60
|
+
/** Copy only present metadata, never inserting defaults into old records. */
|
|
61
|
+
export function askFields(value) {
|
|
62
|
+
return Object.fromEntries(ASK_FIELDS.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
63
|
+
}
|
|
64
|
+
/** Parent-facing text; the stored question and machine-facing text remain unchanged. */
|
|
65
|
+
export function askText(value, question) {
|
|
66
|
+
if (value.decision_needed === undefined)
|
|
67
|
+
return question;
|
|
68
|
+
return [value.decision_needed, ...(value.options ?? []).map((o, i) => `${i + 1}. ${o.label}${o.preferred ? ' (preferred)' : ''}`), question].join('\n');
|
|
69
|
+
}
|
|
59
70
|
/** A command call (CallSpec.command): no agent, task or model at runtime even though the type declares them. */
|
|
60
71
|
export const isCommandCall = (spec) => spec?.command !== undefined;
|
|
61
72
|
// ---------------------------------------------------------------------------
|
|
@@ -68,6 +79,7 @@ export const ENV = {
|
|
|
68
79
|
inbox: "DSA_INBOX", // absolute path of this call's inbox dir
|
|
69
80
|
journal: "DSA_JOURNAL", // absolute path of the workflow journal (read-only snapshot for the launch gate)
|
|
70
81
|
schema: "DSA_SCHEMA", // absolute path of report JSON schema, if any
|
|
82
|
+
askRequireDecision: "DSA_ASK_REQUIRE_DECISION", // execution-start snapshot of config.askRequireDecision (default false)
|
|
71
83
|
budget: "DSA_BUDGET", // JSON {tokens?, costUsd?}: per-call budget; the child refuses the next provider request once reached (P31b)
|
|
72
84
|
model: "DSA_MODEL", // "provider/id" the executor holds a slot for; the child re-applies it if pi started without it (C8)
|
|
73
85
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-durable-subagents",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
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",
|