@llblab/pi-actors 0.20.2 → 0.22.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 (41) hide show
  1. package/BACKLOG.md +34 -80
  2. package/CHANGELOG.md +29 -0
  3. package/README.md +7 -1
  4. package/dist/index.js +11 -0
  5. package/dist/lib/actor-rooms.d.ts +1 -0
  6. package/dist/lib/actor-rooms.js +33 -1
  7. package/dist/lib/async-runs.d.ts +35 -1
  8. package/dist/lib/async-runs.js +318 -36
  9. package/dist/lib/command-templates.js +8 -1
  10. package/dist/lib/observability.d.ts +15 -0
  11. package/dist/lib/observability.js +103 -18
  12. package/dist/lib/recipe-discovery.js +13 -5
  13. package/dist/lib/recipe-references.js +137 -11
  14. package/dist/lib/runtime-notifier.d.ts +48 -0
  15. package/dist/lib/runtime-notifier.js +137 -0
  16. package/dist/lib/tools.js +18 -9
  17. package/docs/README.md +1 -1
  18. package/docs/actor-messages.md +8 -3
  19. package/docs/async-runs.md +7 -5
  20. package/docs/recipe-library.md +25 -8
  21. package/docs/template-recipes.md +37 -7
  22. package/docs/tool-registry.md +4 -3
  23. package/index.ts +14 -0
  24. package/lib/actor-rooms.ts +46 -1
  25. package/lib/async-runs.ts +433 -49
  26. package/lib/command-templates.ts +8 -1
  27. package/lib/observability.ts +133 -20
  28. package/lib/recipe-discovery.ts +21 -6
  29. package/lib/recipe-references.ts +141 -17
  30. package/lib/runtime-notifier.ts +207 -0
  31. package/lib/tools.ts +36 -13
  32. package/package.json +2 -3
  33. package/recipes/music-player.json +1 -1
  34. package/recipes/pipeline-room-swarm.json +1 -1
  35. package/scripts/coordinator.mjs +276 -135
  36. package/scripts/locker.mjs +87 -28
  37. package/scripts/music-player.mjs +401 -94
  38. package/scripts/validate-recipe.mjs +2 -2
  39. package/skills/actors/SKILL.md +10 -9
  40. package/skills/swarm/SKILL.md +1 -1
  41. package/index.js +0 -19
@@ -70,7 +70,7 @@ inspect target=run:docs_review view=tail
70
70
 
71
71
  Pipeline recipes demonstrate second-order composition:
72
72
 
73
- - `recipes/coordinator-locker.json`: Long-lived coordinator cell with queue, acquire/renew/release lease locks, journal, and actor messages for worker coordination.
73
+ - `recipes/coordinator-locker.json`: Long-lived coordinator cell with queue, acquire/renew/release lease locks, journal, actor messages for worker coordination, and platform-adapted control metadata.
74
74
  - `recipes/subagent-review-coordinator.json`: Lens reviewers → verifier → merger → judge → normalizer.
75
75
  - `recipes/pipeline-release-readiness.json`: Task-first release cell: changelog section → package summary → packaged skill summary → validation → release review → artifact report.
76
76
  - `recipes/pipeline-release-summary.json`: Evidence-only release summary cell: changelog section → package summary → packaged skill summary → validation → release summary / risks / PR body draft artifact. It does not commit, open a PR, merge, tag, publish, or perform external release side effects.
@@ -84,7 +84,7 @@ Pipeline recipes demonstrate second-order composition:
84
84
  - `recipes/pipeline-development-tasking.json`: Plan → task card → critique → integrator handoff.
85
85
  - `recipes/pipeline-docs-maintenance.json`: Docs index → documentation review → maintenance plan → artifact report.
86
86
  - `recipes/pipeline-media-library.json`: Playlist build → media-library artifact report.
87
- - `recipes/pipeline-room-swarm.json`: Room participants join `room:<run>`, coordinate over repeated room-visible rounds, leave cleanly, and synthesize the room transcript into a caller-provided artifact path. Keep model/thinking/mission policy caller-owned. Custom roles can be supplied with `roles_path` as a JSON array of `{ "name", "persona" }` objects; `name` stays ASCII-safe for `branch:<run>/<name>` addresses and debugger output remains plain and name-driven. The packaged swarm uses contacts for peer awareness but does not rely on direct branch delivery unless a caller-specific worker protocol consumes branch envelopes. Set `locker=true` to compose a local `coordinator-locker` cell under `{state_dir}/locker` for artifact ownership, resource lease locks, and a decision journal without merging locker policy into the room-participant script.
87
+ - `recipes/pipeline-room-swarm.json`: Room participants join `room:<run>`, coordinate over repeated room-visible rounds, leave cleanly, and synthesize the room transcript into a caller-provided artifact path. Supported coordinator modes are `consensus`, `pipeline`, `fanout`, and `pool`; unknown modes fail closed instead of silently running consensus. Keep model/thinking/mission policy caller-owned. Custom roles can be supplied with `roles_path` as a JSON array of `{ "name", "persona" }` objects; `name` stays ASCII-safe for `branch:<run>/<name>` addresses and debugger output remains plain and name-driven. The packaged swarm uses contacts for peer awareness but does not rely on direct branch delivery unless a caller-specific worker protocol consumes branch envelopes. Set `locker=true` to compose a local `coordinator-locker` cell under `{state_dir}/locker` for artifact ownership, resource lease locks, and a decision journal without merging locker policy into the room-participant script.
88
88
  - `recipes/pipeline-artifact-report.json`: Normalize → artifact-shaped output → actor-message-shaped record. This pipeline prepares a candidate artifact and emits `artifact.prepared`/`artifact.blocked`; the `artifact_path` is a target path, not a guarantee that the file was written.
89
89
  - `recipes/pipeline-artifact-write.json`: Normalize → artifact-shaped output → deterministic artifact write → actor-message-shaped record. Use only when the caller explicitly wants filesystem writes; `write_mode` is `create`, `overwrite`, or `append`.
90
90
  - `recipes/pipeline-artifact-bundle.json`: Optional validation → deterministic artifact write → machine-readable manifest generation → deterministic manifest write → actor-message-shaped record. Use when the caller explicitly wants a filesystem handoff bundle with both artifact and manifest paths.
@@ -97,7 +97,7 @@ Utility recipes cover local operator workflows that do not need subagents:
97
97
 
98
98
  - `recipes/utility-markdown-index.json`: List Markdown files in a directory as input for README/docs index maintenance.
99
99
  - `recipes/utility-jsonl-tail.json`: Tail a JSONL message/log file with a configurable line count.
100
- - `recipes/utility-validation-wrapper.json`: Run a caller-supplied validation command in a scoped directory with a bounded timeout.
100
+ - `recipes/utility-validation-wrapper.json`: Run a caller-supplied validation command in a scoped directory with a bounded timeout. This intentionally crosses a trusted shell boundary; discovery surfaces it as a diagnostic, and callers should pass explicit validation commands only.
101
101
  - `recipes/utility-git-status.json`: Read concise branch/worktree state for a repo.
102
102
  - `recipes/utility-git-log.json`: Read recent decorated commit history for a repo.
103
103
  - `recipes/utility-run-state-files.json`: List run-state files such as `run.json` under an async run state root.
@@ -115,7 +115,17 @@ Utility recipes cover local operator workflows that do not need subagents:
115
115
  - `recipes/utility-skill-summary.json`: Use `scripts/recipe-utils.mjs` to summarize packaged skill frontmatter, body shape, formatter-safe scalar lines, and package-version alignment.
116
116
  - `recipes/utility-validate-recipe.json`: Use `scripts/validate-recipe.mjs` to validate one template recipe file, or all packaged recipes in a directory with `all: true`.
117
117
 
118
- These recipes are intentionally small. Register them only for trusted local commands and prefer narrow scopes. The helper-backed utilities share `scripts/recipe-utils.mjs` so repeated parsing/listing logic stays out of recipe strings.
118
+ These recipes are intentionally small. Register them only for trusted local commands and prefer narrow scopes. Discovery diagnostics flag obvious trust-boundary shapes such as shell/eval/destructive commands; those warnings are operator review aids, not a sandbox. The helper-backed utilities share `scripts/recipe-utils.mjs` so repeated parsing/listing logic stays out of recipe strings.
119
+
120
+ ## Actor OS Smoke Matrix
121
+
122
+ The repeatable smoke surface is the normal validation suite:
123
+
124
+ ```text
125
+ npm test
126
+ ```
127
+
128
+ The scenario coverage is intentionally local-first and bounded: shared room coordination and roster snapshots (`actor-rooms` / `tools` tests), direct branch delivery and claim/handle transitions (`tools` and coordinator tests), inspector navigation (`actor-inspector-tui` tests), recipe context injection (`actor-recipe-context` / async-run tests), recipe persistence suggestions (`observability` tests), and opt-in retirement candidate/execution smoke (`observability` / async-run tests). These scenarios exercise public `spawn` / `message` / `inspect` behavior or the packaged script surfaces rather than relying on manual swarm demos.
119
129
 
120
130
  ## Music Player
121
131
 
@@ -126,12 +136,12 @@ Files:
126
136
 
127
137
  Purpose: start a local or URL audio source as an async run so the agent can continue working while playback runs in the background. The running script exposes a run-local mailbox, so addressed `message` calls can control playback without a second recipe.
128
138
 
129
- Requirements: Linux, macOS, or WSL, Node.js, and one of `mpv`, `ffplay`, `cvlc`, or SoX `play`. Native Windows is not supported by the standard wrapper; use WSL or a platform-specific recipe transport.
139
+ Requirements: Node.js and one playback backend. Supported backends are `mpv`, macOS `afplay`, `ffplay`, `cvlc`, SoX `play`, or `wmp` on native Windows through the legacy Windows Media Player COM control exposed by `powershell.exe`. The `wmp` backend validates `wmplayer.exe` under `Program Files/Windows Media Player` or `Program Files (x86)/Windows Media Player`; it does not target the newer UWP/Store Media Player. Playback format support depends on the selected player; the actor control path itself uses the portable mailbox/wake runtime layer.
130
140
 
131
141
  The required `source` arg accepts:
132
142
 
133
143
  - A single local file or URL.
134
- - A directory containing audio files; the wrapper scans `.mp3`, `.ogg`, `.wav`, `.flac`, and `.m4a` files.
144
+ - A directory containing audio files; the wrapper scans `.aac`, `.aif`, `.aiff`, `.flac`, `.m4a`, `.mp3`, `.ogg`, and `.wav` files.
135
145
  - An `.m3u`, `.m3u8`, or `.txt` playlist file.
136
146
  - A `|`-separated inline list of local files or URLs.
137
147
 
@@ -148,7 +158,7 @@ Register playback:
148
158
  register_tool name=music_player \
149
159
  description="Start async music player playback through the Node.js wrapper" \
150
160
  template="music-player.json" \
151
- args="source:string,loop:bool=true,volume:int=70,player:enum(auto,mpv,ffplay,cvlc,play)=auto"
161
+ args="source:string,loop:bool=true,volume:int=70,player:enum(auto,mpv,afplay,ffplay,cvlc,play,wmp)=auto"
152
162
  ```
153
163
 
154
164
  Start playback:
@@ -175,7 +185,14 @@ The wrapper also accepts control commands directly when a caller already has the
175
185
  scripts/music-player.mjs next ~/.pi/agent/tmp/pi-actors/runs/music
176
186
  ```
177
187
 
178
- Message body is adapted to the recipe's run-local control channel. The script writes `status.txt`, `player.json`, and track-change actor messages in the same state dir. Track-change messages stay diagnostic by default; interactive recipes should define a small command vocabulary for addressed messages, emit semantic actor messages for decision points, and let the coordinator react to messages rather than sleep-polling state.
188
+ Message body is queued in the recipe's run-local mailbox and reconciled by the player loop. The loop treats `wake.jsonl` and `fs.watch` as advisory signals, then verifies the durable inbox signature before taking the inbox lock so unchanged mailboxes are not reread on every tick. On Unix-like hosts, child players run in their own process group so pause/resume/next/stop controls can signal the playback subtree directly. The script writes `status.txt`, `player.json`, and track-change actor messages in the same state dir. Track-change messages stay diagnostic by default; interactive recipes should define a small command vocabulary for addressed messages, emit semantic actor messages for decision points, and let the coordinator react to messages rather than sleep-polling state.
189
+
190
+ Cross-platform smoke checklist:
191
+
192
+ - Linux: install one backend such as `mpv` or `ffplay`; start `music_player source="~/Music" run_id=music`, send `pause`, `play`, `next`, and `stop`, then inspect `run:music` status/mailbox.
193
+ - macOS: verify `player=auto` selects `afplay` when no preferred CLI backend is installed, then run the same addressed message controls.
194
+ - Native Windows: verify `player=wmp` detects `wmplayer.exe`, starts playback through Windows Media Player COM, handles `pause`/`play`/`next`/`previous`/`stop`, and leaves handled mailbox records visible through `inspect target=run:music view=mailbox`.
195
+ - All hosts: confirm missed wake resilience by checking that queued mailbox commands are eventually claimed without relying on a transport-specific endpoint.
179
196
 
180
197
  ## Safety Notes
181
198
 
@@ -1,10 +1,10 @@
1
1
  # Template Recipe Standard
2
2
 
3
- Template recipes are saved JSON definitions around the synchronous [Command Template Standard](./command-templates.md).
3
+ Template recipes are saved definitions around the synchronous [Command Template Standard](./command-templates.md). JSON remains the canonical precise format; Markdown is a literate authoring format that compiles into the same recipe model.
4
4
 
5
5
  **Meta-contract:** a recipe stores a command-template graph plus defaults and run mode. It does not create a second execution language.
6
6
 
7
- **Scope:** reusable JSON shape, recipe naming, file-backed recipes, co-located recipes, recipe-layer imports/references, call-time values, foreground execution, and the `async: true` handoff to the [Async Run Standard](./async-runs.md).
7
+ **Scope:** reusable JSON/Markdown shape, recipe naming, file-backed recipes, co-located recipes, recipe-layer imports/references, call-time values, foreground execution, and the `async: true` handoff to the [Async Run Standard](./async-runs.md).
8
8
 
9
9
  ---
10
10
 
@@ -27,7 +27,7 @@ Packaged recipes are the pi-actors recipe standard library: declarative actor co
27
27
 
28
28
  Template-recipe standard owns:
29
29
 
30
- - Saved JSON definitions around one command-template graph.
30
+ - Saved JSON definitions around one command-template graph, plus Markdown-authored recipes that compile to that shape.
31
31
  - File-backed and co-located recipe shapes.
32
32
  - Recipe identity through file-backed filename or co-located tool id.
33
33
  - Recipe defaults, values, imports, import references, and import-node expansion.
@@ -67,6 +67,33 @@ Async recipe:
67
67
 
68
68
  A file-backed recipe's id comes from its filename, not a JSON `name` field. Legacy files may still contain `name`, but loaders ignore it for identity. `template` is the command-template tree. `async: true` selects detached run mode when the recipe is invoked through a registered tool.
69
69
 
70
+ ## Markdown Authoring
71
+
72
+ Markdown recipes use `.md` files with YAML-like frontmatter for recipe metadata and one fenced executable block for the recipe/template body. Runtime behavior comes only from frontmatter plus the fenced block; surrounding prose is advisory for humans and future recipe-context use.
73
+
74
+ ````markdown
75
+ ---
76
+ description: Literate docs check
77
+ args:
78
+ - scope:path
79
+ defaults:
80
+ scope: docs
81
+ mailbox:
82
+ accepts:
83
+ - control.stop
84
+ ---
85
+
86
+ Human notes can explain intent, examples, or review guidance.
87
+
88
+ ```template
89
+ npm run check -- {scope}
90
+ ```
91
+ ````
92
+
93
+ Fenced blocks marked `template`, `command-template`, `json`, or `recipe` are executable. A `template` fence stores its text as the command-template string. A JSON fence can contain either a full recipe object with `template` or a raw command-template value. Frontmatter supports the recipe metadata used by JSON recipes, including `args`, `defaults`, `imports`, `mailbox`, `artifacts`, `async`, and command-template flags.
94
+
95
+ JSON remains the source-of-truth format for precise machine editing. If `<id>.json` and `<id>.md` exist in the same discovery priority layer, `<id>.json` wins and the Markdown recipe is reported as shadowed.
96
+
70
97
  ## Discovery Priority
71
98
 
72
99
  Recipe priority only matters when two discovered recipes have the same filename id. The conceptual ladder from lowest to highest priority is:
@@ -74,11 +101,11 @@ Recipe priority only matters when two discovered recipes have the same filename
74
101
  1. No recipe for that id.
75
102
  2. Packaged pi-actors recipe components, acting as the standard library.
76
103
  3. Explicitly referenced ad hoc user recipe files located outside `~/.pi/agent/recipes`.
77
- 4. User recipe files under `~/.pi/agent/recipes/*.json`.
104
+ 4. User recipe files under `~/.pi/agent/recipes/*.json` or `*.md`.
78
105
 
79
106
  The high-priority user recipe directory is also the default tool set: recipes placed there are agent tools by location. This preserves the old advantage of a tool-only registry because listing `~/.pi/agent/recipes` shows the operator-managed tool surface. Packaged and ad hoc recipes are recipe components by default; they become tools only when copied or registered into the agent recipe root.
80
107
 
81
- Higher-priority files shadow lower-priority files with the same basename. A highest-priority invalid recipe is still visible and blocks fallback so operators do not accidentally run packaged behavior when a user override is broken. A highest-priority recipe with `disabled: true` also blocks fallback and intentionally disables that id.
108
+ Higher-priority files shadow lower-priority files with the same basename. Within one priority layer, same-id JSON shadows Markdown because JSON is the canonical precise format. A highest-priority invalid recipe is still visible and blocks fallback so operators do not accidentally run packaged behavior when a user override is broken. A highest-priority recipe with `disabled: true` also blocks fallback and intentionally disables that id.
82
109
 
83
110
  ## Usage Metadata
84
111
 
@@ -203,19 +230,22 @@ Reusable local recipes live in:
203
230
 
204
231
  ```text
205
232
  ~/.pi/agent/recipes/*.json
233
+ ~/.pi/agent/recipes/*.md
206
234
  ```
207
235
 
208
236
  Bare recipe names resolve under that directory, so `file: "review-docs"` loads:
209
237
 
210
238
  ```text
211
239
  ~/.pi/agent/recipes/review-docs.json
240
+ # or, when no same-id JSON file exists:
241
+ ~/.pi/agent/recipes/review-docs.md
212
242
  ```
213
243
 
214
244
  Call-time params override file params. `values` are merged with file values; call-time values win. If a run id is omitted for an explicit async start, the file basename becomes the default run id.
215
245
 
216
246
  ## Registered Recipe Tools
217
247
 
218
- A registered tool is a recipe file exposed as an agent tool. User recipes under `~/.pi/agent/recipes/*.json` are tools by location; packaged/ad hoc recipes are components unless copied or registered into that user recipe root:
248
+ A registered tool is a recipe file exposed as an agent tool. User recipes under `~/.pi/agent/recipes/*.json` or `*.md` are tools by location; packaged/ad hoc recipes are components unless copied or registered into that user recipe root:
219
249
 
220
250
  ```json
221
251
  {
@@ -312,6 +342,6 @@ Nested object keys are dot-separated. Import references are resolved before norm
312
342
 
313
343
  ## Recipe Shape
314
344
 
315
- Use the filename for file-backed recipe ids, and use `async: true` for detached runs. Use `parallel: true` for fanout, `when` for node guards, and semantic public args such as `tools`, `all`, or `timeout_ms` instead of leaking CLI fragments or reusing node-control names. Local files belong under `~/.pi/agent/recipes/*.json` before relying on recipe launchers.
345
+ Use the filename for file-backed recipe ids, and use `async: true` for detached runs. Use `parallel: true` for fanout, `when` for node guards, and semantic public args such as `tools`, `all`, or `timeout_ms` instead of leaking CLI fragments or reusing node-control names. Local files belong under `~/.pi/agent/recipes/*.json` or `*.md` before relying on recipe launchers.
316
346
 
317
347
  If a proposed recipe needs a scheduler, queue daemon, `goto`, or custom workflow syntax, stop. Keep the recipe as saved command-template JSON and put policy in the registered tool, script, or caller.
@@ -1,6 +1,6 @@
1
1
  # Tool Registry
2
2
 
3
- `pi-actors` stores persistent agent tools as recipe files under `~/.pi/agent/recipes/*.json` and registers the active tool set automatically on session start.
3
+ `pi-actors` stores persistent agent tools as recipe files under `~/.pi/agent/recipes/*.json` or `*.md` and registers the active tool set automatically on session start.
4
4
 
5
5
  This document is the local adaptation of the portable [Command Template Standard](./command-templates.md) and the recipe-file runtime described in [Template Recipe Standard](./template-recipes.md).
6
6
 
@@ -8,11 +8,12 @@ This document is the local adaptation of the portable [Command Template Standard
8
8
 
9
9
  The registry source is location-discovered recipes, not a live tool-only JSON file and not a recipe-owned boolean:
10
10
 
11
- - `~/.pi/agent/recipes/*.json` is the highest-priority user recipe root and the operator-managed tool set.
11
+ - `~/.pi/agent/recipes/*.json` and `*.md` are the highest-priority user recipe root and the operator-managed tool set.
12
12
  - Recipes in that root are tools by location.
13
13
  - Packaged pi-actors recipes are the lower-priority standard library of declarative actor config components, not automatically registered tools.
14
14
  - Ad hoc recipe files outside the user recipe root are components unless explicitly registered/copied into `~/.pi/agent/recipes`.
15
- - Recipe identity is the filename basename; `~/.pi/agent/recipes/docs_review.json` has id/tool name `docs_review`.
15
+ - Recipe identity is the filename basename; `~/.pi/agent/recipes/docs_review.json` and `docs_review.md` both have id/tool name `docs_review`.
16
+ - Same-id JSON shadows Markdown in the same priority layer.
16
17
 
17
18
 
18
19
  Because the user recipe directory is sticky agent muscle memory, runtime launches update `usage.calls`, `usage.last_called`, and a content `usage.fingerprint` on user-owned recipe files. If authored recipe content changes, the next launch resets `usage.calls` and records `usage.reset_at` before counting the launch, so usage evidence follows the current recipe meaning rather than an older file history. `inspect target=recipes view=summary verbose=true` includes usage metadata and operator-gated cleanup recommendations for invalid, shadowed, disabled, component-only, unused, or overriding recipes. Recommended actions stay explicit: keep as a tool/component, enable, merge, fix, delete, or archive. The extension does not maintain a failure counter and agents should not silently clean tools during unrelated work.
package/index.ts CHANGED
@@ -13,6 +13,7 @@ import type {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
 
15
15
  import * as ActorInspectorTui from "./lib/actor-inspector-tui.ts";
16
+ import * as AsyncRuns from "./lib/async-runs.ts";
16
17
  import * as CommandTemplates from "./lib/command-templates.ts";
17
18
  import * as Observability from "./lib/observability.ts";
18
19
  import * as Paths from "./lib/paths.ts";
@@ -47,6 +48,7 @@ export default function toolRegistryExtension(pi: ExtensionAPI) {
47
48
  const runDirWatchers = new Map<string, FSWatcher>();
48
49
  const observedRuns = new Map<string, Observability.RunObservedStatus>();
49
50
  const observedRunEventLines = new Map<string, number>();
51
+ const retirementAttempts = new Set<string>();
50
52
  let runStatusFrame = 0;
51
53
  let communicationWidgetVisible = false;
52
54
  let actorInspectorRows = 12;
@@ -61,6 +63,17 @@ export default function toolRegistryExtension(pi: ExtensionAPI) {
61
63
  let recipeWatcherFailureNotified = false;
62
64
  const getRunOwnerId = (ctx: ExtensionContext): string =>
63
65
  ctx.sessionManager.getSessionId();
66
+ const retireCandidateRuns = (
67
+ ctx: ExtensionContext,
68
+ summary: Observability.RunSummary,
69
+ ): void => {
70
+ void Observability.executeRunRetirements(summary, {
71
+ attempted: retirementAttempts,
72
+ cancelRun: (candidate) => AsyncRuns.cancelRun(candidate.stateDir),
73
+ notify: (message, level) => ctx.ui.notify(message, level),
74
+ sendStop: (candidate) => AsyncRuns.sendRunMessage(candidate.stateDir, "stop"),
75
+ });
76
+ };
64
77
  const updateRunUi = (ctx: ExtensionContext, notify = false): void => {
65
78
  const ownerId = getRunOwnerId(ctx);
66
79
  const summary = Observability.summarizeRuns(undefined, ownerId);
@@ -139,6 +152,7 @@ export default function toolRegistryExtension(pi: ExtensionAPI) {
139
152
  summary,
140
153
  );
141
154
  if (!notify) return;
155
+ retireCandidateRuns(ctx, summary);
142
156
  for (const transition of transitions) {
143
157
  if (!Observability.shouldNotifyRunTransition(transition)) continue;
144
158
  const text = Observability.formatRunTransitionMessage(transition);
@@ -9,10 +9,12 @@ import { randomUUID } from "node:crypto";
9
9
  import * as path from "node:path";
10
10
 
11
11
  import type { ActorMessage } from "./actor-messages.ts";
12
+ import { notifyRuntimeWake } from "./runtime-notifier.ts";
12
13
 
13
14
  const STATE_LOCK_MAX_AGE_MS = 5 * 60 * 1000;
14
15
  const STATE_LOCK_TIMEOUT_MS = 5000;
15
16
  const DEFAULT_ROOM_MAX_MESSAGES = 10000;
17
+ const DEFAULT_BRANCH_INBOX_TERMINAL_RETAINED = 2000;
16
18
  const DEFAULT_SNAPSHOT_MIN_INTERVAL_MS = 250;
17
19
 
18
20
  export interface RoomMember {
@@ -180,6 +182,19 @@ function writeJsonFile(file: string, value: unknown): void {
180
182
  fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
181
183
  }
182
184
 
185
+ function notifyActorWake(
186
+ stateDir: string,
187
+ actor: string,
188
+ reason: string,
189
+ metadata: Record<string, unknown> = {},
190
+ ): void {
191
+ try {
192
+ notifyRuntimeWake(stateDir, { actor, metadata, reason });
193
+ } catch {
194
+ // Runtime wakes are advisory; durable room/inbox state remains canonical.
195
+ }
196
+ }
197
+
183
198
  function positiveEnvInt(name: string, fallback: number): number {
184
199
  const value = Number(process.env[name] ?? fallback);
185
200
  return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
@@ -386,6 +401,26 @@ export function readBranchInboxMessages(
386
401
  }
387
402
  }
388
403
 
404
+ export function getBranchInboxTerminalRetainLimit(): number {
405
+ const value = Number(process.env.PI_ACTORS_BRANCH_INBOX_TERMINAL_RETAINED ?? "");
406
+ return Number.isInteger(value) && value >= 0
407
+ ? value
408
+ : DEFAULT_BRANCH_INBOX_TERMINAL_RETAINED;
409
+ }
410
+
411
+ function compactBranchInboxMessages<T extends { status?: string }>(
412
+ messages: T[],
413
+ ): T[] {
414
+ const retainTerminal = getBranchInboxTerminalRetainLimit();
415
+ const active = messages.filter(
416
+ (message) => message.status !== "handled" && message.status !== "failed",
417
+ );
418
+ const terminal = messages.filter(
419
+ (message) => message.status === "handled" || message.status === "failed",
420
+ );
421
+ return [...terminal.slice(-retainTerminal), ...active];
422
+ }
423
+
389
424
  export function appendBranchInboxMessage(
390
425
  stateDir: string,
391
426
  run: string,
@@ -401,6 +436,10 @@ export function appendBranchInboxMessage(
401
436
  `${JSON.stringify({ ...message, id: randomUUID(), queued_at: new Date().toISOString(), status: "queued" })}\n`,
402
437
  { flag: "a" },
403
438
  );
439
+ notifyActorWake(stateDir, address, "branch.message", {
440
+ ...(message.from ? { from: message.from } : {}),
441
+ type: message.type,
442
+ });
404
443
  } finally {
405
444
  releaseLock();
406
445
  }
@@ -428,7 +467,9 @@ export function updateBranchInboxMessageStatus(
428
467
  return { ...message, ...metadata, [timestampKey]: new Date().toISOString(), status };
429
468
  });
430
469
  if (!changed) return false;
431
- fs.writeFileSync(file, `${updated.map((message) => JSON.stringify(message)).join("\n")}\n`);
470
+ const compacted = compactBranchInboxMessages(updated);
471
+ fs.writeFileSync(file, `${compacted.map((message) => JSON.stringify(message)).join("\n")}\n`);
472
+ notifyActorWake(stateDir, address, "branch.inbox.status", { id, status });
432
473
  return true;
433
474
  } finally {
434
475
  releaseLock();
@@ -450,6 +491,10 @@ export function appendRoomMessage(
450
491
  const run = runFromRoomAddress(message.to);
451
492
  if (run) {
452
493
  writeCommunicationSnapshot(stateDir, run);
494
+ notifyActorWake(stateDir, message.to, "room.message", {
495
+ ...(message.from ? { from: message.from } : {}),
496
+ type: message.type,
497
+ });
453
498
  if (message.from && branchIdFromAddress(message.from, run)) {
454
499
  writeBranchCommunicationSnapshotDebounced(stateDir, run, message.from);
455
500
  }