@llblab/pi-kit 0.1.13 → 0.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +2 -2
  3. package/node_modules/@llblab/pi-actors/AGENTS.md +5 -3
  4. package/node_modules/@llblab/pi-actors/BACKLOG.md +1 -1
  5. package/node_modules/@llblab/pi-actors/CHANGELOG.md +15 -0
  6. package/node_modules/@llblab/pi-actors/README.md +5 -3
  7. package/node_modules/@llblab/pi-actors/dist/index.js +4 -1
  8. package/node_modules/@llblab/pi-actors/dist/lib/async-runs.d.ts +2 -2
  9. package/node_modules/@llblab/pi-actors/dist/lib/async-runs.js +42 -19
  10. package/node_modules/@llblab/pi-actors/dist/lib/extension-runtime.d.ts +2 -1
  11. package/node_modules/@llblab/pi-actors/dist/lib/extension-runtime.js +7 -2
  12. package/node_modules/@llblab/pi-actors/dist/lib/limits.d.ts +9 -0
  13. package/node_modules/@llblab/pi-actors/dist/lib/limits.js +9 -0
  14. package/node_modules/@llblab/pi-actors/dist/lib/observability.d.ts +10 -11
  15. package/node_modules/@llblab/pi-actors/dist/lib/observability.js +81 -56
  16. package/node_modules/@llblab/pi-actors/dist/lib/pi.d.ts +31 -0
  17. package/node_modules/@llblab/pi-actors/dist/lib/pi.js +180 -0
  18. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery.d.ts +115 -0
  19. package/node_modules/@llblab/pi-actors/dist/lib/run-delivery.js +623 -0
  20. package/node_modules/@llblab/pi-actors/dist/lib/run-ui-runtime.d.ts +3 -0
  21. package/node_modules/@llblab/pi-actors/dist/lib/run-ui-runtime.js +341 -13
  22. package/node_modules/@llblab/pi-actors/dist/lib/runs-trace.d.ts +1 -1
  23. package/node_modules/@llblab/pi-actors/dist/lib/runs-trace.js +5 -3
  24. package/node_modules/@llblab/pi-actors/dist/lib/session-evidence.d.ts +16 -0
  25. package/node_modules/@llblab/pi-actors/dist/lib/session-evidence.js +143 -0
  26. package/node_modules/@llblab/pi-actors/dist/lib/temp.js +1 -1
  27. package/node_modules/@llblab/pi-actors/dist/lib/tools-inspect.js +3 -1
  28. package/node_modules/@llblab/pi-actors/dist/scripts/async-runner.mjs +5 -19
  29. package/node_modules/@llblab/pi-actors/dist/skills/actors/SKILL.md +2 -2
  30. package/node_modules/@llblab/pi-actors/dist/skills/actors/references/runs.md +1 -1
  31. package/node_modules/@llblab/pi-actors/dist/skills/swarm/SKILL.md +1 -1
  32. package/node_modules/@llblab/pi-actors/docs/README.md +1 -0
  33. package/node_modules/@llblab/pi-actors/docs/async-runs.md +8 -4
  34. package/node_modules/@llblab/pi-actors/docs/coordinator-delivery.md +207 -0
  35. package/node_modules/@llblab/pi-actors/index.ts +4 -1
  36. package/node_modules/@llblab/pi-actors/lib/async-runs.ts +42 -21
  37. package/node_modules/@llblab/pi-actors/lib/extension-runtime.ts +8 -3
  38. package/node_modules/@llblab/pi-actors/lib/limits.ts +9 -0
  39. package/node_modules/@llblab/pi-actors/lib/observability.ts +97 -78
  40. package/node_modules/@llblab/pi-actors/lib/pi.ts +210 -0
  41. package/node_modules/@llblab/pi-actors/lib/run-delivery.ts +800 -0
  42. package/node_modules/@llblab/pi-actors/lib/run-ui-runtime.ts +370 -18
  43. package/node_modules/@llblab/pi-actors/lib/runs-trace.ts +6 -4
  44. package/node_modules/@llblab/pi-actors/lib/session-evidence.ts +153 -0
  45. package/node_modules/@llblab/pi-actors/lib/temp.ts +1 -1
  46. package/node_modules/@llblab/pi-actors/lib/tools-inspect.ts +4 -1
  47. package/node_modules/@llblab/pi-actors/package.json +3 -3
  48. package/node_modules/@llblab/pi-actors/scripts/async-runner.mjs +5 -19
  49. package/node_modules/@llblab/pi-actors/skills/actors/SKILL.md +2 -2
  50. package/node_modules/@llblab/pi-actors/skills/actors/references/runs.md +1 -1
  51. package/node_modules/@llblab/pi-actors/skills/swarm/SKILL.md +1 -1
  52. package/node_modules/@llblab/pi-telegram/AGENTS.md +4 -4
  53. package/node_modules/@llblab/pi-telegram/CHANGELOG.md +11 -0
  54. package/node_modules/@llblab/pi-telegram/README.md +1 -1
  55. package/node_modules/@llblab/pi-telegram/docs/activity.md +4 -4
  56. package/node_modules/@llblab/pi-telegram/docs/architecture.md +5 -5
  57. package/node_modules/@llblab/pi-telegram/docs/outbound.md +2 -2
  58. package/node_modules/@llblab/pi-telegram/docs/public-api.md +3 -4
  59. package/node_modules/@llblab/pi-telegram/docs/ui-style.md +4 -5
  60. package/node_modules/@llblab/pi-telegram/docs/voice.md +12 -2
  61. package/node_modules/@llblab/pi-telegram/index.ts +0 -1
  62. package/node_modules/@llblab/pi-telegram/lib/activity.ts +3 -5
  63. package/node_modules/@llblab/pi-telegram/lib/bindings.ts +13 -17
  64. package/node_modules/@llblab/pi-telegram/lib/bus-leader.ts +1 -1
  65. package/node_modules/@llblab/pi-telegram/lib/config.ts +25 -25
  66. package/node_modules/@llblab/pi-telegram/lib/menu-settings.ts +10 -73
  67. package/node_modules/@llblab/pi-telegram/lib/status.ts +11 -1
  68. package/node_modules/@llblab/pi-telegram/package.json +1 -1
  69. package/node_modules/@llblab/pi-telegram/skills/generated-control-surface/SKILL.md +5 -3
  70. package/package.json +3 -3
@@ -284,9 +284,6 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
284
284
  complete_allowed: missing.length === 0,
285
285
  };
286
286
  }
287
- function getCommandDoneDelivery(result) {
288
- return result.code !== 0 || activeSubagents > 0 ? "followup" : "log";
289
- }
290
287
  function progressRunning() {
291
288
  progress("running", {
292
289
  activeSubagents,
@@ -433,21 +430,6 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
433
430
  ...(preflightDiagnostic ? { preflight: preflightDiagnostic } : {}),
434
431
  });
435
432
  }
436
- event("command.done", {
437
- activeSubagents,
438
- command_id: commandId,
439
- code: result.code,
440
- command: commandDetail,
441
- killed: result.killed,
442
- ...captureDetails(result),
443
- ...(materialized.promptFile ? { prompt_file: materialized.promptFile } : {}),
444
- ...(materialized.promptBytes ? { prompt_bytes: materialized.promptBytes } : {}),
445
- ...(session.sessionDir ? { session_dir: relative(stateDir, session.sessionDir).replaceAll("\\", "/") } : {}),
446
- ...(commandSessionFiles(session.sessionDir).length > 0
447
- ? { session_files: commandSessionFiles(session.sessionDir) }
448
- : {}),
449
- ...(preflightDiagnostic ? { preflight: preflightDiagnostic } : {}),
450
- });
451
433
  observation(
452
434
  "command.done",
453
435
  `Command ${summarizeCommandDetail(commandDetail)} completed with code ${result.code}`,
@@ -462,9 +444,13 @@ export async function runAsyncRunner(stateDir = process.argv[2]) {
462
444
  ...captureDetails(result),
463
445
  ...(materialized.promptFile ? { prompt_file: materialized.promptFile } : {}),
464
446
  ...(materialized.promptBytes ? { prompt_bytes: materialized.promptBytes } : {}),
447
+ ...(session.sessionDir ? { session_dir: relative(stateDir, session.sessionDir).replaceAll("\\", "/") } : {}),
448
+ ...(commandSessionFiles(session.sessionDir).length > 0
449
+ ? { session_files: commandSessionFiles(session.sessionDir) }
450
+ : {}),
465
451
  ...(preflightDiagnostic ? { preflight: preflightDiagnostic } : {}),
466
452
  },
467
- getCommandDoneDelivery(result),
453
+ "log",
468
454
  result.code === 0 ? "info" : "error",
469
455
  );
470
456
  progressRunning();
@@ -85,7 +85,7 @@ There are two distinct multi-instance shapes:
85
85
 
86
86
  In host-coordinator mode, the top-level agent receives declarative outcomes, preserves user authority and global context, delegates bounded concrete execution, and owns integration plus final validation. It is not merely another worker after delegation begins. One bounded implementation worker normally runs with reasoning off; consequential output receives a separate reasoning-enabled review. Several independent participants or reviewers additionally use `swarm`.
87
87
 
88
- Delegation is not mandatory for every prompt. Work inline when one short bounded act has one natural validation boundary and spawning would add more coordination than isolation, latency hiding, clean context, or continued coordinator availability can repay. For admitted delegation, prefer terminal follow-up and durable Trace/artifacts; inspect on meaningful attention, operator request, or an evidence-based overdue timer rather than busy polling.
88
+ Delegation is not mandatory for every prompt. Work inline when one short bounded act has one natural validation boundary and spawning would add more coordination than isolation, latency hiding, clean context, or continued coordinator availability can repay. For admitted delegation, prefer the settled completion batch and durable Trace/artifacts; inspect on meaningful attention, operator request, or an evidence-based overdue timer rather than busy polling. Treat `attention: "steer"` as an actor-authored urgent semantic checkpoint at Pi's next safe boundary, never as a status-derived completion signal; the later root terminal still arrives through its ordinary completion batch.
89
89
 
90
90
  ## Run workflow
91
91
 
@@ -97,7 +97,7 @@ Run = Recipe + Trace + Control
97
97
  ```
98
98
 
99
99
  1. Spawn with the exact logical Recipe identity and caller-owned values.
100
- 2. Retain the returned `run:<id>` and normally wait for terminal follow-up instead of polling.
100
+ 2. Retain the returned `run:<id>` and normally wait for its settled completion batch instead of polling.
101
101
  3. Inspect `view=trace` when retained observations or attention matter.
102
102
  4. Inspect `view=control` before diagnosing service readiness, stale work, or saturation.
103
103
  5. Send `message` only for an action declared and consumed by that controlled Recipe.
@@ -14,7 +14,7 @@ A rare Skill Recipe may declare `singleton: true`. Do not pass `as`: the runtime
14
14
 
15
15
  ## Observe
16
16
 
17
- Normally wait for terminal follow-up. Inspect only when requested, when meaningful attention arrives, or when the Run is overdue or blocked:
17
+ Normally wait for the settled completion batch. Inspect only when requested, when meaningful attention arrives, or when the Run is overdue or blocked:
18
18
 
19
19
  ```text
20
20
  inspect target=run:<id> view=recipe
@@ -15,7 +15,7 @@ A swarm can be coordinated without an external gateway. In this model the curren
15
15
 
16
16
  This resembles gateway orchestration in dependency direction but not in ownership: the coordinator is itself an agent instance with inspectable Runs, not an infrastructure service that implicitly creates sessions. Preserve that distinction in prompts, docs, recovery, and target routing.
17
17
 
18
- Once work is delegated, keep the coordinator available for decisions and integration instead of duplicating participant implementation. Wait for terminal follow-up by default; use meaningful attention or evidence-based timers for overdue work rather than a tight inspection loop.
18
+ Once work is delegated, keep the coordinator available for decisions and integration instead of duplicating participant implementation. Wait for the settled completion batch by default; use meaningful attention or evidence-based timers for overdue work rather than a tight inspection loop.
19
19
 
20
20
  ## Reasoning allocation
21
21
 
@@ -7,6 +7,7 @@ Living index of all documentation in the `/docs` directory.
7
7
  - [command-templates.md](./command-templates.md) — Portable synchronous command execution standard
8
8
  - [template-recipes.md](./template-recipes.md) — Saved JSON/Markdown recipe standard, imports, and reusable command-template graph composition
9
9
  - [async-runs.md](./async-runs.md) — Run lifecycle, state, Control, Trace, cancellation, and terminal reconciliation
10
+ - [coordinator-delivery.md](./coordinator-delivery.md) — Accepted next-minor design for durable terminal batching and explicit urgent Pi steering
10
11
  - [actor-inspector.md](./actor-inspector.md) — Owner-filtered actor-instance navigation through Recipe, Trace, and Control
11
12
  - [inspection.md](./inspection.md) — Complete `inspect` target/view matrix, authorization boundaries, and diagnostic routes
12
13
  - [tool-registry.md](./tool-registry.md) — Local `pi-actors` registry storage and `register_tool` adaptation
@@ -52,12 +52,14 @@ diagnostics.jsonl
52
52
  Trace records strict bounded events:
53
53
 
54
54
  ```json
55
- {"id":"…","ts":"…","kind":"command.done","summary":"Command completed","data":{"code":0},"level":"info","attention":"followup"}
55
+ {"id":"…","ts":"…","kind":"command.done","summary":"Command completed","data":{"code":0},"level":"info"}
56
+ {"id":"…","ts":"…","kind":"checkpoint.ready","summary":"Review needs a decision","level":"info","attention":"followup"}
57
+ {"id":"…","ts":"…","kind":"checkpoint.blocked","summary":"Approval required before migration","level":"warning","attention":"steer"}
56
58
  ```
57
59
 
58
60
  Required fields: `id`, `ts`, `kind`. Optional fields: `summary`, `data`, `level`, `attention`. Trace rejects addressed-envelope fields and malformed or oversized data. It retains a recent suffix within 2,048 events and 4 MiB. When either bound would be exceeded, the canonical lock atomically keeps a newest suffix near the lower targets, the new event, and one cumulative warning-only `runtime.trace_compacted` marker. The marker means older history was discarded; it reports cumulative drop evidence and never requests attention.
59
61
 
60
- Runtime lifecycle, runner progress, command completion, cancellation, kill, parent teardown, and controlled-service observations use Trace. Bounded reads preserve complete UTF-8 lines and disclose omitted legacy prefixes. `inspect view=trace` reports retained-history completeness and projects events with Controls, owned Pi turns, logs, results, artifacts, and diagnostics newest-first. Equal timestamps use same-source physical order, then fixed source rank and stable id without claiming cross-source causality. Terminal state, `result.json`, `execution.json`, and artifacts remain authoritative even when old Trace has compacted.
62
+ Runtime lifecycle, runner progress, command completion, cancellation, kill, parent teardown, and controlled-service observations use Trace. Generic command lifecycle is Trace-only: runner-owned `command.done` records preserve level, captures, session provenance, and execution evidence but never request or project attention, even if malformed legacy evidence carries `steer`. No Recipe field configures command-completion delivery. Semantic checkpoints opt in explicitly: `attention: "notify"` is visible status, `attention: "followup"` supplies ordinary checkpoint context, and `attention: "steer"` requests urgent delivery at Pi's next safe assistant/tool boundary. Steer is never inferred from exit status; its exact Run generation and event id enter the bounded owner journal before Pi delivery, recover through owned session evidence, and require exact model-bound context acknowledgment. Presentation appends a generation-fenced non-attention `delivery.steer_presented` Trace marker so historical retained steer events cannot replay after bounded owner receipts rotate. The eventual root terminal remains independently eligible for its completion batch. Bounded reads preserve complete UTF-8 lines and disclose omitted legacy prefixes. `inspect view=trace` reports retained-history completeness and projects events with Controls, owned Pi turns, logs, results, artifacts, and diagnostics newest-first. Equal timestamps use same-source physical order, then fixed source rank and stable id without claiming cross-source causality. Terminal state, `result.json`, `execution.json`, and artifacts remain authoritative even when old Trace has compacted.
61
63
 
62
64
  ## Control
63
65
 
@@ -106,9 +108,11 @@ Review acceptance remains a command-stage concern. General execution evidence do
106
108
 
107
109
  Statuses include `running`, `done`, `failed`, `exited`, `cancelled`, and `killed`. Status resolution combines persisted metadata, result/terminal evidence, and verified process state.
108
110
 
109
- Ambient observation detects terminal transitions and retained Trace attention. Canonical attention is an in-memory wake hint, not a durable queue: observers prime retained ids at startup, deliver each later retained unseen id once, and bound memory to the current retained set across compaction. Persist durable recovery state or an artifact before emitting attention; compaction may discard older hints and its marker makes that history loss explicit. Terminal follow-up delivery persists handled/failure evidence so reloads retry unhandled transitions without duplicating completed notifications.
111
+ Ambient observation detects root terminal transitions and explicit retained Trace attention. Terminal transitions reconcile before semantic attention. Canonical attention is an in-memory wake hint, not a durable queue: observers prime retained ids at startup, deliver each later retained unseen id once, and bound memory to the current retained set across compaction. Persist durable recovery state or an artifact before emitting attention; compaction may discard older hints and its marker makes that history loss explicit. Terminal follow-up delivery persists handled/failure evidence so reloads retry unhandled transitions without duplicating completed notifications.
110
112
 
111
- Large semantic results stay outside compact visible follow-up text and remain available in structured details, execution captures, or artifacts.
113
+ Ordinary finite Runs project root terminal results through one completion scheduler. Eligible terminals remain authoritative in Run state while Pi is active; after `agent_settled`, session recovery, or an idle debounce, the scheduler snapshots at most 256 exact generations into one owner-fenced immutable batch. One batch causes one automatic agent turn, exposes at most 64 bounded model-facing rows, and marks member terminals handled only after the exact batch id and content appear in model-bound Pi context. Pending send failures retain bounded retry evidence. On restart, queued recovery inspects only a bounded active Pi session parent chain: exact message evidence waits for presentation without resend, proven absence returns the same batch to pending, and incomplete or conflicting evidence stays queued with a diagnostic. Duplicate exact context envelopes collapse before presentation.
114
+
115
+ Sequence, parallel, repeat, and imported branches are internal execution topology and never own branch-level turns. Each separately launched Run owns its own generation and terminal lifecycle; compatible singleton reuse is not a new launch. Explicit semantic attention may intentionally add a checkpoint turn; Runs marked silent and synchronously acknowledged stop outcomes suppress automatic projection. Large semantic results stay outside compact completion rows and remain available in structured details, execution captures, or artifacts.
112
116
 
113
117
  ## Cancellation and Kill
114
118
 
@@ -0,0 +1,207 @@
1
+ # Coordinator Delivery Scheduler
2
+
3
+ Status: Accepted next-minor design. Implementation is in progress; public delivery behavior remains unchanged until the complete acceptance boundary passes.
4
+
5
+ ## Goal
6
+
7
+ Separate durable Run completion truth from the scheduling of model turns:
8
+
9
+ ```text
10
+ one Run generation -> one root terminal record
11
+ one bounded completion epoch -> one coordinator turn
12
+ ```
13
+
14
+ Ordinary root terminals accumulate while Pi is active and reach the coordinator in one bounded batch after Pi settles. Only an explicitly actor-authored urgent semantic checkpoint may steer an active agent loop.
15
+
16
+ ## Non-Goals
17
+
18
+ - Do not interrupt generation mid-token.
19
+ - Do not stream generic progress or Command lifecycle into model context.
20
+ - Do not infer urgency from exit codes, failure status, artifacts, branch position, or active subagent counts.
21
+ - Do not change Run, Recipe, Trace, Control, artifact, generation, ownership, or Inspect authority.
22
+ - Do not add transport-specific behavior or restore Recipe-level Command delivery grammar.
23
+
24
+ ## Delivery Classes
25
+
26
+ - Generic Trace and runner-owned `command.done` remain Trace-only.
27
+ - `attention: "notify"` remains visible UI status without a model turn.
28
+ - `attention: "followup"` retains its existing explicit semantic follow-up behavior.
29
+ - New `attention: "steer"` requests urgent semantic delivery at Pi's next safe assistant/tool boundary.
30
+ - Root terminal transitions enter durable completion batching instead of sending one follow-up per Run.
31
+
32
+ `command.done` remains non-projectable even if malformed or legacy Trace attaches any attention value.
33
+
34
+ ## Ownership
35
+
36
+ - Run terminal state remains completion truth; the absence of `terminal-handled.json` makes that generation eligible for projection.
37
+ - `runs-trace.ts` owns admission of the new `steer` attention value.
38
+ - `observability.ts` discovers terminal candidates and explicit semantic attention without deciding Pi delivery timing.
39
+ - A new `run-delivery.ts` domain owns the owner-scoped delivery journal, batch construction, bounds, phases, formatting, recovery, and acknowledgments.
40
+ - `run-ui-runtime.ts` owns idle detection, debounce, reconciliation, flushing, and stale-context containment.
41
+ - `extension-runtime.ts` orders completion flushes before automatic Recipe review.
42
+ - `index.ts` remains a thin registration root and adds only the required Pi lifecycle adapter.
43
+ - `pi.ts` exposes narrow ports for batched follow-up and urgent steer delivery.
44
+
45
+ The local TypeScript dependency graph must remain acyclic. No public tool, target, view, Recipe field, or transport contract is added by default.
46
+
47
+ ## Durable Delivery State
48
+
49
+ Store one journal per exact coordinator owner under an internal path derived from a safe owner hash:
50
+
51
+ ```text
52
+ <extension-temp>/delivery/<owner-hash>/projection.json
53
+ ```
54
+
55
+ The journal records the exact internal owner and contains at most one active completion batch plus a bounded set of unpresented urgent steer envelopes.
56
+
57
+ Completion batch shape:
58
+
59
+ ```json
60
+ {
61
+ "batch_id": "uuid",
62
+ "owner_id": "exact internal owner",
63
+ "phase": "pending",
64
+ "members": [
65
+ {
66
+ "run": "review-a",
67
+ "run_instance_id": "generation-id",
68
+ "status": "done",
69
+ "state_dir": "internal path"
70
+ }
71
+ ],
72
+ "created_at": "timestamp"
73
+ }
74
+ ```
75
+
76
+ Phases are monotonic:
77
+
78
+ 1. `pending`: The exact member snapshot is durable but no Pi message has been accepted.
79
+ 2. `queued`: Pi accepted a custom message carrying the exact batch or steer ID.
80
+ 3. `presented`: A Pi `context` event observed that ID in messages being supplied to an LLM call.
81
+
82
+ Every journal mutation uses the canonical token-owned lock, expected-phase fencing, owner and generation validation, and atomic replacement. Repeated transitions are idempotent. Corrupt, oversized, foreign-owner, or stale-generation state fails closed with bounded diagnostics.
83
+
84
+ A queued envelope is not treated as presented merely because `sendMessage()` returned. Only presentation marks completion members through their existing terminal-handled authority. If a member was synchronously archived or pruned after queueing, the bounded delivery snapshot remains sufficient and the missing state write becomes a diagnostic rather than invalidating the batch.
85
+
86
+ ## Completion Collection
87
+
88
+ Reconciliation admits unhandled root terminal generations with status `done`, `failed`, `killed`, or `exited`.
89
+
90
+ It excludes:
91
+
92
+ - Runs with silent notification policy;
93
+ - synchronous stop or cancel outcomes already acknowledged by their caller;
94
+ - handled terminal generations;
95
+ - internal composition branches;
96
+ - every Command lifecycle event.
97
+
98
+ Candidates sort by terminal timestamp, then stable Run identity, then `run_instance_id`. Replacement generations with the same logical Run id remain distinct internal members.
99
+
100
+ While `ctx.isIdle()` is false, candidates remain durable in their Run state and no terminal follow-up is sent. A flush snapshots eligible candidates into one immutable batch. While that batch remains unpresented, newer terminals stay unhandled for the next bounded completion epoch.
101
+
102
+ ## Batch Flush
103
+
104
+ Flush one batch when:
105
+
106
+ 1. `agent_settled` fires for the still-active context and `ctx.isIdle()` remains true;
107
+ 2. terminals arrive while Pi is already idle and survive one short debounce window;
108
+ 3. session restoration discovers unhandled terminal generations or recoverable queued delivery state.
109
+
110
+ The model-facing custom message uses `customType: "pi-actors-run-batch"`, `deliverAs: "followUp"`, and `triggerTurn: true`. It includes:
111
+
112
+ - batch ID and completion window;
113
+ - counts by terminal status;
114
+ - stable Run, status, compact semantic summary, and bounded artifact rows;
115
+ - explicit overflow evidence and the canonical runtime Inspect route.
116
+
117
+ The journal may retain at most 256 members and 1 MiB. Model-facing content lists at most 64 exact rows within the centralized model-output bound. Additional members remain represented by exact status counts and supported Inspect guidance. More than 256 unhandled generations form a later batch rather than being discarded.
118
+
119
+ Completion member details remain redacted through existing terminal projection rules: no raw model policy, secrets, private Recipe paths, or machine-local source paths enter the message.
120
+
121
+ ## Presentation Acknowledgment And Recovery
122
+
123
+ Register a `context` lifecycle adapter that scans model-bound messages for exact pi-actors batch and steer IDs. On a matching active-owner envelope it atomically:
124
+
125
+ 1. moves the envelope to `presented`;
126
+ 2. marks every still-present member generation terminal-handled;
127
+ 3. records a non-attention `delivery.steer_presented` marker in the exact Run generation for a presented steer;
128
+ 4. retains a bounded owner receipt sufficient for near-term deduplication and diagnostics.
129
+
130
+ The generation-fenced Trace marker prevents a retained historical steer from replaying after bounded owner receipts rotate: suffix compaction cannot retain the older steer while discarding its newer presentation marker. Missing, archived, pruned, or replaced Run state needs no marker because it can no longer replay that original generation.
131
+
132
+ Recovery rules:
133
+
134
+ - Send failure: keep `pending`, record failure evidence, and retry.
135
+ - Crash after queueing: inspect existing owned Pi session evidence for the exact custom message ID.
136
+ - Queued message exists: do not resend; wait for `context` presentation.
137
+ - Queued message is absent: return the envelope to `pending`.
138
+ - Presented envelope: never resend.
139
+ - Session or context replacement: close timers and callbacks; never deliver through stale context.
140
+ - Owner mismatch: do not inspect, acknowledge, or deliver the envelope.
141
+
142
+ Session evidence inspection must reuse the existing bounded owned-session readers rather than adding raw unbounded session parsing.
143
+
144
+ ## Explicit Urgent Steer
145
+
146
+ Extend canonical Trace attention with `"steer"`:
147
+
148
+ ```json
149
+ {
150
+ "kind": "checkpoint.blocked",
151
+ "summary": "Approval required before destructive migration",
152
+ "attention": "steer"
153
+ }
154
+ ```
155
+
156
+ A steer event is:
157
+
158
+ - explicit and actor-authored;
159
+ - admitted to the durable owner delivery journal before Pi delivery;
160
+ - sent through `deliverAs: "steer"` with `triggerTurn: true`;
161
+ - presented only when its exact event ID appears in model-bound `context`;
162
+ - retried after delivery failure without duplicate presentation;
163
+ - independent from the eventual root-terminal batch.
164
+
165
+ Pi steering is a safe-boundary continuation, not token-level interruption: while streaming, Pi delivers it after the current assistant turn finishes its tool calls and before the next LLM call. If Pi is idle, it triggers a new turn immediately.
166
+
167
+ Urgent steer capacity is bounded to 64 unpresented envelopes within the same 1 MiB owner journal. Capacity pressure remains visible and retryable; it never degrades into generic follow-up or drops an admitted envelope silently.
168
+
169
+ ## Settled Lifecycle Ordering
170
+
171
+ `onAgentSettled` must use this order:
172
+
173
+ ```text
174
+ active-context and exact-owner check
175
+ -> completion flush
176
+ -> if a batch was sent, defer automatic Recipe review
177
+ -> batch-triggered model run settles
178
+ -> schedule automatic review only when no batch remains
179
+ ```
180
+
181
+ Another extension may start work during `agent_settled`; recheck `ctx.isIdle()` immediately before sending. A completion/settled race places each generation in either the current immutable batch or the next batch, never both.
182
+
183
+ ## Validation Contract
184
+
185
+ Implementation is complete only when source and packed-extension tests prove:
186
+
187
+ 1. Multiple Runs finishing during one agent run cause no immediate terminal turns and one settled batch.
188
+ 2. Idle completions inside the debounce window form one batch.
189
+ 3. Completion/settled races project every generation exactly once.
190
+ 4. Send failure and restart before queueing retry without a handled marker.
191
+ 5. Restart after queueing but before presentation neither loses nor duplicates the batch.
192
+ 6. Exact `context` presentation acknowledges members atomically and idempotently.
193
+ 7. Replacement generations sharing a Run id remain distinct.
194
+ 8. Silent, stopped, cancelled, handled, and foreign-owner Runs remain excluded.
195
+ 9. Legacy or malformed `command.done` attention, including `steer`, remains non-projectable.
196
+ 10. Explicit steer reaches the next safe Pi boundary once and root terminal still batches later.
197
+ 11. Overflow, corruption, journal backpressure, archive/prune races, and stale contexts fail safely.
198
+ 12. Completion flushing precedes automatic Recipe review.
199
+ 13. Pi 0.84.4 remains the exact minimum source and packed lifecycle baseline.
200
+
201
+ Focused observability and delivery tests precede TypeScript/build/import checks. The acceptance checkpoint then runs full product validation, dependency audit, package dry-run, and ABCd context validation.
202
+
203
+ ## Rollout
204
+
205
+ This is one minor release because durable batching, presentation acknowledgment, lifecycle ordering, and explicit steer share one model-delivery invariant. Do not ship partial batching that marks terminals handled at `sendMessage()` acceptance, and do not ship steer before its durable deduplication path exists.
206
+
207
+ Update README and Run documentation only when implementation establishes the new public behavior. Move the accepted outcome from BACKLOG to CHANGELOG only after complete validation.
@@ -14,7 +14,10 @@ export default function toolRegistryExtension(pi: Pi.ExtensionAPI) {
14
14
  runtime.discoverResources(import.meta.url),
15
15
  );
16
16
  pi.on("session_start", async (_event, ctx) => runtime.onSessionStart(ctx));
17
- pi.on("agent_end", async (_event, ctx) => runtime.onAgentEnd(ctx));
17
+ pi.on("agent_settled", async (_event, ctx) => runtime.onAgentSettled(ctx));
18
+ pi.on("context", async (event, ctx) => ({
19
+ messages: runtime.onContext(event.messages, ctx) as typeof event.messages,
20
+ }));
18
21
  pi.on("session_shutdown", async (event, ctx) =>
19
22
  runtime.onSessionShutdown(event.reason, ctx),
20
23
  );
@@ -1136,30 +1136,51 @@ function stopRun(
1136
1136
  export function markRunTerminalNotificationHandled(
1137
1137
  stateDir: string,
1138
1138
  status: string,
1139
- ): void {
1140
- markTerminalHandled(stateDir, {
1141
- event: "run.notification",
1142
- status,
1143
- });
1139
+ expectedRunInstanceId: string,
1140
+ ): boolean {
1141
+ const releaseLock = RunsStart.acquireStateStartLock(stateDir);
1142
+ try {
1143
+ if (!existsSync(join(stateDir, "run.json"))) return false;
1144
+ const current = getRunStatus(stateDir);
1145
+ if (
1146
+ current.run_instance_id !== expectedRunInstanceId ||
1147
+ current.status !== status
1148
+ ) return false;
1149
+ markTerminalHandled(stateDir, {
1150
+ event: "run.notification",
1151
+ run_instance_id: expectedRunInstanceId,
1152
+ status,
1153
+ });
1154
+ rmSync(join(stateDir, "terminal-delivery-failure.json"), { force: true });
1155
+ return true;
1156
+ } finally {
1157
+ releaseLock();
1158
+ }
1144
1159
  }
1145
1160
 
1146
- export function recordRunTerminalDeliveryFailure(
1161
+ export function markRunSteerPresentationHandled(
1147
1162
  stateDir: string,
1148
- status: string,
1149
- error: unknown,
1150
- ): void {
1151
- const path = join(stateDir, "terminal-delivery-failure.json");
1152
- const previous = readJson(path);
1153
- const message = (error instanceof Error ? error.message : String(error))
1154
- .replaceAll(/\s+/g, " ")
1155
- .trim()
1156
- .slice(0, 500);
1157
- writeJsonAtomic(path, {
1158
- attempts: Math.max(0, Number(previous?.attempts ?? 0)) + 1,
1159
- error: message || "unknown delivery failure",
1160
- status,
1161
- ts: new Date().toISOString(),
1162
- });
1163
+ expectedRunInstanceId: string,
1164
+ eventId: string,
1165
+ steerId: string,
1166
+ ): boolean {
1167
+ const releaseLock = RunsStart.acquireStateStartLock(stateDir);
1168
+ try {
1169
+ if (!existsSync(join(stateDir, "run.json"))) return false;
1170
+ const current = getRunStatus(stateDir);
1171
+ if (current.run_instance_id !== expectedRunInstanceId) return false;
1172
+ appendRunTraceEvent(stateDir, {
1173
+ data: {
1174
+ event_id: eventId,
1175
+ run_instance_id: expectedRunInstanceId,
1176
+ steer_id: steerId,
1177
+ },
1178
+ kind: "delivery.steer_presented",
1179
+ });
1180
+ return true;
1181
+ } finally {
1182
+ releaseLock();
1183
+ }
1163
1184
  }
1164
1185
 
1165
1186
  export function cancelRun(
@@ -25,7 +25,8 @@ export interface ActorExtensionRuntime {
25
25
  ): { systemPrompt: string };
26
26
  discoverResources(metaUrl: string): { skillPaths: string[] } | undefined;
27
27
  getRunOwnerId(ctx: Pi.ExtensionContext): string;
28
- onAgentEnd(ctx: Pi.ExtensionContext): void;
28
+ onAgentSettled(ctx: Pi.ExtensionContext): void;
29
+ onContext(messages: unknown[], ctx: Pi.ExtensionContext): unknown[];
29
30
  onSessionShutdown(reason: string, ctx: Pi.ExtensionContext): void;
30
31
  onSessionStart(ctx: Pi.ExtensionContext): Promise<void>;
31
32
  registerCoreTools(): void;
@@ -141,8 +142,12 @@ export function createActorExtensionRuntime(
141
142
  return skillPaths.length > 0 ? { skillPaths } : undefined;
142
143
  },
143
144
  getRunOwnerId,
144
- onAgentEnd(ctx) {
145
- if (activeRunContext === ctx) automaticReview.schedule();
145
+ onAgentSettled(ctx) {
146
+ if (activeRunContext !== ctx) return;
147
+ if (!runUiRuntime.flushCompletionBatch(ctx)) automaticReview.schedule();
148
+ },
149
+ onContext(messages, ctx) {
150
+ return runUiRuntime.projectContext(messages, ctx);
146
151
  },
147
152
  onSessionShutdown(reason, ctx) {
148
153
  const ownerId = runOwnerIdsByContext.get(ctx);
@@ -28,3 +28,12 @@ export const RUN_CONTROL_ERROR_MAX_BYTES = 4 * 1024;
28
28
  export const RUN_CONTROL_JOURNAL_MAX_BYTES = 1024 * 1024;
29
29
  export const RUN_RETENTION_MAX_RECORDS = 256;
30
30
  export const RUN_RETENTION_MAX_BYTES = 1024 * 1024;
31
+ export const RUN_DELIVERY_BATCH_MAX_MEMBERS = 256;
32
+ export const RUN_DELIVERY_MODEL_MAX_MEMBERS = 64;
33
+ export const RUN_DELIVERY_MODEL_MAX_BYTES = 16 * 1024;
34
+ export const RUN_DELIVERY_RECEIPT_LIMIT = 128;
35
+ export const RUN_DELIVERY_SESSION_MAX_ENTRIES = 256;
36
+ export const RUN_DELIVERY_SESSION_MAX_BYTES = 1024 * 1024;
37
+ export const RUN_DELIVERY_STEER_MAX_ENVELOPES = 64;
38
+ export const RUN_DELIVERY_STEER_MAX_BYTES = 16 * 1024;
39
+ export const RUN_DELIVERY_JOURNAL_MAX_BYTES = 1024 * 1024;