@howaboua/pi-shepherdr 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Igor Warzocha
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,89 @@
1
+ # pi-shepherdr
2
+
3
+ Talk to one Pi. Let it run the others.
4
+
5
+ Shepherdr turns one Pi session into an orchestrator for Pi agents running across [Herdr](https://herdr.dev). Give work to the master; it can find existing agents, start new ones in explicit locations, send follow-ups and bring their full replies back into the same conversation.
6
+
7
+ The master gets one small JSON-schema tool with the actions and arguments it needs. Its complete active surface measures 271 `o200k` tokens: 228 for the OpenAI Responses tool declaration and 43 for the master guideline. Workers load none of it.
8
+
9
+ Enable master mode and Pi already knows its job. You do not have to explain Herdr, ask it to load an orchestration skill or remind it to delegate. The schema handles ordinary delegation without `--help` or improvised CLI commands. Herdr and Shepherdr should be enough on their own; any other Pi extensions and skills continue to work alongside them.
10
+
11
+ This is particularly handy with realtime voice. You keep talking to one agent while the workers operate in their panes and project directories. Finished work comes back automatically. If a worker needs approval or an answer, the master is steered at the next opportunity instead of leaving you to hunt through panes.
12
+
13
+ Herdr still owns the terminals, layout and restored sessions. Shepherdr connects them to one Pi conversation.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pi install npm:@howaboua/pi-shepherdr
19
+ ```
20
+
21
+ Requires Pi 0.84.1 or newer and the Herdr Pi integration:
22
+
23
+ ```bash
24
+ herdr integration install pi
25
+ ```
26
+
27
+ Shepherdr supports Herdr 0.8.x. It was developed and validated with 0.8.0; Herdr 0.7.x and older are unsupported. The controlling Pi session must run inside Herdr.
28
+
29
+ ## Set up the master
30
+
31
+ Pi sessions remain ordinary workers by default. They receive no orchestration tool or master instructions.
32
+
33
+ To try master mode in the current session:
34
+
35
+ ```text
36
+ /herdr master
37
+ ```
38
+
39
+ For a lasting setup, open Pi in a dedicated control directory and run:
40
+
41
+ ```text
42
+ /herdr json
43
+ ```
44
+
45
+ That command atomically merges the following setting into `.pi/shepherdr.json`:
46
+
47
+ ```json
48
+ {
49
+ "master": true
50
+ }
51
+ ```
52
+
53
+ Future Pi sessions in that directory start as masters. `/herdr master` affects only the current session.
54
+
55
+ While master mode is active, Pi is guided to delegate project implementation and synthesize the results. It works directly when you explicitly ask, and for configuration, documentation and routine operations in its current directory.
56
+
57
+ ## What the master can do
58
+
59
+ Shepherdr adds one compact `herdr_agents` tool. Its schema is the complete model-facing control surface:
60
+
61
+ | Action | What it does |
62
+ | --- | --- |
63
+ | `list` | Find Pi agents and Herdr workspaces. |
64
+ | `start` | Launch a named Pi agent in an explicitly selected new workspace, new tab or existing pane. An optional prompt starts work immediately. |
65
+ | `watch` | Subscribe to an existing Pi agent. |
66
+ | `send` | Send a follow-up to any Pi agent and monitor it automatically. |
67
+ | `unwatch` | Stop reporting an agent without stopping or moving it. |
68
+
69
+ Delegation is fire-and-forget. A `start` with an initial prompt, plus every `watch` and `send`, tells the master not to poll. Completion or blockage arrives automatically.
70
+
71
+ Shepherdr does not invent another workspace model or resume mechanism. It never silently moves, focuses, releases or closes existing panes. Herdr remains responsible for detach, reattach, layout restoration and native Pi session restoration.
72
+
73
+ ## Results and blocked workers
74
+
75
+ A live widget shows the watched agents and their state. When work settles, the master receives a labelled purple message containing the original task and the full, untruncated worker response.
76
+
77
+ Finished, failed and blocked events all steer the master. During an active turn, the event arrives after the current tool calls and before the next model response. While idle, it starts a response immediately.
78
+
79
+ A blocked event includes the pane ID and concrete Herdr commands for inspecting and operating it:
80
+
81
+ ```bash
82
+ herdr agent read <pane> --source visible
83
+ herdr agent prompt <pane> "<text>"
84
+ herdr agent send-keys <pane> <keys>
85
+ ```
86
+
87
+ ## License
88
+
89
+ MIT
package/biome.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "includes": [
10
+ "**",
11
+ "!node_modules",
12
+ "!dist",
13
+ "!coverage",
14
+ "!package-lock.json"
15
+ ]
16
+ },
17
+ "formatter": {
18
+ "enabled": true,
19
+ "indentStyle": "tab"
20
+ },
21
+ "linter": {
22
+ "enabled": false
23
+ },
24
+ "javascript": {
25
+ "formatter": {
26
+ "quoteStyle": "double",
27
+ "semicolons": "always",
28
+ "trailingCommas": "all"
29
+ }
30
+ }
31
+ }
package/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { registerMasterMode } from "./src/master-mode.js";
3
+ import { registerAgentEventRenderer } from "./src/messages.js";
4
+ import { AgentMonitor } from "./src/monitor.js";
5
+ import { registerHerdrAgentsTool } from "./src/tool.js";
6
+
7
+ export default function shepherdrExtension(pi: ExtensionAPI): void {
8
+ let monitor: AgentMonitor | undefined;
9
+ const getMonitor = () => (monitor ??= new AgentMonitor(pi));
10
+
11
+ registerAgentEventRenderer(pi);
12
+ registerHerdrAgentsTool(pi, getMonitor);
13
+ registerMasterMode(pi, getMonitor);
14
+ }
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@howaboua/pi-shepherdr",
3
+ "version": "0.1.0",
4
+ "description": "Herdr-native multi-agent orchestration for Pi.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Igor Warzocha",
8
+ "homepage": "https://github.com/IgorWarzocha/howaboua-pi-stuff/tree/main/packages/pi-shepherdr#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/IgorWarzocha/howaboua-pi-stuff.git",
12
+ "directory": "packages/pi-shepherdr"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/IgorWarzocha/howaboua-pi-stuff/issues"
16
+ },
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi-extension",
20
+ "pi",
21
+ "herdr",
22
+ "shepherdr",
23
+ "agents",
24
+ "orchestration"
25
+ ],
26
+ "files": [
27
+ "index.ts",
28
+ "src",
29
+ "README.md",
30
+ "LICENSE",
31
+ "tsconfig.json",
32
+ "biome.json"
33
+ ],
34
+ "scripts": {
35
+ "check": "bun run lint && bun run typecheck",
36
+ "prepack": "bun run check",
37
+ "typecheck": "tsgo --noEmit",
38
+ "lint": "biome check .",
39
+ "format": "biome check --write .",
40
+ "pack:dry": "npm pack --dry-run"
41
+ },
42
+ "peerDependencies": {
43
+ "@earendil-works/pi-ai": ">=0.84.1",
44
+ "@earendil-works/pi-coding-agent": ">=0.84.1",
45
+ "@earendil-works/pi-tui": ">=0.84.1"
46
+ },
47
+ "devDependencies": {
48
+ "@biomejs/biome": "^2.4.16",
49
+ "@earendil-works/pi-ai": "0.84.1",
50
+ "@earendil-works/pi-coding-agent": "0.84.1",
51
+ "@earendil-works/pi-tui": "0.84.1",
52
+ "@types/node": "^24.10.0",
53
+ "typescript": "^6.0.3"
54
+ },
55
+ "pi": {
56
+ "extensions": [
57
+ "./index.ts"
58
+ ]
59
+ },
60
+ "engines": {
61
+ "node": ">=20.6.0"
62
+ },
63
+ "main": "index.ts",
64
+ "exports": "./index.ts",
65
+ "publishConfig": {
66
+ "access": "public"
67
+ }
68
+ }
@@ -0,0 +1,64 @@
1
+ import type {
2
+ AgentActivity,
3
+ AgentStatus,
4
+ PaneInfo,
5
+ SettledAgentStatus,
6
+ StableAgentActivity,
7
+ } from "./types.js";
8
+
9
+ const SETTLED_STATUSES: ReadonlySet<AgentStatus> = new Set([
10
+ "idle",
11
+ "done",
12
+ "blocked",
13
+ ]);
14
+ const AGENT_STATUSES: ReadonlySet<string> = new Set([
15
+ "idle",
16
+ "working",
17
+ "blocked",
18
+ "done",
19
+ "unknown",
20
+ ]);
21
+
22
+ export function activityStatus(activity: AgentActivity): AgentStatus {
23
+ return activity.phase === "settled" ? activity.status : "working";
24
+ }
25
+
26
+ export function activityTask(activity: AgentActivity): string | undefined {
27
+ return activity.phase === "settled" ? undefined : activity.task;
28
+ }
29
+
30
+ export function isSettledStatus(
31
+ status: AgentStatus,
32
+ ): status is SettledAgentStatus {
33
+ return SETTLED_STATUSES.has(status);
34
+ }
35
+
36
+ export function isAgentStatus(value: unknown): value is AgentStatus {
37
+ return typeof value === "string" && AGENT_STATUSES.has(value);
38
+ }
39
+
40
+ export function activityForPanel(panel: PaneInfo): StableAgentActivity {
41
+ return panel.agent_status === "working"
42
+ ? { phase: "working" }
43
+ : { phase: "settled", status: panel.agent_status };
44
+ }
45
+
46
+ export function sameAgentActivity(
47
+ left: AgentActivity,
48
+ right: AgentActivity,
49
+ ): boolean {
50
+ if (left.phase !== right.phase) return false;
51
+ if (left.phase === "settled" && right.phase === "settled") {
52
+ return left.status === right.status;
53
+ }
54
+ if (left.phase === "working" && right.phase === "working") {
55
+ return left.task === right.task;
56
+ }
57
+ return (
58
+ left.phase === "submitting" &&
59
+ right.phase === "submitting" &&
60
+ left.attemptId === right.attemptId &&
61
+ left.task === right.task &&
62
+ sameAgentActivity(left.previous, right.previous)
63
+ );
64
+ }
@@ -0,0 +1,236 @@
1
+ import { createConnection } from "node:net";
2
+ import type { HerdrEvent } from "./types.js";
3
+
4
+ const MAX_FRAME_BUFFER = 8 * 1024 * 1024;
5
+
6
+ function socketEndpoint(socketPath: string): string {
7
+ return process.platform === "win32"
8
+ ? `\\\\.\\pipe\\${socketPath}`
9
+ : socketPath;
10
+ }
11
+
12
+ function errorFromResponse(value: unknown): Error {
13
+ let error: Error & { code?: string; herdrResponse?: true };
14
+ if (
15
+ typeof value === "object" &&
16
+ value !== null &&
17
+ "message" in value &&
18
+ typeof value.message === "string"
19
+ ) {
20
+ error = new Error(value.message);
21
+ if ("code" in value && typeof value.code === "string") {
22
+ error.code = value.code;
23
+ }
24
+ } else {
25
+ error = new Error(`Herdr request failed: ${JSON.stringify(value)}`);
26
+ }
27
+ error.herdrResponse = true;
28
+ return error;
29
+ }
30
+
31
+ export function isHerdrResponseError(error: unknown): boolean {
32
+ return (error as Error & { herdrResponse?: unknown }).herdrResponse === true;
33
+ }
34
+
35
+ export function isHerdrErrorCode(error: unknown, code: string): boolean {
36
+ return (
37
+ isHerdrResponseError(error) &&
38
+ (error as Error & { code?: unknown }).code === code
39
+ );
40
+ }
41
+
42
+ export class HerdrClient {
43
+ readonly socketPath: string;
44
+
45
+ constructor(socketPath = process.env["HERDR_SOCKET_PATH"]) {
46
+ if (!socketPath) {
47
+ throw new Error(
48
+ "HERDR_SOCKET_PATH is not set; run the controlling Pi session inside Herdr",
49
+ );
50
+ }
51
+ this.socketPath = socketPath;
52
+ }
53
+
54
+ request<T>(
55
+ method: string,
56
+ params: object = {},
57
+ timeoutMs = 10_000,
58
+ ): Promise<T> {
59
+ return new Promise((resolve, reject) => {
60
+ const id = `pi-shepherdr:${crypto.randomUUID()}`;
61
+ let buffer = "";
62
+ let settled = false;
63
+ const socket = createConnection(socketEndpoint(this.socketPath));
64
+ socket.setEncoding("utf8");
65
+ const timer = setTimeout(
66
+ () => finish(new Error(`Herdr ${method} timed out`)),
67
+ timeoutMs,
68
+ );
69
+ timer.unref();
70
+
71
+ const finish = (error?: Error, result?: T) => {
72
+ if (settled) return;
73
+ settled = true;
74
+ clearTimeout(timer);
75
+ socket.destroy();
76
+ if (error) reject(error);
77
+ else resolve(result as T);
78
+ };
79
+
80
+ socket.on("connect", () => {
81
+ socket.write(`${JSON.stringify({ id, method, params })}\n`);
82
+ });
83
+ socket.on("error", (error) => finish(error));
84
+ socket.on("end", () => finish(new Error(`Herdr ${method} disconnected`)));
85
+ socket.on("data", (chunk: string) => {
86
+ buffer += chunk;
87
+ if (buffer.length > MAX_FRAME_BUFFER) {
88
+ finish(new Error(`Herdr ${method} response is too large`));
89
+ return;
90
+ }
91
+ const newline = buffer.indexOf("\n");
92
+ if (newline < 0) return;
93
+ try {
94
+ const response = JSON.parse(buffer.slice(0, newline)) as {
95
+ id?: unknown;
96
+ error?: unknown;
97
+ result?: T;
98
+ };
99
+ if (response.id !== id)
100
+ finish(
101
+ new Error(`Herdr ${method} returned a mismatched response ID`),
102
+ );
103
+ else if (response.error !== undefined)
104
+ finish(errorFromResponse(response.error));
105
+ else if (response.result !== undefined)
106
+ finish(undefined, response.result);
107
+ else finish(new Error(`Herdr ${method} returned no result`));
108
+ } catch (error) {
109
+ finish(
110
+ new Error(
111
+ `Herdr ${method} returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
112
+ ),
113
+ );
114
+ }
115
+ });
116
+ });
117
+ }
118
+
119
+ subscribe(
120
+ subscriptions: object[],
121
+ onEvent: (event: HerdrEvent) => void,
122
+ onDisconnect: (error?: Error) => void,
123
+ ): Promise<() => void> {
124
+ return new Promise((resolve, reject) => {
125
+ const id = `pi-shepherdr:subscribe:${crypto.randomUUID()}`;
126
+ let acknowledged = false;
127
+ let buffer = "";
128
+ let closed = false;
129
+ let disconnected = false;
130
+ const socket = createConnection(socketEndpoint(this.socketPath));
131
+ socket.setEncoding("utf8");
132
+ const timer = setTimeout(() => {
133
+ const error = new Error("Herdr events.subscribe timed out");
134
+ socket.destroy();
135
+ reject(error);
136
+ }, 10_000);
137
+ timer.unref();
138
+
139
+ const disconnect = (error?: Error) => {
140
+ if (disconnected) return;
141
+ disconnected = true;
142
+ clearTimeout(timer);
143
+ if (!acknowledged)
144
+ reject(error ?? new Error("Herdr subscription disconnected"));
145
+ else if (!closed) onDisconnect(error);
146
+ };
147
+
148
+ socket.on("connect", () => {
149
+ socket.write(
150
+ `${JSON.stringify({ id, method: "events.subscribe", params: { subscriptions } })}\n`,
151
+ );
152
+ });
153
+ socket.on("error", disconnect);
154
+ socket.on("end", () => disconnect());
155
+ socket.on("close", () => disconnect());
156
+ socket.on("data", (chunk: string) => {
157
+ buffer += chunk;
158
+ if (buffer.length > MAX_FRAME_BUFFER) {
159
+ disconnect(new Error("Herdr event frame is too large"));
160
+ socket.destroy();
161
+ return;
162
+ }
163
+ for (;;) {
164
+ const newline = buffer.indexOf("\n");
165
+ if (newline < 0) break;
166
+ const line = buffer.slice(0, newline);
167
+ buffer = buffer.slice(newline + 1);
168
+ if (!line) continue;
169
+ let value: Record<string, unknown>;
170
+ try {
171
+ value = JSON.parse(line) as Record<string, unknown>;
172
+ } catch (error) {
173
+ disconnect(
174
+ new Error(
175
+ `Herdr events.subscribe returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
176
+ ),
177
+ );
178
+ socket.destroy();
179
+ return;
180
+ }
181
+ if (!acknowledged && value["id"] === id) {
182
+ if (value["error"] !== undefined) {
183
+ disconnect(errorFromResponse(value["error"]));
184
+ socket.destroy();
185
+ return;
186
+ }
187
+ const result = value["result"];
188
+ if (
189
+ typeof result !== "object" ||
190
+ result === null ||
191
+ !("type" in result) ||
192
+ result.type !== "subscription_started"
193
+ ) {
194
+ disconnect(
195
+ new Error(
196
+ "Herdr events.subscribe returned an invalid acknowledgement",
197
+ ),
198
+ );
199
+ socket.destroy();
200
+ return;
201
+ }
202
+ acknowledged = true;
203
+ clearTimeout(timer);
204
+ resolve(() => {
205
+ closed = true;
206
+ socket.destroy();
207
+ });
208
+ continue;
209
+ }
210
+ if (
211
+ acknowledged &&
212
+ typeof value["event"] === "string" &&
213
+ typeof value["data"] === "object" &&
214
+ value["data"] !== null
215
+ ) {
216
+ try {
217
+ onEvent({
218
+ event: value["event"],
219
+ data: value["data"] as Record<string, unknown>,
220
+ });
221
+ } catch (error) {
222
+ disconnect(
223
+ new Error(
224
+ `Shepherdr event handling failed: ${error instanceof Error ? error.message : String(error)}`,
225
+ { cause: error },
226
+ ),
227
+ );
228
+ socket.destroy();
229
+ return;
230
+ }
231
+ }
232
+ }
233
+ });
234
+ });
235
+ }
236
+ }