@howaboua/pi-shepherdr 0.2.23 → 0.2.25

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 (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
@@ -0,0 +1,151 @@
1
+ import { getSnapshot, parsePaneInfo, resolveWorkspace } from "./herdr.js";
2
+ import type { HerdrConnection } from "./herdr-client.js";
3
+ import {
4
+ type CreatedLocationCleanup,
5
+ RolledBackAgentLaunchError,
6
+ requiredStartField,
7
+ type StartAgentParams,
8
+ UnstartedAgentLaunchError,
9
+ } from "./launch-contract.js";
10
+ import type { PaneInfo } from "./types.js";
11
+
12
+ export async function createStartPane(
13
+ client: HerdrConnection,
14
+ params: StartAgentParams,
15
+ cwd: string,
16
+ label: string,
17
+ ): Promise<{
18
+ cleanup?: CreatedLocationCleanup;
19
+ paneId: string;
20
+ }> {
21
+ const placement = params.placement;
22
+ if (!placement) throw new Error("placement is required for start");
23
+ if (placement === "terminal")
24
+ throw new UnstartedAgentLaunchError(
25
+ "terminal placement requires Core; use new_tab or new_workspace in legacy Herdr",
26
+ );
27
+ if (placement === "pane") {
28
+ return { paneId: requiredStartField(params.pane, "pane") };
29
+ }
30
+ if (placement === "new_tab") {
31
+ const workspaceTarget = requiredStartField(params.workspace, "workspace");
32
+ let workspace;
33
+ try {
34
+ workspace = resolveWorkspace(await getSnapshot(client), workspaceTarget);
35
+ } catch (error) {
36
+ throw new UnstartedAgentLaunchError(error);
37
+ }
38
+ // A failed create response may still have created a location.
39
+ const created = createdLocation(
40
+ await client.request<unknown>("tab.create", {
41
+ workspace_id: workspace.workspace_id,
42
+ cwd,
43
+ label,
44
+ focus: false,
45
+ }),
46
+ "tab.create result",
47
+ );
48
+ return {
49
+ paneId: created.root_pane.pane_id,
50
+ cleanup: { method: "tab.close", id: created.tab.tab_id },
51
+ };
52
+ }
53
+ const created = createdLocation(
54
+ await client.request<unknown>("workspace.create", {
55
+ cwd,
56
+ focus: false,
57
+ }),
58
+ "workspace.create result",
59
+ true,
60
+ );
61
+ try {
62
+ await client.request("tab.rename", { tab_id: created.tab.tab_id, label });
63
+ } catch (error) {
64
+ return rollbackCreatedLocation(
65
+ client,
66
+ { method: "workspace.close", id: created.workspace.workspace_id },
67
+ error,
68
+ );
69
+ }
70
+ return {
71
+ paneId: created.root_pane.pane_id,
72
+ cleanup: { method: "workspace.close", id: created.workspace.workspace_id },
73
+ };
74
+ }
75
+
76
+ function createdLocation(
77
+ value: unknown,
78
+ path: string,
79
+ ): { root_pane: PaneInfo; tab: { tab_id: string } };
80
+ function createdLocation(
81
+ value: unknown,
82
+ path: string,
83
+ withWorkspace: true,
84
+ ): {
85
+ root_pane: PaneInfo;
86
+ tab: { tab_id: string };
87
+ workspace: { workspace_id: string };
88
+ };
89
+ function createdLocation(
90
+ value: unknown,
91
+ path: string,
92
+ withWorkspace = false,
93
+ ): {
94
+ root_pane: PaneInfo;
95
+ tab: { tab_id: string };
96
+ workspace?: { workspace_id: string };
97
+ } {
98
+ if (typeof value !== "object" || value === null) {
99
+ throw new Error(`Herdr ${path} must be an object`);
100
+ }
101
+ const result = value as Record<string, unknown>;
102
+ const tabId = nestedId(result["tab"], "tab_id", `${path}.tab`);
103
+ return {
104
+ root_pane: parsePaneInfo(result["root_pane"], `${path}.root_pane`),
105
+ tab: { tab_id: tabId },
106
+ ...(withWorkspace
107
+ ? {
108
+ workspace: {
109
+ workspace_id: nestedId(
110
+ result["workspace"],
111
+ "workspace_id",
112
+ `${path}.workspace`,
113
+ ),
114
+ },
115
+ }
116
+ : {}),
117
+ };
118
+ }
119
+
120
+ function nestedId(value: unknown, key: string, path: string): string {
121
+ if (typeof value !== "object" || value === null) {
122
+ throw new Error(`Herdr ${path} must be an object`);
123
+ }
124
+ const id = (value as Record<string, unknown>)[key];
125
+ if (typeof id !== "string")
126
+ throw new Error(`Herdr ${path}.${key} must be string`);
127
+ return id;
128
+ }
129
+
130
+ export async function rollbackCreatedLocation(
131
+ client: HerdrConnection,
132
+ cleanup: CreatedLocationCleanup | undefined,
133
+ cause: unknown,
134
+ ): Promise<never> {
135
+ if (!cleanup) throw cause;
136
+ try {
137
+ await client.request(cleanup.method, {
138
+ [cleanup.method === "tab.close"
139
+ ? "tab_id"
140
+ : cleanup.method === "terminal.close"
141
+ ? "id"
142
+ : "workspace_id"]: cleanup.id,
143
+ });
144
+ } catch (cleanupError) {
145
+ throw new Error(
146
+ `${cause instanceof Error ? cause.message : String(cause)}; rollback also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
147
+ { cause },
148
+ );
149
+ }
150
+ throw new RolledBackAgentLaunchError(cause);
151
+ }
package/src/launch.ts CHANGED
@@ -1,34 +1,27 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import { parseArgs } from "@earendil-works/pi-coding-agent";
4
- import {
5
- getAgent,
6
- getPane,
7
- getSnapshot,
8
- parsePaneInfo,
9
- resolveWorkspace,
10
- sessionPath,
11
- } from "./herdr.js";
4
+ import { CoreConnection } from "./core/backend.js";
5
+ import { startCoreAgent } from "./core/spawn.js";
6
+ import { getAgent, getPane, parsePaneInfo, sessionPath } from "./herdr.js";
12
7
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
8
+ import {
9
+ requiredStartField,
10
+ type StartAgentParams,
11
+ type StartedAgent,
12
+ UnstartedAgentLaunchError,
13
+ } from "./launch-contract.js";
14
+ import { createStartPane, rollbackCreatedLocation } from "./launch-location.js";
13
15
  import type { PaneInfo } from "./types.js";
14
16
  import { WORKER_FLAG } from "./worker-role.js";
15
17
 
16
- export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
17
- const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
18
+ export {
19
+ RolledBackAgentLaunchError,
20
+ START_PLACEMENTS,
21
+ UnstartedAgentLaunchError,
22
+ } from "./launch-contract.js";
18
23
 
19
- export interface StartAgentParams {
20
- cwd?: string;
21
- label?: string;
22
- name?: string;
23
- pane?: string;
24
- placement?: (typeof START_PLACEMENTS)[number];
25
- workspace?: string;
26
- }
27
-
28
- function required(value: string | undefined, field: string): string {
29
- if (!value?.trim()) throw new Error(`${field} is required for start`);
30
- return value.trim();
31
- }
24
+ const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
32
25
 
33
26
  async function directory(
34
27
  value: string | undefined,
@@ -66,10 +59,14 @@ export async function resolvePreparationDirectory(
66
59
  fallbackCwd: string,
67
60
  resolveDirectory: DirectoryResolver = directory,
68
61
  ): Promise<string> {
62
+ if (client instanceof CoreConnection && params.placement === "pane")
63
+ throw new UnstartedAgentLaunchError(
64
+ "Core cannot start Pi in an existing terminal without terminal input; use terminal, new_tab or new_workspace placement",
65
+ );
69
66
  if (params.placement !== "pane") {
70
67
  return resolveStartDirectory(params, fallbackCwd, resolveDirectory);
71
68
  }
72
- const pane = await getPane(client, required(params.pane, "pane"));
69
+ const pane = await getPane(client, requiredStartField(params.pane, "pane"));
73
70
  return pane.foreground_cwd?.trim() || pane.cwd?.trim() || fallbackCwd;
74
71
  }
75
72
 
@@ -77,143 +74,6 @@ interface StartAgentOptions {
77
74
  agentArgs?: string[];
78
75
  }
79
76
 
80
- interface CreatedLocationCleanup {
81
- id: string;
82
- method: "tab.close" | "workspace.close";
83
- }
84
-
85
- export interface StartedAgent {
86
- agent: PaneInfo;
87
- cleanup?: CreatedLocationCleanup;
88
- id: string;
89
- }
90
-
91
- export class RolledBackAgentLaunchError extends Error {
92
- constructor(cause: unknown) {
93
- super(cause instanceof Error ? cause.message : String(cause), { cause });
94
- }
95
- }
96
-
97
- export class UnstartedAgentLaunchError extends Error {
98
- constructor(cause: unknown) {
99
- super(cause instanceof Error ? cause.message : String(cause), { cause });
100
- }
101
- }
102
-
103
- async function createStartPane(
104
- client: HerdrConnection,
105
- params: StartAgentParams,
106
- cwd: string,
107
- label: string,
108
- ): Promise<{
109
- cleanup?: CreatedLocationCleanup;
110
- paneId: string;
111
- }> {
112
- const placement = params.placement;
113
- if (!placement) throw new Error("placement is required for start");
114
- if (placement === "pane") {
115
- return { paneId: required(params.pane, "pane") };
116
- }
117
- if (placement === "new_tab") {
118
- const workspaceTarget = required(params.workspace, "workspace");
119
- let workspace;
120
- try {
121
- workspace = resolveWorkspace(await getSnapshot(client), workspaceTarget);
122
- } catch (error) {
123
- throw new UnstartedAgentLaunchError(error);
124
- }
125
- // A failed create response may still have created a location.
126
- const created = createdLocation(
127
- await client.request<unknown>("tab.create", {
128
- workspace_id: workspace.workspace_id,
129
- cwd,
130
- label,
131
- focus: false,
132
- }),
133
- "tab.create result",
134
- );
135
- return {
136
- paneId: created.root_pane.pane_id,
137
- cleanup: { method: "tab.close", id: created.tab.tab_id },
138
- };
139
- }
140
- const created = createdLocation(
141
- await client.request<unknown>("workspace.create", {
142
- cwd,
143
- focus: false,
144
- }),
145
- "workspace.create result",
146
- true,
147
- );
148
- try {
149
- await client.request("tab.rename", { tab_id: created.tab.tab_id, label });
150
- } catch (error) {
151
- return rollbackCreatedLocation(
152
- client,
153
- { method: "workspace.close", id: created.workspace.workspace_id },
154
- error,
155
- );
156
- }
157
- return {
158
- paneId: created.root_pane.pane_id,
159
- cleanup: { method: "workspace.close", id: created.workspace.workspace_id },
160
- };
161
- }
162
-
163
- function createdLocation(
164
- value: unknown,
165
- path: string,
166
- ): { root_pane: PaneInfo; tab: { tab_id: string } };
167
- function createdLocation(
168
- value: unknown,
169
- path: string,
170
- withWorkspace: true,
171
- ): {
172
- root_pane: PaneInfo;
173
- tab: { tab_id: string };
174
- workspace: { workspace_id: string };
175
- };
176
- function createdLocation(
177
- value: unknown,
178
- path: string,
179
- withWorkspace = false,
180
- ): {
181
- root_pane: PaneInfo;
182
- tab: { tab_id: string };
183
- workspace?: { workspace_id: string };
184
- } {
185
- if (typeof value !== "object" || value === null) {
186
- throw new Error(`Herdr ${path} must be an object`);
187
- }
188
- const result = value as Record<string, unknown>;
189
- const tabId = nestedId(result["tab"], "tab_id", `${path}.tab`);
190
- return {
191
- root_pane: parsePaneInfo(result["root_pane"], `${path}.root_pane`),
192
- tab: { tab_id: tabId },
193
- ...(withWorkspace
194
- ? {
195
- workspace: {
196
- workspace_id: nestedId(
197
- result["workspace"],
198
- "workspace_id",
199
- `${path}.workspace`,
200
- ),
201
- },
202
- }
203
- : {}),
204
- };
205
- }
206
-
207
- function nestedId(value: unknown, key: string, path: string): string {
208
- if (typeof value !== "object" || value === null) {
209
- throw new Error(`Herdr ${path} must be an object`);
210
- }
211
- const id = (value as Record<string, unknown>)[key];
212
- if (typeof id !== "string")
213
- throw new Error(`Herdr ${path}.${key} must be string`);
214
- return id;
215
- }
216
-
217
77
  export async function startAgent(
218
78
  client: HerdrConnection,
219
79
  params: StartAgentParams,
@@ -221,7 +81,7 @@ export async function startAgent(
221
81
  resolveDirectory: DirectoryResolver = directory,
222
82
  options: StartAgentOptions = {},
223
83
  ): Promise<StartedAgent> {
224
- const name = required(params.name, "name");
84
+ const name = requiredStartField(params.name, "name");
225
85
  if (!AGENT_NAME.test(name)) {
226
86
  throw new Error(
227
87
  "name must be 1–32 characters, start with a lowercase letter, and contain only lowercase letters, digits, underscores or hyphens. Omit name to generate it from label; label can be longer.",
@@ -250,12 +110,18 @@ export async function startAgent(
250
110
  "cwd cannot change an existing pane; prepare the pane through Herdr",
251
111
  );
252
112
  }
113
+ if (client instanceof CoreConnection && params.placement === "pane")
114
+ throw new UnstartedAgentLaunchError(
115
+ "Core cannot start Pi in an existing terminal without terminal input; use terminal, new_tab or new_workspace placement",
116
+ );
253
117
  let cwd: string;
254
118
  try {
255
119
  cwd = await resolveStartDirectory(params, fallbackCwd, resolveDirectory);
256
120
  } catch (error) {
257
121
  throw new UnstartedAgentLaunchError(error);
258
122
  }
123
+ if (client instanceof CoreConnection)
124
+ return startCoreAgent(client, params, cwd, label, args);
259
125
  const created = await createStartPane(client, params, cwd, label);
260
126
  let agent: PaneInfo;
261
127
  try {
@@ -284,25 +150,6 @@ export async function rollbackStartedAgent(
284
150
  return rollbackCreatedLocation(client, started.cleanup, cause);
285
151
  }
286
152
 
287
- async function rollbackCreatedLocation(
288
- client: HerdrConnection,
289
- cleanup: CreatedLocationCleanup | undefined,
290
- cause: unknown,
291
- ): Promise<never> {
292
- if (!cleanup) throw cause;
293
- try {
294
- await client.request(cleanup.method, {
295
- [cleanup.method === "tab.close" ? "tab_id" : "workspace_id"]: cleanup.id,
296
- });
297
- } catch (cleanupError) {
298
- throw new Error(
299
- `${cause instanceof Error ? cause.message : String(cause)}; rollback also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
300
- { cause },
301
- );
302
- }
303
- throw new RolledBackAgentLaunchError(cause);
304
- }
305
-
306
153
  async function startWhenShellReady(
307
154
  client: HerdrConnection,
308
155
  params: Record<string, unknown>,
@@ -331,11 +178,11 @@ async function startWhenShellReady(
331
178
  }
332
179
  }
333
180
 
334
- const name = required(
181
+ const name = requiredStartField(
335
182
  typeof params["name"] === "string" ? params["name"] : undefined,
336
183
  "name",
337
184
  );
338
- const paneId = required(
185
+ const paneId = requiredStartField(
339
186
  typeof params["pane_id"] === "string" ? params["pane_id"] : undefined,
340
187
  "pane_id",
341
188
  );
@@ -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,84 @@
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(
24
+ agent: PaneInfo,
25
+ labels: AgentEventLabels,
26
+ ): Record<string, string | undefined> {
27
+ const paneName = agent.label || agent.title;
28
+ return {
29
+ ...(agent.backend === "core"
30
+ ? { terminal: agent.terminal_id }
31
+ : { pane: agent.pane_id }),
32
+ ...(agent.workspace_id ? { workspace: agent.workspace_id } : {}),
33
+ ...(agent.tab_id ? { tab: agent.tab_id } : {}),
34
+ ...(agent.name ? { name: agent.name } : {}),
35
+ ...(paneName ? { pane_name: paneName } : {}),
36
+ ...(labels.workspace ? { workspace_name: labels.workspace } : {}),
37
+ ...(labels.tab ? { tab_name: labels.tab } : {}),
38
+ };
39
+ }
40
+
41
+ export function sourceAttributes(
42
+ source: Record<string, string | undefined>,
43
+ ): string {
44
+ return Object.entries(source)
45
+ .filter((entry): entry is [string, string] => entry[1] !== undefined)
46
+ .map(
47
+ ([key, value]) =>
48
+ `${key}="${xml(value).replaceAll("\n", "&#10;").replaceAll("\r", "&#13;")}"`,
49
+ )
50
+ .join(" ");
51
+ }
52
+
53
+ export async function attributeAgentPrompt(
54
+ client: HerdrConnection,
55
+ message: string,
56
+ kind: "message" | "task",
57
+ ): Promise<PeerMessage> {
58
+ const [pane, snapshot] = await Promise.all([
59
+ getCurrentPane(client),
60
+ getSnapshot(client),
61
+ ]);
62
+ const workspace = snapshot.workspaces.find(
63
+ (workspace) => workspace.workspace_id === pane.workspace_id,
64
+ )?.label;
65
+ const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
66
+ const source = {
67
+ kind,
68
+ ...(pane.backend === "core"
69
+ ? await client.machineIdentity()
70
+ : {
71
+ host: hostname(),
72
+ session: process.env["HERDR_SESSION"] || "default",
73
+ }),
74
+ ...agentSource(pane, {
75
+ ...(workspace ? { workspace } : {}),
76
+ ...(tab ? { tab } : {}),
77
+ }),
78
+ };
79
+ return {
80
+ sender: `<herdr_sender ${sourceAttributes(source)} />`,
81
+ text: message,
82
+ ...(kind === "task" ? { context: DELEGATED_WORKER_GUIDANCE } : {}),
83
+ };
84
+ }
@@ -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
+ }