@howaboua/pi-shepherdr 0.2.22 → 0.2.23

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.23
4
+
5
+ - - Worker roles now follow shared project instructions, preserving a longer common startup prefix and exact role whitespace across machines. Update and reload Shepherdr on controllers and worker hosts together.
6
+ - Fixed broken remote connections causing unhandled pipe errors and leaving requests pending.
7
+ - Worker-notice warnings now identify the affected machine and explain how to reconnect.
8
+ - GPT-mode Board briefings use denser guidance.
9
+ - Blocking agent calls can run in parallel while the controller waits for their results.
10
+ - Launched workers identify themselves to compatible extensions so human-only features can stay off.
11
+
3
12
  ## 0.2.22
4
13
 
5
14
  - **Worker integrations**
package/README.md CHANGED
@@ -69,6 +69,8 @@ Call `agents` with `{}` before first use, alone, then send flat request objects
69
69
 
70
70
  `spawn` and `assign` block by default. Set `blocking: false` when the controller should continue other work immediately. A profile's `blocking` setting overrides the call for `spawn`. Task completion and blockage are then delivered automatically.
71
71
 
72
+ Blocking calls can run in parallel. In Code or Notebook, use `await Promise.allSettled([...])` to start independent calls together and wait for every result, including failures. Keep blocking enabled when the controller must wait, such as for parallel reviews. Consecutive `await` calls still run one after another; `Promise.all` can exit early on failure.
73
+
72
74
  Nonblocking extension messages notify the controller once; blocking messages arrive with the worker's blocked result. Both remain visible in `read` and later task reports until the producer closes them. Each replyable message includes a ready `reply` call with its machine, target, extension and message ID. Fill in the extension's reply template. `send` does not resolve an extension message.
73
75
 
74
76
  `reply` returns the extension's receipt after semantic delivery. Blocking messages also wait for resumed work unless another call already owns that wait. Nonblocking replies do not wait for the worker's task to finish. Shepherdr forwards strings unchanged. The producing extension owns their meaning, validation and retries.
@@ -250,6 +252,22 @@ Ordinary delegation stays inside `agents`. For workspace, tab, pane, process, fo
250
252
 
251
253
  Herdr still owns terminals, layout, agent processes and restored sessions. Shepherdr owns event subscriptions, remote routing, the fleet widget and purple settlement messages.
252
254
 
255
+ ## Worker role integration
256
+
257
+ Every Shepherdr launch carries `--shepherdr-worker`, including remote workers, profiles without prompts and resumed workers. The role survives session resume after the first task. Forks do not inherit the saved role, but a fork opened inside a flagged worker process is still a worker. Existing agents reached through `assign` or `attach` are not automatically classified as workers. Pi Codex Conversion is not required.
258
+
259
+ Other extensions can query the current role synchronously through public Pi events, including during `session_start`:
260
+
261
+ ```ts
262
+ let worker = false;
263
+ pi.events.emit("shepherdr:worker-role:v1", {
264
+ sessionManager: ctx.sessionManager,
265
+ reply: (value: boolean) => { worker = value; },
266
+ });
267
+ ```
268
+
269
+ No reply means Shepherdr is unavailable. The query adds no model instructions or tools. Worker launch flags describe the process, so new sessions opened inside that process remain workers.
270
+
253
271
  ## Pulse runner
254
272
 
255
273
  Shepherdr implements Pulses' optional detached-runner contract through Pi events. Pulses owns scheduling. Each worker runs in a separate Pi process, so the main agent remains available. Its final response returns through the same monitored waking delivery as asynchronous `agents` calls, including ordinary kickoff preparation and rollover admission. There is no passive-result or blocking execution mode.
package/index.ts CHANGED
@@ -10,9 +10,11 @@ import { AgentFleet } from "./src/fleet.js";
10
10
  import { registerAgentEventRenderer } from "./src/messages.js";
11
11
  import { createPeerCommands } from "./src/peer-commands.js";
12
12
  import { registerPeerInbox } from "./src/peer-inbox.js";
13
+ import { registerProfilePrompt } from "./src/profile-prompt.js";
13
14
  import { installAgentProfiles } from "./src/profiles.js";
14
15
  import { registerSharedAgentContext } from "./src/shared-context-host.js";
15
16
  import { registerVoiceFocusReceiver } from "./src/voice-handoff.js";
17
+ import { registerWorkerRole } from "./src/worker-role.js";
16
18
  import { registerWorkerService } from "./src/worker-service.js";
17
19
 
18
20
  const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
@@ -21,9 +23,11 @@ const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
21
23
  export default async function shepherdrExtension(
22
24
  pi: ExtensionAPI,
23
25
  ): Promise<void> {
26
+ const workerRole = registerWorkerRole(pi);
24
27
  registerPackageChangelog(pi);
25
28
 
26
29
  await installAgentProfiles();
30
+ registerProfilePrompt(pi);
27
31
  registerDeveloperDelivery(pi);
28
32
  const peerCommands = createPeerCommands(pi);
29
33
  const fleet = new AgentFleet(pi);
@@ -34,7 +38,7 @@ export default async function shepherdrExtension(
34
38
  const board = AgentBoard.create(pi, fleet);
35
39
  registerPeerInbox(pi, peerCommands, fleet, (ctx) => board.promptCatchup(ctx));
36
40
  const sharedContext = await registerSharedAgentContext(pi, fleet, board);
37
- registerWorkerService(pi, fleet, sharedContext, board);
41
+ registerWorkerService(pi, fleet, sharedContext, board, workerRole);
38
42
  let promptMode: { readonly active: boolean } | undefined;
39
43
  const tool = createAgentsTool(
40
44
  fleet,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.22",
3
+ "version": "0.2.23",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=4.0.2",
46
+ "@howaboua/pi-codex-conversion": ">=4.0.3",
47
47
  "@earendil-works/pi-ai": ">=1.1.0",
48
48
  "@earendil-works/pi-coding-agent": ">=1.2.0",
49
49
  "@earendil-works/pi-tui": ">=1.1.0",
@@ -55,10 +55,10 @@
55
55
  }
56
56
  },
57
57
  "dependencies": {
58
- "@howaboua/pi-agent-board": "0.0.2"
58
+ "@howaboua/pi-agent-board": "0.0.3"
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "4.0.2",
61
+ "@howaboua/pi-codex-conversion": "4.0.3",
62
62
  "@biomejs/biome": "^2.5.15",
63
63
  "@earendil-works/pi-ai": "1.3.0",
64
64
  "@earendil-works/pi-coding-agent": "1.3.0",
@@ -77,8 +77,8 @@ export async function agentsHelp(
77
77
  detach:
78
78
  "Stop selected membership; retain counterpart checkpoints read-only; idle target",
79
79
  blocking: gpt
80
- ? "spawn/assign default true; profile overrides spawn. Independent implementation fanout: false. Only waiting? End turn. Completion/blockage arrives after reply; no polling/sleep waits"
81
- : "spawn/assign default true; profile blocking overrides spawn. Fan out independent implementation workers with false; end your turn when only waiting. Completion/blockage arrives after you reply; no polling or sleep waits",
80
+ ? "spawn/assign default true; profile overrides spawn. JS cells parallel+wait: await Promise.allSettled. false=continue other work; completion/blockage after reply. No polling/sleep waits"
81
+ : "spawn/assign default true; profile blocking overrides spawn. In JavaScript cells, use await Promise.allSettled for parallel calls that wait for every result, including failures. Use false only to continue other work; completion/blockage arrives after your reply. No polling or sleep waits",
82
82
  share_context:
83
83
  "Profile false isolates notes/history; otherwise follows controller sharing setting",
84
84
  watch:
@@ -8,9 +8,9 @@ import {
8
8
  shouldBlockAgentSpawn,
9
9
  } from "./agents-contract.js";
10
10
  import {
11
- allocateAgentName,
12
11
  dispatchAgentWork,
13
12
  reportProgress,
13
+ reserveAgentName,
14
14
  settlementResult,
15
15
  toolResult,
16
16
  } from "./agents-work.js";
@@ -65,147 +65,153 @@ export async function spawnAgent(
65
65
  );
66
66
  }
67
67
  const label = required(params.label, "label");
68
- const name = params.name?.trim() || (await allocateAgentName(runtime, label));
69
- const placement =
70
- params.placement ??
71
- (runtime.local && process.env["HERDR_WORKSPACE_ID"]
72
- ? "new_tab"
73
- : "new_workspace");
74
- const workspace =
75
- params.workspace ??
76
- (placement === "new_tab" && runtime.local
77
- ? process.env["HERDR_WORKSPACE_ID"]
78
- : undefined);
79
- const startParams = {
80
- name,
81
- label,
82
- placement,
83
- ...(workspace ? { workspace } : {}),
84
- ...(params.pane ? { pane: params.pane } : {}),
85
- ...(params.cwd ? { cwd: params.cwd } : {}),
86
- };
87
- const cwd = await resolvePreparationDirectory(
88
- runtime.client,
89
- startParams,
90
- runtime.fallbackCwd,
91
- runtime.resolveDirectory,
92
- );
93
- const input = required(params.message, "message");
94
- const message = await prepareProfileMessage(
95
- profile,
96
- {
97
- cwd,
98
- message: input,
99
- ...(params.base ? { base: params.base } : {}),
100
- },
101
- { targetLocal: runtime.local },
102
- );
103
- const attributedMessage = await attributeAgentPrompt(
104
- fleet.connected().client,
105
- input.startsWith("/") ? input : message,
106
- "task",
107
- );
108
- if (input.startsWith("/") && message !== input)
109
- attributedMessage.context = [attributedMessage.context, message]
110
- .filter(Boolean)
111
- .join("\n\n");
112
- if (boardThreadId !== undefined)
113
- attributedMessage.context = [
114
- attributedMessage.context,
115
- `Read shared board thread with board({action:"read_thread",thread_id:${JSON.stringify(boardThreadId)}}) for task context`,
116
- ]
117
- .filter(Boolean)
118
- .join("\n\n");
119
- reportProgress(onUpdate, `Spawning ${label}`, {
120
- machine: runtime.machine,
121
- name,
122
- profile: profile.name,
123
- status: "starting",
124
- });
125
- const agentArgs = profileAgentArgs(profile, { targetLocal: runtime.local });
126
- const relationship = sharedContext.spawns.prepareRelationship(
127
- ctx,
128
- runtime,
129
- agentArgs,
130
- );
131
- const sharing =
132
- profile.shareContext === false
133
- ? undefined
134
- : await sharedContext.spawns.prepare(ctx, runtime, name, agentArgs);
135
- const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
136
- const started = await startAgent(
137
- runtime.client,
138
- startParams,
139
- runtime.fallbackCwd,
140
- runtime.resolveDirectory,
141
- { agentArgs },
142
- );
143
- let promptSubmissionStarted = false;
144
- let promptAccepted = false;
145
- let dispatch;
146
- let shared: { agentName?: string; warning?: string } | undefined;
147
- let boardAgent: string | undefined;
148
- let relationshipWarning: string | undefined;
149
- const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
68
+ const reservation = await reserveAgentName(runtime, label, params.name);
69
+ const { name } = reservation;
150
70
  try {
151
- relationshipWarning = (await relationship?.accept(started.agent))?.warning;
152
- boardAgent = await boardBinding?.accept(started.agent);
153
- shared = await sharing?.accept(started.agent);
154
- dispatch = await dispatchAgentWork(
155
- runtime,
156
- started.agent,
157
- message,
158
- blocking,
159
- signal,
160
- onUpdate,
161
- async () => {
162
- promptSubmissionStarted = true;
163
- const receipt = await runtime.client.sendMessage(
164
- started.agent,
165
- attributedMessage,
166
- );
167
- promptAccepted = true;
168
- return receipt;
71
+ const placement =
72
+ params.placement ??
73
+ (runtime.local && process.env["HERDR_WORKSPACE_ID"]
74
+ ? "new_tab"
75
+ : "new_workspace");
76
+ const workspace =
77
+ params.workspace ??
78
+ (placement === "new_tab" && runtime.local
79
+ ? process.env["HERDR_WORKSPACE_ID"]
80
+ : undefined);
81
+ const startParams = {
82
+ name,
83
+ label,
84
+ placement,
85
+ ...(workspace ? { workspace } : {}),
86
+ ...(params.pane ? { pane: params.pane } : {}),
87
+ ...(params.cwd ? { cwd: params.cwd } : {}),
88
+ };
89
+ const cwd = await resolvePreparationDirectory(
90
+ runtime.client,
91
+ startParams,
92
+ runtime.fallbackCwd,
93
+ runtime.resolveDirectory,
94
+ );
95
+ const input = required(params.message, "message");
96
+ const message = await prepareProfileMessage(
97
+ profile,
98
+ {
99
+ cwd,
100
+ message: input,
101
+ ...(params.base ? { base: params.base } : {}),
169
102
  },
170
- { expectUserMessage: true },
103
+ { targetLocal: runtime.local },
104
+ );
105
+ const attributedMessage = await attributeAgentPrompt(
106
+ fleet.connected().client,
107
+ input.startsWith("/") ? input : message,
108
+ "task",
109
+ );
110
+ if (input.startsWith("/") && message !== input)
111
+ attributedMessage.context = [attributedMessage.context, message]
112
+ .filter(Boolean)
113
+ .join("\n\n");
114
+ if (boardThreadId !== undefined)
115
+ attributedMessage.context = [
116
+ attributedMessage.context,
117
+ `Read shared board thread with board({action:"read_thread",thread_id:${JSON.stringify(boardThreadId)}}) for task context`,
118
+ ]
119
+ .filter(Boolean)
120
+ .join("\n\n");
121
+ reportProgress(onUpdate, `Spawning ${label}`, {
122
+ machine: runtime.machine,
123
+ name,
124
+ profile: profile.name,
125
+ status: "starting",
126
+ });
127
+ const agentArgs = profileAgentArgs(profile);
128
+ const relationship = sharedContext.spawns.prepareRelationship(
129
+ ctx,
130
+ runtime,
131
+ agentArgs,
132
+ );
133
+ const sharing =
134
+ profile.shareContext === false
135
+ ? undefined
136
+ : await sharedContext.spawns.prepare(ctx, runtime, name, agentArgs);
137
+ const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
138
+ const started = await startAgent(
139
+ runtime.client,
140
+ startParams,
141
+ runtime.fallbackCwd,
142
+ runtime.resolveDirectory,
143
+ { agentArgs },
171
144
  );
172
- } catch (error) {
173
- if (
174
- !promptAccepted &&
175
- (!promptSubmissionStarted || isDispatchRejected(error))
176
- ) {
177
- return rollbackStartedAgent(runtime.client, started, error);
145
+ let promptSubmissionStarted = false;
146
+ let promptAccepted = false;
147
+ let dispatch;
148
+ let shared: { agentName?: string; warning?: string } | undefined;
149
+ let boardAgent: string | undefined;
150
+ let relationshipWarning: string | undefined;
151
+ const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
152
+ try {
153
+ relationshipWarning = (await relationship?.accept(started.agent))
154
+ ?.warning;
155
+ boardAgent = await boardBinding?.accept(started.agent);
156
+ shared = await sharing?.accept(started.agent);
157
+ dispatch = await dispatchAgentWork(
158
+ runtime,
159
+ started.agent,
160
+ message,
161
+ blocking,
162
+ signal,
163
+ onUpdate,
164
+ async () => {
165
+ promptSubmissionStarted = true;
166
+ const receipt = await runtime.client.sendMessage(
167
+ started.agent,
168
+ attributedMessage,
169
+ );
170
+ promptAccepted = true;
171
+ return receipt;
172
+ },
173
+ { expectUserMessage: true },
174
+ );
175
+ } catch (error) {
176
+ if (
177
+ !promptAccepted &&
178
+ (!promptSubmissionStarted || isDispatchRejected(error))
179
+ ) {
180
+ return await rollbackStartedAgent(runtime.client, started, error);
181
+ }
182
+ throw error;
178
183
  }
179
- throw error;
180
- }
181
- return toolResult(
182
- {
183
- ...(boardAgent ? { boardAgent } : {}),
184
- ...(shared?.agentName ? { contextAgent: shared.agentName } : {}),
185
- ...(dispatch.command
186
- ? {
187
- spawned: true,
188
- commandSubmitted: true,
189
- machine: runtime.machine,
190
- target: started.id,
191
- name,
192
- }
193
- : dispatch.settlement
184
+ return toolResult(
185
+ {
186
+ ...(boardAgent ? { boardAgent } : {}),
187
+ ...(shared?.agentName ? { contextAgent: shared.agentName } : {}),
188
+ ...(dispatch.command
194
189
  ? {
195
190
  spawned: true,
196
- ...settlementResult(runtime.machine, dispatch.settlement),
197
- }
198
- : {
199
- spawned: true,
191
+ commandSubmitted: true,
200
192
  machine: runtime.machine,
201
193
  target: started.id,
202
194
  name,
203
- status: "working",
204
- next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
205
- }),
206
- },
207
- [dispatch.warning, shared?.warning, relationshipWarning]
208
- .filter(Boolean)
209
- .join("\n") || undefined,
210
- );
195
+ }
196
+ : dispatch.settlement
197
+ ? {
198
+ spawned: true,
199
+ ...settlementResult(runtime.machine, dispatch.settlement),
200
+ }
201
+ : {
202
+ spawned: true,
203
+ machine: runtime.machine,
204
+ target: started.id,
205
+ name,
206
+ status: "working",
207
+ next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
208
+ }),
209
+ },
210
+ [dispatch.warning, shared?.warning, relationshipWarning]
211
+ .filter(Boolean)
212
+ .join("\n") || undefined,
213
+ );
214
+ } finally {
215
+ reservation.release();
216
+ }
211
217
  }
@@ -46,7 +46,7 @@ export function createAgentsTool(
46
46
  description: "Delegate to persistent agents",
47
47
  promptGuidelines: ["Make the first agents discovery call alone"],
48
48
  parameters: AgentsParameters,
49
- executionMode: "sequential",
49
+ executionMode: "parallel",
50
50
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
51
51
  const params = parseAgentsRequest(input);
52
52
  const executionSignal = signal ?? new AbortController().signal;
@@ -2,7 +2,7 @@ import type { AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
2
2
  import { activityTask } from "./activity.js";
3
3
  import type { ConnectedMachine } from "./fleet.js";
4
4
  import { getSnapshot } from "./herdr.js";
5
- import { isDispatchRejected } from "./herdr-client.js";
5
+ import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
6
6
  import { agentSource } from "./messages.js";
7
7
  import type { WorkAttempt } from "./monitor-state.js";
8
8
  import type { ClaimedSettlement } from "./settlement.js";
@@ -38,14 +38,38 @@ function slugify(value: string): string {
38
38
  return named.slice(0, 32).replace(/-+$/u, "") || "agent";
39
39
  }
40
40
 
41
- export async function allocateAgentName(
41
+ const startingNames = new WeakMap<HerdrConnection, Set<string>>();
42
+
43
+ export async function reserveAgentName(
42
44
  runtime: ConnectedMachine,
43
45
  label: string,
44
- ): Promise<string> {
46
+ requested?: string,
47
+ ): Promise<{ name: string; release(): void }> {
45
48
  const snapshot = await getSnapshot(runtime.client);
46
- const names = new Set(
47
- snapshot.agents.map((agent) => agent.name).filter(Boolean),
48
- );
49
+ let reserved = startingNames.get(runtime.client);
50
+ if (!reserved) {
51
+ reserved = new Set<string>();
52
+ startingNames.set(runtime.client, reserved);
53
+ }
54
+ const names = new Set([
55
+ ...snapshot.agents.flatMap((agent) => (agent.name ? [agent.name] : [])),
56
+ ...reserved,
57
+ ]);
58
+ const name = requested?.trim() || availableAgentName(names, label);
59
+ if (names.has(name))
60
+ throw new Error(
61
+ `Agent name ${JSON.stringify(name)} is already in use; omit name or choose another`,
62
+ );
63
+ reserved.add(name);
64
+ return {
65
+ name,
66
+ release: () => {
67
+ reserved.delete(name);
68
+ },
69
+ };
70
+ }
71
+
72
+ function availableAgentName(names: ReadonlySet<string>, label: string): string {
49
73
  const base = slugify(label);
50
74
  if (!names.has(base)) return base;
51
75
  for (let suffix = 2; suffix < 10_000; suffix += 1) {
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
  );
package/src/messages.ts CHANGED
@@ -114,19 +114,27 @@ export function boardBriefing(
114
114
  ) {
115
115
  const state =
116
116
  population === "populated"
117
- ? "Read relevant board threads."
117
+ ? gpt
118
+ ? "Read relevantboardthreads."
119
+ : "Read relevant board threads."
118
120
  : population === "empty"
119
- ? "Shared board available; no posts yet."
120
- : "Shared board status unavailable. Check board help and retry reading when available.";
121
+ ? gpt
122
+ ? "Sharedboard available; posts=none."
123
+ : "Shared board available; no posts yet."
124
+ : gpt
125
+ ? "Sharedboard status unavailable; board help→retry read when available."
126
+ : "Shared board status unavailable. Check board help and retry reading when available.";
121
127
  const setup = member
122
- ? "The root agent owns setup; follow your assigned task."
128
+ ? gpt
129
+ ? "Root owns setup; follow assignedtask."
130
+ : "The root agent owns setup; follow your assigned task."
123
131
  : "";
124
132
  if (gpt)
125
133
  return [
126
134
  state,
127
135
  setup,
128
- "Post only work-changing ownership, decisions, findings or blockers. Reply in existing threads, link instead of repeating. Personal checkpoints belong in notes. No acknowledgements, routine status or duplicate completion reports. Use agents for assignments and urgent messages.",
129
- "Channels group workstreams, threads group topics. Reuse relevant channels, not catch-alls. New channels need distinct coordination purpose, never mere task/result announcements.",
136
+ "Posts=work-changing ownership/decisions/findings/blockers only. Existingthread replies; link≠repeat. Personalcheckpoints→notes. No ack/statusspam/duplicate completionreports. Assignments/urgentmessages→agents.",
137
+ "Channels=workstreams; threads=topics. Reuse relevantchannels≠catchalls. Newchannel requires distinctcoordinationpurpose; never task/result announcement only.",
130
138
  ]
131
139
  .filter(Boolean)
132
140
  .join(" ");
@@ -9,6 +9,8 @@ import type { ExtensionMessage, MonitoredAgent, PaneInfo } from "./types.js";
9
9
 
10
10
  interface MonitorExtensionMessagesOptions {
11
11
  client: HerdrConnection;
12
+ machine: string;
13
+ machineLabel: () => string;
12
14
  reader: AssistantReader;
13
15
  state: MonitorState;
14
16
  notify: (
@@ -176,8 +178,19 @@ export class MonitorExtensionMessages {
176
178
  private warning(error: unknown): void {
177
179
  if (this.warned) return;
178
180
  this.warned = true;
181
+ const label = this.options.machineLabel();
182
+ const machine =
183
+ label === this.options.machine
184
+ ? label
185
+ : `${label} (${this.options.machine})`;
186
+ const detail =
187
+ error instanceof Error && "code" in error && error.code === "EPIPE"
188
+ ? "the connection closed"
189
+ : error instanceof Error
190
+ ? error.message
191
+ : String(error);
179
192
  this.context?.ui.notify(
180
- `Worker extension notifications unavailable: ${error instanceof Error ? error.message : String(error)}. Use agents read to inspect workers; reconnect through /herdr`,
193
+ `Worker notices unavailable on ${machine}: ${detail}. Open /herdr → Status to reconnect. Then use agents read to check worker messages.`,
181
194
  "warning",
182
195
  );
183
196
  }
package/src/monitor.ts CHANGED
@@ -61,6 +61,8 @@ export class AgentMonitor {
61
61
  const reader = options.reader ?? new SessionReader();
62
62
  this.extensionMessages = new MonitorExtensionMessages({
63
63
  client: this.client,
64
+ machine: this.machine,
65
+ machineLabel: options.machineLabel,
64
66
  reader,
65
67
  state: this.state,
66
68
  notify: (ctx, record, agent, message) => {
@@ -0,0 +1,32 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const PROFILE_PROMPT_FLAG = "shepherdr-profile-prompt";
4
+ const SECTION = "shepherdr_profile";
5
+
6
+ export function registerProfilePrompt(pi: ExtensionAPI): void {
7
+ pi.registerFlag(PROFILE_PROMPT_FLAG, {
8
+ type: "string",
9
+ description: "JSON-encoded worker profile prompt",
10
+ });
11
+ pi.on("before_agent_start", async (event, ctx) => {
12
+ const encoded = pi.getFlag(PROFILE_PROMPT_FLAG);
13
+ if (encoded === undefined) return;
14
+ let prompt: unknown;
15
+ try {
16
+ prompt = JSON.parse(String(encoded));
17
+ if (typeof prompt !== "string") throw new Error("Expected a string");
18
+ } catch (cause) {
19
+ await ctx.abort();
20
+ throw new Error("Worker profile prompt is invalid; respawn the worker", {
21
+ cause,
22
+ });
23
+ }
24
+ // Custom sections follow shared project context. Never relocate foreign addenda.
25
+ const options = event.systemPromptOptions;
26
+ if (options.forceSystemPrompt !== undefined) {
27
+ options.forceSystemPrompt += `\n\n<${SECTION}>\n${prompt}\n</${SECTION}>`;
28
+ } else {
29
+ options.sections[SECTION] = prompt;
30
+ }
31
+ });
32
+ }
package/src/profiles.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  import { homedir } from "node:os";
14
14
  import { join, resolve } from "node:path";
15
15
  import { fileURLToPath, pathToFileURL } from "node:url";
16
+ import { PROFILE_PROMPT_FLAG } from "./profile-prompt.js";
16
17
 
17
18
  const PROFILE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
18
19
  const AGENT_DIRECTORY =
@@ -33,7 +34,6 @@ export interface AgentProfile {
33
34
  piArgs: string[];
34
35
  prepare?: string;
35
36
  prompt?: string;
36
- promptPath?: string;
37
37
  shareContext?: boolean;
38
38
  thinking: string;
39
39
  }
@@ -165,7 +165,6 @@ async function readProfile(
165
165
  ...(resolvedPromptPath
166
166
  ? {
167
167
  prompt: await readFile(resolvedPromptPath, "utf8"),
168
- promptPath: resolvedPromptPath,
169
168
  }
170
169
  : {}),
171
170
  ...(prepare ? { prepare } : {}),
@@ -261,37 +260,18 @@ export async function loadAgentProfiles(): Promise<Map<string, AgentProfile>> {
261
260
  return profiles;
262
261
  }
263
262
 
264
- function promptArgument(
265
- profile: AgentProfile,
266
- targetLocal: boolean,
267
- ): string | undefined {
268
- if (
269
- targetLocal &&
270
- profile.promptPath &&
271
- ![...profile.promptPath].some((character) => /\p{Cc}/u.test(character))
272
- ) {
273
- return profile.promptPath;
274
- }
275
- return profile.prompt
276
- ?.replace(/\p{Cc}+/gu, " ")
277
- .replace(/\s+/gu, " ")
278
- .trim();
279
- }
280
-
281
263
  export function profileAgentArgs(
282
264
  profile: AgentProfile,
283
- options: { targetLocal?: boolean; includePrompt?: boolean } = {},
265
+ options: { includePrompt?: boolean } = {},
284
266
  ): string[] {
285
- const prompt =
286
- options.includePrompt === false
287
- ? undefined
288
- : promptArgument(profile, options.targetLocal !== false);
267
+ const prompt = options.includePrompt === false ? undefined : profile.prompt;
289
268
  return [
290
269
  "--model",
291
270
  profile.model,
292
271
  "--thinking",
293
272
  profile.thinking,
294
- ...(prompt ? ["--append-system-prompt", prompt] : []),
273
+ // JSON keeps newlines/control characters out of argv without altering role text.
274
+ ...(prompt ? [`--${PROFILE_PROMPT_FLAG}`, JSON.stringify(prompt)] : []),
295
275
  ...profile.piArgs,
296
276
  ];
297
277
  }
@@ -141,13 +141,17 @@ async function deploy(
141
141
  child.stderr.on("data", (chunk: Buffer) => {
142
142
  stderr = appendBounded(stderr, chunk);
143
143
  });
144
- child.stdin.end(source);
145
144
  await new Promise<void>((resolve, reject) => {
146
145
  const timer = setTimeout(() => {
147
146
  child.kill();
148
147
  reject(new Error("remote bridge deployment timed out"));
149
148
  }, DEPLOY_TIMEOUT_MS);
150
149
  timer.unref();
150
+ child.stdin.on("error", (error) => {
151
+ clearTimeout(timer);
152
+ child.kill();
153
+ reject(error);
154
+ });
151
155
  child.on("error", (error) => {
152
156
  clearTimeout(timer);
153
157
  reject(error);
@@ -164,6 +168,7 @@ async function deploy(
164
168
  ),
165
169
  );
166
170
  });
171
+ child.stdin.end(source);
167
172
  });
168
173
  }
169
174
 
@@ -196,6 +201,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
196
201
  child.stderr.on("data", (chunk: Buffer) => {
197
202
  this.diagnostics = appendBounded(this.diagnostics, chunk);
198
203
  });
204
+ child.stdin.on("error", (error) => this.disconnected(error));
199
205
  child.on("error", (error) => this.disconnected(error));
200
206
  child.on("exit", (code) => {
201
207
  this.disconnected(
@@ -572,7 +578,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
572
578
  `${JSON.stringify({ ...message, id })}\n`,
573
579
  (error) => {
574
580
  if (!error) return;
575
- this.rejectPending(id, error);
581
+ this.disconnected(error);
576
582
  },
577
583
  );
578
584
  });
@@ -712,6 +718,10 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
712
718
 
713
719
  private disconnected(error: Error): void {
714
720
  if (this.closed) return;
721
+ if ("code" in error && error.code === "EPIPE")
722
+ error = new Error("Connection to the remote machine closed", {
723
+ cause: error,
724
+ });
715
725
  this.closed = true;
716
726
  this.child.kill();
717
727
  this.failPending(error, true);
@@ -0,0 +1,83 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+
6
+ export const WORKER_FLAG = "shepherdr-worker";
7
+ export const PULSE_WORKER_FLAG = "shepherdr-pulse-worker";
8
+ const WORKER_MARKER = "herdr-worker-v1";
9
+ const LEGACY_PULSE_MARKER = "herdr-pulse-worker-v1";
10
+ const WORKER_ROLE_CHANNEL = "shepherdr:worker-role:v1";
11
+
12
+ type SessionManager = ExtensionContext["sessionManager"];
13
+
14
+ /** Optional synchronous event request; consumers need no Shepherdr import. */
15
+ interface WorkerRoleRequest {
16
+ sessionManager: SessionManager;
17
+ reply: (worker: boolean) => void;
18
+ }
19
+
20
+ function markedWorker(manager: SessionManager, pulseOnly = false): boolean {
21
+ const sessionId = manager.getSessionId();
22
+ return manager.getEntries().some((entry) => {
23
+ if (
24
+ entry.type !== "custom" ||
25
+ (entry.customType !== WORKER_MARKER &&
26
+ entry.customType !== LEGACY_PULSE_MARKER)
27
+ )
28
+ return false;
29
+ const data = entry.data as
30
+ | { sessionId?: unknown; pulse?: unknown }
31
+ | undefined;
32
+ return (
33
+ data?.sessionId === sessionId &&
34
+ (!pulseOnly ||
35
+ entry.customType === LEGACY_PULSE_MARKER ||
36
+ data.pulse === true)
37
+ );
38
+ });
39
+ }
40
+
41
+ export function registerWorkerRole(pi: ExtensionAPI) {
42
+ pi.registerFlag(WORKER_FLAG, {
43
+ type: "boolean",
44
+ default: false,
45
+ description: "Run as a supervised Shepherdr worker",
46
+ });
47
+ pi.registerFlag(PULSE_WORKER_FLAG, {
48
+ type: "boolean",
49
+ default: false,
50
+ description: "Run as a detached pulse worker",
51
+ });
52
+ const isWorker = (manager: SessionManager) =>
53
+ pi.getFlag(WORKER_FLAG) === true ||
54
+ pi.getFlag(PULSE_WORKER_FLAG) === true ||
55
+ markedWorker(manager);
56
+ const isPulseWorker = (manager: SessionManager) =>
57
+ pi.getFlag(PULSE_WORKER_FLAG) === true || markedWorker(manager, true);
58
+ // Read the supplied native session directly, even before our session_start.
59
+ pi.events.on(WORKER_ROLE_CHANNEL, (request: unknown) => {
60
+ const value = request as Partial<WorkerRoleRequest> | undefined;
61
+ if (
62
+ typeof value?.reply === "function" &&
63
+ typeof value.sessionManager?.getSessionId === "function" &&
64
+ typeof value.sessionManager.getEntries === "function"
65
+ )
66
+ value.reply(isWorker(value.sessionManager));
67
+ });
68
+ pi.on("before_agent_start", (_event, ctx) => {
69
+ const pulse = pi.getFlag(PULSE_WORKER_FLAG) === true;
70
+ if (
71
+ (pi.getFlag(WORKER_FLAG) === true || pulse) &&
72
+ (!markedWorker(ctx.sessionManager) ||
73
+ (pulse && !markedWorker(ctx.sessionManager, true)))
74
+ ) {
75
+ // Startup entries would prevent fresh Notes family adoption before work.
76
+ pi.appendEntry(WORKER_MARKER, {
77
+ sessionId: ctx.sessionManager.getSessionId(),
78
+ ...(pulse ? { pulse: true } : {}),
79
+ });
80
+ }
81
+ });
82
+ return { isWorker, isPulseWorker };
83
+ }
@@ -4,7 +4,7 @@ import type {
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { activityTask } from "./activity.js";
7
- import { allocateAgentName, dispatchAgentWork } from "./agents-work.js";
7
+ import { dispatchAgentWork, reserveAgentName } from "./agents-work.js";
8
8
  import type { AgentBoard } from "./board/host.js";
9
9
  import type { AgentFleet } from "./fleet.js";
10
10
  import { getSnapshot, sessionPath } from "./herdr.js";
@@ -18,10 +18,9 @@ import { attributeAgentPrompt } from "./messages.js";
18
18
  import { loadAgentProfiles, profileAgentArgs } from "./profiles.js";
19
19
  import type { SharedAgentContext } from "./shared-context.js";
20
20
  import type { PaneInfo } from "./types.js";
21
+ import { PULSE_WORKER_FLAG, type registerWorkerRole } from "./worker-role.js";
21
22
 
22
23
  const ENTRY = "herdr-owned-worker-v1";
23
- const WORKER_MARKER = "herdr-pulse-worker-v1";
24
- const WORKER_FLAG = "shepherdr-pulse-worker";
25
24
  const RUNNER_PROTOCOL = "@howaboua/pi-pulses/runner/v1";
26
25
  // Structural implementation of Pulses' optional runner ABI, without a private-package dependency.
27
26
  interface PulseRun {
@@ -84,28 +83,12 @@ export function registerWorkerService(
84
83
  fleet: AgentFleet,
85
84
  shared: SharedAgentContext,
86
85
  board: AgentBoard,
86
+ workerRole: ReturnType<typeof registerWorkerRole>,
87
87
  ): void {
88
88
  let active: ExtensionContext | undefined;
89
89
  let busy = false;
90
- pi.registerFlag(WORKER_FLAG, {
91
- type: "boolean",
92
- default: false,
93
- description: "Run as a detached pulse worker",
94
- });
95
- const markedWorker = (ctx: ExtensionContext) =>
96
- ctx.sessionManager
97
- .getEntries()
98
- .some(
99
- (entry) =>
100
- entry.type === "custom" &&
101
- entry.customType === WORKER_MARKER &&
102
- (entry.data as { sessionId?: unknown } | undefined)?.sessionId ===
103
- ctx.sessionManager.getSessionId(),
104
- );
105
90
  const isController = (ctx: ExtensionContext) =>
106
- ctx.mode === "tui" &&
107
- pi.getFlag(WORKER_FLAG) !== true &&
108
- !markedWorker(ctx);
91
+ ctx.mode === "tui" && !workerRole.isPulseWorker(ctx.sessionManager);
109
92
  function assertContext(ctx: ExtensionContext) {
110
93
  if (!isController(ctx))
111
94
  throw new Error("Detached workers cannot claim or schedule pulses");
@@ -257,7 +240,6 @@ export function registerWorkerService(
257
240
  if (!profile)
258
241
  throw new Error("General worker profile is unavailable");
259
242
  const profileArgs = profileAgentArgs(profile, {
260
- targetLocal: true,
261
243
  includePrompt: false,
262
244
  });
263
245
  if (
@@ -272,70 +254,79 @@ export function registerWorkerService(
272
254
  );
273
255
  const args = [
274
256
  ...profileArgs,
275
- `--${WORKER_FLAG}`,
257
+ `--${PULSE_WORKER_FLAG}`,
276
258
  ...(worker ? ["--session", worker.sessionPath] : []),
277
259
  ];
278
- const name = await allocateAgentName(runtime, input.title);
279
- const relationship = worker
280
- ? undefined
281
- : shared.spawns.prepareRelationship(ctx, runtime, args);
282
- const sharing =
283
- worker || profile.shareContext === false
284
- ? undefined
285
- : await shared.spawns.prepare(ctx, runtime, name, args);
286
- const boardBinding = worker
287
- ? undefined
288
- : await board.prepare(ctx, runtime, name, args);
289
- const workspace = runtime.local
290
- ? process.env["HERDR_WORKSPACE_ID"]
291
- : undefined;
292
- stage = "launch";
293
- const started = await startAgent(
294
- runtime.client,
295
- {
296
- name,
297
- label: input.title,
298
- cwd: input.cwd,
299
- placement: workspace ? "new_tab" : "new_workspace",
300
- ...(workspace ? { workspace } : {}),
301
- },
302
- runtime.fallbackCwd,
303
- runtime.resolveDirectory,
304
- { agentArgs: args },
305
- );
260
+ const reservation = await reserveAgentName(runtime, input.title);
261
+ const { name } = reservation;
306
262
  try {
307
- const relationshipResult = await relationship?.accept(
308
- started.agent,
263
+ const relationship = worker
264
+ ? undefined
265
+ : shared.spawns.prepareRelationship(ctx, runtime, args);
266
+ const sharing =
267
+ worker || profile.shareContext === false
268
+ ? undefined
269
+ : await shared.spawns.prepare(ctx, runtime, name, args);
270
+ const boardBinding = worker
271
+ ? undefined
272
+ : await board.prepare(ctx, runtime, name, args);
273
+ const workspace = runtime.local
274
+ ? process.env["HERDR_WORKSPACE_ID"]
275
+ : undefined;
276
+ stage = "launch";
277
+ const started = await startAgent(
278
+ runtime.client,
279
+ {
280
+ name,
281
+ label: input.title,
282
+ cwd: input.cwd,
283
+ placement: workspace ? "new_tab" : "new_workspace",
284
+ ...(workspace ? { workspace } : {}),
285
+ },
286
+ runtime.fallbackCwd,
287
+ runtime.resolveDirectory,
288
+ { agentArgs: args },
309
289
  );
310
- await boardBinding?.accept(started.agent);
311
- const sharingResult = await sharing?.accept(started.agent);
312
- for (const warning of [
313
- relationshipResult?.warning,
314
- sharingResult?.warning,
315
- ])
316
- if (warning) ctx.ui.notify(warning, "warning");
317
- assertBranch();
318
- panel = started.agent;
319
- const file = sessionPath(panel);
320
- if (!file || (worker && file !== worker.sessionPath))
321
- throw new Error("Worker did not restore its saved session");
322
- const identity = await runtime.client.machineIdentity();
323
- worker = {
324
- workerId: worker?.workerId ?? crypto.randomUUID(),
325
- pulseId: input.taskId,
326
- runId: "",
327
- parent: ctx.sessionManager.getSessionFile()!,
328
- ...identity,
329
- target: panel.pane_id,
330
- terminal: panel.terminal_id,
331
- sessionPath: file,
332
- cwd: input.cwd,
333
- };
334
- pi.appendEntry(ENTRY, worker);
335
- } catch (error) {
336
- return await rollbackStartedAgent(runtime.client, started, error);
290
+ try {
291
+ const relationshipResult = await relationship?.accept(
292
+ started.agent,
293
+ );
294
+ await boardBinding?.accept(started.agent);
295
+ const sharingResult = await sharing?.accept(started.agent);
296
+ for (const warning of [
297
+ relationshipResult?.warning,
298
+ sharingResult?.warning,
299
+ ])
300
+ if (warning) ctx.ui.notify(warning, "warning");
301
+ assertBranch();
302
+ panel = started.agent;
303
+ const file = sessionPath(panel);
304
+ if (!file || (worker && file !== worker.sessionPath))
305
+ throw new Error("Worker did not restore its saved session");
306
+ const identity = await runtime.client.machineIdentity();
307
+ worker = {
308
+ workerId: worker?.workerId ?? crypto.randomUUID(),
309
+ pulseId: input.taskId,
310
+ runId: "",
311
+ parent: ctx.sessionManager.getSessionFile()!,
312
+ ...identity,
313
+ target: panel.pane_id,
314
+ terminal: panel.terminal_id,
315
+ sessionPath: file,
316
+ cwd: input.cwd,
317
+ };
318
+ pi.appendEntry(ENTRY, worker);
319
+ } catch (error) {
320
+ return await rollbackStartedAgent(
321
+ runtime.client,
322
+ started,
323
+ error,
324
+ );
325
+ }
326
+ stage = "preflight";
327
+ } finally {
328
+ reservation.release();
337
329
  }
338
- stage = "preflight";
339
330
  }
340
331
  if (!worker) throw new Error("Worker ownership is unavailable");
341
332
  const attributed = await attributeAgentPrompt(
@@ -397,12 +388,6 @@ export function registerWorkerService(
397
388
  pi.on("session_start", () => {
398
389
  active = undefined;
399
390
  });
400
- pi.on("before_agent_start", (_event, ctx) => {
401
- if (pi.getFlag(WORKER_FLAG) === true && !markedWorker(ctx))
402
- pi.appendEntry(WORKER_MARKER, {
403
- sessionId: ctx.sessionManager.getSessionId(),
404
- });
405
- });
406
391
  pi.on("resources_discover", (_event, ctx) => {
407
392
  active = ctx;
408
393
  });