@howaboua/pi-shepherdr 0.2.14 → 0.2.16

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +40 -33
  3. package/index.ts +16 -26
  4. package/package.json +11 -11
  5. package/src/agents-contract.ts +11 -1
  6. package/src/agents-discovery.ts +21 -7
  7. package/src/agents-focus.ts +242 -0
  8. package/src/agents-spawn.ts +23 -0
  9. package/src/agents-tool.ts +34 -5
  10. package/src/attachment-protocol.ts +7 -3
  11. package/src/attachment-target.ts +3 -1
  12. package/src/attachment.ts +3 -1
  13. package/src/board/host.ts +98 -353
  14. package/src/board/membership.ts +14 -8
  15. package/src/command-config.ts +51 -0
  16. package/src/control-panel-actions.ts +0 -20
  17. package/src/control-panel-items.ts +8 -36
  18. package/src/control-panel-view.ts +2 -11
  19. package/src/control-panel.ts +2 -11
  20. package/src/controller.ts +5 -5
  21. package/src/delivery.ts +0 -33
  22. package/src/herdr-client.ts +39 -6
  23. package/src/messages.ts +61 -6
  24. package/src/monitor-events.ts +24 -2
  25. package/src/monitor-questions.ts +12 -3
  26. package/src/monitor.ts +2 -2
  27. package/src/peer-channel.ts +39 -0
  28. package/src/peer-commands.ts +173 -0
  29. package/src/peer-inbox.ts +218 -55
  30. package/src/remote/shepherdr-channel.mjs +225 -0
  31. package/src/remote/shepherdr-checkpoints.mjs +5 -3
  32. package/src/remote/shepherdr-peer.mjs +151 -22
  33. package/src/remote/shepherdr.mjs +56 -8
  34. package/src/remote-client.ts +115 -11
  35. package/src/settlement.ts +1 -0
  36. package/src/shared-context.ts +104 -1
  37. package/src/types.ts +23 -0
  38. package/src/voice-handoff.ts +177 -0
  39. package/src/board/archive.ts +0 -77
  40. package/src/board/awareness.ts +0 -115
  41. package/src/board/config.ts +0 -121
  42. package/src/board/contract.ts +0 -181
  43. package/src/board/identity.ts +0 -169
  44. package/src/board/paging.ts +0 -55
  45. package/src/board/protocol.ts +0 -73
  46. package/src/board/queries.ts +0 -176
  47. package/src/board/response.ts +0 -56
  48. package/src/board/store.ts +0 -327
  49. package/src/board/tool.ts +0 -23
  50. package/src/board/turns.ts +0 -100
  51. package/src/context-briefing.ts +0 -226
@@ -0,0 +1,242 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ recordContextBriefing,
8
+ registerContextBriefing,
9
+ } from "@howaboua/pi-agent-board/integration";
10
+ import type { AgentFleet, ConnectedMachine } from "./fleet.js";
11
+ import {
12
+ getAgent,
13
+ getCurrentPane,
14
+ resolvePiAgent,
15
+ sessionPath,
16
+ } from "./herdr.js";
17
+ import { isDispatchRejected } from "./herdr-client.js";
18
+ import { focusArrivalContent } from "./messages.js";
19
+ import type { FocusRequest, PaneInfo } from "./types.js";
20
+ import { activeVoiceService, observeVoiceTransfer } from "./voice-handoff.js";
21
+
22
+ const ARRIVAL = "herdr-focus-arrival";
23
+
24
+ export async function focusAgent(
25
+ pi: ExtensionAPI,
26
+ ctx: ExtensionContext,
27
+ fleet: AgentFleet,
28
+ runtime: ConnectedMachine,
29
+ target: string,
30
+ voice = false,
31
+ handoff?: string,
32
+ ) {
33
+ const service = voice ? activeVoiceService(pi) : undefined;
34
+ const local = fleet.connected();
35
+ const source = await getCurrentPane(local.client);
36
+ const sessionFile = sessionPath(source);
37
+ if (!sessionFile)
38
+ throw new Error("Focus requires a saved source session for returning");
39
+ const panel = await resolvePiAgent(
40
+ runtime.client,
41
+ target,
42
+ runtime.local ? source.pane_id : "",
43
+ );
44
+ if (
45
+ !sessionPath(panel) ||
46
+ panel.launch_pending ||
47
+ panel.interactive_ready === false
48
+ )
49
+ throw new Error(
50
+ "Target session is not running and ready; choose an existing running session",
51
+ );
52
+ const request: FocusRequest = {
53
+ source: {
54
+ ...(await local.client.machineIdentity()),
55
+ pane: source.pane_id,
56
+ terminal: source.terminal_id,
57
+ sessionFile,
58
+ },
59
+ ...(handoff?.trim() ? { handoff } : {}),
60
+ voice,
61
+ ...(service
62
+ ? { voiceAudioTransport: service.audioTransport ?? "webrtc" }
63
+ : {}),
64
+ };
65
+ if (service) {
66
+ const channel = await runtime.client.openFocusChannel(panel, request);
67
+ let completion: Promise<void>;
68
+ try {
69
+ completion = service.depart(channel);
70
+ } catch (error) {
71
+ completion = Promise.reject(error);
72
+ }
73
+ observeVoiceTransfer(
74
+ pi,
75
+ ctx,
76
+ completion,
77
+ channel,
78
+ "source",
79
+ `${runtime.machine}/${panel.pane_id}`,
80
+ );
81
+ return {
82
+ status: "transferring",
83
+ machine: runtime.machine,
84
+ target: panel.pane_id,
85
+ voice: true,
86
+ ...(runtime.local ? {} : { display: "target-machine-only" }),
87
+ };
88
+ }
89
+ await runtime.client.focus(panel, request);
90
+ return {
91
+ focused: true,
92
+ machine: runtime.machine,
93
+ target: panel.pane_id,
94
+ voice: false,
95
+ ...(runtime.local ? {} : { display: "target-machine-only" }),
96
+ };
97
+ }
98
+
99
+ export function readFocus(value: unknown): FocusRequest {
100
+ if (!value || typeof value !== "object" || !("source" in value))
101
+ throw new Error("Invalid focus arrival");
102
+ if (
103
+ !value.source ||
104
+ typeof value.source !== "object" ||
105
+ Array.isArray(value.source)
106
+ )
107
+ throw new Error("Invalid focus source");
108
+ const source = value.source as Record<string, unknown>;
109
+ for (const field of [
110
+ "host",
111
+ "session",
112
+ "pane",
113
+ "terminal",
114
+ "sessionFile",
115
+ ] as const) {
116
+ if (
117
+ !(field in source) ||
118
+ typeof source[field] !== "string" ||
119
+ !source[field].trim()
120
+ )
121
+ throw new Error("Invalid focus source");
122
+ }
123
+ if ("handoff" in value && typeof value.handoff !== "string")
124
+ throw new Error("Invalid focus handoff");
125
+ if ("voice" in value && typeof value.voice !== "boolean")
126
+ throw new Error("Invalid focus voice selection");
127
+ if (
128
+ "voiceAudioTransport" in value &&
129
+ value.voiceAudioTransport !== "webrtc" &&
130
+ value.voiceAudioTransport !== "pcm24"
131
+ )
132
+ throw new Error("Invalid focus audio transport");
133
+ return value as FocusRequest;
134
+ }
135
+
136
+ export async function acceptFocus(
137
+ pi: ExtensionAPI,
138
+ ctx: ExtensionContext,
139
+ fleet: AgentFleet,
140
+ pane: PaneInfo,
141
+ value: unknown,
142
+ ): Promise<void> {
143
+ const request = readFocus(value);
144
+ const source = request.source;
145
+ const routes: string[] = [];
146
+ for (const status of fleet.statuses()) {
147
+ if (status.status !== "connected") continue;
148
+ const runtime = fleet.connected(status.id);
149
+ try {
150
+ const identity = await runtime.client.machineIdentity();
151
+ if (identity.host !== source.host || identity.session !== source.session)
152
+ continue;
153
+ const agent = await getAgent(runtime.client, source.pane);
154
+ if (
155
+ agent.agent === "pi" &&
156
+ agent.terminal_id === source.terminal &&
157
+ sessionPath(agent) === source.sessionFile &&
158
+ !agent.launch_pending &&
159
+ agent.interactive_ready !== false
160
+ )
161
+ routes.push(runtime.machine);
162
+ } catch {
163
+ // A disconnected or changed source is not a return route.
164
+ }
165
+ }
166
+ if (!routes.length)
167
+ throw new Error(
168
+ "No live return route from the destination; ask the user to connect the source machine in the destination's /herdr panel, then retry",
169
+ );
170
+ const machine = routes.includes("local") ? "local" : routes[0]!;
171
+ const tools = pi.getActiveTools();
172
+ const { returnFocus, content } = focusArrivalContent(
173
+ request,
174
+ machine,
175
+ tools.includes("exec") ||
176
+ tools.includes("code") ||
177
+ tools.includes("notebook"),
178
+ );
179
+ // Recheck the receiver session after remote route verification, before mutation.
180
+ if (ctx.sessionManager.getSessionFile() !== sessionPath(pane))
181
+ throw new Error("Destination session changed; resolve it again");
182
+ const local = fleet.connected();
183
+ const current = await getAgent(local.client, pane.pane_id);
184
+ if (
185
+ current.terminal_id !== pane.terminal_id ||
186
+ sessionPath(current) !== sessionPath(pane)
187
+ )
188
+ throw new Error("Destination session changed; resolve it again");
189
+ try {
190
+ await local.client.request("agent.focus", { target: pane.pane_id });
191
+ } catch (error) {
192
+ if (isDispatchRejected(error)) throw error;
193
+ throw Object.assign(
194
+ new Error(
195
+ `Focus was not confirmed; inspect the destination before retrying: ${String(error)}`,
196
+ ),
197
+ { focusChanged: true },
198
+ );
199
+ }
200
+ // Custom data persists immediately, even during a tool call, without inserting
201
+ // a model message between that call and its result or starting an agent turn.
202
+ try {
203
+ pi.appendEntry(ARRIVAL, {
204
+ content,
205
+ source: { ...source, machine },
206
+ returnFocus,
207
+ timestamp: Date.now(),
208
+ });
209
+ await recordContextBriefing(
210
+ pi,
211
+ ctx,
212
+ ARRIVAL,
213
+ randomUUID(),
214
+ async () => content,
215
+ );
216
+ } catch (error) {
217
+ throw Object.assign(
218
+ new Error(
219
+ `Session focused, but arrival could not be saved; inspect the destination before retrying: ${String(error)}`,
220
+ ),
221
+ { focusChanged: true },
222
+ );
223
+ }
224
+ ctx.ui.notify("Session focused", "info");
225
+ }
226
+
227
+ export function registerFocusArrivals(pi: ExtensionAPI): void {
228
+ registerContextBriefing(
229
+ pi,
230
+ "session arrivals",
231
+ (ctx) =>
232
+ ctx.sessionManager
233
+ .getBranch()
234
+ .some(
235
+ (entry) =>
236
+ entry.type === "custom" &&
237
+ (entry.customType === ARRIVAL ||
238
+ entry.customType === "herdr-voice-focus-report"),
239
+ ),
240
+ async () => undefined,
241
+ );
242
+ }
@@ -49,6 +49,22 @@ export async function spawnAgent(
49
49
  ctx: ExtensionContext,
50
50
  board: AgentBoard,
51
51
  ) {
52
+ const boardThreadId =
53
+ params.board_thread_id === undefined
54
+ ? undefined
55
+ : required(params.board_thread_id, "board_thread_id");
56
+ if (boardThreadId !== undefined) {
57
+ await board.execute(
58
+ ctx,
59
+ {
60
+ action: "read_thread",
61
+ thread_id: boardThreadId,
62
+ limit: 1,
63
+ max_chars_per_post: 1,
64
+ },
65
+ crypto.randomUUID(),
66
+ );
67
+ }
52
68
  const profiles = await loadAgentProfiles();
53
69
  const profileName = required(params.agent_type, "agent_type");
54
70
  const profile = profiles.get(profileName);
@@ -102,6 +118,13 @@ export async function spawnAgent(
102
118
  attributedMessage.context = [attributedMessage.context, message]
103
119
  .filter(Boolean)
104
120
  .join("\n\n");
121
+ if (boardThreadId !== undefined)
122
+ attributedMessage.context = [
123
+ attributedMessage.context,
124
+ `Read shared board thread with board({action:"read_thread",thread_id:${JSON.stringify(boardThreadId)}}) for task context`,
125
+ ]
126
+ .filter(Boolean)
127
+ .join("\n\n");
105
128
  reportProgress(onUpdate, `Spawning ${label}`, {
106
129
  machine: runtime.machine,
107
130
  name,
@@ -1,4 +1,8 @@
1
- import { defineTool, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ defineTool,
3
+ type ExtensionAPI,
4
+ getMarkdownTheme,
5
+ } from "@earendil-works/pi-coding-agent";
2
6
  import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
3
7
  import { answerAgent } from "./agents-answer.js";
4
8
  import {
@@ -14,6 +18,7 @@ import {
14
18
  listFleetAgents,
15
19
  readAgentTerminal,
16
20
  } from "./agents-discovery.js";
21
+ import { focusAgent } from "./agents-focus.js";
17
22
  import { spawnAgent } from "./agents-spawn.js";
18
23
  import {
19
24
  dispatchAgentWork,
@@ -30,11 +35,12 @@ export function createAgentsTool(
30
35
  fleet: AgentFleet,
31
36
  sharedContext: SharedAgentContext,
32
37
  board: AgentBoard,
38
+ pi: ExtensionAPI,
33
39
  ) {
34
40
  return defineTool({
35
41
  name: "agents",
36
42
  label: "Shepherdr",
37
- description: "Delegate to persistent agents; call help first, alone",
43
+ description: "Delegate to persistent agents; discover first, alone",
38
44
  parameters: AgentsParameters,
39
45
  executionMode: "sequential",
40
46
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
@@ -42,7 +48,7 @@ export function createAgentsTool(
42
48
  const executionSignal = signal ?? new AbortController().signal;
43
49
  const update = onUpdate ?? (() => undefined);
44
50
  if (params.action === "help") {
45
- return toolResult(await agentsHelp());
51
+ return toolResult(await agentsHelp(board.enabled(ctx)));
46
52
  }
47
53
  if (params.action === "list") {
48
54
  return toolResult(await listFleetAgents(fleet, params));
@@ -51,7 +57,7 @@ export function createAgentsTool(
51
57
  return toolResult(await findFleetAgents(fleet, params));
52
58
  }
53
59
 
54
- const runtime = fleet.connected(params.machine);
60
+ let runtime = fleet.connected(params.machine);
55
61
  if (params.action === "spawn") {
56
62
  return spawnAgent(
57
63
  fleet,
@@ -65,7 +71,30 @@ export function createAgentsTool(
65
71
  );
66
72
  }
67
73
 
68
- const target = required(params.target, "target");
74
+ let target = required(params.target, "target");
75
+ if (target === "/root") {
76
+ const root = await sharedContext.resolveRoot(
77
+ ctx,
78
+ params.machine,
79
+ executionSignal,
80
+ );
81
+ runtime = root.runtime;
82
+ target = root.target;
83
+ }
84
+ if (params.action === "focus") {
85
+ executionSignal.throwIfAborted();
86
+ return toolResult(
87
+ await focusAgent(
88
+ pi,
89
+ ctx,
90
+ fleet,
91
+ runtime,
92
+ target,
93
+ params.voice ?? false,
94
+ params.handoff,
95
+ ),
96
+ );
97
+ }
69
98
  if (params.action === "unwatch") {
70
99
  const record = runtime.monitor
71
100
  .list()
@@ -1,10 +1,10 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import { Type } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { BindingSchema } from "@howaboua/pi-agent-board/integration";
4
5
  import type { SharedContextResult } from "@howaboua/pi-codex-conversion/context-sharing";
5
6
  import type { Static, TSchema } from "typebox";
6
7
  import { Check } from "typebox/value";
7
- import { BindingSchema } from "./board/identity.js";
8
8
 
9
9
  const AgentPath = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
10
10
  export const Identity = Type.Object({
@@ -112,7 +112,11 @@ export function remapResult(
112
112
  to: string,
113
113
  ): SharedContextResult {
114
114
  if (
115
- typeof result.details.codexHistoryNotes["encrypted_output"] === "string"
115
+ typeof result.details.codexHistoryNotes["encrypted_output"] === "string" ||
116
+ ("externalNotesResponses" in result.details &&
117
+ Array.isArray(result.details.externalNotesResponses) &&
118
+ result.details.externalNotesResponses.length > 0) ||
119
+ Object.keys(result.details.codexHistoryNotes).length === 0
116
120
  ) {
117
121
  const hint = `Source ${from}, access through ${to}. Use ${to}/notes for note paths and ${to} for history agent_name`;
118
122
  // Ciphertext paths cannot be remapped. Preserve host-only provenance on the original details.
@@ -132,7 +136,7 @@ export function remapResult(
132
136
  return {
133
137
  ...result,
134
138
  content: [{ type: "text", text: JSON.stringify(details) }],
135
- details: { codexHistoryNotes: details },
139
+ details: { ...result.details, codexHistoryNotes: details },
136
140
  };
137
141
  }
138
142
 
@@ -3,6 +3,7 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import { binding } from "@howaboua/pi-agent-board/integration";
6
7
  import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
7
8
  import type { Static } from "typebox";
8
9
  import { Check } from "typebox/value";
@@ -19,7 +20,6 @@ import {
19
20
  Plan,
20
21
  } from "./attachment-protocol.js";
21
22
  import type { AgentBoard } from "./board/host.js";
22
- import { binding } from "./board/identity.js";
23
23
  import { sendPolicyMessage } from "./delivery.js";
24
24
  import { attachmentMessage, detachmentMessage } from "./messages.js";
25
25
 
@@ -125,6 +125,7 @@ export class AttachmentTarget {
125
125
  )
126
126
  throw new Error("Invalid attachment request");
127
127
  const plan = input.plan as AttachmentPlan;
128
+ if (plan.board) this.board.requireAvailable();
128
129
  if (
129
130
  (!plan.context && !plan.board) ||
130
131
  plan.controllerSessionId === plan.targetSessionId ||
@@ -254,6 +255,7 @@ export class AttachmentTarget {
254
255
  ) {
255
256
  if (!Check(Detachment, input)) throw new Error("Invalid detach request");
256
257
  const requested = input as Static<typeof Detachment>;
258
+ if (requested.board) this.board.requireAvailable();
257
259
  const { plan } = requested;
258
260
  if (
259
261
  !isDeepStrictEqual(attachmentOwner(ctx), plan) ||
package/src/attachment.ts CHANGED
@@ -4,6 +4,7 @@ import type {
4
4
  ExtensionAPI,
5
5
  ExtensionContext,
6
6
  } from "@earendil-works/pi-coding-agent";
7
+ import { binding } from "@howaboua/pi-agent-board/integration";
7
8
  import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
8
9
  import type { Static } from "typebox";
9
10
  import { Check } from "typebox/value";
@@ -19,7 +20,6 @@ import {
19
20
  import { AttachmentRouting } from "./attachment-routing.js";
20
21
  import { AttachmentTarget } from "./attachment-target.js";
21
22
  import type { AgentBoard } from "./board/host.js";
22
- import { binding } from "./board/identity.js";
23
23
  import type { ConnectedMachine } from "./fleet.js";
24
24
  import { sessionPath } from "./herdr.js";
25
25
  import { sessionContextPath } from "./remote/shepherdr-context.mjs";
@@ -50,6 +50,7 @@ export class AgentAttachment {
50
50
  params: AgentsParams,
51
51
  signal: AbortSignal,
52
52
  ) {
53
+ if (params.board) this.board.requireAvailable();
53
54
  const sessionFile = sessionPath(panel);
54
55
  const controllerFile = ctx.sessionManager.getSessionFile();
55
56
  const controllerSessionId = ctx.sessionManager.getSessionId();
@@ -213,6 +214,7 @@ export class AgentAttachment {
213
214
  params: AgentsParams,
214
215
  signal: AbortSignal,
215
216
  ) {
217
+ if (params.board) this.board.requireAvailable();
216
218
  const route = attachmentRoutes(ctx).find(
217
219
  (entry) =>
218
220
  entry.machine === runtime.machine &&