pi-subagent-manager 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,7 +76,7 @@ They inherit your current model until you set preferences. Details: [docs/defaul
76
76
  | `/agents reload` | Reload definitions and settings |
77
77
  | `/agents reap` | Confirm the eligible count, then forget completed agents and free retained-thread slots (cannot be resumed); preserves active parents and ancestors of retained threads. Session files remain on disk. |
78
78
 
79
- A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
79
+ A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. Arrow keys walk **tree ← full ← minimal**: press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings, and **Left** at the start of the draft to step back to full and then, while subagents are starting or running, into the tree (otherwise Left stays native). With the Minimal setting the walk is just **tree ← minimal**. In the tree, **Right** on a leaf returns to the widget. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
80
80
 
81
81
  **Cost accounting:** Agent rows show estimated USD cost (including cache reads/writes) when reported. Completed, paused, stopped, and failed agents roll up only newly incurred cost. Accounting survives resume, reload, branch navigation, and reaping; nested agents' own costs are counted once. Running-agent costs remain in their rows until settlement. This changes the footer display, not Pi's native session statistics.
82
82
 
@@ -90,6 +90,8 @@ Enable **[labs] Enable subagent extensions** in `/agents settings` to reload con
90
90
 
91
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).
92
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).
94
+
93
95
  ## Docs
94
96
 
95
97
  - [Your own agent](docs/custom-agents.md) — walkthrough for writing an agent type
@@ -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
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,
@@ -58,7 +59,7 @@ Controls the subagent status display above the input box. Choose **Status Widget
58
59
  | `full` (default) | A compact tree with one row per agent, task/state, metrics and navigation hints. |
59
60
  | `minimal` | One line of theme-colored status counts plus cumulative input `↑` / output `↓` tokens for agents currently starting or running. |
60
61
 
61
- Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode. In full mode, press **Right (→)** at the end of the main draft (or in an empty input) to collapse to one line for this session only, without saving preferences. Session startup/switch/reload restores the configured mode. **Left (←)** at the start of the draft still opens the full dialog while agents are active.
62
+ Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode. Arrow keys at the draft edge walk a fixed line: **tree ← full ← minimal**. With **Full** configured, all three states are reachable: **Right (→)** at the end of the main draft (or in an empty input) collapses full to the one-line minimal view for this session only, without saving preferences; **Left (←)** at the start of the draft first returns minimal to full, and from full opens the tree (only while agents are starting or running). With **Minimal** configured the line is just **tree ← minimal**: Left opens the tree, and Right does nothing because minimal is already the right edge. In the fullscreen tree, **Right** on a leaf row (after folds and descents are exhausted) closes the tree and returns to the widget (full, or minimal if configured). Session startup/switch/reload restores the configured mode.
62
63
 
63
64
  ## [labs] Nerd Font icons (`nerdFontIcons`)
64
65
 
@@ -111,6 +112,19 @@ 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.
@@ -186,8 +200,15 @@ Lower it to keep the tree tidy. Raise it for long sessions with many agents. Whe
186
200
 
187
201
  Settings are read in order: **built-in defaults → Global → trusted Current Project**.
188
202
  All keys are optional. The dialog saves only values different from the lower layer,
189
- so unchanged settings continue inheriting future global changes. Restoring defaults
190
- is a draft edit; in Project scope it can explicitly override non-default global values.
203
+ so unchanged settings continue inheriting future global changes.
204
+
205
+ **Restore defaults** asks you to pick **Global** or **Project** (Project only in a
206
+ trusted project). The picker shows the exact `settings.json` path each choice
207
+ deletes. Choosing one deletes that file immediately — nothing is rewritten with
208
+ default or empty values — then reloads settings and discards unsaved edits. A
209
+ missing file is not an error. There is no undo, and Cancel in the outer dialog
210
+ cannot bring the file back. Deleting the Project file returns the save scope to
211
+ Global; Global values still apply beneath any remaining Project file.
191
212
 
192
213
  Colored dots before each setting describe saved changes: an **accent dot** means
193
214
  changed in Global relative to defaults; a **warning dot** means changed in Current
@@ -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.
@@ -84,7 +84,7 @@ The fullscreen watcher renders steer and agent messages (including thinking) as
84
84
 
85
85
  While any subagent is **starting or running**, press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. With no active subagents, or elsewhere in the draft, Left retains normal cursor movement. `/agents tree` remains available regardless of agent activity. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
86
86
 
87
- Press physical **Right (→)** at the end of the main draft (or in an empty input) to collapse the full widget to a single status line for this session. This does not save settings or change the configured **Status Widget** mode. Refreshes, agent resumes, new main turns and session-tree navigation keep it collapsed; starting, switching or reloading a session restores the configured mode. Left still opens the full dialog while subagents are active, without expanding the widget. Elsewhere in the draft Right retains normal cursor movement; autocomplete, jumps, paste and shortcuts take precedence.
87
+ Press physical **Right (→)** at the end of the main draft (or in an empty input) to collapse the full widget to a single status line for this session. This does not save settings or change the configured **Status Widget** mode. Refreshes, agent resumes, new main turns and session-tree navigation keep it collapsed; starting, switching or reloading a session restores the configured mode. Left from that collapsed line first returns to the full widget; Left again opens the full dialog while subagents are active. In the fullscreen tree, Right on a leaf row closes the tree and returns to the full widget, so the keys always walk **tree ← full ← minimal**. When **Status Widget** is set to Minimal, the walk is **tree ← minimal**: Left opens the tree directly, Right in the tree returns to the minimal line, and Right at the draft does nothing. Elsewhere in the draft Right retains normal cursor movement; autocomplete, jumps, paste and shortcuts take precedence.
88
88
 
89
89
  Arrow-key shortcuts are enabled by default in the TUI; `/agents tree` remains available everywhere. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
90
90
 
@@ -99,7 +99,7 @@ The widget above the input editor has two display modes, selected with **Status
99
99
  - **Full** (default): the existing compact tree, at most twelve lines.
100
100
  - **Minimal**: a summary line such as `3 running, 2 stopped, 1 failed, 1 paused ↑12k ↓3k`, with semantic theme colors. Starting agents count as running; completed agents are counted when present. Token totals include only currently starting/running agents, not the main conversation or settled threads. Use `/agents tree` for details.
101
101
 
102
- Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A fresh main prompt hides agents that were already settled (completed, failed, stopped or paused); they remain in `/agents tree` and reappear in the widget only when resumed. Agents still starting or running remain visible, and new agents appear normally. Automatic Final Recap turns keep the current task's results visible. Visible agents use the configured display mode unless Right has collapsed the widget for this session.
102
+ Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A fresh main prompt hides agents that were already settled (completed, failed, stopped or paused); they remain in `/agents tree` and reappear in the widget only when resumed. Agents still starting or running remain visible, and new agents appear normally. Automatic Final Recap turns keep the current task's results visible. Visible agents use the configured display mode unless Right has collapsed the widget for this session (Left expands it again).
103
103
 
104
104
  In full mode:
105
105
 
@@ -107,7 +107,7 @@ In full mode:
107
107
  - Activity and lifecycle messages (such as `Completed; session retained`) are omitted to save space; detailed status remains available in `/agents tree` and `agent_status`.
108
108
  - Agents are ordered newest-started first (spawn or resume); a branch ranks by its most recently started agent. The most recently started agents are preferred when previews overflow. Overflow is counted, not listed.
109
109
  - Time freezes while paused and resumes on continue.
110
- - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. The full footer also shows **→ collapse**. Minimal mode keeps **← browser** inline so it stays one line. Browser hints appear only while subagents are starting or running; RPC output omits keyboard hints.
110
+ - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. The full footer also shows **→ collapse**. Minimal mode keeps **← browser** inline so it stays one line (**← expand** when it is a session collapse of full). Browser hints appear only while subagents are starting or running; RPC output omits keyboard hints.
111
111
  - With **[labs] Nerd Font icons** enabled, the selected Circle, Braille, or Hourglass loader appears before the preserved role icon in the widget and fullscreen tree/live-view headers. Each family provides completed, paused, failed, and stopped state icons. The minimal summary uses the same indicators for its status counts. Preview all families and states under **[labs] Loader style**. Animation timers stop on settlement or disposal; RPC output stays static.
112
112
 
113
113
  ### Interrupts and stopping agents
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.26.0",
3
+ "version": "0.28.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
@@ -39,6 +39,7 @@
39
39
  "check": "tsc --noEmit",
40
40
  "changelog": "tsx .github/scripts/changelog.ts",
41
41
  "test": "tsx --test tests/*.test.ts",
42
+ "test:ttyd": "node .agents/skills/ttyd-testing/scripts/smoke-test.mjs && node .agents/skills/ttyd-testing/scripts/lifecycle-test.mjs",
42
43
  "test:coverage": "mkdir -p coverage && tsx --test --experimental-test-coverage --test-coverage-include='src/**' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info tests/*.test.ts",
43
44
  "prepublishOnly": "npm run check && npm test",
44
45
  "format": "prettier --write --print-width 100 src tests agents .github docs/default-agents.md README.md",
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,6 +75,8 @@ 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>();
@@ -94,7 +97,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
94
97
  summaryTimer = undefined;
95
98
  summaryRunning = false;
96
99
  };
97
- let navigation = new AgentNavigationController();
100
+ // Right at a tree leaf steps tree → full: leave any session collapse behind.
101
+ const returnToWidget = () => {
102
+ if (!widgetCollapsed) return;
103
+ widgetCollapsed = false;
104
+ if (context) refreshWidget(context);
105
+ };
106
+ let navigation = new AgentNavigationController(returnToWidget);
98
107
  let navigationEditor: AgentNavigationEditor | undefined;
99
108
  let navigationEditorFactory: Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
100
109
  let navigationGeneration = 0;
@@ -166,6 +175,19 @@ export default function piSubagent(pi: ExtensionAPI): void {
166
175
  widgetCollapsed = true;
167
176
  if (context) refreshWidget(context);
168
177
  },
178
+ // Left from the session-collapsed one-liner returns to full before the tree.
179
+ canExpand: () =>
180
+ manager !== undefined &&
181
+ context?.mode === "tui" &&
182
+ limits.subagentMode !== "off" &&
183
+ !navigation.isOpen &&
184
+ widgetCollapsed &&
185
+ limits.widgetMode === "full" &&
186
+ widgetThreads().some((thread) => thread.path !== "/root"),
187
+ expandWidget: () => {
188
+ widgetCollapsed = false;
189
+ if (context) refreshWidget(context);
190
+ },
169
191
  onError: (error) =>
170
192
  context?.ui.notify(error instanceof Error ? error.message : String(error), "error"),
171
193
  });
@@ -493,6 +515,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
493
515
  limits.nerdFontIcons,
494
516
  rootTurnEnded,
495
517
  limits.loaderStyle,
518
+ widgetCollapsed && limits.widgetMode === "full",
496
519
  );
497
520
  };
498
521
  pi.on("agent_start", async (_event, ctx) => {
@@ -518,7 +541,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
518
541
  });
519
542
  syncTools();
520
543
  pi.on("before_agent_start", async (event, ctx) => {
521
- const prompt = subagentPrompt(limits);
544
+ // Re-verify on every turn: the Labs opt-in AND live checklist eligibility must both hold.
545
+ const prompt = subagentPrompt(
546
+ limits,
547
+ limits.checklistIntegration && limits.subagentMode !== "off" && currentChecklistStatus(ctx).eligible,
548
+ );
522
549
  if (!prompt) return;
523
550
  if (limits.subagentMode === "opportunistic" && event.prompt.startsWith(IMPORT_REQUEST_PREFIX)) {
524
551
  try {
@@ -540,10 +567,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
540
567
  cancelSummary();
541
568
  const token = ++generation;
542
569
  closeNavigation(installEditor);
543
- navigation = new AgentNavigationController();
570
+ navigation = new AgentNavigationController(returnToWidget);
544
571
  // session_start already belongs to the replacement session: never append the old registry here.
545
572
  if (manager) await manager.shutdown();
546
573
  inheritedTools.reset();
574
+ // pi-checklist reseeds its own state on these same lifecycle events.
575
+ checklistMirror.reset(ctx);
547
576
  context = ctx;
548
577
  costLedger = new CostLedger();
549
578
  costLedger.restore(ctx.sessionManager.getEntries());
@@ -765,6 +794,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
765
794
  settings: limits,
766
795
  agentDir: getAgentDir(),
767
796
  getAllTools: () => pi.getAllTools(),
797
+ checklistStatus: () => currentChecklistStatus(ctx),
768
798
  apply: () => {
769
799
  const diagnostics = loadLimits(ctx);
770
800
  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;
@@ -486,3 +488,29 @@ export function setManagerProjectSettings(options: ManagerSettingsOptions & {
486
488
  }
487
489
  return entry.filePath;
488
490
  }
491
+
492
+ /** Resolved settings.json path for a scope; the file may not exist. */
493
+ export function managerSettingsPath(options: ManagerSettingsOptions, scope: ManagerSaveScope): string {
494
+ if (scope === "project") {
495
+ if (!options.includeProject) throw new Error("Project settings are not enabled/trusted");
496
+ return layer(options.cwd, [".pi", "agent", "subagent-manager"]).filePath;
497
+ }
498
+ return layer(options.agentDir, ["subagent-manager"]).filePath;
499
+ }
500
+
501
+ /** Restore a scope's defaults by deleting its settings file (nothing is written). A missing file is not an error. */
502
+ export function deleteManagerSettings(options: ManagerSettingsOptions & { scope: ManagerSaveScope }): {
503
+ filePath: string;
504
+ deleted: boolean;
505
+ } {
506
+ if (options.scope !== "user" && options.scope !== "project")
507
+ throw new Error("Invalid settings scope");
508
+ const filePath = managerSettingsPath(options, options.scope);
509
+ const entry = options.scope === "project"
510
+ ? layer(options.cwd, [".pi", "agent", "subagent-manager"])
511
+ : layer(options.agentDir, ["subagent-manager"]);
512
+ // Malformed JSON is removable; symlinks and non-files are refused by settingsFileExists.
513
+ if (!settingsFileExists(entry)) return { filePath, deleted: false };
514
+ unlinkSync(entry.filePath);
515
+ return { filePath, deleted: true };
516
+ }
@@ -16,9 +16,15 @@ export interface AgentNavigationEditorOptions {
16
16
  /** Must return the whole navigation interaction, so repeated Left cannot reopen it. */
17
17
  openTree(): void | Promise<void>;
18
18
  canOpen(): boolean;
19
- /** Session-local widget collapse; never saves the configured display mode. */
19
+ /** Session-local widget collapse (full → minimal); never saves the configured display mode. */
20
20
  collapseWidget?(): void | Promise<void>;
21
21
  canCollapse?(): boolean;
22
+ /**
23
+ * Session-local widget expansion (minimal → full). While it is available, Left
24
+ * steps toward the full widget before the tree: tree ← full ← minimal.
25
+ */
26
+ expandWidget?(): void | Promise<void>;
27
+ canExpand?(): boolean;
22
28
  /** Root ownership token; changing it invalidates queued transitions. */
23
29
  generation(): unknown;
24
30
  onError?(error: unknown): void;
@@ -169,10 +175,17 @@ export class AgentNavigationEditor extends CustomEditor {
169
175
  generation: unknown,
170
176
  direction: "left" | "right",
171
177
  ): void {
172
- const allowed = () => direction === "left"
173
- ? this.navigation.canOpen()
174
- : !!this.navigation.collapseWidget && (this.navigation.canCollapse?.() ?? false);
175
- if (this.pending || !allowed()) return;
178
+ // Left walks one step toward the tree: minimal → full first, then full → tree.
179
+ // Right walks one step toward minimal. The decision is rechecked in the microtask.
180
+ const action = (): "expand" | "tree" | "collapse" | undefined => {
181
+ if (direction === "right")
182
+ return this.navigation.collapseWidget && (this.navigation.canCollapse?.() ?? false)
183
+ ? "collapse" : undefined;
184
+ if (this.navigation.expandWidget && (this.navigation.canExpand?.() ?? false)) return "expand";
185
+ return this.navigation.canOpen() ? "tree" : undefined;
186
+ };
187
+ const chosen = action();
188
+ if (this.pending || !chosen) return;
176
189
  this.pending = direction;
177
190
  const epoch = this.inputEpoch;
178
191
  queueMicrotask(() => {
@@ -182,7 +195,7 @@ export class AgentNavigationEditor extends CustomEditor {
182
195
  !this.focused ||
183
196
  this.inputEpoch !== epoch ||
184
197
  this.navigation.generation() !== generation ||
185
- !allowed() ||
198
+ action() !== chosen ||
186
199
  this.isShowingAutocomplete() ||
187
200
  this.getText() !== text ||
188
201
  after.line !== cursor.line ||
@@ -194,8 +207,9 @@ export class AgentNavigationEditor extends CustomEditor {
194
207
  try {
195
208
  // Call within the checked microtask: an extra Promise.then would leave
196
209
  // a gap in which root ownership could change after validation.
197
- void Promise.resolve(direction === "left"
198
- ? this.navigation.openTree() : this.navigation.collapseWidget!())
210
+ void Promise.resolve(chosen === "tree" ? this.navigation.openTree()
211
+ : chosen === "expand" ? this.navigation.expandWidget!()
212
+ : this.navigation.collapseWidget!())
199
213
  .catch((error: unknown) => this.navigation.onError?.(error))
200
214
  .finally(() => {
201
215
  this.pending = undefined;
@@ -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
  ];
@@ -15,7 +15,9 @@ import {
15
15
  type CostValue,
16
16
  LOADER_STYLES,
17
17
  type LoaderStyle,
18
+ deleteManagerSettings,
18
19
  loadManagerSettingsLayers,
20
+ managerSettingsPath,
19
21
  saveManagerOverrides,
20
22
  setManagerProjectSettings,
21
23
  type ManagerSettings,
@@ -28,6 +30,7 @@ import { editAgentTypes } from "./ui.ts";
28
30
  import type { ToolEditorOptions } from "./tool-picker.ts";
29
31
  import { AGENT_LOADERS, availableLoaderStyles, effectiveLoaderStyle } from "./agent-loader.ts";
30
32
  import { costIconGlyph } from "./cost-footer.ts";
33
+ import { CHECKLIST_REQUIREMENTS, type ChecklistStatus } from "../orch/checklist-integration.ts";
31
34
 
32
35
  const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
33
36
  const loader = AGENT_LOADERS[id];
@@ -252,6 +255,8 @@ export async function configureAgents(
252
255
  settings: ManagerSettings;
253
256
  agentDir: string;
254
257
  getAllTools?: ToolEditorOptions["getAllTools"];
258
+ /** Live pi-checklist eligibility; absent means unavailable (fail closed). */
259
+ checklistStatus?: () => ChecklistStatus;
255
260
  apply(): void;
256
261
  },
257
262
  ): Promise<void> {
@@ -261,6 +266,25 @@ export async function configureAgents(
261
266
  );
262
267
  }
263
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
+
264
288
  async function configureAgentsDialog(
265
289
  ctx: ExtensionCommandContext,
266
290
  options: {
@@ -268,9 +292,18 @@ async function configureAgentsDialog(
268
292
  settings: ManagerSettings;
269
293
  agentDir: string;
270
294
  getAllTools?: ToolEditorOptions["getAllTools"];
295
+ /** Live pi-checklist eligibility; absent means unavailable (fail closed). */
296
+ checklistStatus?: () => ChecklistStatus;
271
297
  apply(): void;
272
298
  },
273
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
+ };
274
307
  const readLayers = () => loadManagerSettingsLayers({
275
308
  cwd: ctx.cwd,
276
309
  agentDir: options.agentDir,
@@ -343,6 +376,7 @@ async function configureAgentsDialog(
343
376
  value: draft.subagentExtensions ? "On" : "Off",
344
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.",
345
378
  },
379
+ checklistRow(draft.checklistIntegration, checklistStatus()),
346
380
  {
347
381
  id: "finalRecap",
348
382
  label: "[lab] Final Recap",
@@ -364,7 +398,7 @@ async function configureAgentsDialog(
364
398
  {
365
399
  id: "defaults",
366
400
  label: "Restore defaults",
367
- help: "Replace all values shown with built-in defaults.\nNothing is saved until you choose Save and apply.",
401
+ help: "Pick Global or Project, then delete that scope's settings.json so its defaults apply again.\nThe file is removed, not rewritten; unsaved edits are discarded. This cannot be undone.",
368
402
  },
369
403
  {
370
404
  id: "save",
@@ -451,6 +485,12 @@ async function configureAgentsDialog(
451
485
  if (styles.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
452
486
  } else if (action === "subagentExtensions") {
453
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;
454
494
  } else if (action === "finalRecap") {
455
495
  draft.finalRecap = !draft.finalRecap;
456
496
  } else if (action === "scope") {
@@ -489,7 +529,37 @@ async function configureAgentsDialog(
489
529
  options.apply();
490
530
  }
491
531
  }
492
- } else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
532
+ } else if (action === "defaults") {
533
+ const target = { cwd: ctx.cwd, agentDir: options.agentDir, includeProject: ctx.isProjectTrusted() };
534
+ const globalPath = managerSettingsPath(target, "user");
535
+ const projectPath = target.includeProject ? managerSettingsPath(target, "project") : undefined;
536
+ const explain = (path: string) =>
537
+ `Deletes this file now (nothing is written):\n${path}\nIf it does not exist, nothing happens. Unsaved edits are discarded. No undo.`;
538
+ const rows: DialogRow[] = [
539
+ { id: "user", label: "Global", value: "Restore global defaults", help: explain(globalPath) },
540
+ ...(projectPath
541
+ ? [{ id: "project", label: "Project", value: "Restore project defaults", help: explain(projectPath) }]
542
+ : []),
543
+ { id: "cancel", label: "Cancel", help: "Delete nothing." },
544
+ ];
545
+ const choice = await dialogMenu(ctx, "Restore defaults: delete which settings file?", rows, {
546
+ selectedId: "cancel",
547
+ footer: "↑↓/Tab choose · Enter delete file · Esc cancel",
548
+ });
549
+ if (choice === "user" || choice === "project") {
550
+ const { filePath, deleted } = deleteManagerSettings({ ...target, scope: choice });
551
+ layers = readLayers();
552
+ reportDiagnostics();
553
+ baseline = { ...layers.settings };
554
+ draft = { ...baseline };
555
+ scope = layers.scope;
556
+ options.apply();
557
+ ctx.ui.notify(
558
+ deleted ? `Deleted ${filePath}. Defaults restored.` : `No settings file at ${filePath}; nothing to delete.`,
559
+ "info",
560
+ );
561
+ }
562
+ }
493
563
  else if (action === "types") {
494
564
  await editAgentTypes(ctx, options.store, draft.nerdFontIcons, {
495
565
  getAllTools: options.getAllTools ?? (() => []),
@@ -497,6 +567,11 @@ async function configureAgentsDialog(
497
567
  });
498
568
  options.store.reload();
499
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
+ }
500
575
  const file = saveManagerOverrides({
501
576
  cwd: ctx.cwd,
502
577
  agentDir: options.agentDir,
@@ -114,6 +114,8 @@ export class StatusDialog {
114
114
  state: AgentTreeState;
115
115
  actions(path: string): void;
116
116
  fullscreen?: boolean;
117
+ /** Right on a leaf steps tree → widget; called just before the tree closes. */
118
+ returnToWidget?(): void;
117
119
  },
118
120
  private nerdFontIcons = false,
119
121
  private loaderStyle: LoaderStyle = "circle",
@@ -242,6 +244,12 @@ export class StatusDialog {
242
244
  else {
243
245
  const child = row?.hasChildren ? firstChild(rows, index) : undefined;
244
246
  if (child) this.selectedPath = child.path;
247
+ else if (this.navigation?.fullscreen) {
248
+ // Nothing left to fold or descend into: the next step right is the widget.
249
+ this.navigation.returnToWidget?.();
250
+ this.done(undefined);
251
+ return;
252
+ }
245
253
  }
246
254
  } else {
247
255
  let next = index;
@@ -355,7 +363,7 @@ export class StatusDialog {
355
363
  height,
356
364
  this.heading(rows, start, treeCount),
357
365
  body,
358
- this.navigation ? "Esc main · ↑↓ select · ←→ fold · i Actions · Ctrl+C stop all" : FOOTER,
366
+ this.navigation ? "Esc main · ↑↓ select · ←→ fold · → widget · i Actions · Ctrl+C stop all" : FOOTER,
359
367
  );
360
368
  }
361
369
 
@@ -433,6 +441,8 @@ export class AgentNavigationController {
433
441
  private opening: Promise<void> | undefined;
434
442
  private generation = 0;
435
443
 
444
+ constructor(private returnToWidget?: () => void) {}
445
+
436
446
  get isOpen(): boolean {
437
447
  return this.opening !== undefined;
438
448
  }
@@ -527,6 +537,7 @@ export class AgentNavigationController {
527
537
  {
528
538
  state: this.tree,
529
539
  fullscreen: true,
540
+ returnToWidget: this.returnToWidget,
530
541
  actions: (path) => finish({ kind: "actions", path }),
531
542
  },
532
543
  nerdFontIcons,
package/src/ui/ui.ts CHANGED
@@ -226,6 +226,8 @@ interface AgentWidgetRenderOptions {
226
226
  loaderStyle?: LoaderStyle;
227
227
  /** RPC snapshots use a static running frame and never start an animation. */
228
228
  animate?: boolean;
229
+ /** Minimal line is a session collapse of full: Left steps back to full, not the browser. */
230
+ expandHint?: boolean;
229
231
  }
230
232
 
231
233
  function agentWidgetStatus(
@@ -377,6 +379,7 @@ export function renderAgentSummary(
377
379
  nerdFontIcons = false,
378
380
  animate = true,
379
381
  loaderStyle = "circle",
382
+ expandHint = false,
380
383
  }: AgentWidgetRenderOptions = {},
381
384
  ): string[] {
382
385
  const agents = new Map<string, ThreadView>();
@@ -420,7 +423,7 @@ export function renderAgentSummary(
420
423
  return theme.fg(color, `${progress ? `${progress} ` : ""}${counts[state]} ${state}`);
421
424
  })
422
425
  .join(theme.fg("muted", ", ")) +
423
- (showBrowserHint && counts.running > 0 ? theme.fg("muted", " · ← browser") : "");
426
+ (showBrowserHint && counts.running > 0 ? theme.fg("muted", expandHint ? " · ← expand" : " · ← browser") : "");
424
427
  const right = theme.fg("muted", `↑${formatCount(input)} ↓${formatCount(output)}`);
425
428
  return [fitLine(left, right, Math.max(0, width))];
426
429
  }
@@ -432,6 +435,8 @@ export function updateWidget(
432
435
  nerdFontIcons = false,
433
436
  rootTurnEnded = false,
434
437
  loaderStyle: LoaderStyle = "circle",
438
+ /** True while a configured-full widget is session-collapsed to the minimal line. */
439
+ sessionCollapsed = false,
435
440
  ): void {
436
441
  if (!ctx.hasUI) return;
437
442
  if (!threads.some((thread) => thread.path !== "/root")) {
@@ -470,6 +475,7 @@ export function updateWidget(
470
475
  showBrowserHint: !settled,
471
476
  nerdFontIcons,
472
477
  loaderStyle,
478
+ expandHint: sessionCollapsed,
473
479
  }),
474
480
  invalidate: () => {},
475
481
  dispose: () => {