pi-subagent-manager 0.27.0 → 0.28.1

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/README.md CHANGED
@@ -88,13 +88,16 @@ Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Fo
88
88
 
89
89
  Enable **[labs] Enable subagent extensions** in `/agents settings` to reload configured user and trusted-project extension hooks in each subagent’s separate session. It is off by default and experimental: hooks that assume main-session state can cause bugs or unintended consequences. This is configured-file discovery, **not exact main-session inheritance**; CLI-only, inline, and built-in extensions are not reloaded. See [subagent extension settings](docs/settings.md#labs-enable-subagent-extensions-subagentextensions) and read the [limitations](docs/subagent-extension-limitations.md) before enabling.
90
90
 
91
- Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to summarize detached-agent results, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
91
+ Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to collect detached-agent results and continue unfinished work, or recap when the overall task is complete, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
92
+
93
+ **[labs] Checklist integration** is always listed in `/agents settings` but can only be turned on while a loaded, active [pi-checklist](https://github.com/championswimmer/pi-checklist) ≥3.0.0 has task meta enabled (`/checklist settings meta`). When on and eligible, the main agent's prompt explains tagging tasks with `meta.agent`; in Orchestration mode the main agent must use the checklist. See [Checklist integration](docs/settings.md#labs-checklist-integration-checklistintegration).
92
94
 
93
95
  ## Docs
94
96
 
95
97
  - [Your own agent](docs/custom-agents.md) — walkthrough for writing an agent type
96
98
  - [Settings](docs/settings.md) — every setting and option, and when to use each
97
99
  - [Threads and lifecycle](docs/threads.md) — paths, context, pause/resume, persistence
100
+ - [Asynchronous lifecycle](docs/async-lifecycle.md) — flow and timing diagrams for completion, wakes, and continuation
98
101
  - [Tools and UI](docs/tools-and-ui.md) — model-facing tools, parallel work, dialogs
99
102
  - [Importing agents](docs/importing-agents.md) — migrate from other pi subagent packages
100
103
  - [Bundled agents](docs/default-agents.md) — routing, tool boundaries, model suggestions
@@ -2,7 +2,7 @@
2
2
  name: architect
3
3
  icon: '󰠡'
4
4
  description: Design architecture, weigh tradeoffs, and decompose ambiguous work into verifiable plans. Ground external claims in dated primary evidence when retrieval is actually available. Coordinate specialists only when delegation or execution is explicitly authorized.
5
- color: mdHeading
5
+ color: mdLink
6
6
  thinkingLevel: high
7
7
  modelSuggestions:
8
8
  - opus-5.5
@@ -8,7 +8,7 @@ modelSuggestions:
8
8
  - muse-spark-1.3
9
9
  - sonnet-5.5
10
10
  thinkingLevel: high
11
- color: accent
11
+ color: syntaxVariable
12
12
  tools:
13
13
  allow:
14
14
  - read
package/agents/writer.md CHANGED
@@ -3,7 +3,7 @@ name: writer
3
3
  icon: ''
4
4
  description: Draft or revise original long-form prose for a stated audience and voice. Not for source changes, code review, or UI design, and not for inventing facts, citations, or testimonials.
5
5
  thinkingLevel: medium
6
- color: mdQuote
6
+ color: thinkingXhigh
7
7
  modelSuggestions:
8
8
  - opus-5.5
9
9
  - gemini-4-argon
@@ -0,0 +1,153 @@
1
+ # Asynchronous completion and main-agent wakes
2
+
3
+ A detached spawn (`wait: false`) returns while its agent is still working. Completion and reporting timeouts are separate signals: finishing cancels the agent's reporting timer, then reevaluates whether the main agent should run. It never waits for that timer to expire.
4
+
5
+ With [Final Recap](settings.md#labs-final-recap-finalrecap) enabled, completed, failed, and stopped detached agents contribute to a pending completion batch. The batch becomes ready when **no detached agent is starting or running**, including nested descendants. Without Final Recap, detached settlements request ordinary wakes instead of waiting for a batch. Progress alone does not request a turn; foreground results do not request an extra completion turn. A detached pause requests an ordinary wake, not a final-result recap.
6
+
7
+ The scheduler knows whether a batch is ready—not whether the user's task is finished. Both kinds of trigger tell the main agent to collect results and continue unfinished work, or give a final recap if the overall task is complete.
8
+
9
+ ## Delivery and scheduling flow
10
+
11
+ Root-directed events are persisted before delivery. When main is idle, their notifications enter model context without triggering a turn or appearing as the final visible chat message. A single scheduler then chooses a completion/continuation trigger or an ordinary wake.
12
+
13
+ ```mermaid
14
+ flowchart TD
15
+ Event["Progress, timeout, or settlement"] --> Recipient{"Recipient is /root?"}
16
+ Recipient -->|Yes| Mailbox["Persist root mailbox notification"]
17
+ Recipient -->|No| Parent["Deliver notification to lexical parent"]
18
+ Parent --> Nested{"Settlement?"}
19
+ Nested -->|Yes| Reconcile["Reevaluate root mailbox and scheduler"]
20
+ Nested -->|No| Stop["No root scheduling change"]
21
+ Mailbox --> Reconcile
22
+ Reconcile --> Enabled{"Enabled and not cancelling?"}
23
+ Enabled -->|No| Hold["Do not deliver or start a turn"]
24
+ Enabled -->|Yes| Drain["Deliver pending notifications if main is idle"]
25
+ Drain --> Reserved{"Timer queued or automatic turn reserved?"}
26
+ Reserved -->|Yes| Retain["Leave pending work for reevaluation"]
27
+ Reserved -->|No| Pending{"Ready completion batch or wake intent?"}
28
+ Pending -->|No| Retain
29
+ Pending -->|Yes| Timer["Defer: 0 ms if idle, 100 ms if busy"]
30
+ Timer --> Valid{"Same session and generation, still enabled?"}
31
+ Valid -->|No| Hold
32
+ Valid -->|Yes| Idle{"Main idle?"}
33
+ Idle -->|No| Reconcile
34
+ Idle -->|Yes| Flush["Drain mailbox and recheck live state"]
35
+ Flush --> Batch{"Final Recap on, no outstanding async agents, pending results?"}
36
+ Batch -->|Yes| Recap["Reserve one completion/continuation turn"]
37
+ Batch -->|No| Wake{"Wake intent remains?"}
38
+ Wake -->|Yes| Normal["Reserve one ordinary wake turn"]
39
+ Wake -->|No| Retain
40
+ Recap --> Main["Main collects results and decides what remains"]
41
+ Normal --> Main
42
+ Main --> Settled["Main agent_settled releases reservation"]
43
+ Settled --> Reconcile
44
+ ```
45
+
46
+ A report-only timeout requests a wake while the child is **still running**; it does not stop the child. If a ready completion batch and timeout wake are pending at the same scheduling boundary, the completion trigger takes priority and clears the pending wake intent. Their notifications are available in that one turn. A timeout turn that already started is not retroactively merged with a later completion.
47
+
48
+ The 0 ms deferral leaves the current settlement boundary and coalesces events already arriving together. The 100 ms busy retry also covers compaction, so delivery does not depend solely on a later main-agent `agent_settled` event. These are scheduling delays, not guaranteed response deadlines.
49
+
50
+ ## Timing: siblings finish before their reporting timers
51
+
52
+ This example has Final Recap on. Time runs downward; all three agents finish before their report deadlines.
53
+
54
+ ```mermaid
55
+ sequenceDiagram
56
+ participant Main as Main agent
57
+ participant A as Agent A
58
+ participant B as Agent B
59
+ participant C as Agent C
60
+ participant S as Root scheduler
61
+ Main->>A: Spawn detached with reporting timer
62
+ Main->>B: Spawn detached with reporting timer
63
+ Main->>C: Spawn detached with reporting timer
64
+ Note over Main: Main settles and becomes idle
65
+ A-->>S: Completed, cancel A's timer
66
+ Note over S: Retain result, two async agents remain
67
+ B-->>S: Completed, cancel B's timer
68
+ Note over S: Retain result, one async agent remains
69
+ C-->>S: Completed, cancel C's timer
70
+ Note over S: Zero outstanding, defer and recheck
71
+ S->>Main: One completion/continuation trigger
72
+ Note over Main,C: No reporting timer had to expire
73
+ alt More work remains
74
+ Main->>Main: Collect results and continue the task
75
+ opt Another detached batch is needed
76
+ Main->>C: Spawn new work or resume retained work
77
+ end
78
+ else Overall task is complete
79
+ Main->>Main: Give final recap
80
+ end
81
+ Main-->>S: agent_settled, release turn reservation
82
+ ```
83
+
84
+ “Batch” is a scheduling group, not a separate job object. Readiness is checked against the manager's current detached-agent count. New detached work can make the next completion batch wait again.
85
+
86
+ ## Timing: a nested descendant finishes last
87
+
88
+ A nested result still belongs to its lexical parent. Its settlement must also reevaluate the root scheduler because the global outstanding count includes that descendant.
89
+
90
+ ```mermaid
91
+ sequenceDiagram
92
+ participant Main as Main agent
93
+ participant A as Parent A
94
+ participant B as Sibling B
95
+ participant C as Child C
96
+ participant S as Root scheduler
97
+ Main->>A: Spawn detached
98
+ Main->>B: Spawn detached
99
+ A->>C: Spawn detached child
100
+ A-->>S: A completes, retain root result
101
+ B-->>S: B completes, retain root result
102
+ Note over S: C is still active, so no completion turn
103
+ C-->>A: C completes, deliver result to retained parent
104
+ C-->>S: Settlement reevaluates global readiness
105
+ Note over S: Zero outstanding, root batch is ready
106
+ S->>Main: Completion/continuation trigger for pending root results
107
+ ```
108
+
109
+ C's result is not copied into the root mailbox by this path. The main agent can inspect descendant output when needed. Delivery to a retained parent does not itself restart that parent.
110
+
111
+ ## Timing: busy main, coalesced signals, and follow-up work
112
+
113
+ Final Recap is on here. A timeout and the last completion arrive during compaction. Later, the automatic turn launches dependent work that finishes before main settles.
114
+
115
+ ```mermaid
116
+ sequenceDiagram
117
+ participant Main as Main agent
118
+ participant Child as Detached agent
119
+ participant S as Root scheduler
120
+ Note over Main: Busy with compaction
121
+ Child-->>S: Report timeout, child keeps running
122
+ S->>S: Persist notification, retain wake intent
123
+ Child-->>S: Last completion, clear reporting timer
124
+ S->>S: Persist result, completion batch ready
125
+ loop While main remains busy
126
+ S->>S: Retry after 100 ms, recheck session and idle state
127
+ end
128
+ Note over Main: Compaction ends, no agent_settled required
129
+ S->>Main: Deliver notifications and one completion trigger
130
+ Note over S: Clear wake intent, reserve automatic turn
131
+ Main->>Child: Launch dependent detached work
132
+ Child-->>S: Dependent work completes while main is busy
133
+ S->>S: Retain new result, do not interrupt main
134
+ Main-->>S: agent_settled, release reservation
135
+ S->>S: Reevaluate pending results and defer
136
+ S->>Main: One follow-up completion/continuation trigger
137
+ Main->>Main: Continue remaining work or give final recap
138
+ ```
139
+
140
+ ## Settings, cancellation, and persistence
141
+
142
+ - **Subagent Mode Off:** suppresses notification delivery and automatic turns. Matching-session mailbox entries remain available for reconciliation when enabled. **Final Recap off** changes detached completion behavior to ordinary wakes; it is not a master switch for all automatic turns.
143
+ - **One automatic turn at a time:** `rootTurnRunning` reserves a requested turn until main's `agent_settled`. Results arriving during it remain pending for a follow-up. The reservation covers both ordinary wakes and completion/continuation turns.
144
+ - **Session changes:** tree navigation, switching, and forking cancel scheduled work and suppress cancellation-generated turns while stopping old threads. Attaching a session changes the generation; shutdown cancels the timer and changes the generation too. Deferred callbacks recheck session identity and generation before acting.
145
+ - **Branch-local recovery:** root mailbox entries carry `rootSessionId` and a unique `details.mailboxId`. Delivered `pi-subagent:update` messages identify notifications already placed in context. Completion-trigger messages (`pi-subagent:final-recap`) record the completion `mailboxIds` consumed by that batch, so reconciliation does not recap those same IDs again. Ordinary wake intent is an in-memory flag, not a separate durable acknowledgment log.
146
+
147
+ These records track notification delivery and trigger consumption, not successful completion of the user's task. The scheduler calls `pi.sendMessage` with `triggerTurn: true`; it does not receive an acknowledgment that the resulting model turn succeeded.
148
+
149
+ ## Implementation and regression coverage
150
+
151
+ - [`src/index.ts`](../src/index.ts): `delivery`, `pendingRootNotifications`, `pendingSummaries`, `scheduleRootTurn`, and session lifecycle hooks.
152
+ - [`src/orch/manager.ts`](../src/orch/manager.ts): `outstandingAsync`, reporting timers, and terminal-state settlement.
153
+ - [`tests/final-recap-integration.test.ts`](../tests/final-recap-integration.test.ts): all six completion orders for three timed siblings, nested-last completion, busy-state retry, timeout/completion coalescing, and completion during an automatic continuation. The compaction case simulates the SDK's busy state; it does not run a content-compaction pass.
package/docs/settings.md CHANGED
@@ -22,6 +22,7 @@ All keys are optional. Defaults:
22
22
  "costIcon": "money",
23
23
  "finalRecap": false,
24
24
  "subagentExtensions": false,
25
+ "checklistIntegration": false,
25
26
  "modelSelection": "pick-first-scoped",
26
27
  "toolFiltering": "allowed",
27
28
  "maxLevels": 3,
@@ -111,13 +112,28 @@ When a subagent session opens, it reloads enabled extension files from user conf
111
112
 
112
113
  Save and apply affects newly opened sessions, including retained sessions reopened after reload. Already-open agents keep their extension runtime until disposed. The main agent's extensions and tool set are not changed. Leave this off unless your extensions are safe to run across separate sessions.
113
114
 
115
+ ## [labs] Checklist integration (`checklistIntegration`)
116
+
117
+ Experimental on/off toggle, **off by default**, for use with [pi-checklist](https://github.com/championswimmer/pi-checklist) 3.0.0 or later. The row is always shown in `/agents settings`; it is muted and cannot be turned **On** unless all of these hold right now:
118
+
119
+ - the `checklist_create`, `checklist_read` and `checklist_update` tools are loaded, active, and registered from one real `pi-checklist` package whose `package.json` version is `3.x.y` or later (prereleases, look-alikes and unreadable manifests are rejected);
120
+ - pi-checklist's task **meta** is enabled in the current session (`/checklist settings meta`; turn it off with `/checklist settings no-meta`).
121
+
122
+ Eligibility is rechecked when the menu renders, when you toggle, when you save, and before every main-agent turn. A saved **On** stays stored but is shown as inactive while requirements are unmet, and you can always turn it **Off**.
123
+
124
+ When the setting is on, eligible, and Subagent Mode is not Off, the main agent's system prompt gains a short section explaining how to tag which agent works on each checklist task with a flat meta object such as `meta: { agent: "/root/task-slug" }` (limits: 10 keys, keys ≤40 characters, string values ≤200 characters). In **Orchestration** mode the section also states that the main agent **must** use `checklist_create`, `checklist_read` and `checklist_update` to track its work; in **Opportunistic** mode checklist use stays optional. Subagent (worker) prompts are not changed.
125
+
126
+ pi-checklist exposes no runtime API, events or version query, so this is a source-backed adapter: identity and version come from the checklist tools' registration origin and owning `package.json`, and the current meta state mirrors pi-checklist's own rule (global `pi-checklist.json` preference, else the latest branch snapshot, else off) at session start/tree navigation, then follows meta changes made in this session. Another session editing the global preference does not change this session until it reloads or navigates. Anything unrecognized fails closed (guidance is not added). `meta.agent` is this extension's convention, not part of pi-checklist's API. With **Enable subagent extensions**, child sessions may load their own checklist state separate from the main agent's.
127
+
114
128
  ## [labs] Final Recap (`finalRecap`)
115
129
 
116
130
  **[labs] Final Recap** is an experimental on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"finalRecap": true` in your settings file.
117
131
 
118
- When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent for an automatic summary. The summary is a main-thread response, so child notifications do not become the final visible message. Progress updates do not trigger summaries, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic summaries even if this setting is enabled.
132
+ When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent. It collects results and continues any unfinished work; only when the overall task is complete does it give a final recap. The response stays in the main thread, so child notifications do not become the final visible message. Progress updates do not trigger turns, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic turns even if this setting is enabled.
133
+
134
+ With Final Recap on, async completion events no longer wake the main agent one by one; the completion/continuation turn starts once every outstanding async agent has reported, including nested descendants. Reporting timers need not expire: completion cancels them and reevaluates batch readiness immediately. Spawn-timeout events still wake the main agent; a timeout wake and a ready completion batch are coalesced into one turn.
119
135
 
120
- With Final Recap on, async completion events no longer wake the main agent one by one; the recap turn starts once every outstanding async agent has reported (spawn-timeout events still wake it).
136
+ The scheduler retains pending notifications while the main agent is busy (including compaction), then retries once it is idle. A single turn reservation prevents duplicate wakes. Session switches and shutdown cancel scheduled delivery; completed batch IDs are persisted to avoid replaying consumed results. See the [asynchronous lifecycle flow and timing diagrams](async-lifecycle.md) for sibling completion, nested agents, timeout coalescing, and follow-up work.
121
137
 
122
138
  **Enabling Final Recap may cause extra model turns and uses more tokens and context.** Leave it off if you prefer to inspect results manually in `/agents tree` or request a summary yourself.
123
139
 
@@ -72,7 +72,7 @@ Refreshes every second and keeps your selection, collapse state and scroll posit
72
72
 
73
73
  ### Live agent navigation
74
74
 
75
- The fullscreen watcher renders steer and agent messages (including thinking) as Markdown, same as pi's main transcript. Tool calls and their results share pi's native `ToolExecutionComponent`, with built-in renderers for shell commands, reads, highlighted writes, edit diffs and search tools. Pending, successful and failed executions use pi's active theme colors. Unknown tools use pi's safe generic renderer; nested executions appear beneath their parent. **Ctrl+O** cycles all three detail levels in both steer and browse mode: **preview** (default: pi's native tool previews, first three rendered thinking lines), **compact** (one line per call, thinking hidden), **full** (complete tool output and thinking). Successful reads are collapsed by default, just like pi; expand them with **Ctrl+O**. Inherited context is initially collapsed (**c** toggles it with transcript controls focused). Watching alone never starts a turn, switches sessions, or changes model/tool/resource ownership. Extension renderers are never invoked, raw terminal controls are stripped, and images use safe text placeholders. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
75
+ The fullscreen watcher renders steer and agent messages (including thinking) as Markdown, same as pi's main transcript. Tool calls and their results share pi's native `ToolExecutionComponent`, with built-in renderers for shell commands, reads, highlighted writes, edit diffs and search tools. Pending, successful and failed executions use pi's active theme colors. Unknown tools use pi's safe generic renderer; nested executions appear beneath their parent. **Ctrl+O** cycles all three detail levels in both steer and browse mode: **preview** (default: pi's native tool previews, first three rendered thinking and custom-message lines), **compact** (one line per call, custom-message headings only, thinking hidden), **full** (complete tool output, custom messages and thinking). Custom messages from extensions follow this cycle, including messages inherited from the main session or produced by extensions loaded in subagents; truncated previews show **Ctrl+O to expand**. User and assistant text stays complete at every detail level. Successful reads are collapsed by default, just like pi; expand them with **Ctrl+O**. Inherited context is initially collapsed (**c** toggles it with transcript controls focused). Watching alone never starts a turn, switches sessions, or changes model/tool/resource ownership. Extension renderers are never invoked, raw terminal controls are stripped, and images use safe text placeholders. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
76
76
 
77
77
  - The bottom **Steer** input is focused initially. Type and press **Enter** to send to the inspected agent, including nested descendants, through the same service as `agent_steer`: running agents receive queued input; paused/completed/stopped agents resume their retained session. Empty input is ignored. Sending leaves the viewer open; failures are shown and preserve the draft for retry.
78
78
  - **Tab** switches between steering input and transcript controls. While typing, **c/t/l/r** are ordinary text and **Home/End** move the input cursor. Pasting never submits by itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.27.0",
3
+ "version": "0.28.1",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@ import { AgentNavigationEditor } from "./ui/agent-navigation-editor.ts";
16
16
  import { createDriverFactory } from "./orch/runtime.ts";
17
17
  import { createInheritedToolSource } from "./orch/inherited-tools.ts";
18
18
  import { subagentPrompt } from "./orch/prompt.ts";
19
+ import { ChecklistMetaMirror, checklistStatus } from "./orch/checklist-integration.ts";
19
20
  import { agentTools } from "./orch/tools.ts";
20
21
  import { editAgentTypes, updateWidget } from "./ui/ui.ts";
21
22
  import { canOpenDialog, dialogMenu } from "./ui/dialog.ts";
@@ -74,25 +75,22 @@ export default function piSubagent(pi: ExtensionAPI): void {
74
75
  refreshCostFooter(ctx);
75
76
  return loaded.diagnostics;
76
77
  };
78
+ const checklistMirror = new ChecklistMetaMirror(() => getAgentDir());
79
+ const currentChecklistStatus = (ctx: ExtensionContext) => checklistStatus(pi, checklistMirror, ctx);
77
80
  let generation = 0;
78
81
  let rootTurnEnded = false;
79
82
  const hiddenWidgetThreads = new Set<string>();
80
83
  let widgetCollapsed = false;
81
- let summaryRunning = false;
84
+ let rootTurnRunning = false;
82
85
  let suspendingSummaries = false;
83
- let summaryTimer: ReturnType<typeof setTimeout> | undefined;
86
+ // One arbiter owns both timeout wakes and completion/continuation turns.
87
+ let rootTurnTimer: ReturnType<typeof setTimeout> | undefined;
84
88
  let wakeRequested = false;
85
- let wakeTimer: ReturnType<typeof setTimeout> | undefined;
86
- const cancelWake = () => {
87
- if (wakeTimer !== undefined) clearTimeout(wakeTimer);
88
- wakeTimer = undefined;
89
- wakeRequested = false;
90
- };
91
89
  const cancelSummary = () => {
92
- cancelWake();
93
- if (summaryTimer !== undefined) clearTimeout(summaryTimer);
94
- summaryTimer = undefined;
95
- summaryRunning = false;
90
+ if (rootTurnTimer !== undefined) clearTimeout(rootTurnTimer);
91
+ rootTurnTimer = undefined;
92
+ wakeRequested = false;
93
+ rootTurnRunning = false;
96
94
  };
97
95
  // Right at a tree leaf steps tree → full: leave any session collapse behind.
98
96
  const returnToWidget = () => {
@@ -272,39 +270,6 @@ export default function piSubagent(pi: ExtensionAPI): void {
272
270
  );
273
271
  if (notification.trigger === true) wakeRequested = true;
274
272
  };
275
- /** Wake an idle main agent once for all pending async events (coalesced, after the settle boundary). */
276
- const scheduleWake = (ctx: ExtensionContext) => {
277
- if (!wakeRequested || wakeTimer !== undefined || limits.subagentMode === "off") return;
278
- const currentGeneration = generation;
279
- wakeTimer = setTimeout(() => {
280
- wakeTimer = undefined;
281
- if (
282
- currentGeneration !== generation ||
283
- context?.sessionManager !== ctx.sessionManager ||
284
- limits.subagentMode === "off" ||
285
- suspendingSummaries ||
286
- !wakeRequested
287
- )
288
- return;
289
- if (ctx.isIdle() === false) return; // agent_settled reschedules
290
- wakeRequested = false;
291
- try {
292
- pi.sendMessage(
293
- {
294
- customType: ROOT_WAKE_MESSAGE,
295
- content:
296
- "Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
297
- "React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only (omit message; resets the reporting timer from now without interrupting the running agent).",
298
- display: false,
299
- details: {},
300
- },
301
- { triggerTurn: true },
302
- );
303
- } catch (error) {
304
- warnDelivery(error);
305
- }
306
- }, 0);
307
- };
308
273
  const pendingSummaries = (ctx: ExtensionContext) => {
309
274
  const entries = ctx.sessionManager.getBranch();
310
275
  const summarized = new Set(
@@ -326,63 +291,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
326
291
  : [];
327
292
  });
328
293
  };
329
- const scheduleSummary = (ctx: ExtensionContext) => {
330
- if (
331
- !limits.finalRecap ||
332
- limits.subagentMode === "off" ||
333
- summaryRunning ||
334
- suspendingSummaries ||
335
- summaryTimer !== undefined ||
336
- ctx.isIdle() === false ||
337
- (manager?.outstandingAsync() ?? 0) > 0 ||
338
- !pendingSummaries(ctx).length
339
- )
340
- return;
341
- const currentGeneration = generation;
342
- // Coalesce siblings finishing together and leave the settlement boundary before
343
- // starting a new turn. Recheck settings/session/idle state after the deferral.
344
- summaryTimer = setTimeout(() => {
345
- summaryTimer = undefined;
346
- if (
347
- currentGeneration !== generation ||
348
- context?.sessionManager !== ctx.sessionManager ||
349
- !limits.finalRecap ||
350
- limits.subagentMode === "off" ||
351
- suspendingSummaries ||
352
- ctx.isIdle() === false ||
353
- (manager?.outstandingAsync() ?? 0) > 0
354
- )
355
- return;
356
- const notifications = pendingSummaries(ctx);
357
- if (!notifications.length) return;
358
- summaryRunning = true;
359
- try {
360
- pi.sendMessage(
361
- {
362
- customType: ROOT_SUMMARY_MESSAGE,
363
- content:
364
- "Summarize the newly finished asynchronous subagent results for the user. " +
365
- "Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
366
- "Give a concise main-thread answer covering results and any failures. " +
367
- "Do not spawn or resume agents solely to summarize.\nAgents: " +
368
- [...new Set(notifications.map((notification) => notification.details.path))].join(
369
- ", ",
370
- ),
371
- display: false,
372
- details: {
373
- mailboxIds: notifications.map((notification) => notification.details.mailboxId),
374
- },
375
- },
376
- { triggerTurn: true },
377
- );
378
- } catch (error) {
379
- summaryRunning = false;
380
- warnDelivery(error);
381
- }
382
- }, 0);
383
- };
384
- const restoreRootMailbox = (ctx: ExtensionContext) => {
385
- if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
294
+ const pendingRootNotifications = (ctx: ExtensionContext) => {
386
295
  const entries = ctx.sessionManager.getBranch();
387
296
  const delivered = new Set(
388
297
  entries.flatMap((entry) => {
@@ -391,25 +300,115 @@ export default function piSubagent(pi: ExtensionAPI): void {
391
300
  return typeof id === "string" ? [id] : [];
392
301
  }),
393
302
  );
394
- for (const entry of entries) {
395
- if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) continue;
303
+ return entries.flatMap((entry) => {
304
+ if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
396
305
  const notification = entry.data as RootNotification | undefined;
397
306
  if (
398
- notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
399
- typeof notification.content === "string" &&
400
- typeof notification.details?.mailboxId === "string" &&
401
- !delivered.has(notification.details.mailboxId)
402
- ) {
403
- sendRootNotification(notification);
404
- delivered.add(notification.details.mailboxId);
405
- }
406
- }
407
- scheduleWake(ctx);
408
- scheduleSummary(ctx);
307
+ notification?.rootSessionId !== ctx.sessionManager.getSessionId() ||
308
+ typeof notification.content !== "string" ||
309
+ typeof notification.details?.mailboxId !== "string" ||
310
+ delivered.has(notification.details.mailboxId)
311
+ )
312
+ return [];
313
+ delivered.add(notification.details.mailboxId);
314
+ return [notification];
315
+ });
316
+ };
317
+ const scheduleRootTurn = (ctx: ExtensionContext) => {
318
+ if (
319
+ limits.subagentMode === "off" ||
320
+ rootTurnRunning ||
321
+ suspendingSummaries ||
322
+ rootTurnTimer !== undefined
323
+ )
324
+ return;
325
+ // Include undelivered mailbox entries: a completion may arrive while Pi is
326
+ // compacting, which does not necessarily produce an agent_settled event.
327
+ if (
328
+ !wakeRequested &&
329
+ !(limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0 && pendingSummaries(ctx).length > 0) &&
330
+ !pendingRootNotifications(ctx).some((notification) => notification.trigger === true)
331
+ )
332
+ return;
333
+ const currentGeneration = generation;
334
+ // Zero-delay deferral crosses the SDK settlement boundary; busy retries also
335
+ // cover compaction and other non-agent busy periods. Reporting timers are
336
+ // deliberately irrelevant to completion readiness.
337
+ rootTurnTimer = setTimeout(
338
+ () => {
339
+ rootTurnTimer = undefined;
340
+ if (
341
+ currentGeneration !== generation ||
342
+ context?.sessionManager !== ctx.sessionManager ||
343
+ limits.subagentMode === "off" ||
344
+ suspendingSummaries ||
345
+ rootTurnRunning
346
+ )
347
+ return;
348
+ if (ctx.isIdle() === false) {
349
+ scheduleRootTurn(ctx);
350
+ return;
351
+ }
352
+ drainRootMailbox(ctx);
353
+ const notifications =
354
+ limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
355
+ ? pendingSummaries(ctx)
356
+ : [];
357
+ if (!notifications.length && !wakeRequested) return;
358
+ const wasWakeRequested = wakeRequested;
359
+ wakeRequested = false;
360
+ rootTurnRunning = true; // Also reserves a normal wake until agent_settled.
361
+ try {
362
+ pi.sendMessage(
363
+ notifications.length
364
+ ? {
365
+ customType: ROOT_SUMMARY_MESSAGE,
366
+ content:
367
+ "The asynchronous subagent batch has finished. Collect and inspect its results " +
368
+ "(use agent_output if more detail is needed), then continue any unfinished work in the user's task. " +
369
+ "If the overall task is complete, give a concise final recap covering results and failures. " +
370
+ "Do not spawn or resume agents solely to summarize.\nAgents: " +
371
+ [
372
+ ...new Set(notifications.map((notification) => notification.details.path)),
373
+ ].join(", "),
374
+ display: false,
375
+ details: {
376
+ mailboxIds: notifications.map((notification) => notification.details.mailboxId),
377
+ },
378
+ }
379
+ : {
380
+ customType: ROOT_WAKE_MESSAGE,
381
+ content:
382
+ "Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
383
+ "Collect results with agent_output and continue any unfinished work; recap when the overall task is complete. " +
384
+ "For a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only " +
385
+ "(omit message; resets the reporting timer from now without interrupting the running agent).",
386
+ display: false,
387
+ details: {},
388
+ },
389
+ { triggerTurn: true },
390
+ );
391
+ } catch (error) {
392
+ rootTurnRunning = false;
393
+ wakeRequested = wasWakeRequested;
394
+ warnDelivery(error);
395
+ }
396
+ },
397
+ ctx.isIdle() === false ? 100 : 0,
398
+ );
399
+ rootTurnTimer.unref?.();
400
+ };
401
+ const drainRootMailbox = (ctx: ExtensionContext) => {
402
+ if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
403
+ for (const notification of pendingRootNotifications(ctx)) sendRootNotification(notification);
404
+ };
405
+ const restoreRootMailbox = (ctx: ExtensionContext) => {
406
+ drainRootMailbox(ctx);
407
+ scheduleRootTurn(ctx);
409
408
  };
410
409
  pi.on("agent_settled", async (_event, ctx) => {
411
410
  if (context?.sessionManager === ctx.sessionManager) {
412
- summaryRunning = false;
411
+ rootTurnRunning = false;
413
412
  restoreRootMailbox(ctx);
414
413
  }
415
414
  });
@@ -459,7 +458,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
459
458
  // The eventual transcript message carries its ID for branch-local recovery.
460
459
  pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
461
460
  restoreRootMailbox(requireContext());
462
- } else void requireManager().deliver(event.recipient, message).catch(warnDelivery);
461
+ } else {
462
+ void requireManager().deliver(event.recipient, message).catch(warnDelivery);
463
+ // Global outstandingAsync includes nested descendants, so their last
464
+ // settlement must unblock a root batch even when its parent has finished.
465
+ if (event.kind === "settled") restoreRootMailbox(requireContext());
466
+ }
463
467
  } catch (error) {
464
468
  warnDelivery(error);
465
469
  }
@@ -518,7 +522,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
518
522
  pi.on("agent_start", async (_event, ctx) => {
519
523
  // A new task must not resurrect the previous task's settled agents. Automatic
520
524
  // final-recap turns still belong to that task and keep its results visible.
521
- if (manager && !summaryRunning) {
525
+ if (manager && !rootTurnRunning) {
522
526
  for (const thread of manager.list()) {
523
527
  if (thread.state !== "starting" && thread.state !== "running")
524
528
  hiddenWidgetThreads.add(thread.path);
@@ -538,7 +542,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
538
542
  });
539
543
  syncTools();
540
544
  pi.on("before_agent_start", async (event, ctx) => {
541
- const prompt = subagentPrompt(limits);
545
+ // Re-verify on every turn: the Labs opt-in AND live checklist eligibility must both hold.
546
+ const prompt = subagentPrompt(
547
+ limits,
548
+ limits.checklistIntegration && limits.subagentMode !== "off" && currentChecklistStatus(ctx).eligible,
549
+ );
542
550
  if (!prompt) return;
543
551
  if (limits.subagentMode === "opportunistic" && event.prompt.startsWith(IMPORT_REQUEST_PREFIX)) {
544
552
  try {
@@ -564,6 +572,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
564
572
  // session_start already belongs to the replacement session: never append the old registry here.
565
573
  if (manager) await manager.shutdown();
566
574
  inheritedTools.reset();
575
+ // pi-checklist reseeds its own state on these same lifecycle events.
576
+ checklistMirror.reset(ctx);
567
577
  context = ctx;
568
578
  costLedger = new CostLedger();
569
579
  costLedger.restore(ctx.sessionManager.getEntries());
@@ -785,6 +795,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
785
795
  settings: limits,
786
796
  agentDir: getAgentDir(),
787
797
  getAllTools: () => pi.getAllTools(),
798
+ checklistStatus: () => currentChecklistStatus(ctx),
788
799
  apply: () => {
789
800
  const diagnostics = loadLimits(ctx);
790
801
  requireManager().setLimits(limits);
@@ -0,0 +1,206 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join } from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ /**
6
+ * Optional Labs integration with pi-checklist >= 3.0.0.
7
+ *
8
+ * pi-checklist publishes no runtime API, events or version query, so this adapter is
9
+ * deliberately source-backed and fails closed:
10
+ * - identity/version come from the real registration origin of its tools
11
+ * (`ToolInfo.sourceInfo`) and the nearest owning package.json;
12
+ * - "task metadata is enabled" mirrors pi-checklist's private closure state using the same
13
+ * persistence it writes (see {@link ChecklistMetaMirror}).
14
+ */
15
+
16
+ export const CHECKLIST_PACKAGE = "pi-checklist";
17
+ export const CHECKLIST_MIN_MAJOR = 3;
18
+ export const CHECKLIST_TOOL_NAMES = ["checklist_create", "checklist_read", "checklist_update"] as const;
19
+ /** Session entry type pi-checklist appends for every snapshot (src/index.ts CUSTOM_TYPE). */
20
+ const CHECKLIST_ENTRY_TYPE = "pi-checklist";
21
+ const PREFS_FILE = "pi-checklist.json";
22
+
23
+ export const CHECKLIST_REQUIREMENTS =
24
+ "Requires pi-checklist ≥3.0.0 with its tools loaded and active, and task meta enabled (/checklist settings meta).";
25
+
26
+ export interface ChecklistStatus {
27
+ eligible: boolean;
28
+ /** Why the integration is unavailable; absent when eligible. */
29
+ reason?: string;
30
+ }
31
+
32
+ /** Strict `x.y.z`: prereleases/build metadata fail closed. */
33
+ export function checklistVersionSupported(version: unknown): boolean {
34
+ if (typeof version !== "string") return false;
35
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version.trim());
36
+ return match !== null && Number(match[1]) >= CHECKLIST_MIN_MAJOR;
37
+ }
38
+
39
+ function owningPackage(file: string): { name?: unknown; version?: unknown } | undefined {
40
+ let directory = dirname(realpathSync(file));
41
+ while (true) {
42
+ const manifest = join(directory, "package.json");
43
+ if (existsSync(manifest)) {
44
+ const parsed: unknown = JSON.parse(readFileSync(manifest, "utf8"));
45
+ return typeof parsed === "object" && parsed !== null ? (parsed as { name?: unknown; version?: unknown }) : undefined;
46
+ }
47
+ const parent = dirname(directory);
48
+ if (parent === directory) return undefined;
49
+ directory = parent;
50
+ }
51
+ }
52
+
53
+ /** Identity/version/reachability of the loaded checklist tools; metadata state is separate. */
54
+ export function detectChecklistPackage(pi: Pick<ExtensionAPI, "getAllTools" | "getActiveTools">): ChecklistStatus {
55
+ try {
56
+ const all = pi.getAllTools();
57
+ const active = new Set(pi.getActiveTools());
58
+ const sources = new Set<string>();
59
+ for (const name of CHECKLIST_TOOL_NAMES) {
60
+ const tool = all.find((candidate) => candidate.name === name);
61
+ if (!tool || tool.exposure === "hidden" || !active.has(name))
62
+ return { eligible: false, reason: `pi-checklist tool ${name} is not loaded and active` };
63
+ const path = tool.sourceInfo?.path;
64
+ if (typeof path !== "string" || !isAbsolute(path))
65
+ return { eligible: false, reason: `${name} does not come from a pi-checklist package file` };
66
+ sources.add(realpathSync(path));
67
+ }
68
+ if (sources.size !== 1)
69
+ return { eligible: false, reason: "checklist tools come from different extensions" };
70
+ const pkg = owningPackage([...sources][0]!);
71
+ if (pkg?.name !== CHECKLIST_PACKAGE)
72
+ return { eligible: false, reason: "checklist tools are not provided by the pi-checklist package" };
73
+ if (!checklistVersionSupported(pkg.version))
74
+ return {
75
+ eligible: false,
76
+ reason: `pi-checklist ${typeof pkg.version === "string" ? pkg.version : "(unknown version)"} is unsupported; ≥3.0.0 is required`,
77
+ };
78
+ return { eligible: true };
79
+ } catch (error) {
80
+ return { eligible: false, reason: `could not verify pi-checklist: ${error instanceof Error ? error.message : String(error)}` };
81
+ }
82
+ }
83
+
84
+ interface BranchEntry {
85
+ id?: unknown;
86
+ type?: unknown;
87
+ customType?: unknown;
88
+ data?: unknown;
89
+ message?: { role?: unknown; toolName?: unknown; details?: unknown };
90
+ }
91
+
92
+ /** pi-checklist ChecklistSnapshot guard (src/types.ts): `v === 1` with a `checklist` key. */
93
+ function snapshotOf(value: unknown): { metaEnabled?: unknown } | undefined {
94
+ if (typeof value !== "object" || value === null) return undefined;
95
+ const record = value as Record<string, unknown>;
96
+ return record.v === 1 && "checklist" in record ? record : undefined;
97
+ }
98
+
99
+ /** The snapshot an entry carries, using pi-checklist's loadFromBranch() rules. */
100
+ function entrySnapshot(entry: BranchEntry): { metaEnabled?: unknown } | undefined {
101
+ if (entry.type === "custom" && entry.customType === CHECKLIST_ENTRY_TYPE) return snapshotOf(entry.data);
102
+ if (
103
+ entry.type === "message" &&
104
+ entry.message?.role === "toolResult" &&
105
+ typeof entry.message.toolName === "string" &&
106
+ (CHECKLIST_TOOL_NAMES as readonly string[]).includes(entry.message.toolName)
107
+ )
108
+ return snapshotOf(entry.message.details);
109
+ return undefined;
110
+ }
111
+
112
+ function globalMetaEnabled(agentDir: string): boolean | undefined {
113
+ try {
114
+ const parsed: unknown = JSON.parse(readFileSync(join(agentDir, PREFS_FILE), "utf8"));
115
+ if (typeof parsed !== "object" || parsed === null) return undefined;
116
+ const value = (parsed as { metaEnabled?: unknown }).metaEnabled;
117
+ return typeof value === "boolean" ? value : undefined;
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Mirror of pi-checklist's live `metaEnabled`. pi-checklist computes it only at
125
+ * session_start/session_tree (global prefs file > latest branch snapshot > false) and then
126
+ * changes it solely through its own snapshots. So: seed identically on those lifecycle events,
127
+ * remember a branch checkpoint, and afterwards follow only snapshots appended to this branch.
128
+ * Later edits to the global prefs file by other sessions never affect the local instance, so
129
+ * they are intentionally ignored. Unknown state is `false`.
130
+ */
131
+ export class ChecklistMetaMirror {
132
+ private enabled = false;
133
+ private checkpoint: unknown;
134
+ private ready = false;
135
+
136
+ constructor(private readonly agentDir: () => string) {}
137
+
138
+ /** Re-seed; call on session_start and session_tree. */
139
+ reset(ctx: Pick<ExtensionContext, "sessionManager">): void {
140
+ this.ready = false;
141
+ this.enabled = false;
142
+ this.checkpoint = undefined;
143
+ try {
144
+ const branch = ctx.sessionManager.getBranch() as BranchEntry[];
145
+ let found: { metaEnabled?: unknown } | undefined;
146
+ for (const entry of branch) found = entrySnapshot(entry) ?? found;
147
+ this.enabled = globalMetaEnabled(this.agentDir()) ?? found?.metaEnabled === true;
148
+ this.checkpoint = branch.at(-1)?.id;
149
+ this.ready = true;
150
+ } catch {
151
+ this.enabled = false;
152
+ }
153
+ }
154
+
155
+ /** Apply snapshots appended since the checkpoint; fail closed when the branch moved. */
156
+ metaEnabled(ctx: Pick<ExtensionContext, "sessionManager">): boolean {
157
+ try {
158
+ if (!this.ready) this.reset(ctx);
159
+ if (!this.ready) return false;
160
+ const branch = ctx.sessionManager.getBranch() as BranchEntry[];
161
+ let start = 0;
162
+ if (this.checkpoint !== undefined) {
163
+ const index = branch.findIndex((entry) => entry.id === this.checkpoint);
164
+ if (index < 0) {
165
+ this.reset(ctx);
166
+ return this.ready && this.enabled;
167
+ }
168
+ start = index + 1;
169
+ }
170
+ for (const entry of branch.slice(start)) {
171
+ const snapshot = entrySnapshot(entry);
172
+ if (snapshot) this.enabled = snapshot.metaEnabled === true;
173
+ }
174
+ this.checkpoint = branch.at(-1)?.id ?? this.checkpoint;
175
+ return this.enabled;
176
+ } catch {
177
+ return false;
178
+ }
179
+ }
180
+ }
181
+
182
+ /** Full eligibility: genuine reachable pi-checklist ≥3.0.0 AND live task meta enabled. */
183
+ export function checklistStatus(
184
+ pi: Pick<ExtensionAPI, "getAllTools" | "getActiveTools">,
185
+ mirror: ChecklistMetaMirror,
186
+ ctx: Pick<ExtensionContext, "sessionManager">,
187
+ ): ChecklistStatus {
188
+ const installed = detectChecklistPackage(pi);
189
+ if (!installed.eligible) return installed;
190
+ if (!mirror.metaEnabled(ctx))
191
+ return { eligible: false, reason: "pi-checklist task meta is disabled; run /checklist settings meta" };
192
+ return { eligible: true };
193
+ }
194
+
195
+ /** Prompt addendum, only when the Labs opt-in AND checklist eligibility both hold. */
196
+ export function checklistGuidance(mode: "opportunistic" | "orchestration"): string {
197
+ const tagging =
198
+ 'Task meta is enabled in pi-checklist: tag which agent works on each task with a flat meta object, e.g. meta: { agent: "/root/task-slug" } using the agent\'s thread path. Meta values are strings, numbers or booleans (at most 10 keys, keys ≤40 characters, strings ≤200 characters); updates merge keys and null removes a key. Set or update meta.agent when you assign, reassign or finish delegated work.';
199
+ return [
200
+ "## pi-checklist integration",
201
+ mode === "orchestration"
202
+ ? "As /root in orchestration mode you MUST use checklist_create, checklist_read and checklist_update to plan, track and report orchestration work: create a task for every delegated unit and keep statuses current."
203
+ : "When you track work with checklist_create, checklist_read or checklist_update, you may also label delegated tasks by agent. Using the checklist is optional in opportunistic mode.",
204
+ tagging,
205
+ ].join("\n");
206
+ }
@@ -1,7 +1,12 @@
1
1
  import type { ManagerSettings } from "../prefs/settings.ts";
2
+ import { checklistGuidance } from "./checklist-integration.ts";
2
3
 
3
4
  /** Root-only guidance: child SDK sessions use their own worker prompt. */
4
- export function subagentPrompt(settings: ManagerSettings): string | undefined {
5
+ export function subagentPrompt(
6
+ settings: ManagerSettings,
7
+ /** Caller-verified pi-checklist eligibility; ignored unless the Labs opt-in is also on. */
8
+ checklistEligible = false,
9
+ ): string | undefined {
5
10
  if (settings.subagentMode === "off") return undefined;
6
11
  const policy =
7
12
  settings.subagentMode === "orchestration"
@@ -20,5 +25,6 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
20
25
  'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
21
26
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
22
27
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
28
+ ...(settings.checklistIntegration && checklistEligible ? [checklistGuidance(settings.subagentMode)] : []),
23
29
  ].join("\n");
24
30
  }
@@ -53,6 +53,7 @@ export interface ManagerSettings {
53
53
  loaderStyle: LoaderStyle;
54
54
  finalRecap: boolean;
55
55
  subagentExtensions: boolean;
56
+ checklistIntegration: boolean;
56
57
  maxLevels: number;
57
58
  maxConcurrent: number;
58
59
  maxThreads: number;
@@ -74,10 +75,11 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
74
75
  loaderStyle: "circle",
75
76
  finalRecap: false,
76
77
  subagentExtensions: false,
78
+ checklistIntegration: false,
77
79
  };
78
80
 
79
81
  const KEYS = [
80
- "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "costDisplay", "costValue", "costIcon", "nerdFontIcons", "loaderStyle", "finalRecap", "subagentExtensions",
82
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "costDisplay", "costValue", "costIcon", "nerdFontIcons", "loaderStyle", "finalRecap", "subagentExtensions", "checklistIntegration",
81
83
  ] as const;
82
84
  const MAX_LEVELS = 32;
83
85
 
@@ -115,7 +117,7 @@ function positiveSafeInteger(value: unknown): value is number {
115
117
  }
116
118
 
117
119
  function requirement(key: (typeof KEYS)[number]): string {
118
- if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions") return `${key} must be a boolean`;
120
+ if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions" || key === "checklistIntegration") return `${key} must be a boolean`;
119
121
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
120
122
  if (key === "widgetMode") return "widgetMode must be full or minimal";
121
123
  if (key === "costDisplay") return "costDisplay must be pi-footer-event, pi-footer-status or pi-status";
@@ -154,7 +156,7 @@ function parseSettings(content: string): Partial<ManagerSettings> {
154
156
  for (const key of KEYS) {
155
157
  if (!Object.hasOwn(record, key)) continue;
156
158
  const value = record[key];
157
- if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions") {
159
+ if (key === "nerdFontIcons" || key === "finalRecap" || key === "subagentExtensions" || key === "checklistIntegration") {
158
160
  if (typeof value !== "boolean") throw new Error(requirement(key));
159
161
  layer[key] = value;
160
162
  continue;
@@ -337,10 +337,11 @@ export class LiveAgentView {
337
337
  ).render(Math.max(1, width));
338
338
  }
339
339
 
340
- /** Tool/metadata previews are bounded by rendered rows, not just source newlines. */
341
- private preview(content: unknown, width: number): string[] {
340
+ /** Collapsed content is bounded by rendered rows, not just source newlines. */
341
+ private preview(content: unknown, width: number, markdown = false): string[] {
342
342
  const values = Array.isArray(content) ? content : [content];
343
343
  const lines: string[] = [];
344
+ const more = this.theme.fg("dim", markdown ? "... (Ctrl+O to expand)" : "...");
344
345
  for (const value of values) {
345
346
  const block = object(value);
346
347
  const valueText =
@@ -351,14 +352,15 @@ export class LiveAgentView {
351
352
  : block?.type === "image"
352
353
  ? "[Image — text-only observer]"
353
354
  : json(value);
354
- // Avoid wrapping megabytes of tool output just to display its first three rows.
355
+ // Bound source work before rendering a collapsed preview.
355
356
  const safe = text(valueText);
356
357
  const bounded = safe.slice(0, 32768);
357
- for (const line of bounded.split("\n")) {
358
- lines.push(...wrapTextWithAnsi(line, Math.max(1, width)));
359
- if (lines.length > 3) return [...lines.slice(0, 3), this.theme.fg("dim", "...")];
358
+ const rendered = markdown ? this.markdown(bounded, width) : bounded.split("\n");
359
+ for (const line of rendered) {
360
+ lines.push(...(markdown ? [line] : wrapTextWithAnsi(line, Math.max(1, width))));
361
+ if (lines.length > 3) return [...lines.slice(0, 3), more];
360
362
  }
361
- if (safe.length > bounded.length) return [...lines.slice(0, 3), this.theme.fg("dim", "...")];
363
+ if (safe.length > bounded.length) return [...lines.slice(0, 3), more];
362
364
  }
363
365
  return lines;
364
366
  }
@@ -392,6 +394,13 @@ export class LiveAgentView {
392
394
  return this.preview(json(block), width);
393
395
  }
394
396
 
397
+ /** Extension messages follow the tool detail cycle without running extension renderers. */
398
+ private customBlocks(content: unknown, width: number): string[] {
399
+ if (this.detail === "compact") return [];
400
+ if (this.detail === "full") return this.blocks(content, width);
401
+ return this.pad(this.preview(content, Math.max(1, width - 2), true));
402
+ }
403
+
395
404
  private message(message: AgentMessage, width: number): string[] {
396
405
  if (message.role === "toolResult") {
397
406
  const result = message as unknown as Record<string, unknown>;
@@ -416,7 +425,11 @@ export class LiveAgentView {
416
425
  : [];
417
426
  const lines = [
418
427
  ...this.pad([heading]),
419
- ...(collapsed ? this.pad(this.preview(content, inner)) : this.blocks(content, width)),
428
+ ...(message.role === "custom"
429
+ ? this.customBlocks(content, width)
430
+ : collapsed
431
+ ? this.pad(this.preview(content, inner))
432
+ : this.blocks(content, width)),
420
433
  ...this.pad(errors),
421
434
  "",
422
435
  ];
@@ -30,6 +30,7 @@ import { editAgentTypes } from "./ui.ts";
30
30
  import type { ToolEditorOptions } from "./tool-picker.ts";
31
31
  import { AGENT_LOADERS, availableLoaderStyles, effectiveLoaderStyle } from "./agent-loader.ts";
32
32
  import { costIconGlyph } from "./cost-footer.ts";
33
+ import { CHECKLIST_REQUIREMENTS, type ChecklistStatus } from "../orch/checklist-integration.ts";
33
34
 
34
35
  const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
35
36
  const loader = AGENT_LOADERS[id];
@@ -254,6 +255,8 @@ export async function configureAgents(
254
255
  settings: ManagerSettings;
255
256
  agentDir: string;
256
257
  getAllTools?: ToolEditorOptions["getAllTools"];
258
+ /** Live pi-checklist eligibility; absent means unavailable (fail closed). */
259
+ checklistStatus?: () => ChecklistStatus;
257
260
  apply(): void;
258
261
  },
259
262
  ): Promise<void> {
@@ -263,6 +266,25 @@ export async function configureAgents(
263
266
  );
264
267
  }
265
268
 
269
+ /** Always shown; "disabled" (muted, guarded) unless pi-checklist prerequisites currently hold. */
270
+ function checklistRow(enabled: boolean, status: ChecklistStatus): DialogRow {
271
+ const requirements = `${CHECKLIST_REQUIREMENTS}\nWhen On and eligible, adds prompt guidance to tag which agent works on each checklist task via meta.agent; in Orchestration mode /root must use the checklist. Off by default.`;
272
+ if (status.eligible)
273
+ return {
274
+ id: "checklistIntegration",
275
+ label: "[lab] Checklist integration",
276
+ value: enabled ? "On" : "Off",
277
+ help: `Experimental: integrate with pi-checklist.\n${requirements}\nAvailable now: pi-checklist ≥3.0.0 is loaded with task meta enabled.`,
278
+ };
279
+ return {
280
+ id: "checklistIntegration",
281
+ label: "[lab] Checklist integration",
282
+ value: enabled ? "On · inactive (unavailable)" : "Off · unavailable",
283
+ valueColor: "muted",
284
+ help: `Experimental: integrate with pi-checklist.\nUnavailable: ${status.reason ?? "requirements not met"}.\n${requirements}\n${enabled ? "Saved On but inactive until requirements are met; Enter turns it Off." : "Cannot be turned On until requirements are met."}`,
285
+ };
286
+ }
287
+
266
288
  async function configureAgentsDialog(
267
289
  ctx: ExtensionCommandContext,
268
290
  options: {
@@ -270,9 +292,18 @@ async function configureAgentsDialog(
270
292
  settings: ManagerSettings;
271
293
  agentDir: string;
272
294
  getAllTools?: ToolEditorOptions["getAllTools"];
295
+ /** Live pi-checklist eligibility; absent means unavailable (fail closed). */
296
+ checklistStatus?: () => ChecklistStatus;
273
297
  apply(): void;
274
298
  },
275
299
  ): Promise<void> {
300
+ const checklistStatus = (): ChecklistStatus => {
301
+ try {
302
+ return options.checklistStatus?.() ?? { eligible: false, reason: "pi-checklist status is unavailable" };
303
+ } catch (error) {
304
+ return { eligible: false, reason: `could not verify pi-checklist: ${error instanceof Error ? error.message : String(error)}` };
305
+ }
306
+ };
276
307
  const readLayers = () => loadManagerSettingsLayers({
277
308
  cwd: ctx.cwd,
278
309
  agentDir: options.agentDir,
@@ -345,6 +376,7 @@ async function configureAgentsDialog(
345
376
  value: draft.subagentExtensions ? "On" : "Off",
346
377
  help: "Experimental: reload configured user/trusted-project extension hooks in separate subagent sessions (not CLI-only or inline extensions). Bugs and unintended consequences may occur if hooks assume main-session state.\nRead limitations: https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md\nOff by default. Save and apply affects newly opened sessions, not already-open agents.",
347
378
  },
379
+ checklistRow(draft.checklistIntegration, checklistStatus()),
348
380
  {
349
381
  id: "finalRecap",
350
382
  label: "[lab] Final Recap",
@@ -453,6 +485,12 @@ async function configureAgentsDialog(
453
485
  if (styles.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
454
486
  } else if (action === "subagentExtensions") {
455
487
  draft.subagentExtensions = !draft.subagentExtensions;
488
+ } else if (action === "checklistIntegration") {
489
+ const status = checklistStatus();
490
+ // Turning Off is always allowed; turning On requires current eligibility.
491
+ if (!draft.checklistIntegration && !status.eligible)
492
+ ctx.ui.notify(`Checklist integration cannot be enabled: ${status.reason ?? "requirements not met"}. ${CHECKLIST_REQUIREMENTS}`, "warning");
493
+ else draft.checklistIntegration = !draft.checklistIntegration;
456
494
  } else if (action === "finalRecap") {
457
495
  draft.finalRecap = !draft.finalRecap;
458
496
  } else if (action === "scope") {
@@ -529,6 +567,11 @@ async function configureAgentsDialog(
529
567
  });
530
568
  options.store.reload();
531
569
  } else if (action === "save") {
570
+ if (draft.checklistIntegration && !baseline.checklistIntegration) {
571
+ const status = checklistStatus();
572
+ if (!status.eligible)
573
+ throw new Error(`Checklist integration cannot be enabled: ${status.reason ?? "requirements not met"}. Turn it Off or satisfy: ${CHECKLIST_REQUIREMENTS}`);
574
+ }
532
575
  const file = saveManagerOverrides({
533
576
  cwd: ctx.cwd,
534
577
  agentDir: options.agentDir,