@howaboua/pi-shepherdr 0.2.11 → 0.2.13

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.
@@ -11,7 +11,7 @@ import {
11
11
  import { sendPeerMessage } from "./shepherdr-peer.mjs";
12
12
  import { readSessionView } from "./shepherdr-session.mjs";
13
13
 
14
- const BRIDGE_VERSION = 11;
14
+ const BRIDGE_VERSION = 13;
15
15
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
16
16
  const subscriptions = new Map();
17
17
  const contextRelays = new Map();
@@ -14,10 +14,11 @@ import type {
14
14
  SessionView,
15
15
  } from "./types.js";
16
16
 
17
- const BRIDGE_VERSION = 11;
17
+ const BRIDGE_VERSION = 13;
18
18
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
19
19
  const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
20
20
  const REMOTE_SESSION_HELPER = "~/.pi/agent/shepherdr-session.mjs";
21
+ const REMOTE_CHECKPOINT_HELPER = "~/.pi/agent/shepherdr-checkpoints.mjs";
21
22
  const REMOTE_CONTEXT_HELPER = "~/.pi/agent/shepherdr-context.mjs";
22
23
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
23
24
  const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
@@ -201,7 +202,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
201
202
  config: SshMachine,
202
203
  onClose: (error: Error) => void,
203
204
  ): Promise<RemoteHerdrClient> {
204
- const [source, peerSource, sessionSource, contextSource] =
205
+ const [source, peerSource, sessionSource, contextSource, checkpointSource] =
205
206
  await Promise.all([
206
207
  readFile(
207
208
  fileURLToPath(new URL("./remote/shepherdr.mjs", import.meta.url)),
@@ -221,9 +222,15 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
221
222
  new URL("./remote/shepherdr-context.mjs", import.meta.url),
222
223
  ),
223
224
  ),
225
+ readFile(
226
+ fileURLToPath(
227
+ new URL("./remote/shepherdr-checkpoints.mjs", import.meta.url),
228
+ ),
229
+ ),
224
230
  ]);
225
231
  await deploy(config, peerSource, REMOTE_PEER_HELPER);
226
232
  await deploy(config, sessionSource, REMOTE_SESSION_HELPER);
233
+ await deploy(config, checkpointSource, REMOTE_CHECKPOINT_HELPER);
227
234
  await deploy(config, contextSource, REMOTE_CONTEXT_HELPER);
228
235
  await deploy(config, source, REMOTE_HELPER);
229
236
  const child = spawnConnector(config, remoteCommand(config));
@@ -272,7 +279,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
272
279
  contextRelayPath(): string {
273
280
  if (!this.relayPath)
274
281
  throw new Error(
275
- "Shared context relay is unavailable; run /herdr connect to retry",
282
+ "Shared context relay is unavailable; open /herdr → Status to retry",
276
283
  );
277
284
  return this.relayPath;
278
285
  }
@@ -0,0 +1,151 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import { promisify } from "node:util";
4
+
5
+ interface ProcessRecord {
6
+ pid: number;
7
+ parent: number;
8
+ state: string;
9
+ }
10
+
11
+ async function processSnapshot(): Promise<ProcessRecord[]> {
12
+ const { stdout } = await promisify(execFile)(
13
+ "ps",
14
+ ["-A", "-o", "pid=,ppid=,stat="],
15
+ {
16
+ timeout: 500,
17
+ maxBuffer: 4 * 1024 * 1024,
18
+ encoding: "utf8",
19
+ },
20
+ );
21
+ return stdout
22
+ .trim()
23
+ .split("\n")
24
+ .filter(Boolean)
25
+ .map((line) => {
26
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)$/);
27
+ if (!match) throw new Error("Could not read setup process tree");
28
+ return {
29
+ pid: Number(match[1]),
30
+ parent: Number(match[2]),
31
+ state: match[3] ?? "",
32
+ };
33
+ });
34
+ }
35
+
36
+ function sendSignal(pid: number, signal: NodeJS.Signals): void {
37
+ try {
38
+ process.kill(pid, signal);
39
+ } catch (error) {
40
+ if (
41
+ !(error instanceof Error) ||
42
+ !("code" in error) ||
43
+ error.code !== "ESRCH"
44
+ )
45
+ throw error;
46
+ }
47
+ }
48
+
49
+ async function terminateSetupTree(pid: number): Promise<void> {
50
+ if (process.platform === "win32") {
51
+ await promisify(execFile)(
52
+ join(
53
+ process.env["SystemRoot"] ?? "C:\\Windows",
54
+ "System32",
55
+ "taskkill.exe",
56
+ ),
57
+ ["/F", "/T", "/PID", String(pid)],
58
+ { timeout: 3_000, windowsHide: true },
59
+ );
60
+ return;
61
+ }
62
+ // Keep the controlling TTY: detached:true would create a new session and
63
+ // break OpenSSH's /dev/tty authentication. Freeze this tree, never Pi's PGID.
64
+ const owned = new Set([pid]);
65
+ try {
66
+ sendSignal(pid, "SIGSTOP");
67
+ let settled = false;
68
+ for (let pass = 0; pass < 8; pass++) {
69
+ const records = await processSnapshot();
70
+ const before = owned.size;
71
+ let found: boolean;
72
+ do {
73
+ found = false;
74
+ for (const record of records) {
75
+ if (owned.has(record.parent) && !owned.has(record.pid)) {
76
+ owned.add(record.pid);
77
+ sendSignal(record.pid, "SIGSTOP");
78
+ found = true;
79
+ }
80
+ }
81
+ } while (found);
82
+ if (owned.size === before) {
83
+ settled = true;
84
+ break;
85
+ }
86
+ }
87
+ if (!settled)
88
+ throw new Error("Setup process tree did not settle for cancellation");
89
+ for (const childPid of [...owned].reverse()) {
90
+ sendSignal(childPid, "SIGTERM");
91
+ sendSignal(childPid, "SIGCONT");
92
+ }
93
+ await new Promise((resolve) => setTimeout(resolve, 500));
94
+ } finally {
95
+ // Retain descendants after the parent exits and they are reparented.
96
+ for (const childPid of [...owned].reverse())
97
+ sendSignal(childPid, "SIGKILL");
98
+ }
99
+ for (let pass = 0; pass < 10; pass++) {
100
+ const active = (await processSnapshot()).some(
101
+ (record) => owned.has(record.pid) && !record.state.startsWith("Z"),
102
+ );
103
+ if (!active) return;
104
+ await new Promise((resolve) => setTimeout(resolve, 50));
105
+ }
106
+ throw new Error("Setup process tree is still running after cancellation");
107
+ }
108
+
109
+ export async function runSetupProcess(
110
+ binary: string,
111
+ args: string[],
112
+ signal: AbortSignal,
113
+ ): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
114
+ signal.throwIfAborted();
115
+ const child = spawn(binary, args, {
116
+ shell: false,
117
+ stdio: "inherit",
118
+ env: process.env,
119
+ });
120
+ let cleanup: Promise<void> | undefined;
121
+ let cleanupError: unknown;
122
+ const abort = () => {
123
+ if (cleanup || child.pid === undefined) return;
124
+ cleanup = terminateSetupTree(child.pid).catch((error) => {
125
+ cleanupError = error;
126
+ child.kill("SIGKILL");
127
+ });
128
+ };
129
+ const completed = new Promise<{
130
+ code: number | null;
131
+ signal: NodeJS.Signals | null;
132
+ }>((resolve, reject) => {
133
+ child.once("error", reject);
134
+ child.once("close", (code, childSignal) =>
135
+ resolve({ code, signal: childSignal }),
136
+ );
137
+ });
138
+ signal.addEventListener("abort", abort, { once: true });
139
+ if (signal.aborted) abort();
140
+ try {
141
+ return await completed;
142
+ } finally {
143
+ signal.removeEventListener("abort", abort);
144
+ await cleanup;
145
+ if (cleanupError)
146
+ throw new Error(
147
+ `Setup process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
148
+ { cause: cleanupError },
149
+ );
150
+ }
151
+ }
@@ -1,3 +1,4 @@
1
+ import { isDeepStrictEqual } from "node:util";
1
2
  import type {
2
3
  ExtensionAPI,
3
4
  ExtensionContext,
@@ -7,6 +8,13 @@ import type {
7
8
  SharedContextRequest,
8
9
  SharedContextResult,
9
10
  } from "@howaboua/pi-codex-conversion/context-sharing";
11
+ import { Check } from "typebox/value";
12
+ import { AgentAttachment } from "./attachment.js";
13
+ import {
14
+ attachmentOwner,
15
+ attachmentRoutes,
16
+ Identity,
17
+ } from "./attachment-protocol.js";
10
18
  import type { AgentBoard } from "./board/host.js";
11
19
  import { isBoardEnvelope } from "./board/protocol.js";
12
20
  import type { AgentFleet, ConnectedMachine } from "./fleet.js";
@@ -42,6 +50,7 @@ export class SharedAgentContext {
42
50
  private readonly getService: () => ContextSharingService | undefined;
43
51
  private readonly board: AgentBoard;
44
52
  private running = false;
53
+ readonly attachment: AgentAttachment;
45
54
 
46
55
  constructor(
47
56
  pi: ExtensionAPI,
@@ -53,6 +62,7 @@ export class SharedAgentContext {
53
62
  this.fleet = fleet;
54
63
  this.getService = getService;
55
64
  this.board = board;
65
+ this.attachment = new AgentAttachment(pi, board, getService);
56
66
  pi.on("agent_start", () => {
57
67
  this.running = true;
58
68
  });
@@ -69,8 +79,31 @@ export class SharedAgentContext {
69
79
  if (isBoardEnvelope(value)) return this.board.handle(ctx, value, signal);
70
80
  if (!value || typeof value !== "object")
71
81
  throw new Error("Invalid shared context request");
82
+ if (
83
+ "operation" in value &&
84
+ (value.operation === "attach-inspect" ||
85
+ value.operation === "attach-commit" ||
86
+ value.operation === "attachment-export-notes" ||
87
+ value.operation === "detach-commit")
88
+ )
89
+ return this.attachment.target.handle(ctx, value, signal);
72
90
  const service = this.getService();
73
91
  const identity = service?.describe(ctx);
92
+ if (
93
+ "operation" in value &&
94
+ value.operation === "attachment-persisted-notes"
95
+ ) {
96
+ const file = ctx.sessionManager.getSessionFile();
97
+ if (
98
+ !file ||
99
+ !("identity" in value) ||
100
+ !Check(Identity, value.identity) ||
101
+ !isDeepStrictEqual(identity, value.identity) ||
102
+ identity?.threadId !== ctx.sessionManager.getSessionId()
103
+ )
104
+ throw new Error("Invalid saved checkpoint owner");
105
+ return requestContext(sessionContextPath(file), value, signal);
106
+ }
74
107
  if ("operation" in value && value.operation === "bind") {
75
108
  if (!service || !identity) return null;
76
109
  return service.bind(ctx, "binding" in value ? value.binding : undefined);
@@ -101,6 +134,21 @@ export class SharedAgentContext {
101
134
  ...envelope,
102
135
  visited: [...envelope.visited, identity.threadId],
103
136
  };
137
+ const attached = await this.attachment.routing.route(
138
+ ctx,
139
+ request,
140
+ forwarded.visited,
141
+ async (route, next) =>
142
+ this.fleet
143
+ .connected(route.machine)
144
+ .client.requestContext(
145
+ sessionContextPath(route.sessionFile),
146
+ next,
147
+ signal,
148
+ ) as Promise<SharedContextResult>,
149
+ signal,
150
+ );
151
+ if (attached) return attached;
104
152
  const member = ctx.sessionManager.getEntries().findLast((entry) => {
105
153
  if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
106
154
  return false;
@@ -267,12 +315,46 @@ export async function registerSharedAgentContext(
267
315
  close = undefined;
268
316
  unregister?.();
269
317
  unregister = connection?.service?.registerRouter(
270
- async (context, request, signal) =>
271
- shared.handle(
272
- context,
273
- { operation: "context", request, visited: [] },
274
- signal,
275
- ) as Promise<SharedContextResult>,
318
+ Object.assign(
319
+ async (
320
+ context: ExtensionContext,
321
+ request: SharedContextRequest,
322
+ signal?: AbortSignal,
323
+ ) => {
324
+ const attached = await shared.attachment.routing.route(
325
+ context,
326
+ request,
327
+ [],
328
+ (route, next) =>
329
+ fleet
330
+ .connected(route.machine)
331
+ .client.requestContext(
332
+ sessionContextPath(route.sessionFile),
333
+ next,
334
+ signal,
335
+ ),
336
+ signal,
337
+ );
338
+ if (attached) return attached;
339
+ if (connection?.service?.describe(context)?.storage === "remote")
340
+ return undefined;
341
+ return shared.handle(
342
+ context,
343
+ { operation: "context", request, visited: [] },
344
+ signal,
345
+ ) as Promise<SharedContextResult>;
346
+ },
347
+ {
348
+ requiresRemoteScope: (context: ExtensionContext) =>
349
+ attachmentOwner(context)?.context?.controller.storage ===
350
+ "remote" ||
351
+ attachmentRoutes(context).some(
352
+ (route) =>
353
+ route.phase === "ready" &&
354
+ route.plan.context?.target.storage === "remote",
355
+ ),
356
+ },
357
+ ),
276
358
  );
277
359
  const file = ctx.sessionManager.getSessionFile();
278
360
  if (file)
@@ -0,0 +1,144 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { SettingItem } from "@earendil-works/pi-tui";
3
+ import { readMachineCatalog, withHerdrBinary } from "./machine-catalog.js";
4
+ import { runSetupProcess } from "./setup-process.js";
5
+
6
+ // Herdr's default session is named "default". Pin it explicitly so native
7
+ // interactive session discovery cannot change the identity of a blank draft.
8
+ const DEFAULT_REMOTE_SESSION = "default";
9
+
10
+ export interface SshSetupDraft {
11
+ target: string;
12
+ label: string;
13
+ session: string;
14
+ }
15
+
16
+ export function sshSetupItems(draft: SshSetupDraft): SettingItem[] {
17
+ return [
18
+ {
19
+ id: "ssh:target",
20
+ label: "SSH target",
21
+ currentValue: draft.target || "required",
22
+ values: ["Enter"],
23
+ description:
24
+ "OpenSSH alias or user@host. Uses your SSH keys and configuration.",
25
+ },
26
+ {
27
+ id: "ssh:label",
28
+ label: "Label",
29
+ currentValue: draft.label || "required",
30
+ values: ["Enter"],
31
+ },
32
+ {
33
+ id: "ssh:session",
34
+ label: "Remote session",
35
+ currentValue: draft.session || "Herdr default",
36
+ values: ["Enter"],
37
+ description: "Optional Herdr session name. Leave empty for the default.",
38
+ },
39
+ {
40
+ id: "ssh:add",
41
+ label: "Add connection",
42
+ currentValue: "Enter",
43
+ values: ["Enter"],
44
+ description:
45
+ "Opens Herdr setup in the terminal. Ctrl+C cancels. Installation approvals stay interactive.",
46
+ },
47
+ ];
48
+ }
49
+
50
+ export function sshSetupArgs(draft: SshSetupDraft): string[] {
51
+ const { target, label, session } = draft;
52
+ if (!target || /^[-\s]|[\s\x00-\x1f\x7f]/.test(target))
53
+ throw new Error(
54
+ "Enter an SSH alias or user@host, without spaces or options.",
55
+ );
56
+ if (!label || /[\x00-\x1f\x7f]/.test(label))
57
+ throw new Error("Enter a label without control characters.");
58
+ if (
59
+ session &&
60
+ (!/^[a-zA-Z0-9_.-]{1,64}$/.test(session) ||
61
+ session === "." ||
62
+ session === "..")
63
+ )
64
+ throw new Error(
65
+ "Session must use 1–64 letters, digits, dots, underscores or hyphens.",
66
+ );
67
+ return [
68
+ "machine",
69
+ "add",
70
+ target,
71
+ "--label",
72
+ label,
73
+ "--remote-session",
74
+ session || DEFAULT_REMOTE_SESSION,
75
+ ];
76
+ }
77
+
78
+ export async function addSshConnection(
79
+ ctx: ExtensionContext,
80
+ draft: SshSetupDraft,
81
+ signal: AbortSignal,
82
+ ): Promise<{ message: string; refresh: boolean }> {
83
+ const args = sshSetupArgs(draft);
84
+ const session = draft.session || DEFAULT_REMOTE_SESSION;
85
+ const matchesDraft = (machine: { target: string; session: string }) =>
86
+ machine.target === draft.target && machine.session === session;
87
+ // Inspect on every attempt, including retries after interrupted setup.
88
+ const catalog = await readMachineCatalog(signal);
89
+ signal.throwIfAborted();
90
+ const existing = Object.values(catalog).find(matchesDraft);
91
+ if (existing)
92
+ return {
93
+ message: `Already configured as ${existing.label}. Check Status.`,
94
+ refresh: true,
95
+ };
96
+ const result = await withHerdrBinary((binary) =>
97
+ ctx.ui.custom<{
98
+ code: number | null;
99
+ signal: NodeJS.Signals | null;
100
+ interrupted: boolean;
101
+ }>(async (tui, _theme, _kb, done) => {
102
+ signal.throwIfAborted();
103
+ tui.stop();
104
+ // The terminal sends Ctrl+C to both processes. Let Herdr handle it,
105
+ // without allowing Node's default handler to terminate Pi.
106
+ let interrupted = false;
107
+ const interrupt = () => {
108
+ interrupted = true;
109
+ };
110
+ let result: { code: number | null; signal: NodeJS.Signals | null };
111
+ try {
112
+ process.stdout.write("\x1b[2J\x1b[H");
113
+ process.on("SIGINT", interrupt);
114
+ result = await runSetupProcess(binary, args, signal);
115
+ } finally {
116
+ process.removeListener("SIGINT", interrupt);
117
+ tui.start();
118
+ tui.requestRender(true);
119
+ }
120
+ done({ ...result, interrupted });
121
+ return { render: () => [], invalidate: () => {} };
122
+ }),
123
+ );
124
+ signal.throwIfAborted();
125
+ if (result.interrupted || result.code !== 0)
126
+ return {
127
+ message: `Herdr setup ${result.interrupted || result.signal ? `cancelled (${result.signal ?? "SIGINT"})` : `exited with code ${result.code ?? "unknown"}`}. Profile not confirmed. Retry checks the catalog first.`,
128
+ refresh: false,
129
+ };
130
+ const saved = Object.values(await readMachineCatalog(signal)).some(
131
+ matchesDraft,
132
+ );
133
+ signal.throwIfAborted();
134
+ if (!saved)
135
+ return {
136
+ message:
137
+ "No matching profile saved. Setup may have been cancelled; retry checks the catalog first.",
138
+ refresh: false,
139
+ };
140
+ return {
141
+ message: "Herdr setup completed. Check Status for the connection.",
142
+ refresh: true,
143
+ };
144
+ }
package/src/types.ts CHANGED
@@ -99,6 +99,8 @@ export interface MachineStatus {
99
99
  target?: string;
100
100
  session?: string;
101
101
  monitoringIssue?: MonitoringIssue;
102
+ contextRelayError?: string;
103
+ attempting?: boolean;
102
104
  reason?: string;
103
105
  status: MachineConnectionStatus;
104
106
  }
package/src/widget.ts CHANGED
@@ -95,9 +95,7 @@ export function renderAgentWidget(
95
95
  machine.monitoringIssue.state === "degraded"
96
96
  ? "incomplete"
97
97
  : "unavailable";
98
- const recovery = machine.local
99
- ? "retrying"
100
- : `/herdr connect ${machine.id}`;
98
+ const recovery = machine.local ? "retrying" : "/herdr → Status";
101
99
  lines.push(
102
100
  `${theme.fg("muted", "│")} ${theme.fg("warning", `${machine.id} monitoring ${status} · ${recovery}`)}`,
103
101
  );
@@ -1,98 +0,0 @@
1
- import {
2
- type ExtensionContext,
3
- getSettingsListTheme,
4
- } from "@earendil-works/pi-coding-agent";
5
- import { SettingsList, truncateToWidth } from "@earendil-works/pi-tui";
6
- import type { AgentBoard } from "./host.js";
7
-
8
- export async function openBoardSettings(
9
- ctx: ExtensionContext,
10
- board: AgentBoard,
11
- ) {
12
- // Check root ownership and configuration before opening the menu.
13
- let settings = board.settings(ctx);
14
- let status = board.status(ctx);
15
- await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
16
- let busy = false;
17
- const items = () => {
18
- const value = (enabled: boolean | undefined) =>
19
- enabled === undefined ? "inherit" : enabled ? "on" : "off";
20
- return [
21
- {
22
- id: "session",
23
- label: "This session",
24
- currentValue: value(settings.session),
25
- values: ["inherit", "on", "off"],
26
- },
27
- {
28
- id: "folder",
29
- label: "This folder",
30
- currentValue: value(settings.folder),
31
- values: ["inherit", "on", "off"],
32
- },
33
- {
34
- id: "global",
35
- label: "Enable globally",
36
- currentValue: value(settings.global),
37
- values: ["off", "on"],
38
- },
39
- ];
40
- };
41
- const restoreValues = () => {
42
- for (const item of items()) list.updateValue(item.id, item.currentValue);
43
- tui.requestRender();
44
- };
45
- const reload = () => {
46
- status = board.status(ctx);
47
- try {
48
- settings = board.settings(ctx);
49
- } catch (error) {
50
- ctx.ui.notify(String(error), "error");
51
- }
52
- restoreValues();
53
- };
54
- const list = new SettingsList(
55
- items(),
56
- 3,
57
- getSettingsListTheme(),
58
- (id, value) => {
59
- if (id !== "session" && id !== "folder" && id !== "global") return;
60
- if (busy) {
61
- restoreValues();
62
- return;
63
- }
64
- busy = true;
65
- void board
66
- .setSetting(ctx, id, value === "inherit" ? undefined : value === "on")
67
- .catch((error: unknown) => ctx.ui.notify(String(error), "error"))
68
- .finally(() => {
69
- busy = false;
70
- reload();
71
- });
72
- },
73
- () => {
74
- if (!busy) done(undefined);
75
- },
76
- );
77
- return {
78
- render(width: number) {
79
- return [
80
- theme.bold("Shepherdr message board"),
81
- "",
82
- ...list.render(width),
83
- "",
84
- ...status.split("\n"),
85
- `Folder config: ${settings.paths.folder}`,
86
- `Global config: ${settings.paths.global}`,
87
- "Session overrides folder; folder overrides global. Folder settings never cover child directories.",
88
- "Enter/Space to change · Esc to close",
89
- ].map((line) => truncateToWidth(line, width, ""));
90
- },
91
- invalidate: () => list.invalidate(),
92
- handleInput(data: string) {
93
- list.handleInput(data);
94
- tui.requestRender();
95
- },
96
- };
97
- });
98
- }