@howaboua/pi-shepherdr 0.1.2 → 0.1.4

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/src/types.ts CHANGED
@@ -4,12 +4,18 @@ export type SettledAgentStatus = Exclude<AgentStatus, "working">;
4
4
 
5
5
  export type StableAgentActivity =
6
6
  | { readonly phase: "settled"; readonly status: SettledAgentStatus }
7
- | { readonly phase: "working"; readonly task?: string };
7
+ | {
8
+ readonly attemptId?: string;
9
+ readonly expectedUserAfter?: string | null;
10
+ readonly phase: "working";
11
+ readonly task?: string;
12
+ };
8
13
 
9
14
  export type AgentActivity =
10
15
  | StableAgentActivity
11
16
  | {
12
17
  readonly attemptId: string;
18
+ readonly expectedUserAfter?: string | null;
13
19
  readonly phase: "submitting";
14
20
  readonly previous: StableAgentActivity;
15
21
  readonly task: string;
@@ -29,6 +35,7 @@ export interface PaneInfo {
29
35
  cwd?: string | null;
30
36
  foreground_cwd?: string | null;
31
37
  interactive_ready?: boolean;
38
+ label?: string | null;
32
39
  launch_pending?: boolean;
33
40
  name?: string | null;
34
41
  pane_id: string;
@@ -83,6 +90,29 @@ export interface LatestAssistant {
83
90
  text: string;
84
91
  }
85
92
 
93
+ export interface LatestUser {
94
+ id: string;
95
+ text: string;
96
+ }
97
+
98
+ export interface PendingAsk {
99
+ handoff: boolean;
100
+ prompts: Array<{
101
+ body?: string;
102
+ choices: Array<{ description?: string; label: string }>;
103
+ multiple: boolean;
104
+ title: string;
105
+ }>;
106
+ toolCallId: string;
107
+ }
108
+
109
+ export interface SessionView {
110
+ ask?: PendingAsk;
111
+ assistant?: LatestAssistant;
112
+ assistantAfterUser?: boolean;
113
+ user?: LatestUser;
114
+ }
115
+
86
116
  export interface HerdrEvent {
87
117
  data: Record<string, unknown>;
88
118
  event: string;
@@ -1,61 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
-
5
- function configPath(cwd: string): string {
6
- return join(cwd, ".pi", "shepherdr.json");
7
- }
8
-
9
- export async function isMasterDirectory(cwd: string): Promise<boolean> {
10
- const path = configPath(cwd);
11
- const value = await readConfig(path);
12
- if (!value || !("master" in value)) return false;
13
- if (typeof value["master"] === "boolean") return value["master"];
14
- throw new Error(`${path} master must be boolean`);
15
- }
16
-
17
- export async function enableMasterDirectory(cwd: string): Promise<string> {
18
- const directory = join(cwd, ".pi");
19
- const path = configPath(cwd);
20
- const value = (await readConfig(path)) ?? {};
21
- value["master"] = true;
22
- await mkdir(directory, { recursive: true });
23
- const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
24
- try {
25
- await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
26
- encoding: "utf8",
27
- mode: 0o600,
28
- });
29
- await rename(temporaryPath, path);
30
- } catch (error) {
31
- await unlink(temporaryPath).catch(() => undefined);
32
- throw error;
33
- }
34
- return path;
35
- }
36
-
37
- async function readConfig(
38
- path: string,
39
- ): Promise<Record<string, unknown> | undefined> {
40
- let text: string;
41
- try {
42
- text = await readFile(path, "utf8");
43
- } catch (error) {
44
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
45
- throw new Error(
46
- `could not read ${path}: ${error instanceof Error ? error.message : String(error)}`,
47
- );
48
- }
49
- let value: unknown;
50
- try {
51
- value = JSON.parse(text);
52
- } catch (error) {
53
- throw new Error(
54
- `could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`,
55
- );
56
- }
57
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
58
- throw new Error(`${path} must contain a JSON object`);
59
- }
60
- return value as Record<string, unknown>;
61
- }
@@ -1,295 +0,0 @@
1
- import type {
2
- ExtensionAPI,
3
- ExtensionContext,
4
- } from "@earendil-works/pi-coding-agent";
5
- import type { AgentFleet } from "./fleet.js";
6
- import {
7
- isMachineName,
8
- LOCAL_MACHINE,
9
- readMachinesConfig,
10
- writeMachinesConfig,
11
- } from "./machines-config.js";
12
- import { enableMasterDirectory, isMasterDirectory } from "./master-config.js";
13
-
14
- const TOOL_NAME = "herdr_agents";
15
-
16
- function parseSshArguments(value: string): string[] {
17
- const parts: string[] = [];
18
- let current = "";
19
- let quote: "'" | '"' | undefined;
20
- let escaped = false;
21
- let started = false;
22
- for (const character of value) {
23
- if (escaped) {
24
- current += character;
25
- escaped = false;
26
- started = true;
27
- continue;
28
- }
29
- if (character === "\\" && quote !== "'") {
30
- escaped = true;
31
- started = true;
32
- continue;
33
- }
34
- if (quote) {
35
- if (character === quote) quote = undefined;
36
- else current += character;
37
- continue;
38
- }
39
- if (character === "'" || character === '"') {
40
- quote = character;
41
- started = true;
42
- } else if (/\s/.test(character)) {
43
- if (started) {
44
- parts.push(current);
45
- current = "";
46
- started = false;
47
- }
48
- } else {
49
- current += character;
50
- started = true;
51
- }
52
- }
53
- if (quote) throw new Error("SSH arguments contain an unclosed quote");
54
- if (escaped) throw new Error("SSH arguments end with an incomplete escape");
55
- if (started) parts.push(current);
56
- if (parts.length === 0) throw new Error("SSH target is required");
57
- const target = parts.pop()!;
58
- return [...parts, "--", target];
59
- }
60
-
61
- export function registerMasterMode(pi: ExtensionAPI, fleet: AgentFleet): void {
62
- pi.registerCommand("herdr", {
63
- description: "Manage Herdr master mode and machines",
64
- getArgumentCompletions: (prefix) =>
65
- ["master", "json", "connect"]
66
- .filter((action) => action.startsWith(prefix.trim().toLowerCase()))
67
- .map((value) => ({ label: value, value })),
68
- handler: async (args, ctx) => {
69
- const [rawAction = "", target] = args.trim().split(/\s+/, 2);
70
- const action = rawAction.toLowerCase();
71
- if (!action) {
72
- await showHerdrMenu(pi, fleet, ctx);
73
- return;
74
- }
75
- if (action === "connect") {
76
- if (!fleet.isActive()) {
77
- ctx.ui.notify("Enable Herdr master mode first", "warning");
78
- return;
79
- }
80
- try {
81
- ctx.ui.notify(fleet.connect(target), "info");
82
- } catch (error) {
83
- ctx.ui.notify(
84
- error instanceof Error ? error.message : String(error),
85
- "error",
86
- );
87
- }
88
- return;
89
- }
90
- if (action !== "master" && action !== "json") {
91
- ctx.ui.notify(
92
- "Usage: /herdr [master|json|connect [machine]]",
93
- "warning",
94
- );
95
- return;
96
- }
97
- if (!(await activateMaster(pi, fleet, ctx))) return;
98
- if (action === "master") {
99
- ctx.ui.notify("Herdr master enabled for this Pi session", "info");
100
- return;
101
- }
102
- try {
103
- const path = await enableMasterDirectory(ctx.cwd);
104
- ctx.ui.notify(`Herdr master enabled in ${path}`, "info");
105
- } catch (error) {
106
- ctx.ui.notify(
107
- `Herdr master is active for this session but could not save ${ctx.cwd}/.pi/shepherdr.json: ${error instanceof Error ? error.message : String(error)}`,
108
- "error",
109
- );
110
- }
111
- },
112
- });
113
-
114
- pi.on("session_start", async (_event, ctx) => {
115
- fleet.deactivate();
116
- let master = false;
117
- try {
118
- master = await isMasterDirectory(ctx.cwd);
119
- } catch (error) {
120
- ctx.ui.notify(
121
- `Herdr master config is invalid: ${error instanceof Error ? error.message : String(error)}`,
122
- "error",
123
- );
124
- }
125
- if (!master) {
126
- setToolActive(pi, false);
127
- return;
128
- }
129
- await activateMaster(pi, fleet, ctx);
130
- });
131
-
132
- pi.on("session_shutdown", async () => {
133
- fleet.deactivate();
134
- });
135
- }
136
-
137
- async function showHerdrMenu(
138
- pi: ExtensionAPI,
139
- fleet: AgentFleet,
140
- ctx: ExtensionContext,
141
- ): Promise<void> {
142
- const config = await readMachinesConfig().catch((error) => {
143
- ctx.ui.notify(
144
- `Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
145
- "error",
146
- );
147
- return undefined;
148
- });
149
- if (!config) return;
150
- const statuses = fleet.isActive()
151
- ? fleet.statuses()
152
- : Object.keys(config.machines).map((name) => ({
153
- local: false,
154
- name,
155
- status: "unavailable" as const,
156
- }));
157
- const selected = await ctx.ui.select("Shepherdr", [
158
- ...(fleet.isActive() ? [] : ["Enable master for this session"]),
159
- "Enable master in this folder",
160
- "Add machine",
161
- ...statuses
162
- .filter((machine) => !machine.local)
163
- .map(
164
- (machine) =>
165
- `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
166
- ),
167
- ]);
168
- if (!selected) return;
169
- if (selected === "Enable master for this session") {
170
- if (await activateMaster(pi, fleet, ctx))
171
- ctx.ui.notify("Herdr master enabled for this Pi session", "info");
172
- return;
173
- }
174
- if (selected === "Enable master in this folder") {
175
- if (!fleet.isActive() && !(await activateMaster(pi, fleet, ctx))) return;
176
- try {
177
- const path = await enableMasterDirectory(ctx.cwd);
178
- ctx.ui.notify(`Herdr master enabled in ${path}`, "info");
179
- } catch (error) {
180
- ctx.ui.notify(
181
- error instanceof Error ? error.message : String(error),
182
- "error",
183
- );
184
- }
185
- return;
186
- }
187
- if (selected === "Add machine") {
188
- await addMachine(ctx, fleet);
189
- return;
190
- }
191
- const name = selected.slice(2).split(" · ", 1)[0];
192
- if (!name) return;
193
- const status = statuses.find((machine) => machine.name === name);
194
- const action = await ctx.ui.select(name, [
195
- ...(status?.status !== "connected" ? ["Connect"] : []),
196
- "Remove",
197
- ]);
198
- if (action === "Connect") {
199
- if (!fleet.isActive() && !(await activateMaster(pi, fleet, ctx))) return;
200
- ctx.ui.notify(fleet.connect(name), "info");
201
- } else if (action === "Remove") {
202
- const confirmed = await ctx.ui.confirm(
203
- `Remove ${name}?`,
204
- "The remote Shepherdr helper will remain available for other controllers",
205
- );
206
- if (!confirmed) return;
207
- delete config.machines[name];
208
- await writeMachinesConfig(config);
209
- await fleet.reload();
210
- ctx.ui.notify(`Removed ${name}`, "info");
211
- }
212
- }
213
-
214
- async function addMachine(
215
- ctx: ExtensionContext,
216
- fleet: AgentFleet,
217
- ): Promise<void> {
218
- const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
219
- if (!name) return;
220
- if (!isMachineName(name)) {
221
- ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
222
- return;
223
- }
224
- const ssh = (
225
- await ctx.ui.input("SSH options and target (target last)", name)
226
- )?.trim();
227
- if (!ssh) return;
228
- let sshArguments: string[];
229
- try {
230
- sshArguments = parseSshArguments(ssh);
231
- } catch (error) {
232
- ctx.ui.notify(
233
- error instanceof Error ? error.message : String(error),
234
- "error",
235
- );
236
- return;
237
- }
238
- const session = (
239
- await ctx.ui.input("Herdr session", "default (leave blank)")
240
- )?.trim();
241
- const config = await readMachinesConfig();
242
- if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
243
- ctx.ui.notify(`Machine ${name} already exists`, "error");
244
- return;
245
- }
246
- config.machines[name] = {
247
- command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
248
- herdr: "herdr",
249
- node: "node",
250
- ...(session && session !== "default (leave blank)" ? { session } : {}),
251
- };
252
- const path = await writeMachinesConfig(config);
253
- await fleet.reload();
254
- ctx.ui.notify(
255
- `Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
256
- "info",
257
- );
258
- }
259
-
260
- async function activateMaster(
261
- pi: ExtensionAPI,
262
- fleet: AgentFleet,
263
- ctx: ExtensionContext,
264
- ): Promise<boolean> {
265
- if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
266
- setToolActive(pi, false);
267
- ctx.ui.notify("Herdr master mode requires Pi to run inside Herdr", "error");
268
- return false;
269
- }
270
- try {
271
- setToolActive(pi, true);
272
- await fleet.activate(ctx);
273
- return true;
274
- } catch (error) {
275
- setToolActive(pi, false);
276
- fleet.deactivate();
277
- ctx.ui.notify(
278
- `Herdr master could not start: ${error instanceof Error ? error.message : String(error)}`,
279
- "error",
280
- );
281
- return false;
282
- }
283
- }
284
-
285
- function setToolActive(pi: ExtensionAPI, active: boolean): void {
286
- const current = pi.getActiveTools();
287
- const withoutTool = current.filter((name) => name !== TOOL_NAME);
288
- const next = active ? [...withoutTool, TOOL_NAME] : withoutTool;
289
- if (
290
- next.length !== current.length ||
291
- next.some((name, index) => name !== current[index])
292
- ) {
293
- pi.setActiveTools(next);
294
- }
295
- }
package/src/tool.ts DELETED
@@ -1,234 +0,0 @@
1
- import { StringEnum, Type } from "@earendil-works/pi-ai";
2
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
- import type { AgentFleet } from "./fleet.js";
4
- import { resolvePiAgent } from "./herdr.js";
5
- import {
6
- START_PLACEMENTS,
7
- type StartAgentParams,
8
- startAgent,
9
- } from "./launch.js";
10
- import type { AgentMonitor } from "./monitor.js";
11
- import type { MonitoredAgent, PaneInfo, SessionSnapshot } from "./types.js";
12
-
13
- const ACTIONS = ["list", "start", "watch", "unwatch", "send"] as const;
14
- const FIRE_AND_FORGET =
15
- "Do not poll; completion or blockage will be delivered automatically";
16
-
17
- type ToolParams = StartAgentParams & {
18
- action: (typeof ACTIONS)[number];
19
- machine?: string;
20
- target?: string;
21
- };
22
-
23
- function required(value: string | undefined, field: string): string {
24
- if (!value?.trim()) throw new Error(`${field} is required for this action`);
25
- return value.trim();
26
- }
27
-
28
- function result(value: Record<string, unknown>) {
29
- return {
30
- content: [{ type: "text" as const, text: JSON.stringify(value) }],
31
- details: value,
32
- };
33
- }
34
-
35
- function labels(snapshot: SessionSnapshot) {
36
- return {
37
- workspaces: new Map(
38
- snapshot.workspaces.map((workspace) => [
39
- workspace.workspace_id,
40
- workspace.label,
41
- ]),
42
- ),
43
- tabs: new Map(snapshot.tabs.map((tab) => [tab.tab_id, tab.label])),
44
- };
45
- }
46
-
47
- function compactAgent(
48
- agent: PaneInfo,
49
- snapshot: SessionSnapshot,
50
- monitored: boolean,
51
- machine: string,
52
- ): Record<string, unknown> {
53
- const names = labels(snapshot);
54
- return {
55
- machine,
56
- id: agent.pane_id,
57
- ...(agent.name ? { name: agent.name } : {}),
58
- status: agent.agent_status,
59
- cwd: agent.foreground_cwd ?? agent.cwd ?? null,
60
- workspace: names.workspaces.get(agent.workspace_id) ?? agent.workspace_id,
61
- workspaceId: agent.workspace_id,
62
- tab: names.tabs.get(agent.tab_id) ?? agent.tab_id,
63
- tabId: agent.tab_id,
64
- monitored,
65
- };
66
- }
67
-
68
- function findRecord(
69
- monitor: AgentMonitor,
70
- target: string,
71
- ): MonitoredAgent | undefined {
72
- const matches = monitor
73
- .list()
74
- .filter((agent) => agent.paneId === target || agent.name === target);
75
- if (matches.length > 1) {
76
- throw new Error(
77
- `monitored agent name ${JSON.stringify(target)} is ambiguous`,
78
- );
79
- }
80
- return matches[0];
81
- }
82
-
83
- export function registerHerdrAgentsTool(
84
- pi: ExtensionAPI,
85
- fleet: AgentFleet,
86
- ): void {
87
- pi.registerTool({
88
- name: "herdr_agents",
89
- label: "Shepherdr",
90
- description:
91
- "Herdr Pi agents across configured machines. start needs name and placement; new_tab needs workspace; pane placement needs pane ID. watch/unwatch need target; send needs target and prompt.",
92
- promptGuidelines: [
93
- "Act as an orchestrator: delegate project implementation, synthesize worker results, and report them to the user. Work directly only when explicitly asked or for configuration, documentation, and routine operations in the current working directory",
94
- ],
95
- parameters: Type.Object({
96
- action: StringEnum(ACTIONS),
97
- machine: Type.Optional(
98
- Type.String({ description: "Configured machine; defaults to local" }),
99
- ),
100
- target: Type.Optional(
101
- Type.String({ description: "Agent name or pane ID" }),
102
- ),
103
- name: Type.Optional(
104
- Type.String({
105
- description: "Agent name; [a-z][a-z0-9_-]{0,31}",
106
- }),
107
- ),
108
- label: Type.Optional(
109
- Type.String({
110
- description:
111
- "Pi session label; also labels a new tab; defaults to name",
112
- }),
113
- ),
114
- placement: Type.Optional(StringEnum(START_PLACEMENTS)),
115
- workspace: Type.Optional(
116
- Type.String({ description: "Workspace label or ID" }),
117
- ),
118
- pane: Type.Optional(Type.String()),
119
- cwd: Type.Optional(
120
- Type.String({
121
- description:
122
- "Working directory for a new location; defaults to current",
123
- }),
124
- ),
125
- prompt: Type.Optional(
126
- Type.String({
127
- description: "Initial task (start) or message (send)",
128
- }),
129
- ),
130
- }),
131
- executionMode: "sequential",
132
- async execute(_toolCallId, params: ToolParams, _signal, _onUpdate, ctx) {
133
- if (params.action === "list") {
134
- const machines = await fleet.snapshots(params.machine);
135
- return result({
136
- machines: machines.map(
137
- ({
138
- snapshot: _snapshot,
139
- monitoredPaneIds: _monitoredPaneIds,
140
- ...machine
141
- }) => machine,
142
- ),
143
- agents: machines.flatMap((machine) => {
144
- if (!machine.snapshot) return [];
145
- return machine.snapshot.agents
146
- .filter(
147
- (agent) =>
148
- agent.agent === "pi" &&
149
- (!machine.local ||
150
- agent.pane_id !== process.env["HERDR_PANE_ID"]),
151
- )
152
- .map((agent) =>
153
- compactAgent(
154
- agent,
155
- machine.snapshot!,
156
- machine.monitoredPaneIds?.has(agent.pane_id) ?? false,
157
- machine.name,
158
- ),
159
- );
160
- }),
161
- workspaces: machines.flatMap((machine) =>
162
- (machine.snapshot?.workspaces ?? []).map((workspace) => ({
163
- machine: machine.name,
164
- id: workspace.workspace_id,
165
- label: workspace.label,
166
- })),
167
- ),
168
- });
169
- }
170
- const runtime = fleet.connected(params.machine);
171
- const { client, machine, monitor } = runtime;
172
- if (params.action === "start") {
173
- const started = await startAgent(
174
- client,
175
- monitor,
176
- params,
177
- runtime.local ? ctx.cwd : runtime.fallbackCwd,
178
- runtime.resolveDirectory,
179
- );
180
- return result({
181
- started: true,
182
- machine,
183
- id: started.id,
184
- ...(params.prompt?.trim() ? { next: FIRE_AND_FORGET } : {}),
185
- });
186
- }
187
-
188
- const target = required(params.target, "target");
189
- if (params.action === "unwatch") {
190
- const record = findRecord(monitor, target);
191
- if (!record) return result({ unwatched: false, machine, target });
192
- await monitor.unwatch(record.paneId);
193
- return result({ unwatched: true, machine, id: record.paneId });
194
- }
195
-
196
- const agent = await resolvePiAgent(
197
- client,
198
- target,
199
- runtime.local ? process.env["HERDR_PANE_ID"] : "",
200
- );
201
- if (params.action === "watch") {
202
- await monitor.watch(agent);
203
- return result({
204
- watched: true,
205
- machine,
206
- id: agent.pane_id,
207
- next: FIRE_AND_FORGET,
208
- });
209
- }
210
- if (params.action === "send") {
211
- const prompt = required(params.prompt, "prompt");
212
- if (!monitor.isMonitored(agent.pane_id)) await monitor.watch(agent);
213
- const attempt = monitor.beginWork(agent.pane_id, prompt);
214
- try {
215
- await client.request("agent.prompt", {
216
- target: agent.pane_id,
217
- text: prompt,
218
- });
219
- monitor.acceptWork(attempt);
220
- } catch (error) {
221
- await monitor.handleWorkFailure(attempt, error);
222
- throw error;
223
- }
224
- return result({
225
- sent: true,
226
- machine,
227
- id: agent.pane_id,
228
- next: FIRE_AND_FORGET,
229
- });
230
- }
231
- throw new Error(`unsupported action ${params.action}`);
232
- },
233
- });
234
- }