@narumitw/pi-herdr 0.0.1 โ†’ 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,16 +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
+ - Publishes bounded `model`, `provider`, `thinking`, `session`, and `context_usage` tokens for Herdr sidebar rows.
10
11
  - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor.
11
12
  - Updates the widget from Herdr pane lifecycle and agent-status events without polling the CLI.
12
13
  - Coalesces rapid state changes and retries short-lived local socket failures without interrupting Pi.
13
14
  - Derives blocked state from Pi's public `ui_prompt_start` and `ui_prompt_end` lifecycle events.
14
- - 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.
15
17
  - Keeps extension and skill installation in one Pi package.
16
18
 
17
19
  ## ๐Ÿ“ฆ Install
@@ -43,6 +45,7 @@ Start Pi inside a Herdr-managed pane after installing the package.
43
45
  The extension activates automatically when `HERDR_ENV=1`, `HERDR_SOCKET_PATH`, and `HERDR_PANE_ID` are present.
44
46
  When the current Herdr workspace contains another recognized agent, Pi shows its state in a widget above the editor.
45
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.
46
49
 
47
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:
48
51
 
@@ -65,10 +68,40 @@ Local socket delivery is best-effort.
65
68
  A failed request is retried once with bounded timeouts, and reporting failures never stop Pi.
66
69
  Session shutdown aborts in-flight reporting and prevents stale session work from publishing later state.
67
70
 
71
+ ## ๐Ÿท๏ธ Pane metadata
72
+
73
+ The extension publishes only the `model`, `provider`, `thinking`, `session`, and `context_usage` token keys through `pane.report_metadata` under the `herdr:pi` source.
74
+ `model` and `provider` come from Pi's selected model, `thinking` comes from Pi's effective Thinking level, and `session` comes only from Pi's explicit session display name.
75
+ `context_usage` is Pi's current context percentage rounded to the nearest whole percent.
76
+ Every report is a full five-key patch, and an unavailable value is sent as JSON `null` so old data is cleared instead of retained.
77
+ Values are stripped of terminal controls, trimmed, and limited to 80 Unicode characters before crossing the socket.
78
+ The extension never publishes prompts, conversation text, tool arguments, credentials, raw session paths, or inferred session titles as metadata tokens.
79
+ It also never sets Herdr's pane `title`, `display_agent`, `state_labels`, agent lifecycle state, or session restore fields through metadata.
80
+
81
+ Metadata is evaluated after `session_start`, `session_info_changed`, `model_select`, `thinking_level_select`, `agent_settled`, and successful `session_compact` events.
82
+ Unchanged event snapshots are suppressed, rapid changes are coalesced, and the latest unchanged snapshot is refreshed no more often than every 30 minutes.
83
+ Each token has a one-hour TTL, so data from a crashed Pi process expires without steady socket traffic.
84
+ Orderly shutdown sends one best-effort five-key clear patch, while abrupt shutdown and failed clears fall back to the TTL.
85
+ Metadata uses the lifecycle reporter's monotonic sequence allocator and bounded best-effort sender, so older delayed reports cannot replace newer accepted values and socket failures never interrupt Pi.
86
+
87
+ Herdr custom pane tokens use a `$name` row entry.
88
+ For example, this Herdr configuration displays Pi's model context without replacing pane labels or agent identity:
89
+
90
+ ```toml
91
+ [ui.sidebar.agents]
92
+ rows = [
93
+ ["state_icon", "agent"],
94
+ ["$provider", "$model", "$thinking"],
95
+ ["$session", "$context_usage"],
96
+ ]
97
+ ```
98
+
68
99
  ## ๐Ÿ‘ Agent widget
69
100
 
70
101
  The widget lists only recognized agents in the current Herdr workspace and excludes the pane running the current Pi session.
71
102
  Each row presents state, agent, pane, and workspace in that order, using theme hierarchy instead of repeating field labels.
103
+ State icons follow Herdr's distinct static symbols: `ร—` blocked, `โ—` working, `โœ“` done, `โ—‹` idle, and `ยท` unknown.
104
+ Pi theme roles map blocked to `error`, working to `warning`, done to `accent`, idle to `success`, and unknown to `dim` without hard-coded terminal colors.
72
105
  Agent identity prefers the name assigned by `herdr agent rename`, then Herdr display metadata, and finally the detected agent kind.
73
106
  Pane identity uses its label or metadata title with a short pane ID, while workspace identity uses its label with a short workspace ID.
74
107
  Terminal titles are not used as agent identity.
@@ -84,7 +117,8 @@ Session replacement and shutdown abort the subscription, pending requests, recon
84
117
  ## ๐Ÿ”’ Security and privacy
85
118
 
86
119
  The extension connects only to the Unix socket or Windows named pipe provided by `HERDR_SOCKET_PATH`.
87
- It sends the current Herdr pane ID, Pi session path or ID, lifecycle state, session start reason, and blocked label to that endpoint.
120
+ Lifecycle reporting sends the current Herdr pane ID, Pi session path or ID, lifecycle state, session start reason, and blocked label to that endpoint.
121
+ Metadata reporting sends the current Herdr pane ID plus only the selected model ID, provider ID, effective Thinking level, explicit Pi session name, and rounded context-usage percentage.
88
122
  For the widget, it reads the canonical current pane, current workspace metadata, current workspace pane list, and session agent list, then subscribes to pane creation, closure, movement, exit, agent detection, and agent-status events.
89
123
  The session agent list can contain agent metadata from other workspaces, but the extension retains names only for panes in the current workspace list.
90
124
  Widget fields can include workspace, tab, pane, terminal, agent, display, name, title, label, state-label, and lifecycle identifiers supplied by Herdr.
@@ -92,17 +126,20 @@ The subscription can deliver matching pane events from other workspaces in the s
92
126
  The extension filters presentation to the current workspace, strips terminal controls at the display boundary, and never reads sibling terminal output for the widget.
93
127
  The package does not authenticate the endpoint, so trust the environment that launches Pi and controls these variables.
94
128
 
95
- The bundled skill can direct Pi to inspect terminals, create panes, start agents, send input, and run commands through the local `herdr` CLI.
129
+ The bundled bootstrap loads operating guidance from the local `herdr --skill` command only after an explicit user request involving Herdr.
130
+ 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.
96
131
  Those commands execute with the same user permissions as Pi and can affect live terminal sessions.
97
- The skill requires an explicit user request involving Herdr and stops when `HERDR_ENV` is not `1`.
132
+ The bootstrap stops when `HERDR_ENV` is not `1`, when the CLI is unavailable, or when `herdr --skill` fails.
133
+ Command recipes, approval handling, and other operating safety rules come from the installed Herdr version instead of being duplicated by this package.
98
134
 
99
135
  ## ๐Ÿšง Limitations
100
136
 
101
- - State reporting and the agent widget are disabled in RPC, JSON, and print modes.
137
+ - Lifecycle reporting, metadata reporting, and the agent widget are disabled in RPC, JSON, and print modes.
102
138
  - The widget has no settings for placement, workspace scope, visibility, or row count.
103
139
  - The widget cannot show blocked prompt text because Herdr does not expose it through public pane responses.
104
140
  - 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.
105
141
  - Integration requires a running compatible Herdr session and valid injected environment variables.
142
+ - Model control requires an installed Herdr CLI that supports `herdr --skill`.
106
143
  - Socket failures are intentionally silent after the bounded retry.
107
144
  - The package does not install, start, update, or configure Herdr itself.
108
145
 
@@ -111,18 +148,21 @@ The skill requires an explicit user request involving Herdr and stops when `HERD
111
148
  ```text
112
149
  packages/pi-herdr/
113
150
  โ”œโ”€โ”€ skills/herdr/
114
- โ”‚ โ””โ”€โ”€ SKILL.md # Herdr control workflow and safety rules
151
+ โ”‚ โ””โ”€โ”€ SKILL.md # Thin bootstrap for CLI-owned operating guidance
115
152
  โ”œโ”€โ”€ src/
116
153
  โ”‚ โ”œโ”€โ”€ index.ts # Thin Pi entrypoint
117
154
  โ”‚ โ”œโ”€โ”€ herdr-agent-state.ts # Pi lifecycle and integration ownership
118
155
  โ”‚ โ”œโ”€โ”€ herdr-client.ts # Bounded Herdr socket transport
156
+ โ”‚ โ”œโ”€โ”€ herdr-metadata.ts # Token normalization and request helpers
119
157
  โ”‚ โ”œโ”€โ”€ herdr-observer.ts # Read-only event subscription lifecycle
120
158
  โ”‚ โ”œโ”€โ”€ herdr-protocol.ts # Narrow response and event validation
121
159
  โ”‚ โ””โ”€โ”€ herdr-widget.ts # Agent state model and presentation
122
160
  โ”œโ”€โ”€ test/
123
161
  โ”‚ โ”œโ”€โ”€ herdr-agent-state.test.ts
124
162
  โ”‚ โ”œโ”€โ”€ herdr-client.test.ts
163
+ โ”‚ โ”œโ”€โ”€ herdr-metadata.test.ts
125
164
  โ”‚ โ”œโ”€โ”€ herdr-observer.test.ts
165
+ โ”‚ โ”œโ”€โ”€ herdr-skill.test.ts
126
166
  โ”‚ โ””โ”€โ”€ herdr-widget.test.ts
127
167
  โ”œโ”€โ”€ package.json # Pi extension and skill declarations
128
168
  โ”œโ”€โ”€ tsconfig.json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-herdr",
3
- "version": "0.0.1",
3
+ "version": "0.1.1",
4
4
  "description": "Herdr agent-state integration and operating skill for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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
- `agent start` returns only after Herdr detects the expected agent in the same pane and considers it ready for interactive input. It defaults to a 30-second startup 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` atomically submits text and encoded Enter while honoring the pane's live bracketed-paste mode. 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.
@@ -1,6 +1,14 @@
1
1
  import path from "node:path";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { createBestEffortSender, type HerdrRequest } from "./herdr-client.js";
4
+ import {
5
+ createHerdrMetadataClearSnapshot,
6
+ createHerdrMetadataRequest,
7
+ createHerdrMetadataSnapshot,
8
+ HERDR_METADATA_REFRESH_MS,
9
+ type HerdrMetadataSnapshot,
10
+ herdrMetadataSnapshotsEqual,
11
+ } from "./herdr-metadata.js";
4
12
  import { createHerdrWidgetObserver, type HerdrWidgetObserver } from "./herdr-observer.js";
5
13
 
6
14
  const SOURCE = "herdr:pi";
@@ -20,6 +28,13 @@ interface QueuedState {
20
28
  signal: AbortSignal;
21
29
  }
22
30
 
31
+ interface QueuedMetadata {
32
+ snapshot: HerdrMetadataSnapshot;
33
+ seq: number;
34
+ signal: AbortSignal;
35
+ generation: number;
36
+ }
37
+
23
38
  export interface HerdrAgentStateOptions {
24
39
  environment?: HerdrEnvironment;
25
40
  now?: () => number;
@@ -77,6 +92,7 @@ export function createHerdrAgentStateExtension(
77
92
 
78
93
  let sessionGeneration = 0;
79
94
  let sessionController = new AbortController();
95
+ let activeSession: ExtensionContext["sessionManager"] | undefined;
80
96
  let currentAgentSessionId: string | undefined;
81
97
  let currentAgentSessionPath: string | undefined;
82
98
  let agentActive = false;
@@ -87,6 +103,13 @@ export function createHerdrAgentStateExtension(
87
103
  let rootSession = false;
88
104
  let queuedState: QueuedState | undefined;
89
105
  let drainTask: Promise<void> | undefined;
106
+ let queuedMetadata: QueuedMetadata | undefined;
107
+ let metadataDrainTask: Promise<void> | undefined;
108
+ let lastMetadataSnapshot: HerdrMetadataSnapshot | undefined;
109
+ let metadataRefreshTimer: ReturnType<typeof setTimeout> | undefined;
110
+ let shutdownClearController: AbortController | undefined;
111
+ let shutdownSession: ExtensionContext["sessionManager"] | undefined;
112
+ let shutdownTask: Promise<void> | undefined;
90
113
 
91
114
  function requestId(kind?: "session"): string {
92
115
  const segment = kind ? `${kind}:` : "";
@@ -163,6 +186,38 @@ export function createHerdrAgentStateExtension(
163
186
  };
164
187
  }
165
188
 
189
+ function readMetadataSnapshot(ctx: ExtensionContext): HerdrMetadataSnapshot {
190
+ let session: string | undefined;
191
+ let contextUsagePercent: number | null | undefined;
192
+ try {
193
+ session = pi.getSessionName();
194
+ } catch {
195
+ // Metadata is best-effort and optional Pi fields can be unavailable.
196
+ }
197
+ try {
198
+ contextUsagePercent = ctx.getContextUsage()?.percent;
199
+ } catch {
200
+ // Clear unknown usage instead of retaining a stale percentage.
201
+ }
202
+ return createHerdrMetadataSnapshot({
203
+ model: ctx.model?.id,
204
+ provider: ctx.model?.provider,
205
+ thinking: ctx.thinkingLevel,
206
+ session,
207
+ contextUsagePercent,
208
+ });
209
+ }
210
+
211
+ function metadataRequest(metadata: QueuedMetadata): HerdrRequest {
212
+ return createHerdrMetadataRequest({
213
+ id: requestId(),
214
+ paneId: environment.paneId,
215
+ source: SOURCE,
216
+ seq: metadata.seq,
217
+ snapshot: metadata.snapshot,
218
+ });
219
+ }
220
+
166
221
  async function drainStateQueue(): Promise<void> {
167
222
  while (queuedState) {
168
223
  const next = queuedState;
@@ -185,6 +240,65 @@ export function createHerdrAgentStateExtension(
185
240
  });
186
241
  }
187
242
 
243
+ async function drainMetadataQueue(): Promise<void> {
244
+ while (queuedMetadata) {
245
+ const next = queuedMetadata;
246
+ queuedMetadata = undefined;
247
+ if (next.signal.aborted || next.generation !== sessionGeneration || !rootSession) {
248
+ continue;
249
+ }
250
+ await safeSend(metadataRequest(next), next.signal);
251
+ }
252
+ }
253
+
254
+ function startMetadataDrain(): void {
255
+ if (metadataDrainTask) return;
256
+ metadataDrainTask = drainMetadataQueue().finally(() => {
257
+ metadataDrainTask = undefined;
258
+ if (queuedMetadata) startMetadataDrain();
259
+ });
260
+ }
261
+
262
+ function scheduleMetadataRefresh(generation: number): void {
263
+ if (metadataRefreshTimer) clearTimeout(metadataRefreshTimer);
264
+ metadataRefreshTimer = setTimeout(() => {
265
+ metadataRefreshTimer = undefined;
266
+ if (
267
+ generation !== sessionGeneration ||
268
+ sessionController.signal.aborted ||
269
+ !rootSession ||
270
+ !lastMetadataSnapshot
271
+ ) {
272
+ return;
273
+ }
274
+ queueMetadata(lastMetadataSnapshot, true);
275
+ }, HERDR_METADATA_REFRESH_MS);
276
+ metadataRefreshTimer.unref?.();
277
+ }
278
+
279
+ function queueMetadata(snapshot: HerdrMetadataSnapshot, force = false): void {
280
+ if (!rootSession || sessionController.signal.aborted) return;
281
+ if (!force && herdrMetadataSnapshotsEqual(lastMetadataSnapshot, snapshot)) return;
282
+ lastMetadataSnapshot = snapshot;
283
+ queuedMetadata = {
284
+ snapshot,
285
+ seq: nextReportSeq(),
286
+ signal: sessionController.signal,
287
+ generation: sessionGeneration,
288
+ };
289
+ scheduleMetadataRefresh(sessionGeneration);
290
+ startMetadataDrain();
291
+ }
292
+
293
+ function owns(ctx: ExtensionContext): boolean {
294
+ return rootSession && ctx.sessionManager === activeSession;
295
+ }
296
+
297
+ function publishMetadata(ctx: ExtensionContext): void {
298
+ if (!owns(ctx)) return;
299
+ queueMetadata(readMetadataSnapshot(ctx));
300
+ }
301
+
188
302
  function desiredState(): { state: AgentState; message?: string } {
189
303
  if (blockedCount > 0) return { state: "blocked", message: blockedMessage };
190
304
  if (agentActive) return { state: "working" };
@@ -199,15 +313,15 @@ export function createHerdrAgentStateExtension(
199
313
  queueState(next.state, next.message);
200
314
  }
201
315
 
202
- pi.on("ui_prompt_start", (event) => {
203
- if (!rootSession) return;
316
+ pi.on("ui_prompt_start", (event, ctx) => {
317
+ if (!owns(ctx)) return;
204
318
  blockedCount += 1;
205
319
  blockedMessage = event.title?.trim() || event.kind;
206
320
  publishState();
207
321
  });
208
322
 
209
- pi.on("ui_prompt_end", () => {
210
- if (!rootSession) return;
323
+ pi.on("ui_prompt_end", (_event, ctx) => {
324
+ if (!owns(ctx)) return;
211
325
  blockedCount = Math.max(0, blockedCount - 1);
212
326
  if (blockedCount === 0) blockedMessage = undefined;
213
327
  publishState();
@@ -215,8 +329,16 @@ export function createHerdrAgentStateExtension(
215
329
 
216
330
  pi.on("session_start", async (event, ctx) => {
217
331
  const generation = ++sessionGeneration;
218
- sessionController.abort(new DOMException("Herdr session replaced", "AbortError"));
332
+ const replaced = new DOMException("Herdr session replaced", "AbortError");
333
+ sessionController.abort(replaced);
334
+ shutdownClearController?.abort(replaced);
335
+ shutdownClearController = undefined;
336
+ if (metadataRefreshTimer) clearTimeout(metadataRefreshTimer);
337
+ metadataRefreshTimer = undefined;
338
+ queuedMetadata = undefined;
339
+ lastMetadataSnapshot = undefined;
219
340
  sessionController = new AbortController();
341
+ activeSession = ctx.sessionManager;
220
342
  rootSession = ctx.mode === "tui";
221
343
  if (rootSession) widgetObserver.start(ctx);
222
344
  agentActive = false;
@@ -227,7 +349,9 @@ export function createHerdrAgentStateExtension(
227
349
  if (!rootSession) return;
228
350
 
229
351
  updateSessionRef(ctx);
230
- await reportSession(event.reason);
352
+ const sessionReport = reportSession(event.reason);
353
+ publishMetadata(ctx);
354
+ await sessionReport;
231
355
  if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
232
356
  return;
233
357
  }
@@ -236,7 +360,7 @@ export function createHerdrAgentStateExtension(
236
360
  });
237
361
 
238
362
  pi.on("agent_start", (_event, ctx) => {
239
- if (!rootSession) return;
363
+ if (!owns(ctx)) return;
240
364
  updateSessionRef(ctx);
241
365
  void reportSession();
242
366
  agentActive = true;
@@ -244,19 +368,71 @@ export function createHerdrAgentStateExtension(
244
368
  });
245
369
 
246
370
  pi.on("agent_settled", (_event, ctx) => {
247
- if (!rootSession || !ctx.isIdle()) return;
371
+ if (!owns(ctx)) return;
372
+ publishMetadata(ctx);
373
+ if (!ctx.isIdle()) return;
248
374
  agentActive = false;
249
375
  publishState();
250
376
  });
251
377
 
378
+ pi.on("session_info_changed", (_event, ctx) => publishMetadata(ctx));
379
+ pi.on("model_select", (_event, ctx) => publishMetadata(ctx));
380
+ pi.on("thinking_level_select", (_event, ctx) => publishMetadata(ctx));
381
+ pi.on("session_compact", (_event, ctx) => publishMetadata(ctx));
382
+
252
383
  pi.on("session_shutdown", async (_event, ctx) => {
253
- ++sessionGeneration;
254
- rootSession = false;
255
- sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
256
- queuedState = undefined;
257
- await Promise.all([drainTask, widgetObserver.shutdown(ctx)]);
258
- currentAgentSessionId = undefined;
259
- currentAgentSessionPath = undefined;
384
+ if (ctx.sessionManager !== activeSession) {
385
+ await Promise.allSettled([widgetObserver.shutdown(ctx)]);
386
+ return;
387
+ }
388
+ if (shutdownTask && shutdownSession === ctx.sessionManager) {
389
+ await shutdownTask;
390
+ return;
391
+ }
392
+
393
+ const session = ctx.sessionManager;
394
+ const task = (async () => {
395
+ const shouldClearMetadata = rootSession;
396
+ const shutdownGeneration = ++sessionGeneration;
397
+ rootSession = false;
398
+ if (metadataRefreshTimer) clearTimeout(metadataRefreshTimer);
399
+ metadataRefreshTimer = undefined;
400
+ sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
401
+ queuedState = undefined;
402
+ queuedMetadata = undefined;
403
+ await Promise.allSettled([drainTask, metadataDrainTask, widgetObserver.shutdown(ctx)]);
404
+ const stillOwnsShutdown =
405
+ shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
406
+ if (shouldClearMetadata && stillOwnsShutdown) {
407
+ const controller = new AbortController();
408
+ shutdownClearController = controller;
409
+ await safeSend(
410
+ createHerdrMetadataRequest({
411
+ id: requestId(),
412
+ paneId: environment.paneId,
413
+ source: SOURCE,
414
+ seq: nextReportSeq(),
415
+ snapshot: createHerdrMetadataClearSnapshot(),
416
+ }),
417
+ controller.signal,
418
+ );
419
+ if (shutdownClearController === controller) shutdownClearController = undefined;
420
+ }
421
+ if (shutdownGeneration !== sessionGeneration || activeSession !== session || rootSession) {
422
+ return;
423
+ }
424
+ lastMetadataSnapshot = undefined;
425
+ currentAgentSessionId = undefined;
426
+ currentAgentSessionPath = undefined;
427
+ activeSession = undefined;
428
+ })();
429
+ shutdownSession = session;
430
+ shutdownTask = task;
431
+ await task;
432
+ if (shutdownTask === task) {
433
+ shutdownTask = undefined;
434
+ shutdownSession = undefined;
435
+ }
260
436
  });
261
437
  };
262
438
  }
@@ -0,0 +1,87 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import type { HerdrRequest } from "./herdr-client.js";
3
+
4
+ export const HERDR_METADATA_TOKEN_KEYS = [
5
+ "model",
6
+ "provider",
7
+ "thinking",
8
+ "session",
9
+ "context_usage",
10
+ ] as const;
11
+
12
+ export type HerdrMetadataTokenKey = (typeof HERDR_METADATA_TOKEN_KEYS)[number];
13
+ export type HerdrMetadataSnapshot = Readonly<Record<HerdrMetadataTokenKey, string | null>>;
14
+
15
+ export const HERDR_METADATA_MAX_CHARACTERS = 80;
16
+ export const HERDR_METADATA_TTL_MS = 60 * 60 * 1000;
17
+ export const HERDR_METADATA_REFRESH_MS = 30 * 60 * 1000;
18
+
19
+ export interface HerdrMetadataInputs {
20
+ model?: unknown;
21
+ provider?: unknown;
22
+ thinking?: unknown;
23
+ session?: unknown;
24
+ contextUsagePercent?: unknown;
25
+ }
26
+
27
+ export interface HerdrMetadataRequestOptions {
28
+ id: string;
29
+ paneId: string;
30
+ source: string;
31
+ seq: number;
32
+ snapshot: HerdrMetadataSnapshot;
33
+ ttlMs?: number;
34
+ }
35
+
36
+ export function normalizeHerdrMetadataValue(value: unknown): string | null {
37
+ if (typeof value !== "string") return null;
38
+ const normalized = sanitizeTerminalText(value).trim();
39
+ if (normalized.length === 0) return null;
40
+ return [...normalized].slice(0, HERDR_METADATA_MAX_CHARACTERS).join("");
41
+ }
42
+
43
+ export function formatContextUsagePercent(value: unknown): string | null {
44
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
45
+ return `${Math.round(value)}%`;
46
+ }
47
+
48
+ export function createHerdrMetadataSnapshot(inputs: HerdrMetadataInputs): HerdrMetadataSnapshot {
49
+ return Object.freeze({
50
+ model: normalizeHerdrMetadataValue(inputs.model),
51
+ provider: normalizeHerdrMetadataValue(inputs.provider),
52
+ thinking: normalizeHerdrMetadataValue(inputs.thinking),
53
+ session: normalizeHerdrMetadataValue(inputs.session),
54
+ context_usage: formatContextUsagePercent(inputs.contextUsagePercent),
55
+ });
56
+ }
57
+
58
+ export function createHerdrMetadataClearSnapshot(): HerdrMetadataSnapshot {
59
+ return Object.freeze({
60
+ model: null,
61
+ provider: null,
62
+ thinking: null,
63
+ session: null,
64
+ context_usage: null,
65
+ });
66
+ }
67
+
68
+ export function herdrMetadataSnapshotsEqual(
69
+ left: HerdrMetadataSnapshot | undefined,
70
+ right: HerdrMetadataSnapshot,
71
+ ): boolean {
72
+ return left !== undefined && HERDR_METADATA_TOKEN_KEYS.every((key) => left[key] === right[key]);
73
+ }
74
+
75
+ export function createHerdrMetadataRequest(options: HerdrMetadataRequestOptions): HerdrRequest {
76
+ return {
77
+ id: options.id,
78
+ method: "pane.report_metadata",
79
+ params: {
80
+ pane_id: options.paneId,
81
+ source: options.source,
82
+ seq: options.seq,
83
+ tokens: { ...options.snapshot },
84
+ ttl_ms: options.ttlMs ?? HERDR_METADATA_TTL_MS,
85
+ },
86
+ };
87
+ }
@@ -225,13 +225,13 @@ export class HerdrWidgetModel {
225
225
  function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string {
226
226
  switch (state) {
227
227
  case "blocked":
228
- return theme.fg("warning", text);
228
+ return theme.fg("error", text);
229
229
  case "done":
230
- return theme.fg("success", text);
231
- case "working":
232
230
  return theme.fg("accent", text);
231
+ case "working":
232
+ return theme.fg("warning", text);
233
233
  case "idle":
234
- return theme.fg("muted", text);
234
+ return theme.fg("success", text);
235
235
  case "unknown":
236
236
  return theme.fg("dim", text);
237
237
  }
@@ -240,15 +240,15 @@ function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string
240
240
  function stateSymbol(state: HerdrAgentStatus): string {
241
241
  switch (state) {
242
242
  case "blocked":
243
- return "!";
243
+ return "ร—";
244
244
  case "done":
245
245
  return "โœ“";
246
246
  case "working":
247
- return "โ—";
247
+ return "โ—";
248
248
  case "idle":
249
249
  return "โ—‹";
250
250
  case "unknown":
251
- return "?";
251
+ return "ยท";
252
252
  }
253
253
  }
254
254