@howaboua/pi-shepherdr 0.2.21 → 0.2.22

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,21 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.22
4
+
5
+ - **Worker integrations**
6
+
7
+ - Fresh workers now share their parent's cache routing with compatible Codex Conversion. Shared notes remain optional, and native sessions and histories remain separate.
8
+ - Fresh workers inherit the live Board setting before their first request, keeping Board tools and guidance available from startup.
9
+ - Added an optional Pulses runner with persistent workers, saved-session reuse and completion reports that wake the parent.
10
+
11
+ **Agent tools and guidance**
12
+
13
+ - Expanded tool calls now show outgoing tasks, messages, replies and focus handoffs in full.
14
+ - Added compact agent help and hosted Board briefings for PCC GPT prompt mode.
15
+ - Agent discovery now uses the same help contract across native, Code and Notebook tools.
16
+ - Added delegation guidance for distinct scopes, shared project context and combined validation.
17
+ - Invalid spawn names now explain naming limits and how to use a longer label. Spawn guidance favours short two-word names.
18
+
3
19
  ## 0.2.21
4
20
 
5
21
  - Fixed duplicate sessions showing a stack trace instead of a warning explaining how to restore shared context.
package/README.md CHANGED
@@ -194,7 +194,7 @@ Child board calls use the owning Pi sessions and existing SSH connections, not a
194
194
 
195
195
  ## Shared notes and history
196
196
 
197
- With compatible Pi Codex Conversion on both ends, Shepherdr marks fresh spawned workers before their first task with their immediate parent's native Pi session ID and `subagentKind: "collab_spawn"`. Each worker keeps its own native session ID. This relationship works with shared notes disabled and does not grant notes access. Resume preserves it; forks and profiles selecting existing sessions do not acquire an inherited relationship. Older PCC versions without the optional capability retain ordinary delegation. The [extension API guide](../../docs/extension-apis.md#parent-and-worker-relationships) documents PCC's `bindRelationship` service contract for other orchestrators. Shepherdr owns transport, not a separate public relationship RPC API.
197
+ With compatible Pi Codex Conversion on both ends, Shepherdr marks fresh spawned workers before their first task with their immediate parent's native Pi session ID and `subagentKind: "collab_spawn"`. Workers also inherit the parent's effective cache routing identity, including nested and remote spawns. Each worker keeps its own native session, sockets and history. Cache routing works with shared notes disabled and does not grant notes access or copy the parent's transcript. Only matching prompt prefixes can benefit. Resume preserves the relationship; forks and profiles selecting existing sessions do not acquire it. Older PCC versions retain ordinary delegation and any supported parent linkage. The [extension API guide](../../docs/extension-apis.md#parent-and-worker-relationships) documents PCC's service contract for other orchestrators. Shepherdr owns transport, not a separate public relationship RPC API.
198
198
 
199
199
  With Pi Codex Conversion 3.0.40 or newer and notes-based continuity, enable **Share subagent context** under `/codex context` in the controller. It is off by default. Shared `spawn` gives each child a unique context identity before its first turn; `contextAgent` in the result identifies its notes and history. Shared nested spawns stay in the same family. Turning sharing off affects new spawns only; existing identity survives resume. `assign` and independently started agents remain unchanged. Older compatible Conversion versions keep ordinary delegation without sharing.
200
200
 
@@ -250,6 +250,14 @@ Ordinary delegation stays inside `agents`. For workspace, tab, pane, process, fo
250
250
 
251
251
  Herdr still owns terminals, layout, agent processes and restored sessions. Shepherdr owns event subscriptions, remote routing, the fleet widget and purple settlement messages.
252
252
 
253
+ ## Pulse runner
254
+
255
+ 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.
256
+
257
+ The adapter reuses owned saved sessions, refuses overlapping work and verifies parent session, branch and pane identity. Worker receipts are opaque to Pulses. Use ordinary Shepherdr controls to manage worker panes. Detached pulse workers cannot become schedulers themselves.
258
+
259
+ Fresh and restored workers use the `general` profile's model, thinking level and explicit Pi arguments without its implementation-role prompt. Ordinary agent spawns still use the complete profile. Fresh workers inherit the existing family board independently of their working directory, alongside optional shared Notes and cache affinity. The adapter does not choose an output destination or keep the controlling Pi alive.
260
+
253
261
  ## License
254
262
 
255
263
  MIT
package/index.ts CHANGED
@@ -13,6 +13,7 @@ import { registerPeerInbox } from "./src/peer-inbox.js";
13
13
  import { installAgentProfiles } from "./src/profiles.js";
14
14
  import { registerSharedAgentContext } from "./src/shared-context-host.js";
15
15
  import { registerVoiceFocusReceiver } from "./src/voice-handoff.js";
16
+ import { registerWorkerService } from "./src/worker-service.js";
16
17
 
17
18
  const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
18
19
  const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
@@ -33,10 +34,37 @@ export default async function shepherdrExtension(
33
34
  const board = AgentBoard.create(pi, fleet);
34
35
  registerPeerInbox(pi, peerCommands, fleet, (ctx) => board.promptCatchup(ctx));
35
36
  const sharedContext = await registerSharedAgentContext(pi, fleet, board);
36
- const tool = createAgentsTool(fleet, sharedContext, board, pi, peerCommands);
37
+ registerWorkerService(pi, fleet, sharedContext, board);
38
+ let promptMode: { readonly active: boolean } | undefined;
39
+ const tool = createAgentsTool(
40
+ fleet,
41
+ sharedContext,
42
+ board,
43
+ pi,
44
+ peerCommands,
45
+ () => promptMode?.active ?? false,
46
+ );
37
47
 
38
48
  registerAgentEventRenderer(pi);
39
49
  pi.registerTool(tool);
50
+ try {
51
+ const { registerGptPromptMode } = await import(
52
+ "@howaboua/pi-codex-conversion/prompt-mode"
53
+ );
54
+ promptMode = registerGptPromptMode(pi, () => [tool]);
55
+ } catch (error) {
56
+ if (
57
+ !(error instanceof Error) ||
58
+ !("code" in error) ||
59
+ ![
60
+ "ERR_MODULE_NOT_FOUND",
61
+ "MODULE_NOT_FOUND",
62
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
63
+ ].includes(String(error.code)) ||
64
+ !error.message.includes(CODE_MODE_PACKAGE)
65
+ )
66
+ throw error;
67
+ }
40
68
  await registerAgentsInCodeMode(pi, tool);
41
69
  registerAgentController(pi, fleet, peerCommands);
42
70
  }
@@ -52,7 +80,7 @@ async function registerAgentsInCodeMode(
52
80
  adaptToolForCodeMode(tool, {
53
81
  prepareInput: (input) => (input === undefined ? {} : input),
54
82
  blocking: isBlockingAgentsCall,
55
- usage: "await tools.agents() // Persistent agents; first call alone",
83
+ discovery: "help",
56
84
  }),
57
85
  ]);
58
86
  pi.on("session_shutdown", () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.21",
3
+ "version": "0.2.22",
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.1",
46
+ "@howaboua/pi-codex-conversion": ">=4.0.2",
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.1"
58
+ "@howaboua/pi-agent-board": "0.0.2"
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "4.0.1",
61
+ "@howaboua/pi-codex-conversion": "4.0.2",
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",
@@ -25,11 +25,13 @@ function describeProfiles(profiles: Map<string, AgentProfile>) {
25
25
 
26
26
  export async function agentsHelp(
27
27
  boardAvailable = false,
28
+ gpt = false,
28
29
  ): Promise<Record<string, unknown>> {
29
30
  const profiles = await loadAgentProfiles();
30
31
  return {
31
- commands:
32
- "commands: true lists available slash commands with descriptions; defaults to this session, target and machine optionally select another session; does not execute commands",
32
+ commands: gpt
33
+ ? "commands:true lists slash commands/descriptions, never executes. Default this session; target/machine select another"
34
+ : "commands: true lists available slash commands with descriptions; defaults to this session, target and machine optionally select another session; does not execute commands",
33
35
  actions: {
34
36
  help: "",
35
37
  list: "machine?",
@@ -48,13 +50,14 @@ export async function agentsHelp(
48
50
  reply: "target extension id message machine?",
49
51
  },
50
52
  rules: {
51
- reply:
52
- "Use the extension-authored template from its report/read; send does not resolve it. Blocking messages wait for resumed work; other replies return after semantic delivery",
53
+ reply: gpt
54
+ ? "Use extension report/read template; send cannot resolve. Blocking waits for resumed work; others return after semantic delivery"
55
+ : "Use the extension-authored template from its report/read; send does not resolve it. Blocking messages wait for resumed work; other replies return after semantic delivery",
53
56
  machine:
54
57
  "Omit for local (host running Pi); list/find omit for all machines. Remote: profile ID from list, not label/hostname",
55
58
  target:
56
59
  "Use spawn/find target exactly; /root selects this family's live root",
57
- label: "Concise tab/session name",
60
+ label: "Short tab/session name; prefer two words when useful",
58
61
  ...(boardAvailable
59
62
  ? {
60
63
  board_thread_id:
@@ -62,25 +65,30 @@ export async function agentsHelp(
62
65
  }
63
66
  : {}),
64
67
  send: "Message or work update; wakes idle agents, no wait/watch. Close finished workers with /quit, not acknowledgement messages",
65
- assign:
66
- "Delegate or update work; active updates share its pending result, never replace an existing wait",
67
- focus:
68
- "Select a running session; passive arrival with return call, no task/watch. voice defaults false; true carries the active microphone asynchronously. handoff adds context. Remote focus selects the target's Herdr session, not the client's machine",
68
+ assign: gpt
69
+ ? "Delegate/update work. Active updates share pending result, never replace existing wait"
70
+ : "Delegate or update work; active updates share its pending result, never replace an existing wait",
71
+ focus: gpt
72
+ ? "Running session; passive arrival+return call, no task/watch. voice=false default; true transfers active mic asynchronously. handoff=context. Remote selects target Herdr session, not client machine"
73
+ : "Select a running session; passive arrival with return call, no task/watch. voice defaults false; true carries the active microphone asynchronously. handoff adds context. Remote focus selects the target's Herdr session, not the client's machine",
69
74
  attach: boardAvailable
70
75
  ? "Idle target; context/board booleans choose shared access and board membership independently; no task/watch"
71
76
  : "Idle target; context shares notes/history; use board:false while shared boards are unavailable; no task/watch",
72
77
  detach:
73
78
  "Stop selected membership; retain counterpart checkpoints read-only; idle target",
74
- blocking:
75
- "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",
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",
76
82
  share_context:
77
83
  "Profile false isolates notes/history; otherwise follows controller sharing setting",
78
84
  watch:
79
85
  "Delegation and watch keep reporting subsequent work until unwatch or close",
80
- prompt:
81
- "Only task + inaccessible context; no method/evidence/reporting boilerplate",
82
- slash:
83
- "Leading / routes target commands/skills/templates. Commands skip task waiting, even with assign/spawn; blocked commands return available choices. /quit shuts down Pi and closes its pane",
86
+ prompt: gpt
87
+ ? "Distinct worker scope, outcome, project context, issue references. Define success, not forbidden investigations"
88
+ : "Give each worker a distinct scope, desired outcome, relevant project context and issue references. Describe success rather than lists of forbidden investigations",
89
+ slash: gpt
90
+ ? "Leading / routes target commands/skills/templates. Commands skip task waiting including assign/spawn; blocked returns choices. /quit exits Pi and closes pane"
91
+ : "Leading / routes target commands/skills/templates. Commands skip task waiting, even with assign/spawn; blocked commands return available choices. /quit shuts down Pi and closes its pane",
84
92
  reuse:
85
93
  "Reuse only same investigation; reviews independent; new scope = new agent",
86
94
  ...(profiles.has("general")
@@ -38,11 +38,13 @@ export function createAgentsTool(
38
38
  board: AgentBoard,
39
39
  pi: ExtensionAPI,
40
40
  commands: ReturnType<typeof createPeerCommands>,
41
+ gpt: () => boolean = () => false,
41
42
  ) {
42
43
  return defineTool({
43
44
  name: "agents",
44
45
  label: "Shepherdr",
45
- description: "Delegate to persistent agents; discover first, alone",
46
+ description: "Delegate to persistent agents",
47
+ promptGuidelines: ["Make the first agents discovery call alone"],
46
48
  parameters: AgentsParameters,
47
49
  executionMode: "sequential",
48
50
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
@@ -50,7 +52,7 @@ export function createAgentsTool(
50
52
  const executionSignal = signal ?? new AbortController().signal;
51
53
  const update = onUpdate ?? (() => undefined);
52
54
  if (params.action === "help" && !params.commands) {
53
- return toolResult(await agentsHelp(board.enabled(ctx)));
55
+ return toolResult(await agentsHelp(board.enabled(ctx), gpt()));
54
56
  }
55
57
  if (params.commands && params.target === undefined)
56
58
  return toolResult({ commands: commands.available() });
@@ -242,7 +244,7 @@ export function createAgentsTool(
242
244
  params?.name ??
243
245
  params?.agent_type ??
244
246
  "";
245
- return new Text(
247
+ const title = new Text(
246
248
  theme.fg(
247
249
  context && "isBlocked" in context && context.isBlocked === true
248
250
  ? "warning"
@@ -252,6 +254,13 @@ export function createAgentsTool(
252
254
  0,
253
255
  0,
254
256
  );
257
+ const message = params?.message ?? params?.handoff;
258
+ if (!context?.expanded || !message) return title;
259
+ const container = new Container();
260
+ container.addChild(title);
261
+ container.addChild(new Spacer(1));
262
+ container.addChild(new Text(message, 0, 0));
263
+ return container;
255
264
  },
256
265
  renderResult(toolResult, options, theme) {
257
266
  const details =
package/src/board/host.ts CHANGED
@@ -57,7 +57,8 @@ export class AgentBoard {
57
57
  discoverBoard(pi, (runtime) => {
58
58
  this.runtime = runtime;
59
59
  runtime.attach({
60
- briefing: boardBriefing,
60
+ briefing: (member, population) =>
61
+ boardBriefing(member, population, runtime.gptPromptMode),
61
62
  request: requestContext,
62
63
  commitDirectory: (own, directory, caller, request) =>
63
64
  this.membership.commitDirectory(own, directory, caller, request),
@@ -136,7 +137,7 @@ export class AgentBoard {
136
137
  args: readonly string[],
137
138
  ) {
138
139
  if (!this.enabled(ctx)) return undefined;
139
- const own = binding(ctx);
140
+ const own = { ...binding(ctx), enabled: true };
140
141
  if (
141
142
  args.some((arg) =>
142
143
  /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
package/src/launch.ts CHANGED
@@ -87,6 +87,18 @@ export interface StartedAgent {
87
87
  id: string;
88
88
  }
89
89
 
90
+ export class RolledBackAgentLaunchError extends Error {
91
+ constructor(cause: unknown) {
92
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
93
+ }
94
+ }
95
+
96
+ export class UnstartedAgentLaunchError extends Error {
97
+ constructor(cause: unknown) {
98
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
99
+ }
100
+ }
101
+
90
102
  async function createStartPane(
91
103
  client: HerdrConnection,
92
104
  params: StartAgentParams,
@@ -103,10 +115,13 @@ async function createStartPane(
103
115
  }
104
116
  if (placement === "new_tab") {
105
117
  const workspaceTarget = required(params.workspace, "workspace");
106
- const workspace = resolveWorkspace(
107
- await getSnapshot(client),
108
- workspaceTarget,
109
- );
118
+ let workspace;
119
+ try {
120
+ workspace = resolveWorkspace(await getSnapshot(client), workspaceTarget);
121
+ } catch (error) {
122
+ throw new UnstartedAgentLaunchError(error);
123
+ }
124
+ // A failed create response may still have created a location.
110
125
  const created = createdLocation(
111
126
  await client.request<unknown>("tab.create", {
112
127
  workspace_id: workspace.workspace_id,
@@ -207,7 +222,9 @@ export async function startAgent(
207
222
  ): Promise<StartedAgent> {
208
223
  const name = required(params.name, "name");
209
224
  if (!AGENT_NAME.test(name)) {
210
- throw new Error("name must match [a-z][a-z0-9_-]{0,31}");
225
+ throw new Error(
226
+ "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.",
227
+ );
211
228
  }
212
229
  const label = params.label?.trim() || name;
213
230
  const args = ["--name", label, ...(options.agentArgs ?? [])];
@@ -221,11 +238,12 @@ export async function startAgent(
221
238
  "cwd cannot change an existing pane; prepare the pane through Herdr",
222
239
  );
223
240
  }
224
- const cwd = await resolveStartDirectory(
225
- params,
226
- fallbackCwd,
227
- resolveDirectory,
228
- );
241
+ let cwd: string;
242
+ try {
243
+ cwd = await resolveStartDirectory(params, fallbackCwd, resolveDirectory);
244
+ } catch (error) {
245
+ throw new UnstartedAgentLaunchError(error);
246
+ }
229
247
  const created = await createStartPane(client, params, cwd, label);
230
248
  let agent: PaneInfo;
231
249
  try {
@@ -270,7 +288,7 @@ async function rollbackCreatedLocation(
270
288
  { cause },
271
289
  );
272
290
  }
273
- throw cause;
291
+ throw new RolledBackAgentLaunchError(cause);
274
292
  }
275
293
 
276
294
  async function startWhenShellReady(
package/src/messages.ts CHANGED
@@ -72,8 +72,8 @@ export function orchestrationGuidance(enabled: boolean, general: boolean) {
72
72
  if (!enabled)
73
73
  return `Work normally. Delegate only when useful or requested. ${ownership}`;
74
74
  const guidance = general
75
- ? "Your main goal from now on is to orchestrate agents. Fan out suitable work to general agents, synthesize their results, and report the outcome. Work directly only when asked or for routine local tasks."
76
- : "Your main goal from now on is to orchestrate agents. Fan out suitable work, synthesize agent results, and report the outcome. Work directly only when asked or for routine local tasks.";
75
+ ? "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."
76
+ : "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.";
77
77
  return `${guidance} ${ownership}`;
78
78
  }
79
79
  export function activeAgentsBriefing(
@@ -110,6 +110,7 @@ export function boardMigrationWarning() {
110
110
  export function boardBriefing(
111
111
  member: boolean,
112
112
  population: "empty" | "populated" | "unavailable",
113
+ gpt = false,
113
114
  ) {
114
115
  const state =
115
116
  population === "populated"
@@ -120,6 +121,15 @@ export function boardBriefing(
120
121
  const setup = member
121
122
  ? "The root agent owns setup; follow your assigned task."
122
123
  : "";
124
+ if (gpt)
125
+ return [
126
+ state,
127
+ 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.",
130
+ ]
131
+ .filter(Boolean)
132
+ .join(" ");
123
133
  return (
124
134
  [
125
135
  state,
package/src/profiles.ts CHANGED
@@ -280,9 +280,12 @@ function promptArgument(
280
280
 
281
281
  export function profileAgentArgs(
282
282
  profile: AgentProfile,
283
- options: { targetLocal?: boolean } = {},
283
+ options: { targetLocal?: boolean; includePrompt?: boolean } = {},
284
284
  ): string[] {
285
- const prompt = promptArgument(profile, options.targetLocal !== false);
285
+ const prompt =
286
+ options.includePrompt === false
287
+ ? undefined
288
+ : promptArgument(profile, options.targetLocal !== false);
286
289
  return [
287
290
  "--model",
288
291
  profile.model,
@@ -36,7 +36,8 @@ export class SpawnContext {
36
36
  runtime: ConnectedMachine,
37
37
  args: readonly string[],
38
38
  ) {
39
- if (!this.getService()?.bindRelationship) return undefined;
39
+ const service = this.getService();
40
+ if (!service?.bindRelationship) return undefined;
40
41
  // Session-selection profiles resume existing identities rather than creating workers.
41
42
  if (
42
43
  args.some((arg) =>
@@ -47,7 +48,12 @@ export class SpawnContext {
47
48
  )
48
49
  return undefined;
49
50
  const parentThreadId = ctx.sessionManager.getSessionId();
50
- const relationship = { parentThreadId, subagentKind: "collab_spawn" };
51
+ const cacheAffinityId = service.cacheAffinityId?.(ctx);
52
+ const linkage = { parentThreadId, subagentKind: "collab_spawn" };
53
+ const relationship = {
54
+ ...linkage,
55
+ ...(cacheAffinityId ? { cacheAffinityId } : {}),
56
+ };
51
57
  return {
52
58
  accept: async (agent: PaneInfo) => {
53
59
  const file = sessionPath(agent);
@@ -66,6 +72,12 @@ export class SpawnContext {
66
72
  warning:
67
73
  "Worker relationship marking requires Codex conversion on the target",
68
74
  };
75
+ // Older targets preserve linkage but do not recognise cache affinity.
76
+ if (cacheAffinityId && isDeepStrictEqual(value, linkage))
77
+ return {
78
+ warning:
79
+ "Worker started without shared cache routing; update Codex Conversion on the target to enable it",
80
+ };
69
81
  if (!isDeepStrictEqual(value, relationship))
70
82
  throw new Error(
71
83
  "Spawned agent did not adopt its parent relationship",
@@ -0,0 +1,412 @@
1
+ import { isAbsolute } from "node:path";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { activityTask } from "./activity.js";
7
+ import { allocateAgentName, dispatchAgentWork } from "./agents-work.js";
8
+ import type { AgentBoard } from "./board/host.js";
9
+ import type { AgentFleet } from "./fleet.js";
10
+ import { getSnapshot, sessionPath } from "./herdr.js";
11
+ import {
12
+ RolledBackAgentLaunchError,
13
+ rollbackStartedAgent,
14
+ startAgent,
15
+ UnstartedAgentLaunchError,
16
+ } from "./launch.js";
17
+ import { attributeAgentPrompt } from "./messages.js";
18
+ import { loadAgentProfiles, profileAgentArgs } from "./profiles.js";
19
+ import type { SharedAgentContext } from "./shared-context.js";
20
+ import type { PaneInfo } from "./types.js";
21
+
22
+ const ENTRY = "herdr-owned-worker-v1";
23
+ const WORKER_MARKER = "herdr-pulse-worker-v1";
24
+ const WORKER_FLAG = "shepherdr-pulse-worker";
25
+ const RUNNER_PROTOCOL = "@howaboua/pi-pulses/runner/v1";
26
+ // Structural implementation of Pulses' optional runner ABI, without a private-package dependency.
27
+ interface PulseRun {
28
+ taskId: string;
29
+ title: string;
30
+ prompt: string;
31
+ cwd: string;
32
+ runId: string;
33
+ workerId?: string;
34
+ }
35
+ interface PulseWorker {
36
+ workerId: string;
37
+ state: "working" | "idle" | "closed";
38
+ }
39
+ interface OwnedWorker {
40
+ workerId: string;
41
+ pulseId: string;
42
+ runId: string;
43
+ parent: string;
44
+ host: string;
45
+ session: string;
46
+ target: string;
47
+ terminal: string;
48
+ sessionPath: string;
49
+ cwd: string;
50
+ }
51
+
52
+ function records(ctx: ExtensionContext): OwnedWorker[] {
53
+ const workers = new Map<string, OwnedWorker>();
54
+ for (const entry of ctx.sessionManager.getBranch()) {
55
+ if (entry.type !== "custom" || entry.customType !== ENTRY) continue;
56
+ const value = entry.data as Record<string, unknown> | undefined;
57
+ if (
58
+ !value ||
59
+ ![
60
+ "workerId",
61
+ "pulseId",
62
+ "runId",
63
+ "parent",
64
+ "host",
65
+ "session",
66
+ "target",
67
+ "terminal",
68
+ "sessionPath",
69
+ "cwd",
70
+ ].every((key) => typeof value[key] === "string")
71
+ )
72
+ throw new Error(
73
+ "Saved pulse worker ownership is invalid; inspect the session before retrying",
74
+ );
75
+ const worker = value as unknown as OwnedWorker;
76
+ if (worker.parent === ctx.sessionManager.getSessionFile())
77
+ workers.set(worker.workerId, worker);
78
+ }
79
+ return [...workers.values()];
80
+ }
81
+
82
+ export function registerWorkerService(
83
+ pi: ExtensionAPI,
84
+ fleet: AgentFleet,
85
+ shared: SharedAgentContext,
86
+ board: AgentBoard,
87
+ ): void {
88
+ let active: ExtensionContext | undefined;
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
+ const isController = (ctx: ExtensionContext) =>
106
+ ctx.mode === "tui" &&
107
+ pi.getFlag(WORKER_FLAG) !== true &&
108
+ !markedWorker(ctx);
109
+ function assertContext(ctx: ExtensionContext) {
110
+ if (!isController(ctx))
111
+ throw new Error("Detached workers cannot claim or schedule pulses");
112
+ if (
113
+ !active ||
114
+ !ctx.sessionManager.getSessionFile() ||
115
+ ctx.sessionManager.getSessionFile() !==
116
+ active.sessionManager.getSessionFile()
117
+ )
118
+ throw new Error(
119
+ "Worker service is unavailable for this session; retry after session startup",
120
+ );
121
+ }
122
+ async function owned(ctx: ExtensionContext, workerId: string) {
123
+ assertContext(ctx);
124
+ const worker = records(ctx).find((value) => value.workerId === workerId);
125
+ if (!worker) throw new Error("Worker is not owned by this session branch");
126
+ const identity = await fleet.connected().client.machineIdentity();
127
+ if (identity.host !== worker.host || identity.session !== worker.session)
128
+ throw new Error("Worker belongs to another host or Herdr session");
129
+ return worker;
130
+ }
131
+ async function panelFor(worker: OwnedWorker): Promise<PaneInfo | undefined> {
132
+ const snapshot = await getSnapshot(fleet.connected().client);
133
+ if (
134
+ snapshot.agents.some(
135
+ (value) =>
136
+ value.pane_id !== worker.target &&
137
+ sessionPath(value) === worker.sessionPath,
138
+ )
139
+ )
140
+ throw new Error(
141
+ "Worker session is open in another pane; refusing to control it",
142
+ );
143
+ const panel = snapshot.agents.find(
144
+ (value) => value.pane_id === worker.target,
145
+ );
146
+ if (panel) {
147
+ if (
148
+ panel.pane_id === process.env["HERDR_PANE_ID"] ||
149
+ panel.terminal_id !== worker.terminal ||
150
+ panel.agent !== "pi" ||
151
+ sessionPath(panel) !== worker.sessionPath
152
+ )
153
+ throw new Error("Worker pane identity changed; refusing to control it");
154
+ return panel;
155
+ }
156
+ if (
157
+ snapshot.agents.some((value) => sessionPath(value) === worker.sessionPath)
158
+ )
159
+ throw new Error(
160
+ "Worker session is open in another pane; refusing to control it",
161
+ );
162
+ return undefined;
163
+ }
164
+ async function inspect(
165
+ ctx: ExtensionContext,
166
+ workerId: string,
167
+ ): Promise<PulseWorker> {
168
+ const worker = await owned(ctx, workerId);
169
+ const panel = await panelFor(worker);
170
+ const record = fleet
171
+ .connected()
172
+ .monitor.list()
173
+ .find((value) => value.terminalId === worker.terminal);
174
+ return {
175
+ workerId,
176
+ state: !panel
177
+ ? "closed"
178
+ : (panel.agent_status !== "idle" && panel.agent_status !== "done") ||
179
+ panel.interactive_ready !== true ||
180
+ panel.launch_pending ||
181
+ (record &&
182
+ (record.activity.phase !== "settled" ||
183
+ activityTask(record.activity)))
184
+ ? "working"
185
+ : "idle",
186
+ };
187
+ }
188
+ const service = {
189
+ protocol: RUNNER_PROTOCOL,
190
+ id: "shepherdr",
191
+ isController,
192
+ inspect,
193
+ subscribe: (listener: () => void) => fleet.subscribe(listener),
194
+ async start(ctx: ExtensionContext, input: PulseRun) {
195
+ let stage: "preflight" | "launch" | "dispatch" = "dispatch";
196
+ try {
197
+ stage = records(ctx).some(
198
+ (worker) =>
199
+ worker.pulseId === input.taskId && worker.runId === input.runId,
200
+ )
201
+ ? "dispatch"
202
+ : "preflight";
203
+ assertContext(ctx);
204
+ const parentFile = ctx.sessionManager.getSessionFile();
205
+ const branchAnchor = ctx.sessionManager.getLeafId();
206
+ const assertBranch = () => {
207
+ assertContext(ctx);
208
+ if (
209
+ ctx.sessionManager.getSessionFile() !== parentFile ||
210
+ (branchAnchor &&
211
+ !ctx.sessionManager
212
+ .getBranch()
213
+ .some((entry) => entry.id === branchAnchor))
214
+ )
215
+ throw new Error(
216
+ "Parent branch changed during worker startup; inspect before retrying",
217
+ );
218
+ };
219
+ if (busy) throw new Error("A worker operation is already in progress");
220
+ for (const field of [
221
+ "taskId",
222
+ "title",
223
+ "prompt",
224
+ "cwd",
225
+ "runId",
226
+ ] as const)
227
+ if (!input[field]?.trim()) throw new Error(`${field} is required`);
228
+ if (!isAbsolute(input.cwd))
229
+ throw new Error("Worker cwd must be absolute");
230
+ if (input.prompt.trimStart().startsWith("/"))
231
+ throw new Error("Scheduled work must be a task, not a slash command");
232
+ busy = true;
233
+ try {
234
+ const runtime = fleet.connected();
235
+ let worker = records(ctx).find(
236
+ (value) => value.pulseId === input.taskId,
237
+ );
238
+ if (input.workerId && input.workerId !== worker?.workerId)
239
+ throw new Error("Worker is not owned by this pulse in this branch");
240
+ if (worker) await owned(ctx, worker.workerId);
241
+ let panel = worker ? await panelFor(worker) : undefined;
242
+ if (worker?.runId === input.runId) {
243
+ stage = "dispatch";
244
+ return await inspect(ctx, worker.workerId);
245
+ }
246
+ if (
247
+ worker &&
248
+ (await inspect(ctx, worker.workerId)).state === "working"
249
+ )
250
+ throw new Error("Worker already has active responsibility");
251
+ if (worker && worker.cwd !== input.cwd)
252
+ throw new Error(
253
+ "Saved worker cwd differs; use its original working directory",
254
+ );
255
+ if (!panel) {
256
+ const profile = (await loadAgentProfiles()).get("general");
257
+ if (!profile)
258
+ throw new Error("General worker profile is unavailable");
259
+ const profileArgs = profileAgentArgs(profile, {
260
+ targetLocal: true,
261
+ includePrompt: false,
262
+ });
263
+ if (
264
+ profileArgs.some((arg) =>
265
+ /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
266
+ arg,
267
+ ),
268
+ )
269
+ )
270
+ throw new Error(
271
+ "Worker profile cannot select an existing session",
272
+ );
273
+ const args = [
274
+ ...profileArgs,
275
+ `--${WORKER_FLAG}`,
276
+ ...(worker ? ["--session", worker.sessionPath] : []),
277
+ ];
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
+ );
306
+ try {
307
+ const relationshipResult = await relationship?.accept(
308
+ started.agent,
309
+ );
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);
337
+ }
338
+ stage = "preflight";
339
+ }
340
+ if (!worker) throw new Error("Worker ownership is unavailable");
341
+ const attributed = await attributeAgentPrompt(
342
+ runtime.client,
343
+ input.prompt,
344
+ "task",
345
+ );
346
+ assertBranch();
347
+ const dispatch = await dispatchAgentWork(
348
+ runtime,
349
+ panel,
350
+ input.prompt,
351
+ false,
352
+ new AbortController().signal,
353
+ () => {},
354
+ () => {
355
+ assertBranch();
356
+ stage = "dispatch";
357
+ return runtime.client.sendMessage(panel!, attributed);
358
+ },
359
+ { expectUserMessage: true },
360
+ );
361
+ worker = { ...worker, runId: input.runId };
362
+ assertBranch();
363
+ pi.appendEntry(ENTRY, worker);
364
+ if (dispatch.warning) ctx.ui.notify(dispatch.warning, "warning");
365
+ return inspect(ctx, worker.workerId);
366
+ } finally {
367
+ busy = false;
368
+ }
369
+ } catch (error) {
370
+ if (
371
+ stage === "preflight" ||
372
+ (stage === "launch" &&
373
+ (error instanceof RolledBackAgentLaunchError ||
374
+ error instanceof UnstartedAgentLaunchError))
375
+ )
376
+ throw Object.assign(
377
+ new Error(error instanceof Error ? error.message : String(error), {
378
+ cause: error,
379
+ }),
380
+ { dispatched: false as const },
381
+ );
382
+ throw error;
383
+ }
384
+ },
385
+ };
386
+ pi.events.on(`${RUNNER_PROTOCOL}/request`, (request: unknown) => {
387
+ const value = request as {
388
+ protocol?: unknown;
389
+ accept?: (value: typeof service) => void;
390
+ };
391
+ if (
392
+ value?.protocol === RUNNER_PROTOCOL &&
393
+ typeof value.accept === "function"
394
+ )
395
+ value.accept(service);
396
+ });
397
+ pi.on("session_start", () => {
398
+ active = undefined;
399
+ });
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
+ pi.on("resources_discover", (_event, ctx) => {
407
+ active = ctx;
408
+ });
409
+ pi.on("session_shutdown", () => {
410
+ active = undefined;
411
+ });
412
+ }