@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.
@@ -0,0 +1,297 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { getAgent } from "./herdr.js";
5
+ import type { HerdrConnection } from "./herdr-client.js";
6
+ import type { AgentMonitor } from "./monitor.js";
7
+ import type { PaneInfo, PendingAsk } from "./types.js";
8
+
9
+ export interface AskAnswer {
10
+ comment?: string;
11
+ other?: string;
12
+ selections?: string[];
13
+ }
14
+
15
+ interface InputStep {
16
+ final?: boolean;
17
+ keys?: string[];
18
+ text?: string;
19
+ }
20
+
21
+ interface AskControls {
22
+ confirm: string;
23
+ down: string;
24
+ next: string;
25
+ }
26
+
27
+ function down(count: number, key: string): string[] {
28
+ return Array.from({ length: Math.max(0, count) }, () => key);
29
+ }
30
+
31
+ function answerPlan(
32
+ prompts: PendingAsk["prompts"],
33
+ answers: AskAnswer[],
34
+ controls: AskControls,
35
+ ): InputStep[] {
36
+ if (answers.length !== prompts.length) {
37
+ throw new Error(
38
+ `answer requires ${prompts.length} response${prompts.length === 1 ? "" : "s"}, in prompt order`,
39
+ );
40
+ }
41
+ const steps: InputStep[] = [];
42
+ for (const [promptIndex, prompt] of prompts.entries()) {
43
+ const answer = answers[promptIndex]!;
44
+ const labels = answer.selections ?? [];
45
+ const indexes = labels.map((label) => {
46
+ const index = prompt.choices.findIndex(
47
+ (choice) => choice.label === label,
48
+ );
49
+ if (index < 0) {
50
+ throw new Error(
51
+ `unknown choice ${JSON.stringify(label)} for ${JSON.stringify(prompt.title)}`,
52
+ );
53
+ }
54
+ return index;
55
+ });
56
+ if (new Set(indexes).size !== indexes.length) {
57
+ throw new Error(`duplicate choice for ${JSON.stringify(prompt.title)}`);
58
+ }
59
+ if (!prompt.multiple && indexes.length > 1) {
60
+ throw new Error(`${JSON.stringify(prompt.title)} accepts one choice`);
61
+ }
62
+ if (!prompt.multiple && indexes.length > 0 && answer.other !== undefined) {
63
+ throw new Error(
64
+ `${JSON.stringify(prompt.title)} cannot combine a choice with Other/rephrase`,
65
+ );
66
+ }
67
+ indexes.sort((left, right) => left - right);
68
+ let focus = 0;
69
+ for (const index of indexes) {
70
+ steps.push({
71
+ keys: [...down(index - focus, controls.down), controls.confirm],
72
+ });
73
+ focus = index;
74
+ }
75
+ const needsOther =
76
+ answer.other !== undefined ||
77
+ (indexes.length === 0 && answer.comment !== undefined);
78
+ if (needsOther) {
79
+ steps.push({
80
+ keys: [
81
+ ...down(prompt.choices.length - focus, controls.down),
82
+ controls.confirm,
83
+ ],
84
+ });
85
+ steps.push({
86
+ text: answer.other ?? "",
87
+ keys: [controls.confirm],
88
+ });
89
+ focus = prompt.choices.length;
90
+ }
91
+ if (answer.comment !== undefined) {
92
+ steps.push({
93
+ keys: [
94
+ ...down(prompt.choices.length + 1 - focus, controls.down),
95
+ controls.confirm,
96
+ ],
97
+ });
98
+ steps.push({ text: answer.comment, keys: [controls.next] });
99
+ } else {
100
+ steps.push({ keys: [controls.next] });
101
+ }
102
+ }
103
+ steps.push({ keys: [controls.confirm], final: true });
104
+ return steps;
105
+ }
106
+
107
+ async function readKeybindings(
108
+ client: HerdrConnection,
109
+ ): Promise<Record<string, unknown>> {
110
+ if ("keybindings" in client && typeof client.keybindings === "function") {
111
+ const value = await client.keybindings();
112
+ return typeof value === "object" && value !== null
113
+ ? (value as Record<string, unknown>)
114
+ : {};
115
+ }
116
+ const directory =
117
+ process.env["PI_CODING_AGENT_DIR"] ?? join(homedir(), ".pi", "agent");
118
+ try {
119
+ const value = JSON.parse(
120
+ await readFile(join(directory, "keybindings.json"), "utf8"),
121
+ ) as unknown;
122
+ return typeof value === "object" && value !== null
123
+ ? (value as Record<string, unknown>)
124
+ : {};
125
+ } catch {
126
+ return {};
127
+ }
128
+ }
129
+
130
+ function keyFor(
131
+ bindings: Record<string, unknown>,
132
+ action: string,
133
+ fallback: string,
134
+ ): string {
135
+ const configured = bindings[action];
136
+ if (typeof configured === "string" && configured) return configured;
137
+ if (Array.isArray(configured)) {
138
+ const first = configured.find(
139
+ (key) => typeof key === "string" && key.length > 0,
140
+ );
141
+ if (typeof first === "string") return first;
142
+ if (configured.length === 0) {
143
+ throw new Error(`${action} has no configured keybinding`);
144
+ }
145
+ }
146
+ return fallback;
147
+ }
148
+
149
+ async function screen(
150
+ client: HerdrConnection,
151
+ paneId: string,
152
+ ): Promise<string> {
153
+ const result = await client.request<unknown>("agent.read", {
154
+ target: paneId,
155
+ source: "visible",
156
+ format: "text",
157
+ lines: 80,
158
+ strip_ansi: true,
159
+ });
160
+ if (
161
+ typeof result !== "object" ||
162
+ result === null ||
163
+ !("read" in result) ||
164
+ typeof result.read !== "object" ||
165
+ result.read === null ||
166
+ !("text" in result.read) ||
167
+ typeof result.read.text !== "string"
168
+ ) {
169
+ throw new Error("Herdr agent.read returned no text");
170
+ }
171
+ return result.read.text;
172
+ }
173
+
174
+ function askFrame(value: string): string {
175
+ const lines = value.split("\n");
176
+ const review = lines.map((line) => line.includes("Review")).lastIndexOf(true);
177
+ return (review >= 0 ? lines.slice(review) : lines.slice(-30)).join("\n");
178
+ }
179
+
180
+ function inspectAskScreen(
181
+ value: string,
182
+ ask: PendingAsk,
183
+ ): { currentPrompt?: string; recognized: boolean; selected?: string } {
184
+ const frame = askFrame(value);
185
+ const selected = frame.match(/^>\s+(.*?)\s*$/m)?.[1];
186
+ const review =
187
+ /^\s*Review\s*$/m.test(frame) && frame.includes("enter submit");
188
+ const currentPrompt = review
189
+ ? "Review"
190
+ : ask.prompts.find((prompt) =>
191
+ frame.split("\n").some((line) => line.trim() === prompt.title),
192
+ )?.title;
193
+ return {
194
+ recognized:
195
+ Boolean(currentPrompt) ||
196
+ (frame.includes("Other/rephrase") &&
197
+ frame.includes("Comment (optional)")),
198
+ ...(currentPrompt ? { currentPrompt } : {}),
199
+ ...(selected ? { selected } : {}),
200
+ };
201
+ }
202
+
203
+ async function sendInput(
204
+ client: HerdrConnection,
205
+ panel: PaneInfo,
206
+ step: InputStep,
207
+ signal: AbortSignal,
208
+ ): Promise<void> {
209
+ signal.throwIfAborted();
210
+ if (step.text !== undefined) {
211
+ await requireSameAgent(client, panel);
212
+ await client.request("pane.send_input", {
213
+ pane_id: panel.pane_id,
214
+ text: step.text,
215
+ });
216
+ }
217
+ if (step.keys) {
218
+ await requireSameAgent(client, panel);
219
+ await client.request("agent.send_keys", {
220
+ target: panel.pane_id,
221
+ keys: step.keys,
222
+ });
223
+ }
224
+ }
225
+
226
+ async function requireSameAgent(
227
+ client: HerdrConnection,
228
+ panel: PaneInfo,
229
+ ): Promise<void> {
230
+ const current = await getAgent(client, panel.pane_id);
231
+ if (current.terminal_id !== panel.terminal_id) {
232
+ throw new Error(`${panel.pane_id} no longer hosts the targeted Pi agent`);
233
+ }
234
+ }
235
+
236
+ export async function prepareAskAnswer(
237
+ client: HerdrConnection,
238
+ monitor: AgentMonitor,
239
+ panel: PaneInfo,
240
+ answers: AskAnswer[],
241
+ signal: AbortSignal,
242
+ ): Promise<{ ask: PendingAsk; submit(): Promise<void> }> {
243
+ if (panel.agent_status !== "blocked") {
244
+ throw new Error(
245
+ `${panel.pane_id} is ${panel.agent_status}, not blocked on ask`,
246
+ );
247
+ }
248
+ const view = await monitor.view(panel);
249
+ if (!view.ask) {
250
+ throw new Error(
251
+ `${panel.pane_id} has no pending pi-ask call on its active branch`,
252
+ );
253
+ }
254
+ const ask = view.ask;
255
+ const initial = inspectAskScreen(await screen(client, panel.pane_id), ask);
256
+ const first = ask.prompts[0];
257
+ const expectedSelection = first?.choices[0]?.label ?? "Other/rephrase";
258
+ if (
259
+ !initial.recognized ||
260
+ initial.currentPrompt !== first?.title ||
261
+ initial.selected !== expectedSelection
262
+ ) {
263
+ throw new Error(
264
+ "ask UI is not at the first prompt's default selection; refusing to send guessed keys",
265
+ );
266
+ }
267
+ const bindings = await readKeybindings(client);
268
+ const plan = answerPlan(ask.prompts, answers, {
269
+ down: keyFor(bindings, "tui.select.down", "down"),
270
+ confirm: keyFor(bindings, "tui.select.confirm", "enter"),
271
+ next: keyFor(bindings, "tui.input.tab", "tab"),
272
+ });
273
+ const final = plan.pop();
274
+ if (!final?.final) throw new Error("ask answer plan has no final submission");
275
+ for (const step of plan) {
276
+ await sendInput(client, panel, step, signal);
277
+ await new Promise((resolve) => setTimeout(resolve, 35));
278
+ const current = await getAgent(client, panel.pane_id);
279
+ if (
280
+ current.terminal_id !== panel.terminal_id ||
281
+ current.agent_status !== "blocked"
282
+ ) {
283
+ throw new Error("ask closed before all requested answers were entered");
284
+ }
285
+ if (
286
+ !inspectAskScreen(await screen(client, panel.pane_id), ask).recognized
287
+ ) {
288
+ throw new Error(
289
+ "ask UI became unrecognized; stopped without retrying input",
290
+ );
291
+ }
292
+ }
293
+ return {
294
+ ask,
295
+ submit: () => sendInput(client, panel, final, signal),
296
+ };
297
+ }
@@ -0,0 +1,178 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { AgentFleet } from "./fleet.js";
6
+ import { showMachineMenu } from "./machine-menu.js";
7
+ import { loadAgentProfiles } from "./profiles.js";
8
+
9
+ interface AgentControllerOptions {
10
+ onActiveChange?(): void;
11
+ }
12
+
13
+ const ORCHESTRATION_STATE_TYPE = "pi-shepherdr-orchestration-state";
14
+ const GENERAL_ORCHESTRATION_MESSAGE =
15
+ "Your main goal from now on is to orchestrate agents. Fan out suitable work to general agents, synthesize their results, and report the outcome. Work directly only when asked or for routine local tasks.";
16
+ const ORCHESTRATION_MESSAGE =
17
+ "Your main goal from now on is to orchestrate agents. Fan out suitable work, synthesize agent results, and report the outcome. Work directly only when asked or for routine local tasks.";
18
+ const NORMAL_MESSAGE = "Work normally. Delegate only when useful or requested.";
19
+
20
+ export function registerAgentController(
21
+ pi: ExtensionAPI,
22
+ fleet: AgentFleet,
23
+ options: AgentControllerOptions = {},
24
+ ): void {
25
+ let orchestrationEnabled = false;
26
+ const setActive = (active: boolean) => {
27
+ setToolActive(pi, "agents", active);
28
+ options.onActiveChange?.();
29
+ };
30
+ pi.registerCommand("herdr", {
31
+ description: "Toggle agent orchestration or manage Herdr machines",
32
+ getArgumentCompletions: (prefix) =>
33
+ ["machines", "connect"]
34
+ .filter((action) => action.startsWith(prefix.trim().toLowerCase()))
35
+ .map((value) => ({ label: value, value })),
36
+ handler: async (args, ctx) => {
37
+ const [rawAction = "", ...rest] = args.trim().split(/\s+/);
38
+ const action = rawAction.toLowerCase();
39
+ if (!action) {
40
+ orchestrationEnabled = restoreOrchestrationState(ctx).enabled;
41
+ if (
42
+ !fleet.isActive() &&
43
+ !(await activateController(fleet, ctx, setActive))
44
+ ) {
45
+ return;
46
+ }
47
+ orchestrationEnabled = !orchestrationEnabled;
48
+ pi.sendMessage(
49
+ {
50
+ customType: ORCHESTRATION_STATE_TYPE,
51
+ content: orchestrationEnabled
52
+ ? await orchestrationMessage()
53
+ : NORMAL_MESSAGE,
54
+ details: { enabled: orchestrationEnabled },
55
+ display: true,
56
+ },
57
+ { triggerTurn: false },
58
+ );
59
+ ctx.ui.notify(
60
+ orchestrationEnabled
61
+ ? "Agent orchestration enabled"
62
+ : "Normal mode enabled",
63
+ "info",
64
+ );
65
+ return;
66
+ }
67
+ if (action === "machines") {
68
+ await showMachineMenu(fleet, ctx);
69
+ return;
70
+ }
71
+ if (action === "connect") {
72
+ if (!fleet.isActive()) {
73
+ ctx.ui.notify("Run /herdr to activate agents first", "warning");
74
+ return;
75
+ }
76
+ try {
77
+ ctx.ui.notify(fleet.connect(rest[0]), "info");
78
+ } catch (error) {
79
+ ctx.ui.notify(
80
+ error instanceof Error ? error.message : String(error),
81
+ "error",
82
+ );
83
+ }
84
+ return;
85
+ }
86
+ ctx.ui.notify("Usage: /herdr [machines|connect [machine]]", "warning");
87
+ },
88
+ });
89
+
90
+ pi.on("session_start", async (_event, ctx) => {
91
+ const state = restoreOrchestrationState(ctx);
92
+ orchestrationEnabled = state.enabled;
93
+ fleet.deactivate();
94
+ setActive(false);
95
+ if (state.recorded) await activateController(fleet, ctx, setActive);
96
+ });
97
+
98
+ pi.on("session_shutdown", () => {
99
+ fleet.deactivate();
100
+ });
101
+ }
102
+
103
+ async function orchestrationMessage(): Promise<string> {
104
+ return (await loadAgentProfiles()).has("general")
105
+ ? GENERAL_ORCHESTRATION_MESSAGE
106
+ : ORCHESTRATION_MESSAGE;
107
+ }
108
+
109
+ function restoreOrchestrationState(ctx: ExtensionContext): {
110
+ enabled: boolean;
111
+ recorded: boolean;
112
+ } {
113
+ let enabled = false;
114
+ let recorded = false;
115
+ for (const entry of ctx.sessionManager.getBranch()) {
116
+ if (
117
+ (entry.type !== "custom" && entry.type !== "custom_message") ||
118
+ entry.customType !== ORCHESTRATION_STATE_TYPE
119
+ ) {
120
+ continue;
121
+ }
122
+ const state = entry.type === "custom" ? entry.data : entry.details;
123
+ if (
124
+ typeof state === "object" &&
125
+ state !== null &&
126
+ "enabled" in state &&
127
+ typeof state.enabled === "boolean"
128
+ ) {
129
+ enabled = state.enabled;
130
+ recorded = true;
131
+ }
132
+ }
133
+ return { enabled, recorded };
134
+ }
135
+
136
+ async function activateController(
137
+ fleet: AgentFleet,
138
+ ctx: ExtensionContext,
139
+ setActive: (active: boolean) => void,
140
+ ): Promise<boolean> {
141
+ if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
142
+ setActive(false);
143
+ ctx.ui.notify(
144
+ "Agent orchestration requires Pi to run inside Herdr",
145
+ "error",
146
+ );
147
+ return false;
148
+ }
149
+ try {
150
+ await fleet.activate(ctx);
151
+ setActive(true);
152
+ return true;
153
+ } catch (error) {
154
+ fleet.deactivate();
155
+ setActive(false);
156
+ ctx.ui.notify(
157
+ `Agent orchestration could not start: ${error instanceof Error ? error.message : String(error)}`,
158
+ "error",
159
+ );
160
+ return false;
161
+ }
162
+ }
163
+
164
+ function setToolActive(
165
+ pi: ExtensionAPI,
166
+ toolName: string,
167
+ active: boolean,
168
+ ): void {
169
+ const current = pi.getActiveTools();
170
+ const withoutTool = current.filter((name) => name !== toolName);
171
+ const next = active ? [...withoutTool, toolName] : withoutTool;
172
+ if (
173
+ next.length !== current.length ||
174
+ next.some((name, index) => name !== current[index])
175
+ ) {
176
+ pi.setActiveTools(next);
177
+ }
178
+ }