@narumitw/pi-herdr 0.0.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/LICENSE +21 -0
- package/README.md +140 -0
- package/package.json +54 -0
- package/skills/herdr/SKILL.md +195 -0
- package/src/herdr-agent-state.ts +266 -0
- package/src/herdr-client.ts +287 -0
- package/src/herdr-observer.ts +415 -0
- package/src/herdr-protocol.ts +237 -0
- package/src/herdr-widget.ts +281 -0
- package/src/index.ts +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 narumiruna
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# 🐑 pi-herdr — Herdr Integration for Pi
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@narumitw/pi-herdr) [](https://pi.dev) [](./LICENSE)
|
|
4
|
+
|
|
5
|
+
Connect Pi's interactive lifecycle to Herdr and bundle the operating guidance needed to control Herdr safely.
|
|
6
|
+
|
|
7
|
+
## ✨ Features
|
|
8
|
+
|
|
9
|
+
- Reports Pi session identity and `working`, `blocked`, and `idle` lifecycle states to the current Herdr pane.
|
|
10
|
+
- Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor.
|
|
11
|
+
- Updates the widget from Herdr pane lifecycle and agent-status events without polling the CLI.
|
|
12
|
+
- Coalesces rapid state changes and retries short-lived local socket failures without interrupting Pi.
|
|
13
|
+
- 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
|
+
- Keeps extension and skill installation in one Pi package.
|
|
16
|
+
|
|
17
|
+
## 📦 Install
|
|
18
|
+
|
|
19
|
+
Install persistently from npm:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pi install npm:@narumitw/pi-herdr
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Try from npm without installing permanently:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pi -e npm:@narumitw/pi-herdr
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Load a local checkout from the repository root:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pi --no-extensions -e ./packages/pi-herdr
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Pi extensions and skills run with your user permissions.
|
|
38
|
+
Install only trusted packages, and review the source and bundled instructions before loading this package.
|
|
39
|
+
|
|
40
|
+
## 🚀 Quick start
|
|
41
|
+
|
|
42
|
+
Start Pi inside a Herdr-managed pane after installing the package.
|
|
43
|
+
The extension activates automatically when `HERDR_ENV=1`, `HERDR_SOCKET_PATH`, and `HERDR_PANE_ID` are present.
|
|
44
|
+
When the current Herdr workspace contains another recognized agent, Pi shows its state in a widget above the editor.
|
|
45
|
+
Ask Pi to use Herdr, or invoke `/skill:herdr`, when you want it to inspect or control the current Herdr session.
|
|
46
|
+
|
|
47
|
+
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
|
+
|
|
49
|
+
```bash
|
|
50
|
+
rm ~/.pi/agent/extensions/herdr-agent-state.ts
|
|
51
|
+
rm -rf ~/.agents/skills/herdr
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Run `/reload` or restart Pi after changing the installed resources.
|
|
55
|
+
|
|
56
|
+
## 🔄 Lifecycle reporting
|
|
57
|
+
|
|
58
|
+
The extension reports only interactive TUI sessions because Herdr displays agents attached to terminal panes.
|
|
59
|
+
A session report contains the Herdr pane ID, the integration source, Pi's agent kind, a monotonic sequence, the session start reason, and an absolute Pi session path when available.
|
|
60
|
+
It falls back to Pi's session ID when no absolute session path is available.
|
|
61
|
+
Agent reports contain the same ownership fields plus the current lifecycle state and optional blocked label.
|
|
62
|
+
Blocking extension prompts use their Pi-provided title as the label and fall back to the prompt kind.
|
|
63
|
+
|
|
64
|
+
Local socket delivery is best-effort.
|
|
65
|
+
A failed request is retried once with bounded timeouts, and reporting failures never stop Pi.
|
|
66
|
+
Session shutdown aborts in-flight reporting and prevents stale session work from publishing later state.
|
|
67
|
+
|
|
68
|
+
## 🐑 Agent widget
|
|
69
|
+
|
|
70
|
+
The widget lists only recognized agents in the current Herdr workspace and excludes the pane running the current Pi session.
|
|
71
|
+
Each row presents state, agent, pane, and workspace in that order, using theme hierarchy instead of repeating field labels.
|
|
72
|
+
Agent identity prefers the name assigned by `herdr agent rename`, then Herdr display metadata, and finally the detected agent kind.
|
|
73
|
+
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
|
+
Terminal titles are not used as agent identity.
|
|
75
|
+
The widget orders agents by `blocked`, `done`, `working`, `idle`, and `unknown`, shows at most five rows, and reports any remaining count.
|
|
76
|
+
A state label published through Herdr metadata can replace the raw state name.
|
|
77
|
+
Herdr's public pane responses do not expose the blocked prompt message, so the widget cannot show that reason.
|
|
78
|
+
The widget is read-only and does not focus panes, read terminal output, send prompts, or mark a background `done` state as seen.
|
|
79
|
+
The extension discovers the current workspace, pane list, and agent names, opens pane-scoped status subscriptions plus topology subscriptions, and then reloads those identities to reconcile changes made during initialization.
|
|
80
|
+
Expected pane creation, movement, or agent detection rebuilds the pane-scoped subscriptions without consuming the bounded failure retry.
|
|
81
|
+
Unexpected disconnection clears the widget before one bounded reconnect attempt, and a second failure leaves it hidden until the next Pi session or `/reload`.
|
|
82
|
+
Session replacement and shutdown abort the subscription, pending requests, reconnect delay, and stale widget publication.
|
|
83
|
+
|
|
84
|
+
## 🔒 Security and privacy
|
|
85
|
+
|
|
86
|
+
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.
|
|
88
|
+
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
|
+
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
|
+
Widget fields can include workspace, tab, pane, terminal, agent, display, name, title, label, state-label, and lifecycle identifiers supplied by Herdr.
|
|
91
|
+
The subscription can deliver matching pane events from other workspaces in the same Herdr session, and the extension ignores them after resolving the current workspace.
|
|
92
|
+
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
|
+
The package does not authenticate the endpoint, so trust the environment that launches Pi and controls these variables.
|
|
94
|
+
|
|
95
|
+
The bundled skill can direct Pi to inspect terminals, create panes, start agents, send input, and run commands through the local `herdr` CLI.
|
|
96
|
+
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`.
|
|
98
|
+
|
|
99
|
+
## 🚧 Limitations
|
|
100
|
+
|
|
101
|
+
- State reporting and the agent widget are disabled in RPC, JSON, and print modes.
|
|
102
|
+
- The widget has no settings for placement, workspace scope, visibility, or row count.
|
|
103
|
+
- The widget cannot show blocked prompt text because Herdr does not expose it through public pane responses.
|
|
104
|
+
- 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
|
+
- Integration requires a running compatible Herdr session and valid injected environment variables.
|
|
106
|
+
- Socket failures are intentionally silent after the bounded retry.
|
|
107
|
+
- The package does not install, start, update, or configure Herdr itself.
|
|
108
|
+
|
|
109
|
+
## 🗂️ Package layout
|
|
110
|
+
|
|
111
|
+
```text
|
|
112
|
+
packages/pi-herdr/
|
|
113
|
+
├── skills/herdr/
|
|
114
|
+
│ └── SKILL.md # Herdr control workflow and safety rules
|
|
115
|
+
├── src/
|
|
116
|
+
│ ├── index.ts # Thin Pi entrypoint
|
|
117
|
+
│ ├── herdr-agent-state.ts # Pi lifecycle and integration ownership
|
|
118
|
+
│ ├── herdr-client.ts # Bounded Herdr socket transport
|
|
119
|
+
│ ├── herdr-observer.ts # Read-only event subscription lifecycle
|
|
120
|
+
│ ├── herdr-protocol.ts # Narrow response and event validation
|
|
121
|
+
│ └── herdr-widget.ts # Agent state model and presentation
|
|
122
|
+
├── test/
|
|
123
|
+
│ ├── herdr-agent-state.test.ts
|
|
124
|
+
│ ├── herdr-client.test.ts
|
|
125
|
+
│ ├── herdr-observer.test.ts
|
|
126
|
+
│ └── herdr-widget.test.ts
|
|
127
|
+
├── package.json # Pi extension and skill declarations
|
|
128
|
+
├── tsconfig.json
|
|
129
|
+
├── README.md
|
|
130
|
+
└── LICENSE
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## 🔎 Keywords
|
|
134
|
+
|
|
135
|
+
Pi, Herdr, terminal multiplexer, coding agents, agent orchestration, lifecycle state.
|
|
136
|
+
|
|
137
|
+
## 📄 License
|
|
138
|
+
|
|
139
|
+
MIT.
|
|
140
|
+
See [`LICENSE`](./LICENSE).
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@narumitw/pi-herdr",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Herdr agent-state integration and operating skill for Pi.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"private": false,
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi-package",
|
|
10
|
+
"pi-extension",
|
|
11
|
+
"pi",
|
|
12
|
+
"herdr",
|
|
13
|
+
"terminal-multiplexer",
|
|
14
|
+
"agent-orchestration"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"skills",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"pi": {
|
|
23
|
+
"extensions": [
|
|
24
|
+
"./src/index.ts"
|
|
25
|
+
],
|
|
26
|
+
"skills": [
|
|
27
|
+
"./skills"
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"check": "biome check . && npm run typecheck",
|
|
32
|
+
"format": "biome check --write .",
|
|
33
|
+
"typecheck": "tsc --noEmit"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@narumitw/pi-tui-kit": "^0.60.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
40
|
+
"@earendil-works/pi-tui": "*"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
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",
|
|
47
|
+
"typescript": "7.0.2"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "https://github.com/narumiruna/pi-extensions",
|
|
52
|
+
"directory": "packages/pi-herdr"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr
|
|
3
|
+
description: "Control Herdr, a terminal multiplexer for coding agents. Use only when the user explicitly mentions Herdr or asks to use Herdr to inspect or control panes, tabs, workspaces, commands, or another agent. Do not use merely because a task could benefit from a background terminal, delegation, or parallel work. Requires HERDR_ENV=1."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr
|
|
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 `--`:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
herdr agent start reviewer --kind codex --pane <returned-pane-id> -- <agent-args...>
|
|
118
|
+
```
|
|
119
|
+
|
|
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.
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { createBestEffortSender, type HerdrRequest } from "./herdr-client.js";
|
|
4
|
+
import { createHerdrWidgetObserver, type HerdrWidgetObserver } from "./herdr-observer.js";
|
|
5
|
+
|
|
6
|
+
const SOURCE = "herdr:pi";
|
|
7
|
+
|
|
8
|
+
export type AgentState = "working" | "blocked" | "idle";
|
|
9
|
+
|
|
10
|
+
interface HerdrEnvironment {
|
|
11
|
+
enabled: boolean;
|
|
12
|
+
paneId: string;
|
|
13
|
+
socketEndpoint: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface QueuedState {
|
|
17
|
+
state: AgentState;
|
|
18
|
+
message?: string;
|
|
19
|
+
seq: number;
|
|
20
|
+
signal: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface HerdrAgentStateOptions {
|
|
24
|
+
environment?: HerdrEnvironment;
|
|
25
|
+
now?: () => number;
|
|
26
|
+
random?: () => number;
|
|
27
|
+
sendRequest?: (request: HerdrRequest, signal: AbortSignal) => Promise<void>;
|
|
28
|
+
widgetObserver?: HerdrWidgetObserver;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let reportSeq = Date.now() * 1000;
|
|
32
|
+
|
|
33
|
+
function nextReportSeq(): number {
|
|
34
|
+
reportSeq += 1;
|
|
35
|
+
return reportSeq;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resolveSocketEndpoint(
|
|
39
|
+
socketPath: string | undefined,
|
|
40
|
+
platform: NodeJS.Platform = process.platform,
|
|
41
|
+
): string {
|
|
42
|
+
if (!socketPath || platform !== "win32") return socketPath ?? "";
|
|
43
|
+
const normalized = socketPath.toLowerCase();
|
|
44
|
+
if (normalized.startsWith("\\\\.\\pipe\\") || normalized.startsWith("\\\\?\\pipe\\")) {
|
|
45
|
+
return socketPath;
|
|
46
|
+
}
|
|
47
|
+
return `\\\\.\\pipe\\${socketPath}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readEnvironment(environment: NodeJS.ProcessEnv = process.env): HerdrEnvironment {
|
|
51
|
+
const socketPath = environment.HERDR_SOCKET_PATH;
|
|
52
|
+
const paneId = environment.HERDR_PANE_ID;
|
|
53
|
+
return {
|
|
54
|
+
enabled: environment.HERDR_ENV === "1" && !!socketPath && !!paneId,
|
|
55
|
+
paneId: paneId ?? "",
|
|
56
|
+
socketEndpoint: resolveSocketEndpoint(socketPath),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createHerdrAgentStateExtension(
|
|
61
|
+
options: HerdrAgentStateOptions = {},
|
|
62
|
+
): (pi: ExtensionAPI) => void {
|
|
63
|
+
const environment = options.environment ?? readEnvironment();
|
|
64
|
+
const now = options.now ?? Date.now;
|
|
65
|
+
const random = options.random ?? Math.random;
|
|
66
|
+
const sendRequest = options.sendRequest ?? createBestEffortSender(environment.socketEndpoint);
|
|
67
|
+
const widgetObserver =
|
|
68
|
+
options.widgetObserver ??
|
|
69
|
+
createHerdrWidgetObserver({
|
|
70
|
+
environment,
|
|
71
|
+
now,
|
|
72
|
+
random,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
return function herdrAgentState(pi: ExtensionAPI): void {
|
|
76
|
+
if (!environment.enabled) return;
|
|
77
|
+
|
|
78
|
+
let sessionGeneration = 0;
|
|
79
|
+
let sessionController = new AbortController();
|
|
80
|
+
let currentAgentSessionId: string | undefined;
|
|
81
|
+
let currentAgentSessionPath: string | undefined;
|
|
82
|
+
let agentActive = false;
|
|
83
|
+
let blockedCount = 0;
|
|
84
|
+
let blockedMessage: string | undefined;
|
|
85
|
+
let lastState: AgentState | undefined;
|
|
86
|
+
let lastMessage: string | undefined;
|
|
87
|
+
let rootSession = false;
|
|
88
|
+
let queuedState: QueuedState | undefined;
|
|
89
|
+
let drainTask: Promise<void> | undefined;
|
|
90
|
+
|
|
91
|
+
function requestId(kind?: "session"): string {
|
|
92
|
+
const segment = kind ? `${kind}:` : "";
|
|
93
|
+
return `${SOURCE}:${segment}${now()}:${random().toString(36).slice(2)}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function updateSessionRef(ctx: ExtensionContext): void {
|
|
97
|
+
try {
|
|
98
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
99
|
+
currentAgentSessionPath =
|
|
100
|
+
typeof file === "string" && path.isAbsolute(file) ? file : undefined;
|
|
101
|
+
} catch {
|
|
102
|
+
currentAgentSessionPath = undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const id = ctx.sessionManager.getSessionId();
|
|
107
|
+
currentAgentSessionId = typeof id === "string" && id.length > 0 ? id : undefined;
|
|
108
|
+
} catch {
|
|
109
|
+
currentAgentSessionId = undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function currentSessionRef(): Record<string, unknown> | undefined {
|
|
114
|
+
if (currentAgentSessionPath) return { agent_session_path: currentAgentSessionPath };
|
|
115
|
+
if (currentAgentSessionId) return { agent_session_id: currentAgentSessionId };
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function withSessionRef(params: Record<string, unknown>): Record<string, unknown> {
|
|
120
|
+
return { ...params, ...currentSessionRef() };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function safeSend(request: HerdrRequest, signal: AbortSignal): Promise<void> {
|
|
124
|
+
try {
|
|
125
|
+
await sendRequest(request, signal);
|
|
126
|
+
} catch {
|
|
127
|
+
// Herdr reporting is best-effort and must not interrupt Pi.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function reportSession(sessionStartSource?: string): Promise<void> {
|
|
132
|
+
const sessionRef = currentSessionRef();
|
|
133
|
+
if (!sessionRef) return Promise.resolve();
|
|
134
|
+
return safeSend(
|
|
135
|
+
{
|
|
136
|
+
id: requestId("session"),
|
|
137
|
+
method: "pane.report_agent_session",
|
|
138
|
+
params: {
|
|
139
|
+
pane_id: environment.paneId,
|
|
140
|
+
source: SOURCE,
|
|
141
|
+
agent: "pi",
|
|
142
|
+
seq: nextReportSeq(),
|
|
143
|
+
session_start_source: sessionStartSource,
|
|
144
|
+
...sessionRef,
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
sessionController.signal,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function stateRequest(state: QueuedState): HerdrRequest {
|
|
152
|
+
return {
|
|
153
|
+
id: requestId(),
|
|
154
|
+
method: "pane.report_agent",
|
|
155
|
+
params: withSessionRef({
|
|
156
|
+
pane_id: environment.paneId,
|
|
157
|
+
source: SOURCE,
|
|
158
|
+
agent: "pi",
|
|
159
|
+
state: state.state,
|
|
160
|
+
message: state.message,
|
|
161
|
+
seq: state.seq,
|
|
162
|
+
}),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function drainStateQueue(): Promise<void> {
|
|
167
|
+
while (queuedState) {
|
|
168
|
+
const next = queuedState;
|
|
169
|
+
queuedState = undefined;
|
|
170
|
+
if (!next.signal.aborted) await safeSend(stateRequest(next), next.signal);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function queueState(state: AgentState, message?: string): void {
|
|
175
|
+
queuedState = {
|
|
176
|
+
state,
|
|
177
|
+
message,
|
|
178
|
+
seq: nextReportSeq(),
|
|
179
|
+
signal: sessionController.signal,
|
|
180
|
+
};
|
|
181
|
+
if (drainTask) return;
|
|
182
|
+
drainTask = drainStateQueue().finally(() => {
|
|
183
|
+
drainTask = undefined;
|
|
184
|
+
if (queuedState) queueState(queuedState.state, queuedState.message);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function desiredState(): { state: AgentState; message?: string } {
|
|
189
|
+
if (blockedCount > 0) return { state: "blocked", message: blockedMessage };
|
|
190
|
+
if (agentActive) return { state: "working" };
|
|
191
|
+
return { state: "idle" };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function publishState(force = false): void {
|
|
195
|
+
const next = desiredState();
|
|
196
|
+
if (!force && next.state === lastState && next.message === lastMessage) return;
|
|
197
|
+
lastState = next.state;
|
|
198
|
+
lastMessage = next.message;
|
|
199
|
+
queueState(next.state, next.message);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
pi.on("ui_prompt_start", (event) => {
|
|
203
|
+
if (!rootSession) return;
|
|
204
|
+
blockedCount += 1;
|
|
205
|
+
blockedMessage = event.title?.trim() || event.kind;
|
|
206
|
+
publishState();
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
pi.on("ui_prompt_end", () => {
|
|
210
|
+
if (!rootSession) return;
|
|
211
|
+
blockedCount = Math.max(0, blockedCount - 1);
|
|
212
|
+
if (blockedCount === 0) blockedMessage = undefined;
|
|
213
|
+
publishState();
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
pi.on("session_start", async (event, ctx) => {
|
|
217
|
+
const generation = ++sessionGeneration;
|
|
218
|
+
sessionController.abort(new DOMException("Herdr session replaced", "AbortError"));
|
|
219
|
+
sessionController = new AbortController();
|
|
220
|
+
rootSession = ctx.mode === "tui";
|
|
221
|
+
if (rootSession) widgetObserver.start(ctx);
|
|
222
|
+
agentActive = false;
|
|
223
|
+
blockedCount = 0;
|
|
224
|
+
blockedMessage = undefined;
|
|
225
|
+
lastState = undefined;
|
|
226
|
+
lastMessage = undefined;
|
|
227
|
+
if (!rootSession) return;
|
|
228
|
+
|
|
229
|
+
updateSessionRef(ctx);
|
|
230
|
+
await reportSession(event.reason);
|
|
231
|
+
if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
agentActive = !ctx.isIdle();
|
|
235
|
+
publishState(true);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
pi.on("agent_start", (_event, ctx) => {
|
|
239
|
+
if (!rootSession) return;
|
|
240
|
+
updateSessionRef(ctx);
|
|
241
|
+
void reportSession();
|
|
242
|
+
agentActive = true;
|
|
243
|
+
publishState();
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
247
|
+
if (!rootSession || !ctx.isIdle()) return;
|
|
248
|
+
agentActive = false;
|
|
249
|
+
publishState();
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
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;
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export default function herdrAgentState(pi: ExtensionAPI): void {
|
|
265
|
+
createHerdrAgentStateExtension()(pi);
|
|
266
|
+
}
|