@howaboua/pi-shepherdr 0.2.10 → 0.2.12

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.
@@ -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,9 @@ 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 { Identity } from "./attachment-protocol.js";
10
14
  import type { AgentBoard } from "./board/host.js";
11
15
  import { isBoardEnvelope } from "./board/protocol.js";
12
16
  import type { AgentFleet, ConnectedMachine } from "./fleet.js";
@@ -42,6 +46,7 @@ export class SharedAgentContext {
42
46
  private readonly getService: () => ContextSharingService | undefined;
43
47
  private readonly board: AgentBoard;
44
48
  private running = false;
49
+ readonly attachment: AgentAttachment;
45
50
 
46
51
  constructor(
47
52
  pi: ExtensionAPI,
@@ -53,6 +58,7 @@ export class SharedAgentContext {
53
58
  this.fleet = fleet;
54
59
  this.getService = getService;
55
60
  this.board = board;
61
+ this.attachment = new AgentAttachment(pi, board, getService);
56
62
  pi.on("agent_start", () => {
57
63
  this.running = true;
58
64
  });
@@ -69,8 +75,31 @@ export class SharedAgentContext {
69
75
  if (isBoardEnvelope(value)) return this.board.handle(ctx, value, signal);
70
76
  if (!value || typeof value !== "object")
71
77
  throw new Error("Invalid shared context request");
78
+ if (
79
+ "operation" in value &&
80
+ (value.operation === "attach-inspect" ||
81
+ value.operation === "attach-commit" ||
82
+ value.operation === "attachment-export-notes" ||
83
+ value.operation === "detach-commit")
84
+ )
85
+ return this.attachment.target.handle(ctx, value);
72
86
  const service = this.getService();
73
87
  const identity = service?.describe(ctx);
88
+ if (
89
+ "operation" in value &&
90
+ value.operation === "attachment-persisted-notes"
91
+ ) {
92
+ const file = ctx.sessionManager.getSessionFile();
93
+ if (
94
+ !file ||
95
+ !("identity" in value) ||
96
+ !Check(Identity, value.identity) ||
97
+ !isDeepStrictEqual(identity, value.identity) ||
98
+ identity?.threadId !== ctx.sessionManager.getSessionId()
99
+ )
100
+ throw new Error("Invalid saved checkpoint owner");
101
+ return requestContext(sessionContextPath(file), value, signal);
102
+ }
74
103
  if ("operation" in value && value.operation === "bind") {
75
104
  if (!service || !identity) return null;
76
105
  return service.bind(ctx, "binding" in value ? value.binding : undefined);
@@ -101,6 +130,21 @@ export class SharedAgentContext {
101
130
  ...envelope,
102
131
  visited: [...envelope.visited, identity.threadId],
103
132
  };
133
+ const attached = await this.attachment.routing.route(
134
+ ctx,
135
+ request,
136
+ forwarded.visited,
137
+ async (route, next) =>
138
+ this.fleet
139
+ .connected(route.machine)
140
+ .client.requestContext(
141
+ sessionContextPath(route.sessionFile),
142
+ next,
143
+ signal,
144
+ ) as Promise<SharedContextResult>,
145
+ signal,
146
+ );
147
+ if (attached) return attached;
104
148
  const member = ctx.sessionManager.getEntries().findLast((entry) => {
105
149
  if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
106
150
  return false;
@@ -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
- }