@howaboua/pi-shepherdr 0.1.2 → 0.1.4

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,338 @@
1
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentsParams, READ_SOURCES } from "./agents-contract.js";
3
+ import type { AgentFleet, ConnectedMachine } from "./fleet.js";
4
+ import { getSnapshot } from "./herdr.js";
5
+ import { loadAgentProfiles } from "./profiles.js";
6
+ import type { ClaimedSettlement } from "./settlement.js";
7
+ import type { AgentStatus, PaneInfo, SessionSnapshot } from "./types.js";
8
+
9
+ const MAX_LIST_ITEMS = 30;
10
+ const MAX_TERMINAL_READ_CHARS = 36_000;
11
+
12
+ export function toolResult(value: Record<string, unknown>) {
13
+ return {
14
+ content: [{ type: "text" as const, text: JSON.stringify(value) }],
15
+ details: value,
16
+ };
17
+ }
18
+
19
+ export function reportProgress(
20
+ onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
21
+ message: string,
22
+ details: Record<string, unknown>,
23
+ ): void {
24
+ onUpdate({
25
+ content: [{ type: "text", text: message }],
26
+ details,
27
+ });
28
+ }
29
+
30
+ export async function agentsHelp(): Promise<Record<string, unknown>> {
31
+ const profiles = await loadAgentProfiles();
32
+ return {
33
+ actions: {
34
+ help: "",
35
+ list: "machine?",
36
+ find: "query? status? machine?",
37
+ spawn:
38
+ "agent_type label message name? machine? placement? workspace? pane? cwd? base? blocking?",
39
+ watch: "target machine?",
40
+ unwatch: "target machine?",
41
+ send: "target message machine? blocking?",
42
+ read: "target machine? source? lines?",
43
+ answer: "target answers machine? blocking?",
44
+ },
45
+ rules: {
46
+ target: "Use spawn/find target exactly",
47
+ label: "2-3 words; tab/session",
48
+ answers: "[{selections?:string[],other?:string,comment?:string}]",
49
+ blocking:
50
+ "true default; false only while continuing work; results push, never poll",
51
+ prompt:
52
+ "Only task + inaccessible context; no method/evidence/reporting boilerplate",
53
+ reuse:
54
+ "Reuse only same investigation; reviews independent; new scope = new agent",
55
+ ...(profiles.has("general")
56
+ ? {
57
+ general:
58
+ "Only when requested/orchestrating. Current repo: create + bootstrap worktree; pass cwd",
59
+ }
60
+ : {}),
61
+ },
62
+ profiles: Object.fromEntries(
63
+ [...profiles].map(([name, profile]) => [name, profile.description]),
64
+ ),
65
+ advanced: "herdr --skill: workspace/tab/pane/process/focus/layout/terminal",
66
+ };
67
+ }
68
+
69
+ function labels(snapshot: SessionSnapshot) {
70
+ return {
71
+ panes: new Map(snapshot.panes.map((pane) => [pane.pane_id, pane.label])),
72
+ tabs: new Map(snapshot.tabs.map((tab) => [tab.tab_id, tab.label])),
73
+ workspaces: new Map(
74
+ snapshot.workspaces.map((workspace) => [
75
+ workspace.workspace_id,
76
+ workspace.label,
77
+ ]),
78
+ ),
79
+ };
80
+ }
81
+
82
+ function compactAgent(
83
+ agent: PaneInfo,
84
+ snapshot: SessionSnapshot,
85
+ machine: string,
86
+ monitored: boolean,
87
+ ): Record<string, unknown> {
88
+ const names = labels(snapshot);
89
+ return {
90
+ machine,
91
+ target: agent.pane_id,
92
+ ...(agent.name ? { name: agent.name } : {}),
93
+ ...(agent.label || names.panes.get(agent.pane_id)
94
+ ? { label: agent.label ?? names.panes.get(agent.pane_id) }
95
+ : {}),
96
+ status: agent.agent_status,
97
+ cwd: agent.foreground_cwd ?? agent.cwd ?? null,
98
+ workspace: names.workspaces.get(agent.workspace_id) ?? agent.workspace_id,
99
+ tab: names.tabs.get(agent.tab_id) ?? agent.tab_id,
100
+ monitored,
101
+ };
102
+ }
103
+
104
+ function matchesAgent(
105
+ agent: Record<string, unknown>,
106
+ query: string | undefined,
107
+ status: AgentStatus | undefined,
108
+ ): boolean {
109
+ if (status && agent["status"] !== status) return false;
110
+ if (!query) return true;
111
+ const haystack = Object.values(agent)
112
+ .filter((value) => typeof value === "string")
113
+ .join("\n")
114
+ .toLowerCase();
115
+ return haystack.includes(query.toLowerCase());
116
+ }
117
+
118
+ export async function listFleetAgents(
119
+ fleet: AgentFleet,
120
+ params: Pick<AgentsParams, "machine" | "query" | "status">,
121
+ ): Promise<Record<string, unknown>> {
122
+ const [profiles, machines] = await Promise.all([
123
+ loadAgentProfiles(),
124
+ fleet.snapshots(params.machine),
125
+ ]);
126
+ const agents = machines.flatMap((machine) => {
127
+ if (!machine.snapshot) return [];
128
+ return machine.snapshot.agents
129
+ .filter(
130
+ (agent) =>
131
+ agent.agent === "pi" &&
132
+ (!machine.local || agent.pane_id !== process.env["HERDR_PANE_ID"]),
133
+ )
134
+ .map((agent) =>
135
+ compactAgent(
136
+ agent,
137
+ machine.snapshot!,
138
+ machine.name,
139
+ machine.monitoredPaneIds?.has(agent.pane_id) ?? false,
140
+ ),
141
+ )
142
+ .filter((agent) => matchesAgent(agent, params.query, params.status));
143
+ });
144
+ const workspaces = machines.flatMap((machine) =>
145
+ (machine.snapshot?.workspaces ?? []).map((workspace) => ({
146
+ machine: machine.name,
147
+ id: workspace.workspace_id,
148
+ label: workspace.label,
149
+ })),
150
+ );
151
+ return {
152
+ profiles: Object.fromEntries(
153
+ [...profiles].map(([name, profile]) => [name, profile.description]),
154
+ ),
155
+ machines: machines.map(
156
+ ({
157
+ snapshot: _snapshot,
158
+ monitoredPaneIds: _monitoredPaneIds,
159
+ ...machine
160
+ }) => machine,
161
+ ),
162
+ agents: agents.slice(0, MAX_LIST_ITEMS),
163
+ workspaces: workspaces.slice(0, MAX_LIST_ITEMS),
164
+ ...(agents.length > MAX_LIST_ITEMS
165
+ ? { moreAgents: agents.length - MAX_LIST_ITEMS }
166
+ : {}),
167
+ ...(workspaces.length > MAX_LIST_ITEMS
168
+ ? { moreWorkspaces: workspaces.length - MAX_LIST_ITEMS }
169
+ : {}),
170
+ };
171
+ }
172
+
173
+ export async function findFleetAgents(
174
+ fleet: AgentFleet,
175
+ params: Pick<AgentsParams, "machine" | "query" | "status">,
176
+ ): Promise<Record<string, unknown>> {
177
+ const listed = await listFleetAgents(fleet, params);
178
+ return {
179
+ agents: listed["agents"],
180
+ ...(listed["moreAgents"] === undefined
181
+ ? {}
182
+ : { moreAgents: listed["moreAgents"] }),
183
+ };
184
+ }
185
+
186
+ function slugify(value: string): string {
187
+ const slug = value
188
+ .normalize("NFKD")
189
+ .replace(/[\u0300-\u036f]/gu, "")
190
+ .toLowerCase()
191
+ .replace(/[^a-z0-9]+/gu, "-")
192
+ .replace(/^-+|-+$/gu, "");
193
+ const named = /^[a-z]/u.test(slug) ? slug : `agent-${slug}`;
194
+ return named.slice(0, 32).replace(/-+$/u, "") || "agent";
195
+ }
196
+
197
+ export async function allocateAgentName(
198
+ runtime: ConnectedMachine,
199
+ label: string,
200
+ ): Promise<string> {
201
+ const snapshot = await getSnapshot(runtime.client);
202
+ const names = new Set(
203
+ snapshot.agents.map((agent) => agent.name).filter(Boolean),
204
+ );
205
+ const base = slugify(label);
206
+ if (!names.has(base)) return base;
207
+ for (let suffix = 2; suffix < 10_000; suffix += 1) {
208
+ const tail = `-${suffix}`;
209
+ const candidate = `${base.slice(0, 32 - tail.length).replace(/-+$/u, "")}${tail}`;
210
+ if (!names.has(candidate)) return candidate;
211
+ }
212
+ throw new Error(
213
+ `could not allocate an agent name for ${JSON.stringify(label)}`,
214
+ );
215
+ }
216
+
217
+ export function settlementResult(
218
+ machine: string,
219
+ settlement: ClaimedSettlement,
220
+ ): Record<string, unknown> {
221
+ if (settlement.reply?.stopReason === "error") {
222
+ throw new Error(
223
+ settlement.reply.text ||
224
+ `${settlement.agent.pane_id} assistant stopped with an error`,
225
+ );
226
+ }
227
+ return {
228
+ machine,
229
+ target: settlement.agent.pane_id,
230
+ ...(settlement.agent.name ? { name: settlement.agent.name } : {}),
231
+ status: settlement.status,
232
+ ...(settlement.reply ? { reply: settlement.reply.text } : {}),
233
+ ...(settlement.ask
234
+ ? {
235
+ ask: {
236
+ handoff: settlement.ask.handoff,
237
+ prompts: settlement.ask.prompts.map((prompt) => ({
238
+ title: prompt.title,
239
+ multiple: prompt.multiple,
240
+ choices: prompt.choices,
241
+ ...(prompt.body ? { body: prompt.body } : {}),
242
+ })),
243
+ },
244
+ }
245
+ : {}),
246
+ ...(settlement.blockedMessage
247
+ ? { blocked_on: settlement.blockedMessage }
248
+ : {}),
249
+ ...(settlement.status === "done" && !settlement.reply && !settlement.ask
250
+ ? { completed: true }
251
+ : {}),
252
+ };
253
+ }
254
+
255
+ export async function dispatchAgentWork(
256
+ runtime: ConnectedMachine,
257
+ panel: PaneInfo,
258
+ task: string,
259
+ blocking: boolean,
260
+ signal: AbortSignal,
261
+ onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
262
+ send: () => Promise<void>,
263
+ options: { expectUserMessage?: boolean } = {},
264
+ ): Promise<ClaimedSettlement | undefined> {
265
+ signal.throwIfAborted();
266
+ const baseline = options.expectUserMessage
267
+ ? await runtime.monitor.view(panel)
268
+ : undefined;
269
+ const attempt = runtime.monitor.beginWork(
270
+ panel.pane_id,
271
+ task,
272
+ options.expectUserMessage ? (baseline?.user?.id ?? null) : undefined,
273
+ );
274
+ if (!attempt) throw new Error(`${panel.pane_id} is not monitored`);
275
+ let settlement: Promise<ClaimedSettlement> | undefined;
276
+ let sendStarted = false;
277
+ try {
278
+ settlement = blocking
279
+ ? runtime.monitor.claimWork(attempt, signal)
280
+ : undefined;
281
+ void settlement?.catch(() => undefined);
282
+ signal.throwIfAborted();
283
+ sendStarted = true;
284
+ await send();
285
+ runtime.monitor.acceptWork(attempt);
286
+ } catch (error) {
287
+ runtime.monitor.releaseWorkClaim(attempt, error);
288
+ if (sendStarted) await runtime.monitor.handleWorkFailure(attempt, error);
289
+ else runtime.monitor.rejectWork(attempt);
290
+ throw error;
291
+ }
292
+ if (!blocking) return undefined;
293
+ reportProgress(onUpdate, `Waiting for ${panel.name ?? panel.pane_id}`, {
294
+ machine: runtime.machine,
295
+ target: panel.pane_id,
296
+ status: "working",
297
+ });
298
+ return await settlement!;
299
+ }
300
+
301
+ export async function readAgentTerminal(
302
+ runtime: ConnectedMachine,
303
+ panel: PaneInfo,
304
+ source: Exclude<(typeof READ_SOURCES)[number], "latest">,
305
+ lines: number,
306
+ ): Promise<Record<string, unknown>> {
307
+ const value = await runtime.client.request<unknown>("agent.read", {
308
+ target: panel.pane_id,
309
+ source,
310
+ format: "text",
311
+ lines,
312
+ strip_ansi: true,
313
+ });
314
+ if (
315
+ typeof value !== "object" ||
316
+ value === null ||
317
+ !("read" in value) ||
318
+ typeof value.read !== "object" ||
319
+ value.read === null ||
320
+ !("text" in value.read) ||
321
+ typeof value.read.text !== "string"
322
+ ) {
323
+ throw new Error("Herdr agent.read returned no text");
324
+ }
325
+ const truncated = value.read.text.length > MAX_TERMINAL_READ_CHARS;
326
+ return {
327
+ machine: runtime.machine,
328
+ target: panel.pane_id,
329
+ status: panel.agent_status,
330
+ text: truncated
331
+ ? `${value.read.text.slice(0, MAX_TERMINAL_READ_CHARS)}\n…`
332
+ : value.read.text,
333
+ ...(truncated ||
334
+ ("truncated" in value.read && value.read.truncated === true)
335
+ ? { truncated: true }
336
+ : {}),
337
+ };
338
+ }