@howaboua/pi-shepherdr 0.2.5 → 0.2.7

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.
@@ -1,67 +1,41 @@
1
1
  import { defineTool, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
2
2
  import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
3
+ import { answerAgent } from "./agents-answer.js";
3
4
  import {
4
5
  AgentsParameters,
5
6
  type AgentsParams,
6
7
  type AgentsToolParams,
7
8
  parseAgentsRequest,
8
- shouldBlockAgentSpawn,
9
+ requiredAgentField as required,
9
10
  } from "./agents-contract.js";
10
11
  import {
11
12
  agentsHelp,
12
- allocateAgentName,
13
- dispatchAgentWork,
14
13
  findFleetAgents,
15
14
  listFleetAgents,
16
15
  readAgentTerminal,
17
- reportProgress,
16
+ } from "./agents-discovery.js";
17
+ import { spawnAgent } from "./agents-spawn.js";
18
+ import {
19
+ dispatchAgentWork,
18
20
  settlementResult,
19
21
  toolResult,
20
- } from "./agents-operations.js";
21
- import { type AskAnswer, prepareAskAnswer } from "./ask-answer.js";
22
+ } from "./agents-work.js";
22
23
  import type { AgentFleet } from "./fleet.js";
23
24
  import { resolvePiAgent } from "./herdr.js";
24
- import { isDispatchRejected } from "./herdr-client.js";
25
- import {
26
- resolvePreparationDirectory,
27
- rollbackStartedAgent,
28
- startAgent,
29
- } from "./launch.js";
30
- import { attributeAgentPrompt } from "./messages.js";
31
- import {
32
- loadAgentProfiles,
33
- prepareProfileMessage,
34
- profileAgentArgs,
35
- } from "./profiles.js";
36
-
37
- function required(value: string | undefined, field: string): string {
38
- if (!value?.trim()) throw new Error(`${field} is required for this action`);
39
- return value.trim();
40
- }
25
+ import { attributeAgentPrompt, modelAsk } from "./messages.js";
26
+ import type { SharedAgentContext } from "./shared-context.js";
41
27
 
42
- function agentLabel(value: string | undefined): string {
43
- const label = required(value, "label");
44
- const words = label.split(/\s+/u);
45
- if (words.length < 2 || words.length > 3) {
46
- throw new Error("label must contain 2 or 3 words");
47
- }
48
- return label;
49
- }
50
-
51
- export function createAgentsTool(fleet: AgentFleet) {
28
+ export function createAgentsTool(
29
+ fleet: AgentFleet,
30
+ sharedContext: SharedAgentContext,
31
+ ) {
52
32
  return defineTool({
53
33
  name: "agents",
54
34
  label: "Shepherdr",
55
35
  description: "Delegate to persistent agents; call help first, alone",
56
36
  parameters: AgentsParameters,
57
37
  executionMode: "sequential",
58
- async execute(
59
- _toolCallId,
60
- input: AgentsToolParams,
61
- signal,
62
- onUpdate,
63
- _ctx,
64
- ) {
38
+ async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
65
39
  const params = parseAgentsRequest(input);
66
40
  const executionSignal = signal ?? new AbortController().signal;
67
41
  const update = onUpdate ?? (() => undefined);
@@ -77,130 +51,14 @@ export function createAgentsTool(fleet: AgentFleet) {
77
51
 
78
52
  const runtime = fleet.connected(params.machine);
79
53
  if (params.action === "spawn") {
80
- const profiles = await loadAgentProfiles();
81
- const profileName = required(params.agent_type, "agent_type");
82
- const profile = profiles.get(profileName);
83
- if (!profile) {
84
- throw new Error(
85
- `unknown agent_type ${JSON.stringify(profileName)}; available: ${[...profiles.keys()].join(", ")}`,
86
- );
87
- }
88
- const label = agentLabel(params.label);
89
- const name =
90
- params.name?.trim() || (await allocateAgentName(runtime, label));
91
- const placement =
92
- params.placement ??
93
- (runtime.local && process.env["HERDR_WORKSPACE_ID"]
94
- ? "new_tab"
95
- : "new_workspace");
96
- const workspace =
97
- params.workspace ??
98
- (placement === "new_tab" && runtime.local
99
- ? process.env["HERDR_WORKSPACE_ID"]
100
- : undefined);
101
- const startParams = {
102
- name,
103
- label,
104
- placement,
105
- ...(workspace ? { workspace } : {}),
106
- ...(params.pane ? { pane: params.pane } : {}),
107
- ...(params.cwd ? { cwd: params.cwd } : {}),
108
- };
109
- const cwd = await resolvePreparationDirectory(
110
- runtime.client,
111
- startParams,
112
- runtime.fallbackCwd,
113
- runtime.resolveDirectory,
114
- );
115
- const input = required(params.message, "message");
116
- const message = await prepareProfileMessage(
117
- profile,
118
- {
119
- cwd,
120
- message: input,
121
- ...(params.base ? { base: params.base } : {}),
122
- },
123
- { targetLocal: runtime.local },
124
- );
125
- const attributedMessage = await attributeAgentPrompt(
126
- fleet.connected().client,
127
- input.startsWith("/") ? input : message,
128
- "task",
129
- );
130
- if (input.startsWith("/") && message !== input)
131
- attributedMessage.context = message;
132
- reportProgress(update, `Spawning ${label}`, {
133
- machine: runtime.machine,
134
- name,
135
- profile: profile.name,
136
- status: "starting",
137
- });
138
- const started = await startAgent(
139
- runtime.client,
140
- startParams,
141
- runtime.fallbackCwd,
142
- runtime.resolveDirectory,
143
- {
144
- agentArgs: profileAgentArgs(profile, {
145
- targetLocal: runtime.local,
146
- }),
147
- },
148
- );
149
- let promptSubmissionStarted = false;
150
- let promptAccepted = false;
151
- let dispatch;
152
- const blocking = shouldBlockAgentSpawn(profile.name, params.blocking);
153
- try {
154
- dispatch = await dispatchAgentWork(
155
- runtime,
156
- started.agent,
157
- message,
158
- blocking,
159
- executionSignal,
160
- update,
161
- async () => {
162
- promptSubmissionStarted = true;
163
- const receipt = await runtime.client.sendMessage(
164
- started.agent,
165
- attributedMessage,
166
- );
167
- promptAccepted = true;
168
- return receipt;
169
- },
170
- { expectUserMessage: true },
171
- );
172
- } catch (error) {
173
- if (
174
- !promptAccepted &&
175
- (!promptSubmissionStarted || isDispatchRejected(error))
176
- ) {
177
- return rollbackStartedAgent(runtime.client, started, error);
178
- }
179
- throw error;
180
- }
181
- return toolResult(
182
- dispatch.command
183
- ? {
184
- spawned: true,
185
- commandSubmitted: true,
186
- machine: runtime.machine,
187
- target: started.id,
188
- name,
189
- }
190
- : dispatch.settlement
191
- ? {
192
- spawned: true,
193
- ...settlementResult(runtime.machine, dispatch.settlement),
194
- }
195
- : {
196
- spawned: true,
197
- machine: runtime.machine,
198
- target: started.id,
199
- name,
200
- status: "working",
201
- next: "Completion or blockage will be delivered automatically; do not poll",
202
- },
203
- dispatch.warning,
54
+ return spawnAgent(
55
+ fleet,
56
+ runtime,
57
+ params,
58
+ executionSignal,
59
+ update,
60
+ sharedContext,
61
+ ctx,
204
62
  );
205
63
  }
206
64
 
@@ -255,10 +113,7 @@ export function createAgentsTool(fleet: AgentFleet) {
255
113
  : { reply: null }),
256
114
  ...(panel.agent_status === "blocked" && view.ask
257
115
  ? {
258
- ask: {
259
- handoff: view.ask.handoff,
260
- prompts: view.ask.prompts,
261
- },
116
+ ask: modelAsk(view.ask),
262
117
  }
263
118
  : {}),
264
119
  });
@@ -322,40 +177,7 @@ export function createAgentsTool(fleet: AgentFleet) {
322
177
  );
323
178
  }
324
179
  if (params.action === "answer") {
325
- const prepared = await prepareAskAnswer(
326
- runtime.client,
327
- runtime.monitor,
328
- panel,
329
- (params.answers ?? []) as AskAnswer[],
330
- executionSignal,
331
- );
332
- const task = `Answer: ${prepared.ask.prompts
333
- .map((prompt) => prompt.title)
334
- .join(", ")}`;
335
- const { settlement, warning } = await dispatchAgentWork(
336
- runtime,
337
- panel,
338
- task,
339
- params.blocking !== false,
340
- executionSignal,
341
- update,
342
- prepared.submit,
343
- );
344
- return toolResult(
345
- settlement
346
- ? {
347
- answered: true,
348
- ...settlementResult(runtime.machine, settlement),
349
- }
350
- : {
351
- answered: true,
352
- machine: runtime.machine,
353
- target: panel.pane_id,
354
- status: "working",
355
- next: "Completion or blockage will be delivered automatically; do not poll",
356
- },
357
- warning,
358
- );
180
+ return answerAgent(runtime, panel, params, executionSignal, update);
359
181
  }
360
182
  throw new Error(`unsupported action ${params.action}`);
361
183
  },
@@ -0,0 +1,194 @@
1
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
2
+ import { activityTask } from "./activity.js";
3
+ import type { ConnectedMachine } from "./fleet.js";
4
+ import { getSnapshot } from "./herdr.js";
5
+ import { isDispatchRejected } from "./herdr-client.js";
6
+ import { agentSource, modelAsk } from "./messages.js";
7
+ import type { WorkAttempt } from "./monitor-state.js";
8
+ import type { ClaimedSettlement } from "./settlement.js";
9
+ import type { PaneInfo, PeerDelivery } from "./types.js";
10
+
11
+ export function toolResult(value: Record<string, unknown>, warning?: string) {
12
+ if (warning) value = { ...value, next: warning };
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
+ function slugify(value: string): string {
31
+ const slug = value
32
+ .normalize("NFKD")
33
+ .replace(/[\u0300-\u036f]/gu, "")
34
+ .toLowerCase()
35
+ .replace(/[^a-z0-9]+/gu, "-")
36
+ .replace(/^-+|-+$/gu, "");
37
+ const named = /^[a-z]/u.test(slug) ? slug : `agent-${slug}`;
38
+ return named.slice(0, 32).replace(/-+$/u, "") || "agent";
39
+ }
40
+
41
+ export async function allocateAgentName(
42
+ runtime: ConnectedMachine,
43
+ label: string,
44
+ ): Promise<string> {
45
+ const snapshot = await getSnapshot(runtime.client);
46
+ const names = new Set(
47
+ snapshot.agents.map((agent) => agent.name).filter(Boolean),
48
+ );
49
+ const base = slugify(label);
50
+ if (!names.has(base)) return base;
51
+ for (let suffix = 2; suffix < 10_000; suffix += 1) {
52
+ const tail = `-${suffix}`;
53
+ const candidate = `${base.slice(0, 32 - tail.length).replace(/-+$/u, "")}${tail}`;
54
+ if (!names.has(candidate)) return candidate;
55
+ }
56
+ throw new Error(
57
+ `could not allocate an agent name for ${JSON.stringify(label)}`,
58
+ );
59
+ }
60
+
61
+ export function settlementResult(
62
+ machine: string,
63
+ settlement: ClaimedSettlement,
64
+ options: { reportWorkerError?: boolean } = {},
65
+ ): Record<string, unknown> {
66
+ const workerError =
67
+ settlement.reply?.stopReason === "error"
68
+ ? settlement.reply.text ||
69
+ `${settlement.agent.pane_id} assistant stopped with an error`
70
+ : undefined;
71
+ if (workerError && !options.reportWorkerError) throw new Error(workerError);
72
+ const { pane, name, ...source } = agentSource(
73
+ settlement.agent,
74
+ settlement.labels,
75
+ );
76
+ return {
77
+ machine,
78
+ target: pane,
79
+ ...(name ? { name } : {}),
80
+ source,
81
+ status: settlement.status,
82
+ ...(workerError ? { worker_error: workerError } : {}),
83
+ ...(settlement.reply ? { reply: settlement.reply.text } : {}),
84
+ ...(settlement.ask
85
+ ? {
86
+ ask: modelAsk(settlement.ask),
87
+ }
88
+ : {}),
89
+ ...(settlement.blockedMessage
90
+ ? { blocked_on: settlement.blockedMessage }
91
+ : {}),
92
+ ...(settlement.status === "done" && !settlement.reply && !settlement.ask
93
+ ? { completed: true }
94
+ : {}),
95
+ };
96
+ }
97
+
98
+ export async function dispatchAgentWork(
99
+ runtime: ConnectedMachine,
100
+ panel: PaneInfo,
101
+ task: string,
102
+ blocking: boolean,
103
+ signal: AbortSignal,
104
+ onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
105
+ send: () => Promise<PeerDelivery | void>,
106
+ options: { expectUserMessage?: boolean; answeringAskId?: string } = {},
107
+ ): Promise<{
108
+ settlement?: ClaimedSettlement;
109
+ command?: true;
110
+ warning?: string;
111
+ }> {
112
+ signal.throwIfAborted();
113
+ const addedWatch = !runtime.monitor
114
+ .list()
115
+ .some(
116
+ (record) =>
117
+ record.terminalId === panel.terminal_id ||
118
+ record.paneId === panel.pane_id,
119
+ );
120
+ let attempt: WorkAttempt | undefined;
121
+ let settlement: Promise<ClaimedSettlement> | undefined;
122
+ let receipt: PeerDelivery | void;
123
+ let sendStarted = false;
124
+ try {
125
+ await runtime.monitor.track(panel);
126
+ const baseline = options.expectUserMessage
127
+ ? await runtime.monitor.view(panel)
128
+ : undefined;
129
+ attempt = runtime.monitor.beginWork(
130
+ panel.pane_id,
131
+ task,
132
+ options.expectUserMessage ? (baseline?.input?.id ?? null) : undefined,
133
+ );
134
+ if (!attempt) throw new Error(`${panel.pane_id} is not monitored`);
135
+ settlement = blocking
136
+ ? runtime.monitor.claimWork(attempt, signal, options.answeringAskId)
137
+ : undefined;
138
+ void settlement?.catch(() => undefined);
139
+ signal.throwIfAborted();
140
+ sendStarted = true;
141
+ receipt = await send();
142
+ } catch (error) {
143
+ runtime.monitor.releaseWorkClaim(attempt, error);
144
+ if (sendStarted) await runtime.monitor.handleWorkFailure(attempt, error);
145
+ else runtime.monitor.rejectWork(attempt);
146
+ if (addedWatch && (!sendStarted || isDispatchRejected(error))) {
147
+ const record = runtime.monitor
148
+ .list()
149
+ .find((record) => record.terminalId === panel.terminal_id);
150
+ try {
151
+ if (record?.scope === "task" && !activityTask(record.activity)) {
152
+ await runtime.monitor.unwatch(record.paneId);
153
+ }
154
+ } catch (cleanupError) {
155
+ throw new AggregateError(
156
+ [error, cleanupError],
157
+ "Delegation failed; temporary watch cleanup also failed",
158
+ );
159
+ }
160
+ }
161
+ throw error;
162
+ }
163
+ try {
164
+ if (receipt?.command) {
165
+ runtime.monitor.releaseWorkClaim(
166
+ attempt,
167
+ new Error("Command submitted without task waiting"),
168
+ );
169
+ runtime.monitor.rejectWork(attempt);
170
+ if (addedWatch) {
171
+ const record = runtime.monitor
172
+ .list()
173
+ .find((record) => record.terminalId === panel.terminal_id);
174
+ if (record?.scope === "task" && !activityTask(record.activity))
175
+ await runtime.monitor.unwatch(record.paneId);
176
+ }
177
+ } else runtime.monitor.acceptWork(attempt);
178
+ await runtime.monitor.reconcileNow();
179
+ } catch (error) {
180
+ runtime.monitor.releaseWorkClaim(attempt, error);
181
+ return {
182
+ ...(receipt?.command ? { command: true } : {}),
183
+ warning: `Submitted, but monitoring refresh failed: ${error instanceof Error ? error.message : String(error)}. Inspect the target before resubmitting`,
184
+ };
185
+ }
186
+ if (receipt?.command) return { command: true };
187
+ if (!blocking) return {};
188
+ reportProgress(onUpdate, `Waiting for ${panel.name ?? panel.pane_id}`, {
189
+ machine: runtime.machine,
190
+ target: panel.pane_id,
191
+ status: "working",
192
+ });
193
+ return { settlement: await settlement! };
194
+ }
package/src/ask-answer.ts CHANGED
@@ -6,12 +6,44 @@ import type { HerdrConnection } from "./herdr-client.js";
6
6
  import type { AgentMonitor } from "./monitor.js";
7
7
  import type { PaneInfo, PendingAsk } from "./types.js";
8
8
 
9
+ const REPHRASE_REQUEST_RESPONSE =
10
+ "User asked for rephrase, split, or follow-up.";
11
+
9
12
  export interface AskAnswer {
10
13
  comment?: string;
11
14
  other?: string;
12
15
  selections?: string[];
13
16
  }
14
17
 
18
+ export function answersMatch(
19
+ answers: AskAnswer[],
20
+ responses:
21
+ | Array<{ comment?: string; id: string; selections: string[] }>
22
+ | undefined,
23
+ ): boolean {
24
+ if (!responses || responses.length !== answers.length) return false;
25
+ return answers.every((answer, index) => {
26
+ const response = responses[index];
27
+ if (!response || response.id !== `p${index + 1}`) return false;
28
+ let selections = [...(answer.selections ?? [])];
29
+ if (answer.other !== undefined) {
30
+ const custom = answer.other.trim() || REPHRASE_REQUEST_RESPONSE;
31
+ selections = [
32
+ ...selections.filter((selection) => selection !== custom),
33
+ custom,
34
+ ];
35
+ }
36
+ if (selections.length === 0) selections.push(REPHRASE_REQUEST_RESPONSE);
37
+ if (
38
+ [...selections].sort().join("\0") !==
39
+ [...response.selections].sort().join("\0")
40
+ ) {
41
+ return false;
42
+ }
43
+ return (answer.comment?.trim() || undefined) === response.comment;
44
+ });
45
+ }
46
+
15
47
  interface InputStep {
16
48
  final?: boolean;
17
49
  keys?: string[];
@@ -237,12 +269,28 @@ async function sendInput(
237
269
  }
238
270
  }
239
271
 
272
+ export function sameAgentIdentity(
273
+ expected: PaneInfo,
274
+ current: PaneInfo,
275
+ ): boolean {
276
+ return (
277
+ current.pane_id === expected.pane_id &&
278
+ current.workspace_id === expected.workspace_id &&
279
+ current.tab_id === expected.tab_id &&
280
+ current.terminal_id === expected.terminal_id &&
281
+ current.agent_session?.agent === expected.agent_session?.agent &&
282
+ current.agent_session?.kind === expected.agent_session?.kind &&
283
+ current.agent_session?.source === expected.agent_session?.source &&
284
+ current.agent_session?.value === expected.agent_session?.value
285
+ );
286
+ }
287
+
240
288
  async function requireSameAgent(
241
289
  client: HerdrConnection,
242
290
  panel: PaneInfo,
243
291
  ): Promise<void> {
244
292
  const current = await getAgent(client, panel.pane_id);
245
- if (current.terminal_id !== panel.terminal_id) {
293
+ if (!sameAgentIdentity(panel, current)) {
246
294
  throw new Error(`${panel.pane_id} no longer hosts the targeted Pi agent`);
247
295
  }
248
296
  }
@@ -253,6 +301,7 @@ export async function prepareAskAnswer(
253
301
  panel: PaneInfo,
254
302
  answers: AskAnswer[],
255
303
  signal: AbortSignal,
304
+ expectedAskId: string,
256
305
  ): Promise<{ ask: PendingAsk; submit(): Promise<void> }> {
257
306
  if (panel.agent_status !== "blocked") {
258
307
  throw new Error(
@@ -266,6 +315,9 @@ export async function prepareAskAnswer(
266
315
  );
267
316
  }
268
317
  const ask = view.ask;
318
+ if (ask.toolCallId !== expectedAskId) {
319
+ throw new Error(`${panel.pane_id} is blocked on a different Ask call`);
320
+ }
269
321
  const initial = inspectAskScreen(await screen(client, panel.pane_id), ask);
270
322
  const first = ask.prompts[0];
271
323
  const expectedSelection = first?.choices[0]?.label ?? "Other/rephrase";
@@ -291,7 +343,7 @@ export async function prepareAskAnswer(
291
343
  await new Promise((resolve) => setTimeout(resolve, 35));
292
344
  const current = await getAgent(client, panel.pane_id);
293
345
  if (
294
- current.terminal_id !== panel.terminal_id ||
346
+ !sameAgentIdentity(panel, current) ||
295
347
  current.agent_status !== "blocked"
296
348
  ) {
297
349
  throw new Error("ask closed before all requested answers were entered");
package/src/delivery.ts CHANGED
@@ -91,16 +91,27 @@ export async function registerDeveloperDelivery(
91
91
 
92
92
  export function startPreparedIdleTurn(
93
93
  pi: ExtensionAPI,
94
- ctx: Pick<ExtensionContext, "ui">,
94
+ ctx: Pick<ExtensionContext, "ui" | "sessionManager">,
95
95
  start?: () => void,
96
96
  ): void {
97
+ // Session history survives tree cuts; a new active branch is not a fresh agent.
98
+ const prompt =
99
+ !start &&
100
+ ctx.sessionManager
101
+ .getEntries()
102
+ .some(
103
+ (entry) =>
104
+ entry.type === "message" && entry.message.role === "assistant",
105
+ )
106
+ ? "Continue, unless awaiting for user approval."
107
+ : "Continue.";
97
108
  if (start) {
98
109
  if (preparedPrompts.get(pi)?.(pi, start)) return;
99
110
  if (preparedKickoffs.has(pi) && !preparedPrompts.has(pi))
100
111
  throw new Error(
101
112
  "Update Pi Codex Conversion and reload before sending slash commands",
102
113
  );
103
- } else if (preparedKickoffs.get(pi)?.(pi, ctx)) return;
114
+ } else if (preparedKickoffs.get(pi)?.(pi, ctx, prompt)) return;
104
115
  if (fallbackKickoffs.has(pi)) {
105
116
  if (start)
106
117
  throw new Error(
@@ -118,7 +129,7 @@ export function startPreparedIdleTurn(
118
129
  fallbackKickoffs.set(pi, "preparing");
119
130
  try {
120
131
  if (start) start();
121
- else pi.sendUserMessage("Continue.", { deliverAs: "steer" });
132
+ else pi.sendUserMessage(prompt, { deliverAs: "steer" });
122
133
  } catch (error) {
123
134
  fallbackKickoffs.delete(pi);
124
135
  throw error;