@howaboua/pi-shepherdr 0.1.0 → 0.1.2

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/launch.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  parsePaneInfo,
7
7
  resolveWorkspace,
8
8
  } from "./herdr.js";
9
- import { type HerdrClient, isHerdrErrorCode } from "./herdr-client.js";
9
+ import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
10
10
  import type { AgentMonitor } from "./monitor.js";
11
11
  import type { PaneInfo } from "./types.js";
12
12
 
@@ -43,8 +43,13 @@ async function directory(
43
43
  return path;
44
44
  }
45
45
 
46
+ export type DirectoryResolver = (
47
+ value: string | undefined,
48
+ fallback: string,
49
+ ) => Promise<string>;
50
+
46
51
  async function createStartPane(
47
- client: HerdrClient,
52
+ client: HerdrConnection,
48
53
  params: StartAgentParams,
49
54
  cwd: string,
50
55
  label: string,
@@ -155,10 +160,11 @@ function nestedId(value: unknown, key: string, path: string): string {
155
160
  }
156
161
 
157
162
  export async function startAgent(
158
- client: HerdrClient,
163
+ client: HerdrConnection,
159
164
  monitor: AgentMonitor,
160
165
  params: StartAgentParams,
161
166
  fallbackCwd: string,
167
+ resolveDirectory: DirectoryResolver = directory,
162
168
  ): Promise<{ id: string }> {
163
169
  const name = required(params.name, "name");
164
170
  if (!AGENT_NAME.test(name)) {
@@ -173,7 +179,7 @@ export async function startAgent(
173
179
  const cwd =
174
180
  params.placement === "pane"
175
181
  ? fallbackCwd
176
- : await directory(params.cwd, fallbackCwd);
182
+ : await resolveDirectory(params.cwd, fallbackCwd);
177
183
  const created = await createStartPane(client, params, cwd, label);
178
184
  let agent: PaneInfo;
179
185
  try {
@@ -212,7 +218,7 @@ export async function startAgent(
212
218
  }
213
219
 
214
220
  async function rollbackCreatedLocation(
215
- client: HerdrClient,
221
+ client: HerdrConnection,
216
222
  cleanup: { id: string; method: "tab.close" | "workspace.close" } | undefined,
217
223
  cause: unknown,
218
224
  ): Promise<never> {
@@ -231,7 +237,7 @@ async function rollbackCreatedLocation(
231
237
  }
232
238
 
233
239
  async function startWhenShellReady(
234
- client: HerdrClient,
240
+ client: HerdrConnection,
235
241
  params: Record<string, unknown>,
236
242
  ): Promise<PaneInfo> {
237
243
  const shellDeadline = Date.now() + 3_000;
@@ -305,7 +311,7 @@ async function startWhenShellReady(
305
311
  }
306
312
 
307
313
  async function resolveDuringStart(
308
- client: HerdrClient,
314
+ client: HerdrConnection,
309
315
  name: string,
310
316
  paneId: string,
311
317
  ): Promise<PaneInfo> {
@@ -0,0 +1,148 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ const MACHINE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
7
+
8
+ export const LOCAL_MACHINE = "local";
9
+
10
+ export function isMachineName(value: string): boolean {
11
+ return MACHINE_NAME.test(value);
12
+ }
13
+
14
+ export interface RemoteMachineConfig {
15
+ command: string[];
16
+ herdr: string;
17
+ node: string;
18
+ session?: string;
19
+ socket?: string;
20
+ }
21
+
22
+ export interface MachinesConfig {
23
+ machines: Record<string, RemoteMachineConfig>;
24
+ }
25
+
26
+ function agentDir(): string {
27
+ return (
28
+ process.env["PI_CODING_AGENT_DIR"]?.trim() ||
29
+ join(homedir(), ".pi", "agent")
30
+ );
31
+ }
32
+
33
+ function machinesConfigPath(): string {
34
+ return join(agentDir(), "shepherdr.json");
35
+ }
36
+
37
+ function optionalString(
38
+ value: Record<string, unknown>,
39
+ key: string,
40
+ ): string | undefined {
41
+ const candidate = value[key];
42
+ if (candidate === undefined) return undefined;
43
+ if (typeof candidate !== "string" || !candidate.trim()) {
44
+ throw new Error(`${key} must be a non-empty string`);
45
+ }
46
+ return candidate.trim();
47
+ }
48
+
49
+ function parseMachine(name: string, value: unknown): RemoteMachineConfig {
50
+ if (!isMachineName(name)) {
51
+ throw new Error(
52
+ `machine name ${JSON.stringify(name)} must match ${MACHINE_NAME.source}`,
53
+ );
54
+ }
55
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
56
+ throw new Error(`machine ${JSON.stringify(name)} must be an object`);
57
+ }
58
+ const record = value as Record<string, unknown>;
59
+ const command = record["command"];
60
+ if (
61
+ !Array.isArray(command) ||
62
+ command.length === 0 ||
63
+ command.some((part) => typeof part !== "string" || !part)
64
+ ) {
65
+ throw new Error(
66
+ `machine ${JSON.stringify(name)} command must be a non-empty string array`,
67
+ );
68
+ }
69
+ const session = optionalString(record, "session");
70
+ const socket = optionalString(record, "socket");
71
+ if (session && socket) {
72
+ throw new Error(
73
+ `machine ${JSON.stringify(name)} cannot set both session and socket`,
74
+ );
75
+ }
76
+ return {
77
+ command: command as string[],
78
+ herdr: optionalString(record, "herdr") ?? "herdr",
79
+ node: optionalString(record, "node") ?? "node",
80
+ ...(session ? { session } : {}),
81
+ ...(socket ? { socket } : {}),
82
+ };
83
+ }
84
+
85
+ export async function readMachinesConfig(): Promise<MachinesConfig> {
86
+ const path = machinesConfigPath();
87
+ let text: string;
88
+ try {
89
+ text = await readFile(path, "utf8");
90
+ } catch (error) {
91
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
92
+ return { machines: {} };
93
+ }
94
+ throw new Error(
95
+ `could not read ${path}: ${error instanceof Error ? error.message : String(error)}`,
96
+ );
97
+ }
98
+ let value: unknown;
99
+ try {
100
+ value = JSON.parse(text);
101
+ } catch (error) {
102
+ throw new Error(
103
+ `could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`,
104
+ );
105
+ }
106
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
107
+ throw new Error(`${path} must contain a JSON object`);
108
+ }
109
+ const record = value as Record<string, unknown>;
110
+ const machines = record["machines"] ?? {};
111
+ if (
112
+ typeof machines !== "object" ||
113
+ machines === null ||
114
+ Array.isArray(machines)
115
+ ) {
116
+ throw new Error(`${path} machines must be an object`);
117
+ }
118
+ const parsed = Object.fromEntries(
119
+ Object.entries(machines).map(([name, machine]) => [
120
+ name,
121
+ parseMachine(name, machine),
122
+ ]),
123
+ );
124
+ if (LOCAL_MACHINE in parsed)
125
+ throw new Error(
126
+ `remote machine ${JSON.stringify(LOCAL_MACHINE)} conflicts with local`,
127
+ );
128
+ return { machines: parsed };
129
+ }
130
+
131
+ export async function writeMachinesConfig(
132
+ config: MachinesConfig,
133
+ ): Promise<string> {
134
+ const path = machinesConfigPath();
135
+ await mkdir(dirname(path), { recursive: true });
136
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
137
+ try {
138
+ await writeFile(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, {
139
+ encoding: "utf8",
140
+ mode: 0o600,
141
+ });
142
+ await rename(temporaryPath, path);
143
+ } catch (error) {
144
+ await unlink(temporaryPath).catch(() => undefined);
145
+ throw error;
146
+ }
147
+ return path;
148
+ }
@@ -2,31 +2,99 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
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";
5
12
  import { enableMasterDirectory, isMasterDirectory } from "./master-config.js";
6
- import type { AgentMonitor } from "./monitor.js";
7
13
 
8
14
  const TOOL_NAME = "herdr_agents";
9
15
 
10
- export function registerMasterMode(
11
- pi: ExtensionAPI,
12
- getMonitor: () => AgentMonitor,
13
- ): void {
14
- let monitor: AgentMonitor | undefined;
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 {
15
62
  pi.registerCommand("herdr", {
16
- description: "Enable Herdr master mode for this session or directory",
63
+ description: "Manage Herdr master mode and machines",
17
64
  getArgumentCompletions: (prefix) =>
18
- ["master", "json"]
65
+ ["master", "json", "connect"]
19
66
  .filter((action) => action.startsWith(prefix.trim().toLowerCase()))
20
67
  .map((value) => ({ label: value, value })),
21
68
  handler: async (args, ctx) => {
22
- const action = args.trim().toLowerCase();
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
+ }
23
90
  if (action !== "master" && action !== "json") {
24
- ctx.ui.notify("Usage: /herdr [master|json]", "warning");
91
+ ctx.ui.notify(
92
+ "Usage: /herdr [master|json|connect [machine]]",
93
+ "warning",
94
+ );
25
95
  return;
26
96
  }
27
- const activeMonitor = await activateMaster(pi, getMonitor, ctx);
28
- if (!activeMonitor) return;
29
- monitor = activeMonitor;
97
+ if (!(await activateMaster(pi, fleet, ctx))) return;
30
98
  if (action === "master") {
31
99
  ctx.ui.notify("Herdr master enabled for this Pi session", "info");
32
100
  return;
@@ -44,7 +112,7 @@ export function registerMasterMode(
44
112
  });
45
113
 
46
114
  pi.on("session_start", async (_event, ctx) => {
47
- monitor?.deactivate();
115
+ fleet.deactivate();
48
116
  let master = false;
49
117
  try {
50
118
  master = await isMasterDirectory(ctx.cwd);
@@ -58,39 +126,159 @@ export function registerMasterMode(
58
126
  setToolActive(pi, false);
59
127
  return;
60
128
  }
61
- const activeMonitor = await activateMaster(pi, getMonitor, ctx);
62
- if (activeMonitor) monitor = activeMonitor;
129
+ await activateMaster(pi, fleet, ctx);
63
130
  });
64
131
 
65
132
  pi.on("session_shutdown", async () => {
66
- monitor?.deactivate();
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;
67
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
+ );
68
258
  }
69
259
 
70
260
  async function activateMaster(
71
261
  pi: ExtensionAPI,
72
- getMonitor: () => AgentMonitor,
262
+ fleet: AgentFleet,
73
263
  ctx: ExtensionContext,
74
- ): Promise<AgentMonitor | undefined> {
264
+ ): Promise<boolean> {
75
265
  if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
76
266
  setToolActive(pi, false);
77
267
  ctx.ui.notify("Herdr master mode requires Pi to run inside Herdr", "error");
78
- return undefined;
268
+ return false;
79
269
  }
80
- const monitor = getMonitor();
81
270
  try {
82
- await monitor.client.request("ping");
83
271
  setToolActive(pi, true);
84
- await monitor.activate(ctx);
85
- return monitor;
272
+ await fleet.activate(ctx);
273
+ return true;
86
274
  } catch (error) {
87
275
  setToolActive(pi, false);
88
- monitor.deactivate();
276
+ fleet.deactivate();
89
277
  ctx.ui.notify(
90
278
  `Herdr master could not start: ${error instanceof Error ? error.message : String(error)}`,
91
279
  "error",
92
280
  );
93
- return undefined;
281
+ return false;
94
282
  }
95
283
  }
96
284