@howaboua/pi-shepherdr 0.2.22 → 0.2.24

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 (61) hide show
  1. package/CHANGELOG.md +16 -18
  2. package/README.md +79 -58
  3. package/biome.json +1 -1
  4. package/index.ts +7 -3
  5. package/package.json +14 -9
  6. package/src/agents-discovery.ts +42 -27
  7. package/src/agents-focus.ts +2 -2
  8. package/src/agents-reply.ts +1 -1
  9. package/src/agents-spawn.ts +143 -137
  10. package/src/agents-tool.ts +3 -3
  11. package/src/agents-work.ts +33 -9
  12. package/src/attachment-notes.ts +14 -2
  13. package/src/attachment-protocol.ts +21 -4
  14. package/src/attachment-routing.ts +1 -1
  15. package/src/attachment-target.ts +5 -2
  16. package/src/attachment.ts +2 -3
  17. package/src/board/host.ts +2 -2
  18. package/src/board/membership.ts +1 -1
  19. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  20. package/src/{control-panel.ts → control-panel/index.ts} +4 -4
  21. package/src/{control-panel-items.ts → control-panel/items.ts} +3 -3
  22. package/src/{control-panel-view.ts → control-panel/view.ts} +3 -3
  23. package/src/controller.ts +6 -3
  24. package/src/fleet/index.ts +384 -0
  25. package/src/fleet/inspection.ts +141 -0
  26. package/src/fleet/machine.ts +52 -0
  27. package/src/fleet/monitor.ts +71 -0
  28. package/src/fleet/persistence.ts +42 -0
  29. package/src/fleet/reconnect.ts +75 -0
  30. package/src/fleet/setup.ts +92 -0
  31. package/src/launch.ts +14 -2
  32. package/src/messages/attachments.ts +39 -0
  33. package/src/messages/attribution.ts +75 -0
  34. package/src/messages/event-details.ts +69 -0
  35. package/src/messages/events.ts +189 -0
  36. package/src/messages/focus.ts +38 -0
  37. package/src/messages/guidance.ts +83 -0
  38. package/src/messages/render.ts +89 -0
  39. package/src/messages/voice-announcements.ts +79 -0
  40. package/src/monitor-extension-messages.ts +14 -1
  41. package/src/monitor.ts +4 -2
  42. package/src/peer-inbox.ts +2 -2
  43. package/src/profile-prompt.ts +32 -0
  44. package/src/profiles.ts +5 -25
  45. package/src/remote/client.ts +127 -0
  46. package/src/remote/context-relay.ts +84 -0
  47. package/src/remote/deployment.ts +179 -0
  48. package/src/remote/focus-channels.ts +89 -0
  49. package/src/remote/transport.ts +369 -0
  50. package/src/settlement/collector.ts +122 -0
  51. package/src/settlement/delivery.ts +144 -0
  52. package/src/{settlement.ts → settlement/index.ts} +23 -233
  53. package/src/shared-context-host.ts +33 -11
  54. package/src/shared-context.ts +10 -4
  55. package/src/spawn-context.ts +20 -17
  56. package/src/voice-handoff.ts +1 -1
  57. package/src/worker-role.ts +83 -0
  58. package/src/worker-service.ts +74 -89
  59. package/src/fleet.ts +0 -702
  60. package/src/messages.ts +0 -629
  61. package/src/remote-client.ts +0 -751
@@ -0,0 +1,75 @@
1
+ import type { MachineRuntime } from "./machine.js";
2
+
3
+ /** Explicit reconnect selection and user receipts; never schedules autonomous reconnects. */
4
+ export function connectMachines(
5
+ runtimes: ReadonlyMap<string, MachineRuntime>,
6
+ machine: string | undefined,
7
+ retrySetup: (name: string, runtime: MachineRuntime) => Promise<void>,
8
+ connectMachine: (name: string) => Promise<void>,
9
+ ): string {
10
+ const target = machine?.trim();
11
+ if (target) {
12
+ const runtime = runtimes.get(target);
13
+ if (!runtime)
14
+ throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
15
+ if (
16
+ runtime.status === "connected" &&
17
+ (runtime.monitoringIssue || runtime.contextRelayError)
18
+ ) {
19
+ if (runtime.attempting)
20
+ return `Already retrying connection setup on ${target}`;
21
+ void retrySetup(target, runtime);
22
+ return `Retrying connection setup on ${target}`;
23
+ }
24
+ if (runtime.local) {
25
+ return `${target} is the local machine and is already connected`;
26
+ }
27
+ if (runtime.status === "connected") {
28
+ return `${target} is already connected`;
29
+ }
30
+ if (runtime.attempting || runtime.status === "connecting") {
31
+ return `${target} is already connecting`;
32
+ }
33
+ void connectMachine(target);
34
+ return `Connecting to ${target}`;
35
+ }
36
+
37
+ const retries = [...runtimes.entries()].filter(
38
+ ([, runtime]) =>
39
+ runtime.status === "connected" &&
40
+ (runtime.monitoringIssue || runtime.contextRelayError) &&
41
+ !runtime.attempting,
42
+ );
43
+ for (const [name, runtime] of retries) void retrySetup(name, runtime);
44
+ const names = [...runtimes.entries()]
45
+ .filter(
46
+ ([, runtime]) =>
47
+ !runtime.local && runtime.status !== "connected" && !runtime.attempting,
48
+ )
49
+ .map(([name]) => name);
50
+ for (const name of names) {
51
+ void connectMachine(name);
52
+ }
53
+ if (names.length > 0 || retries.length > 0) {
54
+ return [
55
+ retries.length > 0
56
+ ? `Retrying connection setup on ${retries.map(([name]) => name).join(", ")}`
57
+ : "",
58
+ names.length > 0 ? `Connecting to ${names.join(", ")}` : "",
59
+ ]
60
+ .filter(Boolean)
61
+ .join(". ");
62
+ }
63
+ const remotes = [...runtimes.entries()].filter(
64
+ ([, runtime]) => !runtime.local,
65
+ );
66
+ if (remotes.length === 0) {
67
+ return "No remote machines are configured";
68
+ }
69
+ const connecting = remotes
70
+ .filter(([, runtime]) => runtime.attempting)
71
+ .map(([name]) => name);
72
+ return connecting.length > 0
73
+ ? `Already connecting to ${connecting.join(", ")}`
74
+ : "All configured machines are connected";
75
+ }
@@ -0,0 +1,92 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { RemoteHerdrClient } from "../remote/client.js";
3
+ import { errorMessage, type MachineRuntime } from "./machine.js";
4
+
5
+ /** Explicitly requested sharing/monitor readiness; fleet supplies current-selection leases. */
6
+ export class FleetSetup {
7
+ private readonly refresh: () => void;
8
+ constructor(refresh: () => void) {
9
+ this.refresh = refresh;
10
+ }
11
+ private contextRelay:
12
+ | ((
13
+ ctx: ExtensionContext,
14
+ request: unknown,
15
+ signal: AbortSignal,
16
+ ) => Promise<unknown>)
17
+ | undefined;
18
+ setContextRelay(
19
+ handler: (
20
+ ctx: ExtensionContext,
21
+ request: unknown,
22
+ signal: AbortSignal,
23
+ ) => Promise<unknown>,
24
+ ): void {
25
+ this.contextRelay = handler;
26
+ }
27
+ async prepareContextRelay(
28
+ name: string,
29
+ runtime: MachineRuntime,
30
+ client: RemoteHerdrClient,
31
+ ctx: ExtensionContext,
32
+ isSelected: () => boolean,
33
+ ): Promise<void> {
34
+ if (!this.contextRelay) return;
35
+ try {
36
+ await client.startContextRelay(
37
+ ctx.sessionManager.getSessionId(),
38
+ name,
39
+ (request, signal) => this.contextRelay!(ctx, request, signal),
40
+ );
41
+ if (!isSelected()) return;
42
+ delete runtime.contextRelayError;
43
+ } catch (error) {
44
+ if (!isSelected()) return;
45
+ runtime.contextRelayError = errorMessage(error);
46
+ ctx.ui.notify(
47
+ `Context sharing unavailable on ${name}: ${runtime.contextRelayError}\nOpen /herdr → Status to retry sharing.`,
48
+ "warning",
49
+ );
50
+ }
51
+ }
52
+
53
+ async retrySetup(
54
+ name: string,
55
+ runtime: MachineRuntime,
56
+ ctx: ExtensionContext | undefined,
57
+ isCurrent: () => boolean,
58
+ isRegistered: () => boolean,
59
+ isSelected: () => boolean,
60
+ ): Promise<void> {
61
+ const monitor = runtime.monitor;
62
+ if (!monitor || !ctx || runtime.attempting) return;
63
+ runtime.attempting = true;
64
+ this.refresh();
65
+ try {
66
+ if (
67
+ runtime.contextRelayError &&
68
+ runtime.client instanceof RemoteHerdrClient
69
+ )
70
+ await this.prepareContextRelay(
71
+ name,
72
+ runtime,
73
+ runtime.client,
74
+ ctx,
75
+ isSelected,
76
+ );
77
+ if (isCurrent() && isRegistered() && runtime.monitoringIssue)
78
+ await monitor.retryMonitoring();
79
+ } catch (error) {
80
+ if (isCurrent() && isRegistered() && runtime.monitor === monitor) {
81
+ ctx.ui.notify(
82
+ `Monitoring retry failed on ${name}: ${errorMessage(error)}`,
83
+ "warning",
84
+ );
85
+ }
86
+ } finally {
87
+ if (isRegistered() && runtime.monitor === monitor)
88
+ delete runtime.attempting;
89
+ this.refresh();
90
+ }
91
+ }
92
+ }
package/src/launch.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from "./herdr.js";
12
12
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
13
13
  import type { PaneInfo } from "./types.js";
14
+ import { WORKER_FLAG } from "./worker-role.js";
14
15
 
15
16
  export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
16
17
  const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
@@ -227,8 +228,19 @@ export async function startAgent(
227
228
  );
228
229
  }
229
230
  const label = params.label?.trim() || name;
230
- const args = ["--name", label, ...(options.agentArgs ?? [])];
231
- if (parseArgs(args).noSession) {
231
+ const args = [
232
+ `--${WORKER_FLAG}`,
233
+ "--name",
234
+ label,
235
+ ...(options.agentArgs ?? []),
236
+ ];
237
+ const parsed = parseArgs(args);
238
+ if (parsed.unknownFlags.get(WORKER_FLAG) !== true) {
239
+ throw new Error(
240
+ "spawn requires its worker role; remove --shepherdr-worker from profile pi_args",
241
+ );
242
+ }
243
+ if (parsed.noSession) {
232
244
  throw new Error(
233
245
  "spawn requires a persistent Pi session; remove --no-session from profile pi_args",
234
246
  );
@@ -0,0 +1,39 @@
1
+ import type { BoardBinding } from "@howaboua/pi-agent-board/integration";
2
+
3
+ export function attachmentMessage(
4
+ controllerContextAgent?: string,
5
+ boardAgent?: string,
6
+ ) {
7
+ return {
8
+ customType: "herdr-agent-attachment",
9
+ content: [
10
+ ...(controllerContextAgent
11
+ ? [
12
+ `Controller notes/history: ${controllerContextAgent}; own context unchanged`,
13
+ ]
14
+ : []),
15
+ ...(boardAgent ? [`Shared board: ${boardAgent}`] : []),
16
+ ].join("\n"),
17
+ display: true,
18
+ };
19
+ }
20
+
21
+ export function detachmentMessage(
22
+ controllerContextAgent?: string,
23
+ board?: BoardBinding,
24
+ ) {
25
+ return {
26
+ customType: "herdr-agent-detachment",
27
+ content: [
28
+ ...(controllerContextAgent
29
+ ? [
30
+ `Detached controller: ${controllerContextAgent}; checkpoints read-only, history unavailable; own context unchanged`,
31
+ ]
32
+ : []),
33
+ ...(board
34
+ ? [`Board restored: ${board.boardId} as ${board.agentName}`]
35
+ : []),
36
+ ].join("\n"),
37
+ display: true,
38
+ };
39
+ }
@@ -0,0 +1,75 @@
1
+ import { hostname } from "node:os";
2
+ import { getCurrentPane, getSnapshot } from "../herdr.js";
3
+ import type { HerdrConnection } from "../herdr-client.js";
4
+ import type { PaneInfo, PeerMessage } from "../types.js";
5
+
6
+ const DELEGATED_WORKER_GUIDANCE =
7
+ "If blocked mid-run, use a question-asking tool, not peer messages. Without one, end with the blocker. Finish with an assistant reply, not a separate send report; never watch your parent.";
8
+
9
+ export function xml(value: string): string {
10
+ return value
11
+ .replaceAll("&", "&amp;")
12
+ .replaceAll("<", "&lt;")
13
+ .replaceAll(">", "&gt;")
14
+ .replaceAll('"', "&quot;")
15
+ .replaceAll("'", "&apos;");
16
+ }
17
+
18
+ export interface AgentEventLabels {
19
+ tab?: string;
20
+ workspace?: string;
21
+ }
22
+
23
+ export function agentSource(agent: PaneInfo, labels: AgentEventLabels) {
24
+ const paneName = agent.label || agent.title;
25
+ return {
26
+ pane: agent.pane_id,
27
+ workspace: agent.workspace_id,
28
+ tab: agent.tab_id,
29
+ ...(agent.name ? { name: agent.name } : {}),
30
+ ...(paneName ? { pane_name: paneName } : {}),
31
+ ...(labels.workspace ? { workspace_name: labels.workspace } : {}),
32
+ ...(labels.tab ? { tab_name: labels.tab } : {}),
33
+ };
34
+ }
35
+
36
+ export function sourceAttributes(
37
+ source: Record<string, string | undefined>,
38
+ ): string {
39
+ return Object.entries(source)
40
+ .filter((entry): entry is [string, string] => entry[1] !== undefined)
41
+ .map(
42
+ ([key, value]) =>
43
+ `${key}="${xml(value).replaceAll("\n", "&#10;").replaceAll("\r", "&#13;")}"`,
44
+ )
45
+ .join(" ");
46
+ }
47
+
48
+ export async function attributeAgentPrompt(
49
+ client: HerdrConnection,
50
+ message: string,
51
+ kind: "message" | "task",
52
+ ): Promise<PeerMessage> {
53
+ const [pane, snapshot] = await Promise.all([
54
+ getCurrentPane(client),
55
+ getSnapshot(client),
56
+ ]);
57
+ const workspace = snapshot.workspaces.find(
58
+ (workspace) => workspace.workspace_id === pane.workspace_id,
59
+ )?.label;
60
+ const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
61
+ const source = {
62
+ kind,
63
+ host: hostname(),
64
+ session: process.env["HERDR_SESSION"] || "default",
65
+ ...agentSource(pane, {
66
+ ...(workspace ? { workspace } : {}),
67
+ ...(tab ? { tab } : {}),
68
+ }),
69
+ };
70
+ return {
71
+ sender: `<herdr_sender ${sourceAttributes(source)} />`,
72
+ text: message,
73
+ ...(kind === "task" ? { context: DELEGATED_WORKER_GUIDANCE } : {}),
74
+ };
75
+ }
@@ -0,0 +1,69 @@
1
+ import { readExtensionMessage } from "../remote/shepherdr-session.mjs";
2
+ import type { ExtensionMessage } from "../types.js";
3
+ export const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
4
+
5
+ export interface AgentEventDetails {
6
+ extensionMessages?: ExtensionMessage[];
7
+ blockedOn?: string;
8
+ cwd?: string;
9
+ machine: string;
10
+ machineLabel?: string;
11
+ name?: string;
12
+ paneId: string;
13
+ response?: string;
14
+ state: "blocked" | "failed" | "finished" | "extension-message";
15
+ tab?: string;
16
+ task?: string;
17
+ workspace?: string;
18
+ }
19
+
20
+ function eventExtensionMessages(
21
+ value: unknown,
22
+ ): ExtensionMessage[] | undefined {
23
+ if (!Array.isArray(value)) return undefined;
24
+ const messages = value.map((message) => {
25
+ if (typeof message !== "object" || message === null) return undefined;
26
+ return readExtensionMessage({ ...message, version: 1, state: "pending" });
27
+ });
28
+ return messages.every((message) => message !== undefined)
29
+ ? messages
30
+ : undefined;
31
+ }
32
+
33
+ export function eventDetails(value: unknown): AgentEventDetails | undefined {
34
+ if (typeof value !== "object" || value === null) return undefined;
35
+ const details = value as Record<string, unknown>;
36
+ if (
37
+ typeof details["paneId"] !== "string" ||
38
+ (details["machine"] !== undefined &&
39
+ typeof details["machine"] !== "string") ||
40
+ (details["state"] !== "blocked" &&
41
+ details["state"] !== "extension-message" &&
42
+ details["state"] !== "failed" &&
43
+ details["state"] !== "finished")
44
+ ) {
45
+ return undefined;
46
+ }
47
+ const optional = (field: keyof AgentEventDetails) =>
48
+ typeof details[field] === "string"
49
+ ? { [field]: details[field] as string }
50
+ : {};
51
+ const extensionMessages = eventExtensionMessages(
52
+ details["extensionMessages"],
53
+ );
54
+ return {
55
+ machine:
56
+ typeof details["machine"] === "string" ? details["machine"] : "local",
57
+ paneId: details["paneId"],
58
+ state: details["state"],
59
+ ...(extensionMessages ? { extensionMessages } : {}),
60
+ ...optional("blockedOn"),
61
+ ...optional("cwd"),
62
+ ...optional("machineLabel"),
63
+ ...optional("name"),
64
+ ...optional("response"),
65
+ ...optional("tab"),
66
+ ...optional("task"),
67
+ ...optional("workspace"),
68
+ };
69
+ }
@@ -0,0 +1,189 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { activityTask } from "../activity.js";
6
+ import { sendPolicyMessage } from "../delivery.js";
7
+ import type {
8
+ ExtensionMessage,
9
+ LatestAssistant,
10
+ MonitoredAgent,
11
+ PaneInfo,
12
+ SettledAgentStatus,
13
+ } from "../types.js";
14
+ import {
15
+ type AgentEventLabels,
16
+ agentSource,
17
+ sourceAttributes,
18
+ xml,
19
+ } from "./attribution.js";
20
+ import {
21
+ AGENT_EVENT_MESSAGE_TYPE,
22
+ type AgentEventDetails,
23
+ } from "./event-details.js";
24
+ import { agentVoicePrompt, announceAgentEvent } from "./voice-announcements.js";
25
+
26
+ interface AgentEventOptions {
27
+ agent: PaneInfo;
28
+ agentToolName: string;
29
+ codeMode?: boolean;
30
+ extensionMessages?: ExtensionMessage[];
31
+ blockedMessage?: string;
32
+ labels: AgentEventLabels;
33
+ machine: string;
34
+ machineLabel: string;
35
+ operatorPrefix: string;
36
+ record: MonitoredAgent;
37
+ reply?: LatestAssistant;
38
+ status: SettledAgentStatus | "extension-message";
39
+ }
40
+
41
+ function operatorCommand(operatorPrefix: string, command: string): string {
42
+ return `\`${operatorPrefix} ${command}\``;
43
+ }
44
+
45
+ function blockedOperatorHint(
46
+ agentToolName: string,
47
+ machine: string,
48
+ operatorPrefix: string,
49
+ paneId: string,
50
+ ): string {
51
+ return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through ${agentToolName} with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
52
+ }
53
+
54
+ function failedOperatorHint(
55
+ agentToolName: string,
56
+ machine: string,
57
+ operatorPrefix: string,
58
+ paneId: string,
59
+ ): string {
60
+ return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through ${agentToolName} with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
61
+ }
62
+
63
+ function agentEvent(options: AgentEventOptions): {
64
+ content: string;
65
+ details: AgentEventDetails;
66
+ } {
67
+ const {
68
+ agent,
69
+ agentToolName,
70
+ codeMode,
71
+ extensionMessages,
72
+ blockedMessage,
73
+ labels,
74
+ machine,
75
+ machineLabel,
76
+ operatorPrefix,
77
+ record,
78
+ reply,
79
+ status,
80
+ } = options;
81
+ const task = activityTask(record.activity);
82
+ const blocked = status === "blocked";
83
+ const notification = status === "extension-message";
84
+ const failed = !blocked && reply?.stopReason === "error";
85
+ const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
86
+ const tag = notification
87
+ ? "herdr_agent_extension_message"
88
+ : blocked
89
+ ? "herdr_agent_blocked"
90
+ : failed
91
+ ? "herdr_agent_failed"
92
+ : "herdr_agent_result";
93
+ const attributes = sourceAttributes({
94
+ machine,
95
+ machine_name: machineLabel !== machine ? machineLabel : undefined,
96
+ ...agentSource(agent, labels),
97
+ name: agent.name ?? record.name,
98
+ directory: cwd,
99
+ });
100
+ const lines = [`<${tag} ${attributes}>`];
101
+ if (task && !notification) lines.push(`<task>${xml(task)}</task>`);
102
+ if (blockedMessage) {
103
+ lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
104
+ }
105
+ for (const message of extensionMessages ?? []) {
106
+ lines.push(message.message);
107
+ if (message.reply !== undefined) {
108
+ const request = {
109
+ action: "reply",
110
+ machine,
111
+ target: agent.pane_id,
112
+ extension: message.extension,
113
+ id: message.id,
114
+ message: message.reply,
115
+ };
116
+ const call = codeMode
117
+ ? `await tools.${agentToolName}(${JSON.stringify(request)})`
118
+ : `${agentToolName} ${JSON.stringify(request)}`;
119
+ lines.push(`Reply: ${call}`);
120
+ }
121
+ }
122
+ if (blocked) {
123
+ lines.push(
124
+ `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
125
+ );
126
+ }
127
+ if (failed) {
128
+ lines.push(
129
+ `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
130
+ );
131
+ }
132
+ if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
133
+ lines.push(`</${tag}>`);
134
+
135
+ return {
136
+ content: lines.join("\n"),
137
+ details: {
138
+ machine,
139
+ machineLabel,
140
+ paneId: agent.pane_id,
141
+ state: notification
142
+ ? "extension-message"
143
+ : blocked
144
+ ? "blocked"
145
+ : failed
146
+ ? "failed"
147
+ : "finished",
148
+ ...(extensionMessages ? { extensionMessages } : {}),
149
+ ...(agent.name || record.name ? { name: agent.name || record.name } : {}),
150
+ ...(cwd ? { cwd } : {}),
151
+ ...(labels.workspace ? { workspace: labels.workspace } : {}),
152
+ ...(labels.tab ? { tab: labels.tab } : {}),
153
+ ...(task && !notification ? { task } : {}),
154
+ ...(blockedMessage ? { blockedOn: blockedMessage } : {}),
155
+ ...(reply ? { response: reply.text } : {}),
156
+ },
157
+ };
158
+ }
159
+
160
+ export function injectAgentEvent(
161
+ pi: ExtensionAPI,
162
+ _ctx: ExtensionContext,
163
+ options: AgentEventOptions,
164
+ ): void {
165
+ const tools = pi.getActiveTools();
166
+ const message = agentEvent({
167
+ ...options,
168
+ codeMode:
169
+ tools.includes("exec") ||
170
+ tools.includes("code") ||
171
+ tools.includes("notebook"),
172
+ });
173
+ const delivery = { triggerTurn: true, deliverAs: "steer" as const };
174
+ sendPolicyMessage(
175
+ pi,
176
+ {
177
+ customType: AGENT_EVENT_MESSAGE_TYPE,
178
+ content: message.content,
179
+ details: message.details,
180
+ display: true,
181
+ },
182
+ delivery,
183
+ );
184
+ announceAgentEvent(
185
+ pi,
186
+ `pi-shepherdr:${message.details.machine}:${message.details.paneId}`,
187
+ agentVoicePrompt(message.details),
188
+ );
189
+ }
@@ -0,0 +1,38 @@
1
+ import type { FocusRequest } from "../types.js";
2
+
3
+ function focusOrigin({ source }: FocusRequest) {
4
+ return { host: source.host, session: source.session, pane: source.pane };
5
+ }
6
+
7
+ export function focusArrivalContent(
8
+ request: FocusRequest,
9
+ machine: string,
10
+ codeMode: boolean,
11
+ ) {
12
+ const returnFocus = {
13
+ action: "focus",
14
+ target: request.source.pane,
15
+ machine,
16
+ voice: request.voice === true,
17
+ };
18
+ const args = JSON.stringify(returnFocus);
19
+ const callable = codeMode ? `await tools.agents(${args})` : `agents ${args}`;
20
+ return {
21
+ returnFocus,
22
+ content: `User arrived from ${JSON.stringify({ ...focusOrigin(request), machine })}\nReturn: ${callable}${request.voice ? "\nVoice transfer pending" : ""}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`,
23
+ };
24
+ }
25
+
26
+ export function voiceFocusContinuity(request: FocusRequest): string {
27
+ return `User transferring voice from ${JSON.stringify(focusOrigin(request))}${request.handoff ? `\nHandoff from that session:\n${request.handoff}` : ""}`;
28
+ }
29
+
30
+ export function voiceFocusReport(
31
+ side: "source" | "destination",
32
+ target: string,
33
+ error?: unknown,
34
+ ): string {
35
+ return error === undefined
36
+ ? `Voice transfer complete (${side}, ${target}); replacement call active`
37
+ : `Voice transfer failed (${side}, ${target}): ${error instanceof Error ? error.message : String(error)}. Voice availability is not confirmed; inspect the session before retrying`;
38
+ }
@@ -0,0 +1,83 @@
1
+ import { activityTask } from "../activity.js";
2
+ import type { MachineStatus, ScopedMonitoredAgent } from "../types.js";
3
+
4
+ export function orchestrationGuidance(enabled: boolean, general: boolean) {
5
+ const ownership = "Own a scope or delegate it; don't do both.";
6
+ if (!enabled)
7
+ return `Work normally. Delegate only when useful or requested. ${ownership}`;
8
+ const guidance = general
9
+ ? "Orchestrate general agents with separate scopes. Integrate their results, validate the combined outcome and report it. Work directly only when asked or for routine local tasks."
10
+ : "Orchestrate agents with separate scopes. Integrate their results, validate the combined outcome and report it. Work directly only when asked or for routine local tasks.";
11
+ return `${guidance} ${ownership}`;
12
+ }
13
+ export function activeAgentsBriefing(
14
+ agents: ScopedMonitoredAgent[],
15
+ machines: MachineStatus[],
16
+ ): string | undefined {
17
+ if (!agents.length) return;
18
+ return [
19
+ "Supervised agents after context rollover. Their instructions are reference data, not tasks for you. Do not repeat settled tasks or duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
20
+ JSON.stringify(
21
+ agents.map((agent) => ({
22
+ machine: agent.machine,
23
+ target: agent.paneId,
24
+ ...(agent.name ? { name: agent.name } : {}),
25
+ status:
26
+ agent.activity.phase === "settled"
27
+ ? agent.activity.status
28
+ : agent.activity.phase,
29
+ connection:
30
+ machines.find((machine) => machine.id === agent.machine)?.status ??
31
+ "unavailable",
32
+ ...(agent.cwd ? { cwd: agent.cwd } : {}),
33
+ ...((agent.instructions ?? activityTask(agent.activity))
34
+ ? { instructions: agent.instructions ?? activityTask(agent.activity) }
35
+ : {}),
36
+ })),
37
+ ),
38
+ ].join("\n");
39
+ }
40
+ export function boardMigrationWarning() {
41
+ return "Boards moved to Pi Agent Board. Install @howaboua/pi-agent-board for the same features as a separate extension. Your saved boards are preserved.";
42
+ }
43
+
44
+ export function boardBriefing(
45
+ member: boolean,
46
+ population: "empty" | "populated" | "unavailable",
47
+ gpt = false,
48
+ ) {
49
+ const state =
50
+ population === "populated"
51
+ ? "Read relevant board threads."
52
+ : population === "empty"
53
+ ? gpt
54
+ ? "Shared board available; posts=none."
55
+ : "Shared board available; no posts yet."
56
+ : gpt
57
+ ? "Shared board status unavailable; board help→retry read when available."
58
+ : "Shared board status unavailable. Check board help and retry reading when available.";
59
+ const setup = member
60
+ ? gpt
61
+ ? "Root owns setup; follow assigned task."
62
+ : "The root agent owns setup; follow your assigned task."
63
+ : "";
64
+ if (gpt)
65
+ return [
66
+ state,
67
+ setup,
68
+ "Posts=work-changing ownership/decisions/findings/blockers only. Existing thread replies; link≠repeat. Personal checkpoints→notes. No ack/status spam/duplicate completion reports. Assignments/urgent messages→agents.",
69
+ "Channels=workstreams; threads=topics. Reuse relevant channels≠catchalls. New channel requires distinct coordination purpose; never task/result announcement only.",
70
+ ]
71
+ .filter(Boolean)
72
+ .join(" ");
73
+ return (
74
+ [
75
+ state,
76
+ setup,
77
+ "Post only new information that changes another agent's work: ownership, decisions, findings or blockers. Reply in existing threads; link rather than repeat. Keep personal checkpoints in notes. Skip acknowledgements, routine status and duplicated completion reports. Use agents for assignments and urgent messages.",
78
+ ]
79
+ .filter(Boolean)
80
+ .join(" ") +
81
+ "\n\nChannels group shared workstreams; threads group topics. Reuse a relevant channel, not a catch-all. Create a channel only for a distinct coordination need, never just to announce a task or result."
82
+ );
83
+ }