@howaboua/pi-shepherdr 0.1.1 → 0.1.3

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
@@ -2,11 +2,12 @@ import { stat } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import {
4
4
  getAgent,
5
+ getPane,
5
6
  getSnapshot,
6
7
  parsePaneInfo,
7
8
  resolveWorkspace,
8
9
  } from "./herdr.js";
9
- import { type HerdrClient, isHerdrErrorCode } from "./herdr-client.js";
10
+ import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
10
11
  import type { AgentMonitor } from "./monitor.js";
11
12
  import type { PaneInfo } from "./types.js";
12
13
 
@@ -43,13 +44,56 @@ async function directory(
43
44
  return path;
44
45
  }
45
46
 
47
+ export type DirectoryResolver = (
48
+ value: string | undefined,
49
+ fallback: string,
50
+ ) => Promise<string>;
51
+
52
+ function resolveStartDirectory(
53
+ params: StartAgentParams,
54
+ fallbackCwd: string,
55
+ resolveDirectory: DirectoryResolver = directory,
56
+ ): Promise<string> {
57
+ return params.placement === "pane"
58
+ ? Promise.resolve(fallbackCwd)
59
+ : resolveDirectory(params.cwd, fallbackCwd);
60
+ }
61
+
62
+ export async function resolvePreparationDirectory(
63
+ client: HerdrConnection,
64
+ params: StartAgentParams,
65
+ fallbackCwd: string,
66
+ resolveDirectory: DirectoryResolver = directory,
67
+ ): Promise<string> {
68
+ if (params.placement !== "pane") {
69
+ return resolveStartDirectory(params, fallbackCwd, resolveDirectory);
70
+ }
71
+ const pane = await getPane(client, required(params.pane, "pane"));
72
+ return pane.foreground_cwd?.trim() || pane.cwd?.trim() || fallbackCwd;
73
+ }
74
+
75
+ interface StartAgentOptions {
76
+ agentArgs?: string[];
77
+ }
78
+
79
+ interface CreatedLocationCleanup {
80
+ id: string;
81
+ method: "tab.close" | "workspace.close";
82
+ }
83
+
84
+ export interface StartedAgent {
85
+ agent: PaneInfo;
86
+ cleanup?: CreatedLocationCleanup;
87
+ id: string;
88
+ }
89
+
46
90
  async function createStartPane(
47
- client: HerdrClient,
91
+ client: HerdrConnection,
48
92
  params: StartAgentParams,
49
93
  cwd: string,
50
94
  label: string,
51
95
  ): Promise<{
52
- cleanup?: { id: string; method: "tab.close" | "workspace.close" };
96
+ cleanup?: CreatedLocationCleanup;
53
97
  paneId: string;
54
98
  }> {
55
99
  const placement = params.placement;
@@ -155,11 +199,13 @@ function nestedId(value: unknown, key: string, path: string): string {
155
199
  }
156
200
 
157
201
  export async function startAgent(
158
- client: HerdrClient,
202
+ client: HerdrConnection,
159
203
  monitor: AgentMonitor,
160
204
  params: StartAgentParams,
161
205
  fallbackCwd: string,
162
- ): Promise<{ id: string }> {
206
+ resolveDirectory: DirectoryResolver = directory,
207
+ options: StartAgentOptions = {},
208
+ ): Promise<StartedAgent> {
163
209
  const name = required(params.name, "name");
164
210
  if (!AGENT_NAME.test(name)) {
165
211
  throw new Error("name must match [a-z][a-z0-9_-]{0,31}");
@@ -170,10 +216,11 @@ export async function startAgent(
170
216
  "cwd cannot change an existing pane; prepare the pane through Herdr",
171
217
  );
172
218
  }
173
- const cwd =
174
- params.placement === "pane"
175
- ? fallbackCwd
176
- : await directory(params.cwd, fallbackCwd);
219
+ const cwd = await resolveStartDirectory(
220
+ params,
221
+ fallbackCwd,
222
+ resolveDirectory,
223
+ );
177
224
  const created = await createStartPane(client, params, cwd, label);
178
225
  let agent: PaneInfo;
179
226
  try {
@@ -181,7 +228,7 @@ export async function startAgent(
181
228
  name,
182
229
  kind: "pi",
183
230
  pane_id: created.paneId,
184
- args: ["--name", label],
231
+ args: ["--name", label, ...(options.agentArgs ?? [])],
185
232
  timeout_ms: 30_000,
186
233
  });
187
234
  } catch (error) {
@@ -207,13 +254,26 @@ export async function startAgent(
207
254
  }
208
255
  }
209
256
  return {
257
+ agent,
258
+ ...(created.cleanup ? { cleanup: created.cleanup } : {}),
210
259
  id: agent.pane_id,
211
260
  };
212
261
  }
213
262
 
263
+ export async function rollbackStartedAgent(
264
+ client: HerdrConnection,
265
+ monitor: AgentMonitor,
266
+ started: StartedAgent,
267
+ cause: unknown,
268
+ ): Promise<never> {
269
+ if (!started.cleanup) throw cause;
270
+ await monitor.unwatch(started.id).catch(() => undefined);
271
+ return rollbackCreatedLocation(client, started.cleanup, cause);
272
+ }
273
+
214
274
  async function rollbackCreatedLocation(
215
- client: HerdrClient,
216
- cleanup: { id: string; method: "tab.close" | "workspace.close" } | undefined,
275
+ client: HerdrConnection,
276
+ cleanup: CreatedLocationCleanup | undefined,
217
277
  cause: unknown,
218
278
  ): Promise<never> {
219
279
  if (!cleanup) throw cause;
@@ -231,7 +291,7 @@ async function rollbackCreatedLocation(
231
291
  }
232
292
 
233
293
  async function startWhenShellReady(
234
- client: HerdrClient,
294
+ client: HerdrConnection,
235
295
  params: Record<string, unknown>,
236
296
  ): Promise<PaneInfo> {
237
297
  const shellDeadline = Date.now() + 3_000;
@@ -305,7 +365,7 @@ async function startWhenShellReady(
305
365
  }
306
366
 
307
367
  async function resolveDuringStart(
308
- client: HerdrClient,
368
+ client: HerdrConnection,
309
369
  name: string,
310
370
  paneId: string,
311
371
  ): Promise<PaneInfo> {
@@ -0,0 +1,158 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentFleet } from "./fleet.js";
3
+ import {
4
+ isMachineName,
5
+ LOCAL_MACHINE,
6
+ readMachinesConfig,
7
+ writeMachinesConfig,
8
+ } from "./machines-config.js";
9
+
10
+ function parseSshArguments(value: string): string[] {
11
+ const parts: string[] = [];
12
+ let current = "";
13
+ let quote: "'" | '"' | undefined;
14
+ let escaped = false;
15
+ let started = false;
16
+ for (const character of value) {
17
+ if (escaped) {
18
+ current += character;
19
+ escaped = false;
20
+ started = true;
21
+ continue;
22
+ }
23
+ if (character === "\\" && quote !== "'") {
24
+ escaped = true;
25
+ started = true;
26
+ continue;
27
+ }
28
+ if (quote) {
29
+ if (character === quote) quote = undefined;
30
+ else current += character;
31
+ continue;
32
+ }
33
+ if (character === "'" || character === '"') {
34
+ quote = character;
35
+ started = true;
36
+ } else if (/\s/.test(character)) {
37
+ if (started) {
38
+ parts.push(current);
39
+ current = "";
40
+ started = false;
41
+ }
42
+ } else {
43
+ current += character;
44
+ started = true;
45
+ }
46
+ }
47
+ if (quote) throw new Error("SSH arguments contain an unclosed quote");
48
+ if (escaped) throw new Error("SSH arguments end with an incomplete escape");
49
+ if (started) parts.push(current);
50
+ if (parts.length === 0) throw new Error("SSH target is required");
51
+ const target = parts.pop()!;
52
+ return [...parts, "--", target];
53
+ }
54
+
55
+ export async function showMachineMenu(
56
+ fleet: AgentFleet,
57
+ ctx: ExtensionContext,
58
+ ): Promise<void> {
59
+ const config = await readMachinesConfig().catch((error) => {
60
+ ctx.ui.notify(
61
+ `Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
62
+ "error",
63
+ );
64
+ return undefined;
65
+ });
66
+ if (!config) return;
67
+ const statuses = fleet.isActive()
68
+ ? fleet.statuses()
69
+ : Object.keys(config.machines).map((name) => ({
70
+ local: false,
71
+ name,
72
+ status: "unavailable" as const,
73
+ }));
74
+ const selected = await ctx.ui.select("Shepherdr machines", [
75
+ "Add machine",
76
+ ...statuses
77
+ .filter((machine) => !machine.local)
78
+ .map(
79
+ (machine) =>
80
+ `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
81
+ ),
82
+ ]);
83
+ if (!selected) return;
84
+ if (selected === "Add machine") {
85
+ await addMachine(ctx, fleet);
86
+ return;
87
+ }
88
+ const name = selected.slice(2).split(" · ", 1)[0];
89
+ if (!name) return;
90
+ const status = statuses.find((machine) => machine.name === name);
91
+ const action = await ctx.ui.select(name, [
92
+ ...(status?.status !== "connected" ? ["Connect"] : []),
93
+ "Remove",
94
+ ]);
95
+ if (action === "Connect") {
96
+ if (!fleet.isActive()) {
97
+ ctx.ui.notify("Run /herdr to activate agents first", "warning");
98
+ return;
99
+ }
100
+ ctx.ui.notify(fleet.connect(name), "info");
101
+ } else if (action === "Remove") {
102
+ const confirmed = await ctx.ui.confirm(
103
+ `Remove ${name}?`,
104
+ "The remote Shepherdr helper will remain available for other controllers",
105
+ );
106
+ if (!confirmed) return;
107
+ delete config.machines[name];
108
+ await writeMachinesConfig(config);
109
+ await fleet.reload();
110
+ ctx.ui.notify(`Removed ${name}`, "info");
111
+ }
112
+ }
113
+
114
+ async function addMachine(
115
+ ctx: ExtensionContext,
116
+ fleet: AgentFleet,
117
+ ): Promise<void> {
118
+ const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
119
+ if (!name) return;
120
+ if (!isMachineName(name)) {
121
+ ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
122
+ return;
123
+ }
124
+ const ssh = (
125
+ await ctx.ui.input("SSH options and target (target last)", name)
126
+ )?.trim();
127
+ if (!ssh) return;
128
+ let sshArguments: string[];
129
+ try {
130
+ sshArguments = parseSshArguments(ssh);
131
+ } catch (error) {
132
+ ctx.ui.notify(
133
+ error instanceof Error ? error.message : String(error),
134
+ "error",
135
+ );
136
+ return;
137
+ }
138
+ const session = (
139
+ await ctx.ui.input("Herdr session", "default (leave blank)")
140
+ )?.trim();
141
+ const config = await readMachinesConfig();
142
+ if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
143
+ ctx.ui.notify(`Machine ${name} already exists`, "error");
144
+ return;
145
+ }
146
+ config.machines[name] = {
147
+ command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
148
+ herdr: "herdr",
149
+ node: "node",
150
+ ...(session && session !== "default (leave blank)" ? { session } : {}),
151
+ };
152
+ const path = await writeMachinesConfig(config);
153
+ await fleet.reload();
154
+ ctx.ui.notify(
155
+ `Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
156
+ "info",
157
+ );
158
+ }
@@ -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
+ }