@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.
- package/CHANGELOG.md +52 -0
- package/README.md +55 -50
- package/biome.json +1 -1
- package/changelog.ts +337 -0
- package/index.ts +95 -5
- package/package.json +24 -12
- package/profiles/explorer/profile.json +8 -0
- package/profiles/explorer/prompt.md +1 -0
- package/profiles/general/profile.json +8 -0
- package/profiles/general/prompt.md +1 -0
- package/profiles/reviewer/prepare.mjs +170 -0
- package/profiles/reviewer/profile.json +9 -0
- package/profiles/reviewer/prompt.md +1 -0
- package/src/activity.ts +20 -1
- package/src/agents-contract.ts +142 -0
- package/src/agents-operations.ts +338 -0
- package/src/agents-tool.ts +440 -0
- package/src/ask-answer.ts +297 -0
- package/src/controller.ts +180 -0
- package/src/delivery.ts +68 -0
- package/src/herdr.ts +13 -1
- package/src/launch.ts +62 -8
- package/src/machine-menu.ts +158 -0
- package/src/messages.ts +108 -5
- package/src/monitor-record.ts +34 -1
- package/src/monitor-state.ts +40 -4
- package/src/monitor.ts +63 -6
- package/src/profiles.ts +291 -0
- package/src/remote/shepherdr.mjs +148 -28
- package/src/remote-client.ts +11 -5
- package/src/session-reader.ts +178 -50
- package/src/settlement.ts +228 -33
- package/src/types.ts +31 -1
- package/src/master-config.ts +0 -61
- package/src/master-mode.ts +0 -295
- package/src/tool.ts +0 -234
|
@@ -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,180 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { sendPolicyMessage } from "./delivery.js";
|
|
6
|
+
import type { AgentFleet } from "./fleet.js";
|
|
7
|
+
import { showMachineMenu } from "./machine-menu.js";
|
|
8
|
+
import { loadAgentProfiles } from "./profiles.js";
|
|
9
|
+
|
|
10
|
+
interface AgentControllerOptions {
|
|
11
|
+
onActiveChange?(): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const ORCHESTRATION_STATE_TYPE = "pi-shepherdr-orchestration-state";
|
|
15
|
+
const GENERAL_ORCHESTRATION_MESSAGE =
|
|
16
|
+
"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.";
|
|
17
|
+
const ORCHESTRATION_MESSAGE =
|
|
18
|
+
"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.";
|
|
19
|
+
const NORMAL_MESSAGE = "Work normally. Delegate only when useful or requested.";
|
|
20
|
+
|
|
21
|
+
export function registerAgentController(
|
|
22
|
+
pi: ExtensionAPI,
|
|
23
|
+
fleet: AgentFleet,
|
|
24
|
+
options: AgentControllerOptions = {},
|
|
25
|
+
): void {
|
|
26
|
+
let orchestrationEnabled = false;
|
|
27
|
+
const setActive = (active: boolean) => {
|
|
28
|
+
setToolActive(pi, "agents", active);
|
|
29
|
+
options.onActiveChange?.();
|
|
30
|
+
};
|
|
31
|
+
pi.registerCommand("herdr", {
|
|
32
|
+
description: "Toggle agent orchestration or manage Herdr machines",
|
|
33
|
+
getArgumentCompletions: (prefix) =>
|
|
34
|
+
["machines", "connect"]
|
|
35
|
+
.filter((action) => action.startsWith(prefix.trim().toLowerCase()))
|
|
36
|
+
.map((value) => ({ label: value, value })),
|
|
37
|
+
handler: async (args, ctx) => {
|
|
38
|
+
const [rawAction = "", ...rest] = args.trim().split(/\s+/);
|
|
39
|
+
const action = rawAction.toLowerCase();
|
|
40
|
+
if (!action) {
|
|
41
|
+
orchestrationEnabled = restoreOrchestrationState(ctx).enabled;
|
|
42
|
+
if (
|
|
43
|
+
!fleet.isActive() &&
|
|
44
|
+
!(await activateController(fleet, ctx, setActive))
|
|
45
|
+
) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
orchestrationEnabled = !orchestrationEnabled;
|
|
49
|
+
sendPolicyMessage(
|
|
50
|
+
pi,
|
|
51
|
+
{
|
|
52
|
+
customType: ORCHESTRATION_STATE_TYPE,
|
|
53
|
+
content: orchestrationEnabled
|
|
54
|
+
? await orchestrationMessage()
|
|
55
|
+
: NORMAL_MESSAGE,
|
|
56
|
+
details: { enabled: orchestrationEnabled },
|
|
57
|
+
display: true,
|
|
58
|
+
},
|
|
59
|
+
{ triggerTurn: false },
|
|
60
|
+
);
|
|
61
|
+
ctx.ui.notify(
|
|
62
|
+
orchestrationEnabled
|
|
63
|
+
? "Agent orchestration enabled"
|
|
64
|
+
: "Normal mode enabled",
|
|
65
|
+
"info",
|
|
66
|
+
);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (action === "machines") {
|
|
70
|
+
await showMachineMenu(fleet, ctx);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (action === "connect") {
|
|
74
|
+
if (!fleet.isActive()) {
|
|
75
|
+
ctx.ui.notify("Run /herdr to activate agents first", "warning");
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
ctx.ui.notify(fleet.connect(rest[0]), "info");
|
|
80
|
+
} catch (error) {
|
|
81
|
+
ctx.ui.notify(
|
|
82
|
+
error instanceof Error ? error.message : String(error),
|
|
83
|
+
"error",
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
ctx.ui.notify("Usage: /herdr [machines|connect [machine]]", "warning");
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
93
|
+
const state = restoreOrchestrationState(ctx);
|
|
94
|
+
orchestrationEnabled = state.enabled;
|
|
95
|
+
fleet.deactivate();
|
|
96
|
+
setActive(false);
|
|
97
|
+
if (state.recorded) await activateController(fleet, ctx, setActive);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
pi.on("session_shutdown", () => {
|
|
101
|
+
fleet.deactivate();
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function orchestrationMessage(): Promise<string> {
|
|
106
|
+
return (await loadAgentProfiles()).has("general")
|
|
107
|
+
? GENERAL_ORCHESTRATION_MESSAGE
|
|
108
|
+
: ORCHESTRATION_MESSAGE;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function restoreOrchestrationState(ctx: ExtensionContext): {
|
|
112
|
+
enabled: boolean;
|
|
113
|
+
recorded: boolean;
|
|
114
|
+
} {
|
|
115
|
+
let enabled = false;
|
|
116
|
+
let recorded = false;
|
|
117
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
118
|
+
if (
|
|
119
|
+
(entry.type !== "custom" && entry.type !== "custom_message") ||
|
|
120
|
+
entry.customType !== ORCHESTRATION_STATE_TYPE
|
|
121
|
+
) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const state = entry.type === "custom" ? entry.data : entry.details;
|
|
125
|
+
if (
|
|
126
|
+
typeof state === "object" &&
|
|
127
|
+
state !== null &&
|
|
128
|
+
"enabled" in state &&
|
|
129
|
+
typeof state.enabled === "boolean"
|
|
130
|
+
) {
|
|
131
|
+
enabled = state.enabled;
|
|
132
|
+
recorded = true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { enabled, recorded };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function activateController(
|
|
139
|
+
fleet: AgentFleet,
|
|
140
|
+
ctx: ExtensionContext,
|
|
141
|
+
setActive: (active: boolean) => void,
|
|
142
|
+
): Promise<boolean> {
|
|
143
|
+
if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
|
|
144
|
+
setActive(false);
|
|
145
|
+
ctx.ui.notify(
|
|
146
|
+
"Agent orchestration requires Pi to run inside Herdr",
|
|
147
|
+
"error",
|
|
148
|
+
);
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
await fleet.activate(ctx);
|
|
153
|
+
setActive(true);
|
|
154
|
+
return true;
|
|
155
|
+
} catch (error) {
|
|
156
|
+
fleet.deactivate();
|
|
157
|
+
setActive(false);
|
|
158
|
+
ctx.ui.notify(
|
|
159
|
+
`Agent orchestration could not start: ${error instanceof Error ? error.message : String(error)}`,
|
|
160
|
+
"error",
|
|
161
|
+
);
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function setToolActive(
|
|
167
|
+
pi: ExtensionAPI,
|
|
168
|
+
toolName: string,
|
|
169
|
+
active: boolean,
|
|
170
|
+
): void {
|
|
171
|
+
const current = pi.getActiveTools();
|
|
172
|
+
const withoutTool = current.filter((name) => name !== toolName);
|
|
173
|
+
const next = active ? [...withoutTool, toolName] : withoutTool;
|
|
174
|
+
if (
|
|
175
|
+
next.length !== current.length ||
|
|
176
|
+
next.some((name, index) => name !== current[index])
|
|
177
|
+
) {
|
|
178
|
+
pi.setActiveTools(next);
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/delivery.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type {
|
|
3
|
+
CodexDeveloperCustomMessage,
|
|
4
|
+
CodexDeveloperMessageOptions,
|
|
5
|
+
trySendCodexDeveloperCustomMessage,
|
|
6
|
+
} from "@howaboua/pi-codex-conversion/developer-messages";
|
|
7
|
+
|
|
8
|
+
const senders = new WeakMap<
|
|
9
|
+
ExtensionAPI,
|
|
10
|
+
typeof trySendCodexDeveloperCustomMessage
|
|
11
|
+
>();
|
|
12
|
+
const PACKAGE = "@howaboua/pi-codex-conversion";
|
|
13
|
+
const MODULE = `${PACKAGE}/developer-messages`;
|
|
14
|
+
|
|
15
|
+
export async function registerDeveloperDelivery(
|
|
16
|
+
pi: ExtensionAPI,
|
|
17
|
+
): Promise<void> {
|
|
18
|
+
try {
|
|
19
|
+
const api = await import(
|
|
20
|
+
"@howaboua/pi-codex-conversion/developer-messages"
|
|
21
|
+
);
|
|
22
|
+
if (typeof api.trySendCodexDeveloperCustomMessage === "function")
|
|
23
|
+
senders.set(pi, api.trySendCodexDeveloperCustomMessage);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (!isUnavailable(error)) throw error;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function sendPolicyMessage(
|
|
30
|
+
pi: ExtensionAPI,
|
|
31
|
+
message: CodexDeveloperCustomMessage,
|
|
32
|
+
options: CodexDeveloperMessageOptions,
|
|
33
|
+
): void {
|
|
34
|
+
if (senders.get(pi)?.(pi, message, options)) return;
|
|
35
|
+
pi.sendMessage(message, options);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isUnavailable(error: unknown): boolean {
|
|
39
|
+
if (
|
|
40
|
+
!error ||
|
|
41
|
+
typeof error !== "object" ||
|
|
42
|
+
!("code" in error) ||
|
|
43
|
+
!("message" in error) ||
|
|
44
|
+
typeof error.message !== "string"
|
|
45
|
+
)
|
|
46
|
+
return false;
|
|
47
|
+
if (
|
|
48
|
+
error.code === "ERR_MODULE_NOT_FOUND" ||
|
|
49
|
+
error.code === "MODULE_NOT_FOUND"
|
|
50
|
+
) {
|
|
51
|
+
const missing = error.message.match(
|
|
52
|
+
/Cannot find (?:package|module) ['"]([^'"]+)['"]/,
|
|
53
|
+
)?.[1];
|
|
54
|
+
const normalized = missing?.replaceAll("\\", "/").replace(/\.js$/, "");
|
|
55
|
+
return (
|
|
56
|
+
missing === PACKAGE ||
|
|
57
|
+
normalized === MODULE ||
|
|
58
|
+
normalized?.endsWith(`/${MODULE}`) === true
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
return (
|
|
62
|
+
(error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
|
|
63
|
+
error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
|
|
64
|
+
(error.message.includes(MODULE) ||
|
|
65
|
+
(error.message.includes("Package subpath './developer-messages'") &&
|
|
66
|
+
error.message.includes(PACKAGE)))
|
|
67
|
+
);
|
|
68
|
+
}
|
package/src/herdr.ts
CHANGED
|
@@ -35,6 +35,17 @@ export async function getAgent(
|
|
|
35
35
|
return parsePaneInfo(result["agent"], "agent.get result.agent");
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
export async function getPane(
|
|
39
|
+
client: HerdrConnection,
|
|
40
|
+
paneId: string,
|
|
41
|
+
): Promise<PaneInfo> {
|
|
42
|
+
const result = record(
|
|
43
|
+
await client.request<unknown>("pane.get", { pane_id: paneId }),
|
|
44
|
+
"pane.get result",
|
|
45
|
+
);
|
|
46
|
+
return parsePaneInfo(result["pane"], "pane.get result.pane");
|
|
47
|
+
}
|
|
48
|
+
|
|
38
49
|
export async function resolvePiAgent(
|
|
39
50
|
client: HerdrConnection,
|
|
40
51
|
target: string,
|
|
@@ -88,6 +99,7 @@ export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
|
|
|
88
99
|
...optionalNullableString(pane, "agent", path),
|
|
89
100
|
...optionalNullableString(pane, "cwd", path),
|
|
90
101
|
...optionalNullableString(pane, "foreground_cwd", path),
|
|
102
|
+
...optionalNullableString(pane, "label", path),
|
|
91
103
|
...optionalNullableString(pane, "name", path),
|
|
92
104
|
...optionalBoolean(pane, "interactive_ready", path),
|
|
93
105
|
...optionalBoolean(pane, "launch_pending", path),
|
|
@@ -170,7 +182,7 @@ function parseAgentSession(
|
|
|
170
182
|
}
|
|
171
183
|
|
|
172
184
|
function optionalNullableString<
|
|
173
|
-
K extends "agent" | "cwd" | "foreground_cwd" | "name",
|
|
185
|
+
K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name",
|
|
174
186
|
>(
|
|
175
187
|
value: Record<string, unknown>,
|
|
176
188
|
key: K,
|
package/src/launch.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { stat } from "node:fs/promises";
|
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import {
|
|
4
4
|
getAgent,
|
|
5
|
+
getPane,
|
|
5
6
|
getSnapshot,
|
|
6
7
|
parsePaneInfo,
|
|
7
8
|
resolveWorkspace,
|
|
@@ -48,13 +49,51 @@ export type DirectoryResolver = (
|
|
|
48
49
|
fallback: string,
|
|
49
50
|
) => Promise<string>;
|
|
50
51
|
|
|
52
|
+
function resolveStartDirectory(
|
|
53
|
+
params: StartAgentParams,
|
|
54
|
+
fallbackCwd: string,
|
|
55
|
+
resolveDirectory: DirectoryResolver = directory,
|
|
56
|
+
): Promise<string> {
|
|
57
|
+
return params.placement === "pane"
|
|
58
|
+
? Promise.resolve(fallbackCwd)
|
|
59
|
+
: resolveDirectory(params.cwd, fallbackCwd);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function resolvePreparationDirectory(
|
|
63
|
+
client: HerdrConnection,
|
|
64
|
+
params: StartAgentParams,
|
|
65
|
+
fallbackCwd: string,
|
|
66
|
+
resolveDirectory: DirectoryResolver = directory,
|
|
67
|
+
): Promise<string> {
|
|
68
|
+
if (params.placement !== "pane") {
|
|
69
|
+
return resolveStartDirectory(params, fallbackCwd, resolveDirectory);
|
|
70
|
+
}
|
|
71
|
+
const pane = await getPane(client, required(params.pane, "pane"));
|
|
72
|
+
return pane.foreground_cwd?.trim() || pane.cwd?.trim() || fallbackCwd;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface StartAgentOptions {
|
|
76
|
+
agentArgs?: string[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface CreatedLocationCleanup {
|
|
80
|
+
id: string;
|
|
81
|
+
method: "tab.close" | "workspace.close";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface StartedAgent {
|
|
85
|
+
agent: PaneInfo;
|
|
86
|
+
cleanup?: CreatedLocationCleanup;
|
|
87
|
+
id: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
51
90
|
async function createStartPane(
|
|
52
91
|
client: HerdrConnection,
|
|
53
92
|
params: StartAgentParams,
|
|
54
93
|
cwd: string,
|
|
55
94
|
label: string,
|
|
56
95
|
): Promise<{
|
|
57
|
-
cleanup?:
|
|
96
|
+
cleanup?: CreatedLocationCleanup;
|
|
58
97
|
paneId: string;
|
|
59
98
|
}> {
|
|
60
99
|
const placement = params.placement;
|
|
@@ -165,7 +204,8 @@ export async function startAgent(
|
|
|
165
204
|
params: StartAgentParams,
|
|
166
205
|
fallbackCwd: string,
|
|
167
206
|
resolveDirectory: DirectoryResolver = directory,
|
|
168
|
-
|
|
207
|
+
options: StartAgentOptions = {},
|
|
208
|
+
): Promise<StartedAgent> {
|
|
169
209
|
const name = required(params.name, "name");
|
|
170
210
|
if (!AGENT_NAME.test(name)) {
|
|
171
211
|
throw new Error("name must match [a-z][a-z0-9_-]{0,31}");
|
|
@@ -176,10 +216,11 @@ export async function startAgent(
|
|
|
176
216
|
"cwd cannot change an existing pane; prepare the pane through Herdr",
|
|
177
217
|
);
|
|
178
218
|
}
|
|
179
|
-
const cwd =
|
|
180
|
-
params
|
|
181
|
-
|
|
182
|
-
|
|
219
|
+
const cwd = await resolveStartDirectory(
|
|
220
|
+
params,
|
|
221
|
+
fallbackCwd,
|
|
222
|
+
resolveDirectory,
|
|
223
|
+
);
|
|
183
224
|
const created = await createStartPane(client, params, cwd, label);
|
|
184
225
|
let agent: PaneInfo;
|
|
185
226
|
try {
|
|
@@ -187,7 +228,7 @@ export async function startAgent(
|
|
|
187
228
|
name,
|
|
188
229
|
kind: "pi",
|
|
189
230
|
pane_id: created.paneId,
|
|
190
|
-
args: ["--name", label],
|
|
231
|
+
args: ["--name", label, ...(options.agentArgs ?? [])],
|
|
191
232
|
timeout_ms: 30_000,
|
|
192
233
|
});
|
|
193
234
|
} catch (error) {
|
|
@@ -213,13 +254,26 @@ export async function startAgent(
|
|
|
213
254
|
}
|
|
214
255
|
}
|
|
215
256
|
return {
|
|
257
|
+
agent,
|
|
258
|
+
...(created.cleanup ? { cleanup: created.cleanup } : {}),
|
|
216
259
|
id: agent.pane_id,
|
|
217
260
|
};
|
|
218
261
|
}
|
|
219
262
|
|
|
263
|
+
export async function rollbackStartedAgent(
|
|
264
|
+
client: HerdrConnection,
|
|
265
|
+
monitor: AgentMonitor,
|
|
266
|
+
started: StartedAgent,
|
|
267
|
+
cause: unknown,
|
|
268
|
+
): Promise<never> {
|
|
269
|
+
if (!started.cleanup) throw cause;
|
|
270
|
+
await monitor.unwatch(started.id).catch(() => undefined);
|
|
271
|
+
return rollbackCreatedLocation(client, started.cleanup, cause);
|
|
272
|
+
}
|
|
273
|
+
|
|
220
274
|
async function rollbackCreatedLocation(
|
|
221
275
|
client: HerdrConnection,
|
|
222
|
-
cleanup:
|
|
276
|
+
cleanup: CreatedLocationCleanup | undefined,
|
|
223
277
|
cause: unknown,
|
|
224
278
|
): Promise<never> {
|
|
225
279
|
if (!cleanup) throw cause;
|