@howaboua/pi-shepherdr 0.1.6 → 0.2.0

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/monitor.ts CHANGED
@@ -25,6 +25,7 @@ import type {
25
25
  interface AgentMonitorOptions {
26
26
  client: HerdrConnection;
27
27
  machine: string;
28
+ machineLabel: () => string;
28
29
  onChange: () => void;
29
30
  onRefresh: () => void;
30
31
  operatorPrefix: string;
@@ -57,10 +58,16 @@ export class AgentMonitor {
57
58
  pi,
58
59
  this.client,
59
60
  this.state,
60
- () => this.persist(),
61
+ () => {
62
+ this.persist();
63
+ this.refreshAfterEvent();
64
+ },
61
65
  options.reader,
62
- this.machine,
63
- options.operatorPrefix,
66
+ {
67
+ machine: this.machine,
68
+ label: options.machineLabel,
69
+ operatorPrefix: options.operatorPrefix,
70
+ },
64
71
  );
65
72
  this.events = new MonitorEvents({
66
73
  client: this.client,
@@ -105,10 +112,6 @@ export class AgentMonitor {
105
112
  return this.state.list();
106
113
  }
107
114
 
108
- isMonitored(paneId: string): boolean {
109
- return this.state.isMonitored(paneId);
110
- }
111
-
112
115
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
113
116
  return this.watchPanel(panel, true);
114
117
  }
@@ -4,7 +4,7 @@ import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
 
7
- const BRIDGE_VERSION = 4;
7
+ const BRIDGE_VERSION = 5;
8
8
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
9
9
  const READ_CHUNK_BYTES = 64 * 1024;
10
10
  const subscriptions = new Map();
@@ -24,11 +24,17 @@ function expandHome(path) {
24
24
  }
25
25
 
26
26
  function socketPath() {
27
- const explicit = argument("socket");
28
- if (explicit) return expandHome(explicit);
29
27
  const root = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
30
28
  const session = argument("session");
31
- return session
29
+ if (
30
+ !session ||
31
+ !/^[a-zA-Z0-9_.-]{1,64}$/.test(session) ||
32
+ session === "." ||
33
+ session === ".."
34
+ ) {
35
+ throw new Error("A valid Herdr --session is required");
36
+ }
37
+ return session !== "default"
32
38
  ? join(root, "herdr", "sessions", session, "herdr.sock")
33
39
  : join(root, "herdr", "herdr.sock");
34
40
  }
@@ -247,7 +253,7 @@ function assistantFromMessage(id, message) {
247
253
  };
248
254
  }
249
255
 
250
- function userFromMessage(id, message) {
256
+ function inputFromMessage(id, message) {
251
257
  if (message.role !== "user") return undefined;
252
258
  const text = [];
253
259
  if (typeof message.content === "string") text.push(message.content);
@@ -323,15 +329,15 @@ async function sessionView(path, size) {
323
329
  let assistantDepth;
324
330
  let ask;
325
331
  let depth = 0;
326
- let user;
327
- let userDepth;
332
+ let input;
333
+ let inputDepth;
328
334
  const resolved = new Set();
329
335
  const result = () => ({
330
336
  ...(assistant ? { assistant } : {}),
331
337
  ...(ask ? { ask } : {}),
332
- ...(user ? { user } : {}),
333
- ...(assistantDepth !== undefined && userDepth !== undefined
334
- ? { assistantAfterUser: assistantDepth < userDepth }
338
+ ...(input ? { input } : {}),
339
+ ...(assistantDepth !== undefined && inputDepth !== undefined
340
+ ? { assistantAfterInput: assistantDepth < inputDepth }
335
341
  : {}),
336
342
  });
337
343
  const inspect = (line) => {
@@ -360,6 +366,16 @@ async function sessionView(path, size) {
360
366
  }
361
367
  }
362
368
  }
369
+ if (
370
+ !input &&
371
+ entry.type === "custom_message" &&
372
+ entry.customType === "herdr-agent-message" &&
373
+ typeof entry.content === "string" &&
374
+ entry.content
375
+ ) {
376
+ input = { id: entry.id, text: entry.content };
377
+ inputDepth = currentDepth;
378
+ }
363
379
  const message = entry.message;
364
380
  if (message && typeof message === "object") {
365
381
  if (
@@ -371,9 +387,9 @@ async function sessionView(path, size) {
371
387
  assistant = assistantFromMessage(entry.id, message);
372
388
  if (assistant) assistantDepth = currentDepth;
373
389
  }
374
- if (!user) {
375
- user = userFromMessage(entry.id, message);
376
- if (user) userDepth = currentDepth;
390
+ if (!input) {
391
+ input = inputFromMessage(entry.id, message);
392
+ if (input) inputDepth = currentDepth;
377
393
  }
378
394
  if (
379
395
  !ask &&
@@ -3,11 +3,11 @@ import { randomUUID } from "node:crypto";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import type { HerdrConnection } from "./herdr-client.js";
6
- import type { RemoteMachineConfig } from "./machines-config.js";
6
+ import type { SshMachine } from "./machine-catalog.js";
7
7
  import type { AssistantReader } from "./session-reader.js";
8
8
  import type { HerdrEvent, LatestAssistant, SessionView } from "./types.js";
9
9
 
10
- const BRIDGE_VERSION = 4;
10
+ const BRIDGE_VERSION = 5;
11
11
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
12
12
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
13
13
  const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
@@ -73,26 +73,28 @@ function executablePath(path: string): string {
73
73
  : shellQuote(path);
74
74
  }
75
75
 
76
- function remoteCommand(config: RemoteMachineConfig): string {
76
+ function remoteCommand(config: SshMachine): string {
77
77
  const args = [
78
78
  "exec",
79
- shellQuote(config.node),
79
+ "node",
80
80
  executablePath(REMOTE_HELPER),
81
- ...(config.socket ? ["--socket", shellQuote(config.socket)] : []),
82
- ...(config.session ? ["--session", shellQuote(config.session)] : []),
81
+ "--session",
82
+ shellQuote(config.session),
83
83
  ];
84
84
  return args.join(" ");
85
85
  }
86
86
 
87
87
  function spawnConnector(
88
- config: RemoteMachineConfig,
88
+ config: SshMachine,
89
89
  command: string,
90
90
  ): ChildProcessWithoutNullStreams {
91
- const [program, ...args] = config.command;
92
- if (!program) throw new Error("remote machine command is empty");
93
- return spawn(program, [...args, command], {
94
- stdio: ["pipe", "pipe", "pipe"],
95
- });
91
+ return spawn(
92
+ "ssh",
93
+ ["-T", "-o", "BatchMode=yes", "--", config.target, command],
94
+ {
95
+ stdio: ["pipe", "pipe", "pipe"],
96
+ },
97
+ );
96
98
  }
97
99
 
98
100
  function appendBounded(current: string, chunk: Buffer): string {
@@ -102,12 +104,9 @@ function appendBounded(current: string, chunk: Buffer): string {
102
104
  : next.slice(next.length - MAX_DIAGNOSTIC_BYTES);
103
105
  }
104
106
 
105
- async function deploy(
106
- config: RemoteMachineConfig,
107
- source: Buffer,
108
- ): Promise<void> {
107
+ async function deploy(config: SshMachine, source: Buffer): Promise<void> {
109
108
  const command = [
110
- shellQuote(config.node),
109
+ "node",
111
110
  "-e",
112
111
  shellQuote(DEPLOY_SOURCE),
113
112
  shellQuote(REMOTE_HELPER),
@@ -179,7 +178,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
179
178
  }
180
179
 
181
180
  static async connect(
182
- config: RemoteMachineConfig,
181
+ config: SshMachine,
183
182
  onClose: (error: Error) => void,
184
183
  ): Promise<RemoteHerdrClient> {
185
184
  const source = await readFile(
@@ -1,7 +1,7 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import type {
3
3
  LatestAssistant,
4
- LatestUser,
4
+ LatestInput,
5
5
  PendingAsk,
6
6
  SessionView,
7
7
  } from "./types.js";
@@ -43,10 +43,10 @@ function assistantFromMessage(
43
43
  };
44
44
  }
45
45
 
46
- function userFromMessage(
46
+ function inputFromMessage(
47
47
  id: string,
48
48
  message: Record<string, unknown>,
49
- ): LatestUser | undefined {
49
+ ): LatestInput | undefined {
50
50
  if (message["role"] !== "user") return undefined;
51
51
  const text: string[] = [];
52
52
  if (typeof message["content"] === "string") {
@@ -141,15 +141,15 @@ async function readSessionView(
141
141
  let assistantDepth: number | undefined;
142
142
  let ask: PendingAsk | undefined;
143
143
  let depth = 0;
144
- let user: LatestUser | undefined;
145
- let userDepth: number | undefined;
144
+ let input: LatestInput | undefined;
145
+ let inputDepth: number | undefined;
146
146
  const resolved = new Set<string>();
147
147
  const result = (): SessionView => ({
148
148
  ...(assistant ? { assistant } : {}),
149
149
  ...(ask ? { ask } : {}),
150
- ...(user ? { user } : {}),
151
- ...(assistantDepth !== undefined && userDepth !== undefined
152
- ? { assistantAfterUser: assistantDepth < userDepth }
150
+ ...(input ? { input } : {}),
151
+ ...(assistantDepth !== undefined && inputDepth !== undefined
152
+ ? { assistantAfterInput: assistantDepth < inputDepth }
153
153
  : {}),
154
154
  });
155
155
  const inspect = (line: Buffer): boolean => {
@@ -180,6 +180,16 @@ async function readSessionView(
180
180
  }
181
181
  }
182
182
  }
183
+ if (
184
+ !input &&
185
+ entry["type"] === "custom_message" &&
186
+ entry["customType"] === "herdr-agent-message" &&
187
+ typeof entry["content"] === "string" &&
188
+ entry["content"]
189
+ ) {
190
+ input = { id, text: entry["content"] };
191
+ inputDepth = currentDepth;
192
+ }
183
193
  const message = record(entry["message"]);
184
194
  if (message) {
185
195
  const resolvedId = resolvedToolCallId(message);
@@ -188,9 +198,9 @@ async function readSessionView(
188
198
  assistant = assistantFromMessage(id, message);
189
199
  if (assistant) assistantDepth = currentDepth;
190
200
  }
191
- if (!user) {
192
- user = userFromMessage(id, message);
193
- if (user) userDepth = currentDepth;
201
+ if (!input) {
202
+ input = inputFromMessage(id, message);
203
+ if (input) inputDepth = currentDepth;
194
204
  }
195
205
  if (
196
206
  !ask &&
package/src/settlement.ts CHANGED
@@ -179,8 +179,11 @@ export class SettlementReporter {
179
179
  private readonly collector: SettlementCollector;
180
180
  private readonly persist: () => void;
181
181
  private readonly pi: ExtensionAPI;
182
- private readonly machine: string;
183
- private readonly operatorPrefix: string;
182
+ private readonly origin: {
183
+ machine: string;
184
+ label: () => string;
185
+ operatorPrefix: string;
186
+ };
184
187
  private readonly reporting = new Map<string, SettledAgentStatus>();
185
188
  private readonly pendingBlocked = new Map<string, PendingBlockedSettlement>();
186
189
  private readonly claims = new Map<string, SettlementClaim>();
@@ -192,16 +195,14 @@ export class SettlementReporter {
192
195
  client: HerdrConnection,
193
196
  state: MonitorState,
194
197
  persist: () => void,
195
- reader?: AssistantReader,
196
- machine = "local",
197
- operatorPrefix = "herdr",
198
+ reader: AssistantReader | undefined,
199
+ origin: { machine: string; label: () => string; operatorPrefix: string },
198
200
  ) {
199
201
  this.pi = pi;
200
202
  this.collector = new SettlementCollector(client, reader);
201
203
  this.state = state;
202
204
  this.persist = persist;
203
- this.machine = machine;
204
- this.operatorPrefix = operatorPrefix;
205
+ this.origin = origin;
205
206
  }
206
207
 
207
208
  latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
@@ -328,15 +329,15 @@ export class SettlementReporter {
328
329
  if (
329
330
  !blocked &&
330
331
  expectedUser &&
331
- (settlement.session.assistantAfterUser !== true ||
332
- !settlement.session.user ||
333
- settlement.session.user.id === expectedUser.after)
332
+ (settlement.session.assistantAfterInput !== true ||
333
+ !settlement.session.input ||
334
+ settlement.session.input.id === expectedUser.after)
334
335
  ) {
335
336
  if (!this.retry(lifecycle, retryRequest, retryState)) {
336
337
  this.failReconciliation(
337
338
  lifecycle,
338
339
  current,
339
- "the submitted user message and reply were not persisted",
340
+ "the submitted input and reply were not persisted",
340
341
  );
341
342
  }
342
343
  return;
@@ -466,8 +467,9 @@ export class SettlementReporter {
466
467
  agent: settlement.agent,
467
468
  agentToolName: "agents",
468
469
  ...(settlement.ask ? { ask: settlement.ask } : {}),
469
- machine: this.machine,
470
- operatorPrefix: this.operatorPrefix,
470
+ machine: this.origin.machine,
471
+ machineLabel: this.origin.label(),
472
+ operatorPrefix: this.origin.operatorPrefix,
471
473
  ...(blockedMessage ? { blockedMessage } : {}),
472
474
  labels: settlement.labels,
473
475
  record,
package/src/types.ts CHANGED
@@ -39,6 +39,7 @@ export interface PaneInfo {
39
39
  launch_pending?: boolean;
40
40
  name?: string | null;
41
41
  pane_id: string;
42
+ title?: string | null;
42
43
  tab_id: string;
43
44
  terminal_id: string;
44
45
  workspace_id: string;
@@ -63,6 +64,7 @@ export interface SessionSnapshot {
63
64
  }
64
65
 
65
66
  export interface MonitoredAgent {
67
+ readonly scope: "task" | "persistent";
66
68
  readonly activity: AgentActivity;
67
69
  readonly cwd?: string;
68
70
  readonly lastAssistantId?: string;
@@ -82,7 +84,10 @@ export interface MonitoringIssue {
82
84
 
83
85
  export interface MachineStatus {
84
86
  local: boolean;
85
- name: string;
87
+ id: string;
88
+ label?: string;
89
+ target?: string;
90
+ session?: string;
86
91
  monitoringIssue?: MonitoringIssue;
87
92
  reason?: string;
88
93
  status: MachineConnectionStatus;
@@ -96,7 +101,7 @@ export interface LatestAssistant {
96
101
  text: string;
97
102
  }
98
103
 
99
- export interface LatestUser {
104
+ export interface LatestInput {
100
105
  id: string;
101
106
  text: string;
102
107
  }
@@ -115,8 +120,8 @@ export interface PendingAsk {
115
120
  export interface SessionView {
116
121
  ask?: PendingAsk;
117
122
  assistant?: LatestAssistant;
118
- assistantAfterUser?: boolean;
119
- user?: LatestUser;
123
+ assistantAfterInput?: boolean;
124
+ input?: LatestInput;
120
125
  }
121
126
 
122
127
  export interface HerdrEvent {
package/src/widget.ts CHANGED
@@ -42,7 +42,7 @@ function agentLine(
42
42
  ? ({ icon: "?", tone: "warning" } as const)
43
43
  : statusAppearance(status)
44
44
  : ({ icon: "?", tone: "error" } as const);
45
- const name = `${agent.machine} / ${agent.name ?? agent.paneId}`;
45
+ const name = `${machine?.label ?? agent.machine} / ${agent.name ?? agent.paneId}`;
46
46
  const location = agent.cwd ? basename(agent.cwd) : agent.paneId;
47
47
  return [
48
48
  theme.fg("muted", "│"),
@@ -76,7 +76,7 @@ export function renderAgentWidget(
76
76
  (left.name ?? left.paneId).localeCompare(right.name ?? right.paneId),
77
77
  );
78
78
  const machinesByName = new Map(
79
- machines.map((machine) => [machine.name, machine]),
79
+ machines.map((machine) => [machine.id, machine]),
80
80
  );
81
81
  const lines = [
82
82
  `${theme.fg("accent", "╭─ herdr agents")} ${theme.fg("dim", `${agents.length} · ${machines.filter((machine) => machine.status === "connected").length}/${machines.length} machines`)}`,
@@ -97,9 +97,9 @@ export function renderAgentWidget(
97
97
  : "unavailable";
98
98
  const recovery = machine.local
99
99
  ? "retrying"
100
- : `/herdr connect ${machine.name}`;
100
+ : `/herdr connect ${machine.id}`;
101
101
  lines.push(
102
- `${theme.fg("muted", "│")} ${theme.fg("warning", `${machine.name} monitoring ${status} · ${recovery}`)}`,
102
+ `${theme.fg("muted", "│")} ${theme.fg("warning", `${machine.id} monitoring ${status} · ${recovery}`)}`,
103
103
  );
104
104
  }
105
105
  lines.push(theme.fg("muted", "╰─"));
@@ -1,163 +0,0 @@
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
- import type { MachineStatus } from "./types.js";
10
-
11
- function parseSshArguments(value: string): string[] {
12
- const parts: string[] = [];
13
- let current = "";
14
- let quote: "'" | '"' | undefined;
15
- let escaped = false;
16
- let started = false;
17
- for (const character of value) {
18
- if (escaped) {
19
- current += character;
20
- escaped = false;
21
- started = true;
22
- continue;
23
- }
24
- if (character === "\\" && quote !== "'") {
25
- escaped = true;
26
- started = true;
27
- continue;
28
- }
29
- if (quote) {
30
- if (character === quote) quote = undefined;
31
- else current += character;
32
- continue;
33
- }
34
- if (character === "'" || character === '"') {
35
- quote = character;
36
- started = true;
37
- } else if (/\s/.test(character)) {
38
- if (started) {
39
- parts.push(current);
40
- current = "";
41
- started = false;
42
- }
43
- } else {
44
- current += character;
45
- started = true;
46
- }
47
- }
48
- if (quote) throw new Error("SSH arguments contain an unclosed quote");
49
- if (escaped) throw new Error("SSH arguments end with an incomplete escape");
50
- if (started) parts.push(current);
51
- if (parts.length === 0) throw new Error("SSH target is required");
52
- const target = parts.pop()!;
53
- return [...parts, "--", target];
54
- }
55
-
56
- export async function showMachineMenu(
57
- fleet: AgentFleet,
58
- ctx: ExtensionContext,
59
- ): Promise<void> {
60
- const config = await readMachinesConfig().catch((error) => {
61
- ctx.ui.notify(
62
- `Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
63
- "error",
64
- );
65
- return undefined;
66
- });
67
- if (!config) return;
68
- const statuses: MachineStatus[] = fleet.isActive()
69
- ? fleet.statuses()
70
- : Object.keys(config.machines).map((name) => ({
71
- local: false,
72
- name,
73
- status: "unavailable" as const,
74
- }));
75
- const selected = await ctx.ui.select("Shepherdr machines", [
76
- "Add machine",
77
- ...statuses
78
- .filter((machine) => !machine.local)
79
- .map(
80
- (machine) =>
81
- `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}${machine.monitoringIssue ? " · monitoring needs attention" : ""}`,
82
- ),
83
- ]);
84
- if (!selected) return;
85
- if (selected === "Add machine") {
86
- await addMachine(ctx, fleet);
87
- return;
88
- }
89
- const name = selected.slice(2).split(" · ", 1)[0];
90
- if (!name) return;
91
- const status = statuses.find((machine) => machine.name === name);
92
- const action = await ctx.ui.select(name, [
93
- ...(status?.monitoringIssue ? ["Retry monitoring"] : []),
94
- ...(status?.status !== "connected" ? ["Connect"] : []),
95
- "Remove",
96
- ]);
97
- if (action === "Connect" || action === "Retry monitoring") {
98
- if (!fleet.isActive()) {
99
- ctx.ui.notify(
100
- "Fleet unavailable; run /herdr connect to retry",
101
- "warning",
102
- );
103
- return;
104
- }
105
- ctx.ui.notify(fleet.connect(name), "info");
106
- } else if (action === "Remove") {
107
- const confirmed = await ctx.ui.confirm(
108
- `Remove ${name}?`,
109
- "The remote Shepherdr helper will remain available for other controllers",
110
- );
111
- if (!confirmed) return;
112
- delete config.machines[name];
113
- await writeMachinesConfig(config);
114
- await fleet.reload();
115
- ctx.ui.notify(`Removed ${name}`, "info");
116
- }
117
- }
118
-
119
- async function addMachine(
120
- ctx: ExtensionContext,
121
- fleet: AgentFleet,
122
- ): Promise<void> {
123
- const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
124
- if (!name) return;
125
- if (!isMachineName(name)) {
126
- ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
127
- return;
128
- }
129
- const ssh = (
130
- await ctx.ui.input("SSH options and target (target last)", name)
131
- )?.trim();
132
- if (!ssh) return;
133
- let sshArguments: string[];
134
- try {
135
- sshArguments = parseSshArguments(ssh);
136
- } catch (error) {
137
- ctx.ui.notify(
138
- error instanceof Error ? error.message : String(error),
139
- "error",
140
- );
141
- return;
142
- }
143
- const session = (
144
- await ctx.ui.input("Herdr session", "default (leave blank)")
145
- )?.trim();
146
- const config = await readMachinesConfig();
147
- if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
148
- ctx.ui.notify(`Machine ${name} already exists`, "error");
149
- return;
150
- }
151
- config.machines[name] = {
152
- command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
153
- herdr: "herdr",
154
- node: "node",
155
- ...(session && session !== "default (leave blank)" ? { session } : {}),
156
- };
157
- const path = await writeMachinesConfig(config);
158
- await fleet.reload();
159
- ctx.ui.notify(
160
- `Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
161
- "info",
162
- );
163
- }