@narumitw/pi-herdr 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,17 +2,18 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@narumitw/pi-herdr)](https://www.npmjs.com/package/@narumitw/pi-herdr) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
4
 
5
- Connect Pi's interactive lifecycle to Herdr and bundle the operating guidance needed to control Herdr safely.
5
+ Connect Pi's interactive lifecycle to Herdr and bootstrap the operating guidance supplied by the installed Herdr CLI.
6
6
 
7
7
  ## ✨ Features
8
8
 
9
9
  - Reports Pi session identity and `working`, `blocked`, and `idle` lifecycle states to the current Herdr pane.
10
10
  - Publishes bounded `model`, `provider`, `thinking`, `session`, and `context_usage` tokens for Herdr sidebar rows.
11
- - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor.
11
+ - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor, with a saved visibility toggle in `/herdr`.
12
12
  - Updates the widget from Herdr pane lifecycle and agent-status events without polling the CLI.
13
13
  - Coalesces rapid state changes and retries short-lived local socket failures without interrupting Pi.
14
14
  - Derives blocked state from Pi's public `ui_prompt_start` and `ui_prompt_end` lifecycle events.
15
- - Bundles the `herdr` skill for explicit Herdr inspection and control requests.
15
+ - Bundles a thin `herdr` bootstrap skill for explicit Herdr inspection and control requests.
16
+ - Loads version-matched operating guidance from the installed `herdr --skill` command.
16
17
  - Keeps extension and skill installation in one Pi package.
17
18
 
18
19
  ## 📦 Install
@@ -44,6 +45,7 @@ Start Pi inside a Herdr-managed pane after installing the package.
44
45
  The extension activates automatically when `HERDR_ENV=1`, `HERDR_SOCKET_PATH`, and `HERDR_PANE_ID` are present.
45
46
  When the current Herdr workspace contains another recognized agent, Pi shows its state in a widget above the editor.
46
47
  Ask Pi to use Herdr, or invoke `/skill:herdr`, when you want it to inspect or control the current Herdr session.
48
+ Before the first control command, the bootstrap loads `herdr --skill` once and reuses those instructions while they remain in the current context.
47
49
 
48
50
  If the standalone integration and skill are already installed, remove them after installing this package to avoid duplicate state reports and skill-name collisions:
49
51
 
@@ -54,6 +56,31 @@ rm -rf ~/.agents/skills/herdr
54
56
 
55
57
  Run `/reload` or restart Pi after changing the installed resources.
56
58
 
59
+ ## 💬 Commands
60
+
61
+ `/herdr` opens a menu to toggle the agent widget and view status or help, inspired by `/tool`.
62
+ It accepts no arguments and is available inside Herdr in TUI and RPC modes; print and JSON modes reject it.
63
+ RPC can save the preference but does not display the widget.
64
+ Changes apply immediately and closing the menu does not undo saved changes.
65
+
66
+ ## ⚙️ Settings
67
+
68
+ Toggle **Agent widget** in `/herdr`, or edit `<getAgentDir()>/pi-herdr.json` (normally `~/.pi/agent/pi-herdr.json`):
69
+
70
+ ```json
71
+ {
72
+ "widget": false
73
+ }
74
+ ```
75
+
76
+ `widget` accepts only `true` or `false` and defaults to `true` when absent.
77
+ Only user settings are supported; project files are not read.
78
+ Manual edits apply after `/reload` or the next session start.
79
+ Missing files are not created until an explicit save. Invalid files trigger a warning, use defaults, and block saves until repaired.
80
+ Saves preserve unknown fields and use atomic temporary-file-plus-rename publication, with reads and writes ordered within one Pi process, not across processes.
81
+ Failed saves restore the previous effective value and leave the existing file untouched.
82
+ Turning the widget off closes its subscription and pending requests without disabling lifecycle or metadata reporting.
83
+
57
84
  ## 🔄 Lifecycle reporting
58
85
 
59
86
  The extension reports only interactive TUI sessions because Herdr displays agents attached to terminal panes.
@@ -124,18 +151,20 @@ The subscription can deliver matching pane events from other workspaces in the s
124
151
  The extension filters presentation to the current workspace, strips terminal controls at the display boundary, and never reads sibling terminal output for the widget.
125
152
  The package does not authenticate the endpoint, so trust the environment that launches Pi and controls these variables.
126
153
 
127
- The bundled skill can direct Pi to inspect terminals, create panes, start agents, send input, and run commands through the local `herdr` CLI.
154
+ The bundled bootstrap loads operating guidance from the local `herdr --skill` command only after an explicit user request involving Herdr.
155
+ The returned CLI-owned skill can direct Pi to inspect terminals, create panes, start agents, send input, and run commands through the local `herdr` CLI.
128
156
  Those commands execute with the same user permissions as Pi and can affect live terminal sessions.
129
- The skill requires an explicit user request involving Herdr and stops when `HERDR_ENV` is not `1`.
130
- It treats a startup-blocked agent as not ready, refuses to prompt an already blocked agent, requires inspecting the blocked UI, and requires asking the user before answering an approval or question dialog.
157
+ The bootstrap stops when `HERDR_ENV` is not `1`, when the CLI is unavailable, or when `herdr --skill` fails.
158
+ Command recipes, approval handling, and other operating safety rules come from the installed Herdr version instead of being duplicated by this package.
131
159
 
132
160
  ## 🚧 Limitations
133
161
 
134
162
  - Lifecycle reporting, metadata reporting, and the agent widget are disabled in RPC, JSON, and print modes.
135
- - The widget has no settings for placement, workspace scope, visibility, or row count.
163
+ - The widget has no settings for placement, workspace scope, or row count.
136
164
  - The widget cannot show blocked prompt text because Herdr does not expose it through public pane responses.
137
165
  - Herdr exposes no rename event, so agent and pane renames appear after the next topology refresh, reconnect, Pi `/reload`, or session start rather than immediately.
138
166
  - Integration requires a running compatible Herdr session and valid injected environment variables.
167
+ - Model control requires an installed Herdr CLI that supports `herdr --skill`.
139
168
  - Socket failures are intentionally silent after the bounded retry.
140
169
  - The package does not install, start, update, or configure Herdr itself.
141
170
 
@@ -143,27 +172,11 @@ It treats a startup-blocked agent as not ready, refuses to prompt an already blo
143
172
 
144
173
  ```text
145
174
  packages/pi-herdr/
146
- ├── skills/herdr/
147
- │ └── SKILL.md # Herdr control workflow and safety rules
148
- ├── src/
149
- │ ├── index.ts # Thin Pi entrypoint
150
- │ ├── herdr-agent-state.ts # Pi lifecycle and integration ownership
151
- │ ├── herdr-client.ts # Bounded Herdr socket transport
152
- │ ├── herdr-metadata.ts # Token normalization and request helpers
153
- │ ├── herdr-observer.ts # Read-only event subscription lifecycle
154
- │ ├── herdr-protocol.ts # Narrow response and event validation
155
- │ └── herdr-widget.ts # Agent state model and presentation
156
- ├── test/
157
- │ ├── herdr-agent-state.test.ts
158
- │ ├── herdr-client.test.ts
159
- │ ├── herdr-metadata.test.ts
160
- │ ├── herdr-observer.test.ts
161
- │ ├── herdr-skill.test.ts
162
- │ └── herdr-widget.test.ts
163
- ├── package.json # Pi extension and skill declarations
164
- ├── tsconfig.json
165
- ├── README.md
166
- └── LICENSE
175
+ ├── src/ # Authoritative implementation and helpers
176
+ │ ├── index.ts # Thin Pi entrypoint
177
+ │ └── herdr-agent-state.ts # Herdr lifecycle integration
178
+ ├── skills/herdr/ # Published bootstrap for CLI-owned guidance
179
+ └── test/ # Behavior and lifecycle coverage
167
180
  ```
168
181
 
169
182
  ## 🔎 Keywords
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-herdr",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Herdr agent-state integration and operating skill for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,9 +41,9 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@biomejs/biome": "2.5.11",
44
- "@earendil-works/pi-coding-agent": "0.84.4",
45
- "@earendil-works/pi-tui": "0.84.4",
46
- "@types/node": "26.4.0",
44
+ "@earendil-works/pi-coding-agent": "0.85.0",
45
+ "@earendil-works/pi-tui": "0.85.0",
46
+ "@types/node": "26.4.1",
47
47
  "typescript": "7.0.2"
48
48
  },
49
49
  "repository": {
@@ -5,191 +5,18 @@ description: "Control Herdr, a terminal multiplexer for coding agents. Use only
5
5
 
6
6
  # Herdr
7
7
 
8
- Herdr organizes terminals into workspaces, tabs, and panes, recognizes coding agents running inside panes, and exposes the current session through the `herdr` CLI.
9
-
10
- Before issuing any control command, verify that this agent is running inside a Herdr-managed pane:
11
-
12
- ```bash
13
- test "${HERDR_ENV:-}" = 1
14
- ```
15
-
16
- If the check fails, say that you are not running inside Herdr and stop. Do not inspect or control the focused Herdr session from outside Herdr.
17
-
18
- When the check passes, the `herdr` binary in `PATH` talks to the current session. Use it to inspect neighboring work, create terminal layout, start agents and commands, read output, and wait for state changes.
19
-
20
- ## Learn the current CLI
21
-
22
- The installed binary is the authority for command syntax. Start with:
23
-
24
- ```bash
25
- herdr --help
26
- ```
27
-
28
- Then print the relevant command group by running the group without a subcommand:
29
-
30
- ```bash
31
- herdr agent
32
- herdr pane
33
- herdr workspace
34
- herdr tab
35
- herdr worktree
36
- herdr terminal
37
- herdr notification
38
- herdr integration
39
- herdr session
40
- ```
41
-
42
- Do not run bare `herdr` for discovery; it launches or attaches the TUI. Do not probe a mutating nested command by omitting arguments. Commands such as `herdr workspace create` are valid with defaults and will execute.
43
-
44
- Most control commands return JSON. Read identifiers and state from those responses instead of predicting them.
45
-
46
- ## Understand layout, panes, and agents
47
-
48
- Choose the primitive that matches the job:
49
-
50
- - Workspace, tab, and pane topology organize terminal locations.
51
- - Pane commands control raw terminals, shells, tests, servers, input, and output.
52
- - Agent commands control the recognized coding agent currently occupying a pane.
53
-
54
- A pane exists whether or not it contains an agent. `agent start` requires an existing available shell pane and never creates, splits, or moves layout. Use pane commands for ordinary processes. Use agent commands when Herdr must validate agent identity or interpret `idle`, `working`, `blocked`, `done`, and `unknown` lifecycle states.
55
-
56
- Agent commands accept either a unique live agent name or the pane ID currently hosting that agent. They do not accept terminal IDs or bare agent-kind labels. Names must match `[a-z][a-z0-9_-]{0,31}` and be unique among live agents. A name follows the current pane occupant and is cleared when that agent exits, is released, or is replaced.
57
-
58
- `idle` means the agent is ready for input and its tab has been seen in the focused Herdr UI. `done` is the same underlying idle state after unseen background work finishes. Focusing the tab or targeting the pane or agent with a focus command marks it seen. CLI reads do not mark it seen. `blocked` means Herdr recognized an approval or question UI. `unknown` means an agent is present but Herdr cannot classify it confidently; it does not prove completion.
59
-
60
- ## Use IDs and caller context
61
-
62
- Public IDs are opaque stable handles:
63
-
64
- - workspace: `w1`
65
- - tab: `w1:t1`
66
- - pane: `w1:p1`
67
-
68
- Closed tab and pane IDs are not reused. A pane moved into another workspace receives a new workspace-qualified pane ID. After `pane move`, continue with `.result.move_result.pane.pane_id` or the live agent name. The old value is reported as `.result.move_result.previous_pane_id`; only the moved process's inherited caller context keeps resolving that old ID, so do not use it as a general agent target.
69
-
70
- Herdr injects the caller's context into each managed pane:
71
-
72
- ```bash
73
- printf '%s\n' "$HERDR_WORKSPACE_ID" "$HERDR_TAB_ID" "$HERDR_PANE_ID"
74
- ```
75
-
76
- Prefer `--current` when a pane command should target the calling pane. Omitting a target may use the UI-focused pane, which can belong to the user or another client.
77
-
78
- Discover live state with:
79
-
80
- ```bash
81
- herdr workspace list
82
- herdr tab list --workspace "$HERDR_WORKSPACE_ID"
83
- herdr pane current --current
84
- herdr pane list --workspace "$HERDR_WORKSPACE_ID"
85
- herdr agent list
86
- ```
87
-
88
- Creation responses expose the IDs to use next. `workspace create` returns `.result.workspace`, `.result.tab`, and `.result.root_pane`. `tab create` returns `.result.tab` and `.result.root_pane`. `pane split` returns the new pane as `.result.pane`.
89
-
90
- ## Start and coordinate an agent
91
-
92
- Default to a sibling pane in the current tab and the current working directory. Do not create a workspace, tab, worktree, or different cwd unless the user explicitly requests that topology or location.
93
-
94
- Honor a direction requested by the user. Otherwise inspect the caller pane:
95
-
96
- ```bash
97
- herdr pane layout --pane "$HERDR_PANE_ID"
98
- ```
99
-
100
- Split a wide pane to the right and a narrow or tall pane down. Avoid repeated same-direction splits that create unusably narrow columns or short rows. Keep the user's focus in the calling pane and explicitly preserve the caller's working directory:
101
-
102
- ```bash
103
- herdr pane split --current --direction right --cwd "$PWD" --no-focus
104
- ```
105
-
106
- Replace `right` with `down` when appropriate. Read the new pane ID from `.result.pane.pane_id`.
107
-
108
- An available shell pane must be at its interactive prompt, with the shell itself in the foreground and no foreground command, editor, or agent running. Start a supported agent in that pane with a useful unique name:
109
-
110
- ```bash
111
- herdr agent start reviewer --kind codex --pane <returned-pane-id>
112
- ```
113
-
114
- Use the kind requested by the user. Run `herdr agent` to inspect the installed kind list and options. Pass native agent arguments only after `--`:
8
+ Before the first Herdr control command in a session, check whether the complete output of `herdr --skill` is already present in the current context.
9
+ If it is present, reuse it and do not load it again.
10
+ Otherwise run this single shell call:
115
11
 
116
12
  ```bash
117
- herdr agent start reviewer --kind codex --pane <returned-pane-id> -- <agent-args...>
13
+ test "${HERDR_ENV:-}" = 1 || {
14
+ printf '%s\n' "Not running inside Herdr." >&2
15
+ exit 1
16
+ }
17
+ herdr --skill
118
18
  ```
119
19
 
120
- A successful `agent start` returns only after Herdr detects the expected agent in the same pane and considers it ready for interactive input. If the agent is blocked during startup, the command returns `agent_not_ready` immediately but keeps the name available for `agent read` and `agent send-keys`. Wait until the agent becomes idle before prompting it. Startup defaults to a 30-second timeout.
121
-
122
- Submit work through the agent surface:
123
-
124
- ```bash
125
- herdr agent prompt reviewer "Review the current diff and report only actionable findings." --wait --timeout 120000
126
- ```
127
-
128
- `agent prompt` honors the pane's live bracketed-paste mode and sends text followed by encoded Enter after a short delay. It rejects an agent already waiting at an approval or question dialog with `agent_blocked` before sending any input. Inspect the blocked UI and ask the user before answering it. For normal agent work, `--wait` is enough: it waits for the first settled `idle`, `done`, or `blocked` state. Do not repeat those defaults with `--until`.
129
-
130
- A prompt sent from a non-working state must produce an observed lifecycle change within five seconds. Otherwise Herdr returns `agent_prompt_stalled` instead of waiting indefinitely. This wait tracks lifecycle state, not an individual turn; if the agent is already working, completion of the active turn may satisfy it.
131
-
132
- Use `--until` only for a state-specific workflow, such as waiting for an already-running agent to request input:
133
-
134
- ```bash
135
- herdr agent wait reviewer --until blocked --timeout 120000
136
- ```
137
-
138
- Without `--until`, standalone `agent wait` uses the same settled-state defaults as `agent prompt --wait`.
139
-
140
- Use logical keys for interactive agent UI controls:
141
-
142
- ```bash
143
- herdr agent send-keys reviewer esc
144
- herdr agent send-keys reviewer ctrl+c
145
- ```
146
-
147
- Herdr validates all keys before writing any bytes. Read the result through the resolved agent:
148
-
149
- ```bash
150
- herdr agent get reviewer
151
- herdr agent read reviewer --source recent-unwrapped --lines 120
152
- ```
153
-
154
- If a wait fails or returns `blocked`, inspect `agent get` and `agent read` before deciding what input to send. Use the pane surface only when raw terminal control is intentional.
155
-
156
- ## Run an ordinary command in another pane
157
-
158
- Create a sibling pane with the same geometry rule, preserve the caller's working directory, and keep user focus unchanged:
159
-
160
- ```bash
161
- herdr pane split --current --direction right --cwd "$PWD" --no-focus
162
- ```
163
-
164
- Read the new pane ID from `.result.pane.pane_id`, then run and inspect the command:
165
-
166
- ```bash
167
- herdr pane run <returned-pane-id> "just test"
168
- herdr pane wait-output <returned-pane-id> --match "test result" --timeout 120000
169
- herdr pane read <returned-pane-id> --source recent-unwrapped --lines 120
170
- ```
171
-
172
- `pane run` atomically sends command text and Enter. `pane wait-output` searches the selected snapshot immediately, so output that already exists can match. Use `--match <text>` for a literal substring or `--regex <pattern>` for a Rust regular expression. Omitting `--timeout` allows an indefinite wait.
173
-
174
- Use the read source that matches the task:
175
-
176
- - `visible`: the currently rendered viewport.
177
- - `recent`: recent rendered output, including soft wraps.
178
- - `recent-unwrapped`: recent output with soft wraps joined; prefer it for logs and transcripts.
179
- - `detection`: the plain-text bottom-buffer snapshot used for agent detection.
180
-
181
- Use `--format ansi` when colors and terminal styling are evidence. Otherwise use text.
182
-
183
- `--lines` asks Herdr for more rows from the pane's available screen and host scrollback. If increasing it does not reveal more of a completed response, the pane is probably running the agent on the terminal's alternate screen. Rows that leave the alternate screen do not enter Herdr's host scrollback, so a larger line count cannot recover them.
184
-
185
- After that failed read, ask the agent to write its complete response as Markdown in a temporary directory and reply only with the file path, then read the file directly. Use this only as a fallback; do not request file output in the initial prompt.
186
-
187
- ## Safety and coordination rules
188
-
189
- - Use `--no-focus` for background work unless the user asked to switch context.
190
- - Use `--current`, an explicit pane ID, or a unique agent name. Do not rely on another client's focused pane.
191
- - Parse IDs from JSON responses. Do not derive them from sidebar order or examples.
192
- - Do not close workspaces, tabs, panes, or sessions you did not create unless the user explicitly asked.
193
- - Never run `herdr server stop` from an active session unless the user explicitly intends to stop the server and its pane processes.
194
- - Never kill the main Herdr process. Use named test sessions for experiments that need an isolated server.
195
- - CLI server errors are JSON on stderr with exit status 1. CLI syntax errors exit with status 2.
20
+ If the environment check or command fails, report the error and stop.
21
+ Read the returned skill completely and follow it as the authoritative operating instructions for the installed Herdr version.
22
+ Run it again only after compaction removes those instructions or when the user explicitly asks to refresh them.
@@ -11,6 +11,11 @@ import {
11
11
  } from "./herdr-metadata.js";
12
12
  import { createHerdrWidgetObserver, type HerdrWidgetObserver } from "./herdr-observer.js";
13
13
 
14
+ import {
15
+ createHerdrSettingsController,
16
+ type HerdrSettingsOptions,
17
+ } from "./herdr-settings-controller.js";
18
+
14
19
  const SOURCE = "herdr:pi";
15
20
 
16
21
  export type AgentState = "working" | "blocked" | "idle";
@@ -35,7 +40,7 @@ interface QueuedMetadata {
35
40
  generation: number;
36
41
  }
37
42
 
38
- export interface HerdrAgentStateOptions {
43
+ export interface HerdrAgentStateOptions extends HerdrSettingsOptions {
39
44
  environment?: HerdrEnvironment;
40
45
  now?: () => number;
41
46
  random?: () => number;
@@ -89,6 +94,7 @@ export function createHerdrAgentStateExtension(
89
94
 
90
95
  return function herdrAgentState(pi: ExtensionAPI): void {
91
96
  if (!environment.enabled) return;
97
+ const widget = createHerdrSettingsController(pi, widgetObserver, options);
92
98
 
93
99
  let sessionGeneration = 0;
94
100
  let sessionController = new AbortController();
@@ -340,18 +346,21 @@ export function createHerdrAgentStateExtension(
340
346
  sessionController = new AbortController();
341
347
  activeSession = ctx.sessionManager;
342
348
  rootSession = ctx.mode === "tui";
343
- if (rootSession) widgetObserver.start(ctx);
349
+ const widgetStart = widget.start(ctx);
344
350
  agentActive = false;
345
351
  blockedCount = 0;
346
352
  blockedMessage = undefined;
347
353
  lastState = undefined;
348
354
  lastMessage = undefined;
349
- if (!rootSession) return;
355
+ if (!rootSession) {
356
+ await widgetStart;
357
+ return;
358
+ }
350
359
 
351
360
  updateSessionRef(ctx);
352
361
  const sessionReport = reportSession(event.reason);
353
362
  publishMetadata(ctx);
354
- await sessionReport;
363
+ await Promise.all([sessionReport, widgetStart]);
355
364
  if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
356
365
  return;
357
366
  }
@@ -382,7 +391,7 @@ export function createHerdrAgentStateExtension(
382
391
 
383
392
  pi.on("session_shutdown", async (_event, ctx) => {
384
393
  if (ctx.sessionManager !== activeSession) {
385
- await Promise.allSettled([widgetObserver.shutdown(ctx)]);
394
+ await Promise.allSettled([widget.shutdown(ctx)]);
386
395
  return;
387
396
  }
388
397
  if (shutdownTask && shutdownSession === ctx.sessionManager) {
@@ -400,7 +409,7 @@ export function createHerdrAgentStateExtension(
400
409
  sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
401
410
  queuedState = undefined;
402
411
  queuedMetadata = undefined;
403
- await Promise.allSettled([drainTask, metadataDrainTask, widgetObserver.shutdown(ctx)]);
412
+ await Promise.allSettled([drainTask, metadataDrainTask, widget.shutdown(ctx)]);
404
413
  const stillOwnsShutdown =
405
414
  shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
406
415
  if (shouldClearMetadata && stillOwnsShutdown) {
@@ -0,0 +1,55 @@
1
+ import type { MenuDefinition } from "@narumitw/pi-tui-kit";
2
+
3
+ export function createHerdrMenu(options: {
4
+ settingsPath: string;
5
+ isEnabled(): boolean;
6
+ toggle(signal: AbortSignal): Promise<boolean>;
7
+ }): MenuDefinition<undefined, "main" | "status" | "help", "toggle"> {
8
+ return {
9
+ start: "main",
10
+ screens: {
11
+ // One setting stays on the main menu, matching /tool rather than adding a submenu.
12
+ main: () => ({
13
+ kind: "actions",
14
+ title: "Herdr",
15
+ items: [
16
+ {
17
+ id: "widget",
18
+ label: `Agent widget: ${options.isEnabled() ? "On" : "Off"}`,
19
+ description: "Show or hide sibling agents above the editor",
20
+ action: "toggle",
21
+ },
22
+ { id: "status", label: "Status", to: "status" },
23
+ { id: "help", label: "Help", to: "help" },
24
+ { id: "close", label: "Close", close: true },
25
+ ],
26
+ hint: "close",
27
+ }),
28
+ status: () => ({
29
+ kind: "detail",
30
+ title: "Herdr Status",
31
+ lines: [
32
+ `Agent widget setting: ${options.isEnabled() ? "on" : "off"}`,
33
+ "The widget appears only in TUI mode with recognized sibling agents.",
34
+ "Lifecycle and metadata reporting are independent of this setting.",
35
+ `User settings file: ${options.settingsPath}`,
36
+ ],
37
+ hint: "back",
38
+ }),
39
+ help: () => ({
40
+ kind: "detail",
41
+ title: "Herdr Help",
42
+ lines: [
43
+ "Toggle Agent widget from /herdr. Changes are saved immediately; closing does not undo them.",
44
+ "Manual pi-herdr.json changes apply after /reload or the next session start.",
45
+ "The widget defaults to on. Project overrides are not read.",
46
+ ],
47
+ hint: "back",
48
+ }),
49
+ },
50
+ actions: {
51
+ toggle: async ({ signal }) =>
52
+ (await options.toggle(signal)) ? { kind: "stay" } : { kind: "rejected" },
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,135 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { HerdrWidgetObserver } from "./herdr-observer.js";
3
+ import {
4
+ awaitHerdrSettingsWrites,
5
+ herdrSettingsPath,
6
+ readHerdrSettings,
7
+ updateHerdrSettings,
8
+ } from "./settings.js";
9
+
10
+ export interface HerdrSettingsOptions {
11
+ settingsPath?: string;
12
+ }
13
+
14
+ export function createHerdrSettingsController(
15
+ pi: ExtensionAPI,
16
+ observer: HerdrWidgetObserver,
17
+ options: HerdrSettingsOptions = {},
18
+ ) {
19
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
20
+ let generation = 0;
21
+ let owner: ExtensionContext | undefined;
22
+ let controller = new AbortController();
23
+ let enabled = true;
24
+ let changes = Promise.resolve();
25
+ let menuOpen = false;
26
+ const current = (expected: number) => expected === generation && !controller.signal.aborted;
27
+
28
+ pi.registerCommand("herdr", {
29
+ description: "Configure the Herdr agent widget",
30
+ handler: async (args, ctx) => {
31
+ if (args.trim()) throw new Error("/herdr does not accept arguments.");
32
+ if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
33
+ throw new Error("/herdr requires TUI or RPC mode.");
34
+ }
35
+ if (!owner || ctx.sessionManager !== owner.sessionManager || menuOpen) return;
36
+ const expected = generation;
37
+ const signal = controller.signal;
38
+ menuOpen = true;
39
+ try {
40
+ const [{ runMenu }, { createHerdrMenu }] = await Promise.all([
41
+ import("@narumitw/pi-tui-kit"),
42
+ import("./herdr-menu.js"),
43
+ ]);
44
+ if (!current(expected)) return;
45
+ await runMenu(
46
+ ctx,
47
+ createHerdrMenu({
48
+ settingsPath,
49
+ isEnabled: () => enabled,
50
+ toggle: (actionSignal) => {
51
+ const result = changes.then(async () => {
52
+ if (actionSignal.aborted || !current(expected) || !owner) return false;
53
+ // Once accepted, finish the explicit save even if the menu closes.
54
+ // Session replacement still prevents stale runtime publication.
55
+ const previous = enabled;
56
+ const actionOwner = owner;
57
+ try {
58
+ enabled = !previous;
59
+ if (enabled && actionOwner.mode === "tui") observer.start(actionOwner);
60
+ else await observer.shutdown(actionOwner);
61
+ if (!current(expected)) return false;
62
+ await updateHerdrSettings({ widget: enabled }, { settingsPath });
63
+ return current(expected);
64
+ } catch {
65
+ if (!current(expected)) return false;
66
+ enabled = previous;
67
+ try {
68
+ if (previous && actionOwner.mode === "tui") observer.start(actionOwner);
69
+ else await observer.shutdown(actionOwner);
70
+ } finally {
71
+ if (current(expected))
72
+ ctx.ui.notify(
73
+ "Herdr settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.",
74
+ "warning",
75
+ );
76
+ }
77
+ return false;
78
+ }
79
+ });
80
+ changes = result.then(
81
+ () => undefined,
82
+ () => undefined,
83
+ );
84
+ return result;
85
+ },
86
+ }),
87
+ {
88
+ getState: () => undefined,
89
+ signal,
90
+ isCurrent: () => current(expected),
91
+ onError: () => {
92
+ if (current(expected))
93
+ ctx.ui.notify("The Herdr menu could not be displayed.", "error");
94
+ },
95
+ },
96
+ );
97
+ } finally {
98
+ if (expected === generation) menuOpen = false;
99
+ }
100
+ },
101
+ });
102
+
103
+ return {
104
+ async start(ctx: ExtensionContext) {
105
+ const expected = ++generation;
106
+ controller.abort();
107
+ controller = new AbortController();
108
+ menuOpen = false;
109
+ const previous = owner;
110
+ owner = ctx;
111
+ if (previous) await observer.shutdown(previous);
112
+ if (!current(expected)) return;
113
+ await changes;
114
+ if (!current(expected)) return;
115
+ const loaded = await readHerdrSettings(settingsPath);
116
+ if (!current(expected)) return;
117
+ enabled = loaded.settings.widget;
118
+ if (loaded.kind === "invalid" && ctx.hasUI)
119
+ ctx.ui.notify(
120
+ "Herdr ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.",
121
+ "warning",
122
+ );
123
+ if (enabled && ctx.mode === "tui") observer.start(ctx);
124
+ },
125
+ async shutdown(ctx: ExtensionContext) {
126
+ if (ctx.sessionManager !== owner?.sessionManager) return;
127
+ generation += 1;
128
+ controller.abort();
129
+ owner = undefined;
130
+ menuOpen = false;
131
+ await Promise.all([observer.shutdown(ctx), changes]);
132
+ await awaitHerdrSettingsWrites(settingsPath);
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,192 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+
7
+ export const HERDR_SETTINGS_FILE = "pi-herdr.json";
8
+ const MAX_SETTINGS_BYTES = 64 * 1024;
9
+
10
+ export interface HerdrSettings {
11
+ widget: boolean;
12
+ }
13
+
14
+ export type HerdrSettingsLoadResult =
15
+ | { kind: "missing"; settings: HerdrSettings }
16
+ | { kind: "invalid"; reason: string; settings: HerdrSettings }
17
+ | { kind: "loaded"; settings: HerdrSettings };
18
+
19
+ export interface UpdateHerdrSettingsOptions {
20
+ settingsPath?: string;
21
+ beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
22
+ }
23
+
24
+ type SettingsDocument = Record<string, unknown>;
25
+ const DEFAULT_SETTINGS: HerdrSettings = { widget: true };
26
+ const queues = new Map<string, Promise<void>>();
27
+
28
+ export function herdrSettingsPath(): string {
29
+ return join(getAgentDir(), HERDR_SETTINGS_FILE);
30
+ }
31
+
32
+ export function normalizeHerdrSettings(value: unknown): HerdrSettings | undefined {
33
+ if (!isRecord(value)) return undefined;
34
+ if (Object.hasOwn(value, "widget") && typeof value.widget !== "boolean") {
35
+ return undefined;
36
+ }
37
+ return {
38
+ widget: typeof value.widget === "boolean" ? value.widget : DEFAULT_SETTINGS.widget,
39
+ };
40
+ }
41
+
42
+ export function readHerdrSettings(
43
+ settingsPath = herdrSettingsPath(),
44
+ ): Promise<HerdrSettingsLoadResult> {
45
+ return enqueue(settingsPath, async () => {
46
+ let document: SettingsDocument;
47
+ try {
48
+ document = await readSettingsDocument(settingsPath);
49
+ } catch (error) {
50
+ if (isNodeError(error) && error.code === "ENOENT") {
51
+ return { kind: "missing", settings: { ...DEFAULT_SETTINGS } };
52
+ }
53
+ return {
54
+ kind: "invalid",
55
+ reason: `${settingsPath}: ${safeError(error)}`,
56
+ settings: { ...DEFAULT_SETTINGS },
57
+ };
58
+ }
59
+ const settings = normalizeHerdrSettings(document);
60
+ return settings
61
+ ? { kind: "loaded", settings }
62
+ : {
63
+ kind: "invalid",
64
+ reason: `${settingsPath}: invalid settings shape`,
65
+ settings: { ...DEFAULT_SETTINGS },
66
+ };
67
+ });
68
+ }
69
+
70
+ export function updateHerdrSettings(
71
+ patch: Partial<HerdrSettings>,
72
+ options: UpdateHerdrSettingsOptions = {},
73
+ ): Promise<HerdrSettings> {
74
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
75
+ return enqueue(settingsPath, async () => {
76
+ const current = await readDocumentForUpdate(settingsPath);
77
+ const updated = { ...current, ...patch };
78
+ const settings = normalizeHerdrSettings(updated);
79
+ if (!settings) throw new Error(`Pi Herdr settings at ${settingsPath} have an invalid shape.`);
80
+ await publishSettings(settingsPath, updated, options);
81
+ return settings;
82
+ });
83
+ }
84
+
85
+ export async function awaitHerdrSettingsWrites(settingsPath = herdrSettingsPath()): Promise<void> {
86
+ await queues.get(settingsPath);
87
+ }
88
+
89
+ function enqueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
90
+ const previous = queues.get(path) ?? Promise.resolve();
91
+ const result = previous.then(operation, operation);
92
+ const settled = result.then(
93
+ () => undefined,
94
+ () => undefined,
95
+ );
96
+ queues.set(path, settled);
97
+ void settled.finally(() => {
98
+ if (queues.get(path) === settled) queues.delete(path);
99
+ });
100
+ return result;
101
+ }
102
+
103
+ async function readDocumentForUpdate(path: string): Promise<SettingsDocument> {
104
+ try {
105
+ const document = await readSettingsDocument(path);
106
+ if (!normalizeHerdrSettings(document)) throw new Error("invalid settings shape");
107
+ return document;
108
+ } catch (error) {
109
+ if (isNodeError(error) && error.code === "ENOENT") return {};
110
+ throw new Error(`Pi Herdr settings at ${path} are invalid: ${safeError(error)}`);
111
+ }
112
+ }
113
+
114
+ async function readSettingsDocument(path: string): Promise<SettingsDocument> {
115
+ const pathStats = await lstat(path);
116
+ if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
117
+ throw new Error("settings path is not a regular file");
118
+ }
119
+ if (pathStats.size > MAX_SETTINGS_BYTES) {
120
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
121
+ }
122
+ const noFollow = constants.O_NOFOLLOW ?? 0;
123
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
124
+ try {
125
+ const stats = await handle.stat();
126
+ if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
127
+ throw new Error("settings path changed while opening");
128
+ }
129
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
130
+ let offset = 0;
131
+ while (offset < buffer.length) {
132
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
133
+ if (bytesRead === 0) break;
134
+ offset += bytesRead;
135
+ }
136
+ if (offset > MAX_SETTINGS_BYTES) {
137
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
138
+ }
139
+ let contents: string;
140
+ try {
141
+ contents = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
142
+ buffer.subarray(0, offset),
143
+ );
144
+ } catch {
145
+ throw new Error("settings file is not valid UTF-8");
146
+ }
147
+ let parsed: unknown;
148
+ try {
149
+ parsed = JSON.parse(contents) as unknown;
150
+ } catch {
151
+ throw new Error("invalid JSON");
152
+ }
153
+ if (!isRecord(parsed)) throw new Error("settings document must be a JSON object");
154
+ return parsed;
155
+ } finally {
156
+ await handle.close();
157
+ }
158
+ }
159
+
160
+ async function publishSettings(
161
+ path: string,
162
+ document: SettingsDocument,
163
+ options: UpdateHerdrSettingsOptions,
164
+ ): Promise<void> {
165
+ const contents = `${JSON.stringify(document, null, 2)}\n`;
166
+ if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
167
+ throw new Error(`Pi Herdr settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
168
+ }
169
+ const directory = dirname(path);
170
+ await mkdir(directory, { recursive: true });
171
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
172
+ try {
173
+ await writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx", mode: 0o600 });
174
+ await options.beforeRename?.(temporaryPath, path);
175
+ await rename(temporaryPath, path);
176
+ } catch (error) {
177
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
178
+ throw error;
179
+ }
180
+ }
181
+
182
+ function isRecord(value: unknown): value is SettingsDocument {
183
+ return typeof value === "object" && value !== null && !Array.isArray(value);
184
+ }
185
+
186
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
187
+ return error instanceof Error && "code" in error;
188
+ }
189
+
190
+ function safeError(error: unknown): string {
191
+ return error instanceof Error ? error.message : String(error);
192
+ }