@howaboua/pi-shepherdr 0.2.28-core.12.1.gda85fa2e8a0f → 1.0.0

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 (55) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +34 -5
  3. package/biome.json +1 -1
  4. package/index.ts +5 -2
  5. package/package.json +19 -14
  6. package/src/agents-contract.ts +80 -61
  7. package/src/agents-discovery.ts +14 -10
  8. package/src/agents-focus.ts +7 -0
  9. package/src/agents-reply.ts +3 -12
  10. package/src/agents-spawn.ts +26 -2
  11. package/src/agents-tool.ts +57 -21
  12. package/src/agents-work.ts +9 -4
  13. package/src/ancestry-record.ts +116 -0
  14. package/src/attachment-notes.ts +3 -2
  15. package/src/attachment-protocol.ts +124 -68
  16. package/src/attachment-target.ts +8 -7
  17. package/src/attachment.ts +3 -3
  18. package/src/board/records.ts +50 -36
  19. package/src/close-idle.ts +2 -2
  20. package/src/controller.ts +5 -4
  21. package/src/core/backend.ts +26 -3
  22. package/src/core/helper-bootstrap.mjs +1 -1
  23. package/src/core/helper-core.mjs +4 -3
  24. package/src/core/helper-lifetime.mjs +199 -0
  25. package/src/core/remote-endpoint.ts +10 -3
  26. package/src/core/remote-helper.ts +3 -0
  27. package/src/core/remote-service.mjs +9 -0
  28. package/src/core/remote-transport.ts +11 -1
  29. package/src/core/spawn.ts +1 -1
  30. package/src/core/terminal-peer.mjs +26 -5
  31. package/src/core/terminal.ts +2 -1
  32. package/src/fleet/connection.ts +4 -0
  33. package/src/fleet/index.ts +24 -3
  34. package/src/launch-contract.ts +1 -0
  35. package/src/launch.ts +40 -3
  36. package/src/messages/attribution.ts +14 -5
  37. package/src/messages/focus.ts +4 -3
  38. package/src/messages/peer-sharing.ts +34 -20
  39. package/src/monitor-events.ts +10 -10
  40. package/src/monitor-extension-messages.ts +1 -0
  41. package/src/monitor.ts +5 -5
  42. package/src/profiles.ts +1 -8
  43. package/src/remote/shepherdr-session.mjs +43 -0
  44. package/src/settlement/delivery.ts +32 -14
  45. package/src/settlement/index.ts +3 -0
  46. package/src/shared-context.ts +4 -100
  47. package/src/spawn-ancestry.ts +103 -0
  48. package/src/spawn-ownership.ts +93 -5
  49. package/src/types.ts +1 -0
  50. package/src/worker-ownership.ts +41 -32
  51. package/src/worker-resume.ts +231 -0
  52. package/src/worker-role.ts +9 -35
  53. package/src/worker-service.ts +95 -59
  54. package/worker-api.ts +38 -0
  55. package/src/profile-prompt.ts +0 -32
@@ -0,0 +1,231 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { nativeAgentName } from "./agent-identity.js";
6
+ import { reserveAgentName } from "./agents-work.js";
7
+ import { getSnapshot, resolvePiAgent, sessionPath } from "./core/agents.js";
8
+ import type { AgentFleet, ConnectedMachine } from "./fleet/index.js";
9
+ import { resumeAgentArgs, rollbackStartedAgent, startAgent } from "./launch.js";
10
+ import type { StartedAgent } from "./launch-contract.js";
11
+ import { prepareLaunchAncestry } from "./spawn-ancestry.js";
12
+ import {
13
+ recordResumedChild,
14
+ type SpawnOwnership,
15
+ spawnedChildren,
16
+ } from "./spawn-ownership.js";
17
+ import type { PaneInfo } from "./types.js";
18
+
19
+ interface OwnedTarget {
20
+ runtime: ConnectedMachine;
21
+ panel: PaneInfo;
22
+ resumed: boolean;
23
+ }
24
+
25
+ /** Parent-owned saved sessions, not a general session launcher or delivery retry. */
26
+ export class WorkerResumer {
27
+ private readonly pending = new Map<string, Promise<OwnedTarget>>();
28
+ private readonly pi: ExtensionAPI;
29
+ private readonly fleet: AgentFleet;
30
+ constructor(pi: ExtensionAPI, fleet: AgentFleet) {
31
+ this.pi = pi;
32
+ this.fleet = fleet;
33
+ }
34
+
35
+ async resolve(
36
+ ctx: ExtensionContext,
37
+ target: string,
38
+ machine: string | undefined,
39
+ signal: AbortSignal,
40
+ allowResume = true,
41
+ ): Promise<OwnedTarget | undefined> {
42
+ const selected = machine
43
+ ? this.fleet.connected(machine).machine
44
+ : undefined;
45
+ // A current native address/name always wins over a saved routing alias.
46
+ if (!target.startsWith("/")) {
47
+ const runtime = this.fleet.connected(machine);
48
+ const snapshot = await getSnapshot(runtime.client);
49
+ const exact = snapshot.agents.find((panel) => panel.pane_id === target);
50
+ const live = exact
51
+ ? [exact]
52
+ : snapshot.agents.filter((panel) => panel.name === target);
53
+ if (live.length)
54
+ return {
55
+ runtime,
56
+ panel: await resolvePiAgent(
57
+ runtime.client,
58
+ target,
59
+ runtime.local ? process.env["HC_TERMINAL_ID"] : "",
60
+ ),
61
+ resumed: false,
62
+ };
63
+ }
64
+ const candidates: { child: SpawnOwnership; runtime: ConnectedMachine }[] =
65
+ [];
66
+ for (const child of spawnedChildren(ctx)) {
67
+ const direct =
68
+ child.agent === target ||
69
+ child.pane === target ||
70
+ child.terminal === target ||
71
+ child.aliases?.includes(target) ||
72
+ child.launch?.params.name === target;
73
+ if (!direct && !(target.startsWith("/") && !child.agent)) continue;
74
+ let runtime: ConnectedMachine;
75
+ try {
76
+ runtime = this.fleet.connected(child.session);
77
+ } catch (error) {
78
+ if (direct) throw error;
79
+ continue;
80
+ }
81
+ if (selected !== undefined && runtime.machine !== selected) continue;
82
+ if (!direct) {
83
+ let header: { id: string; cwd: string };
84
+ try {
85
+ header = await runtime.client.sessionHeader(
86
+ child.sessionFile,
87
+ signal,
88
+ );
89
+ } catch {
90
+ signal.throwIfAborted();
91
+ continue;
92
+ }
93
+ if (`/${header.id}` !== target) continue;
94
+ }
95
+ candidates.push({ child, runtime });
96
+ }
97
+ if (!candidates.length) return undefined;
98
+ if (candidates.length !== 1)
99
+ throw new Error(
100
+ "Multiple saved workers match this target; specify its session identity and machine",
101
+ );
102
+ const { child, runtime } = candidates[0]!;
103
+ const key = JSON.stringify([
104
+ ctx.sessionManager.getSessionId(),
105
+ child.session,
106
+ child.sessionFile,
107
+ ]);
108
+ let work = this.pending.get(key);
109
+ if (!work) {
110
+ work = this.open(ctx, child, runtime, signal, allowResume);
111
+ this.pending.set(key, work);
112
+ void work
113
+ .finally(() => {
114
+ if (this.pending.get(key) === work) this.pending.delete(key);
115
+ })
116
+ .catch(() => {});
117
+ }
118
+ const resolved = await work;
119
+ signal.throwIfAborted();
120
+ return resolved;
121
+ }
122
+
123
+ private async open(
124
+ ctx: ExtensionContext,
125
+ child: SpawnOwnership,
126
+ runtime: ConnectedMachine,
127
+ signal: AbortSignal,
128
+ allowResume: boolean,
129
+ ): Promise<OwnedTarget> {
130
+ const sessionId = ctx.sessionManager.getSessionId();
131
+ const current = () => {
132
+ signal.throwIfAborted();
133
+ if (
134
+ ctx.sessionManager.getSessionId() !== sessionId ||
135
+ !spawnedChildren(ctx).some(
136
+ (entry) =>
137
+ entry.parent === child.parent &&
138
+ entry.session === child.session &&
139
+ entry.sessionFile === child.sessionFile,
140
+ )
141
+ )
142
+ throw new Error(
143
+ "Controller changed; retry from the worker's original parent session",
144
+ );
145
+ };
146
+ current();
147
+ const identity = await runtime.client.machineIdentity();
148
+ if (identity.session !== child.session)
149
+ throw new Error(
150
+ "Worker's machine changed; reconnect its original machine before resuming",
151
+ );
152
+ const snapshot = await getSnapshot(runtime.client);
153
+ const live = snapshot.agents.filter(
154
+ (panel) => sessionPath(panel) === child.sessionFile,
155
+ );
156
+ current();
157
+ if (live.length > 1)
158
+ throw new Error(
159
+ "Worker is running in multiple terminals; close the extra session before sending",
160
+ );
161
+ if (live[0]) {
162
+ if (
163
+ child.agent &&
164
+ (await nativeAgentName(runtime.client, live[0], signal)) !== child.agent
165
+ )
166
+ throw new Error(
167
+ "Worker identity changed; resolve its current session before sending",
168
+ );
169
+ return { runtime, panel: live[0], resumed: false };
170
+ }
171
+ if (!allowResume)
172
+ throw new Error("Worker is already closed; no session was resumed");
173
+ const header = await runtime.client.sessionHeader(
174
+ child.sessionFile,
175
+ signal,
176
+ );
177
+ const agent = `/${header.id}`;
178
+ if (child.agent && child.agent !== agent)
179
+ throw new Error(
180
+ "Saved worker identity changed; open its saved session manually",
181
+ );
182
+ const params = child.launch?.params ?? {
183
+ name: `worker-${header.id.replaceAll("-", "").slice(0, 12)}`,
184
+ cwd: header.cwd,
185
+ placement: "terminal" as const,
186
+ };
187
+ const ancestry = await prepareLaunchAncestry(ctx, this.fleet, signal);
188
+ current();
189
+ const reservation = await reserveAgentName(runtime, params.name);
190
+ let started: StartedAgent;
191
+ try {
192
+ started = await startAgent(
193
+ runtime.client,
194
+ { name: reservation.name, cwd: params.cwd, placement: "terminal" },
195
+ header.cwd,
196
+ runtime.resolveDirectory,
197
+ {
198
+ agentArgs: [
199
+ ...resumeAgentArgs(child.launch?.args ?? []),
200
+ "--session",
201
+ child.sessionFile,
202
+ ],
203
+ ancestry,
204
+ signal,
205
+ },
206
+ );
207
+ } finally {
208
+ reservation.release();
209
+ }
210
+ try {
211
+ current();
212
+ if (
213
+ sessionPath(started.agent) !== child.sessionFile ||
214
+ (await nativeAgentName(runtime.client, started.agent, signal)) !== agent
215
+ )
216
+ throw new Error(
217
+ "Resumed worker did not open its saved session; inspect the saved session before retrying",
218
+ );
219
+ current();
220
+ recordResumedChild(
221
+ this.pi,
222
+ { ...child, launch: child.launch ?? { args: [], params } },
223
+ started.agent,
224
+ agent,
225
+ );
226
+ return { runtime, panel: started.agent, resumed: true };
227
+ } catch (error) {
228
+ return rollbackStartedAgent(runtime.client, started, error);
229
+ }
230
+ }
231
+ }
@@ -2,11 +2,10 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
+ import { registerSpawnAncestry } from "./ancestry-record.js";
5
6
 
6
7
  export const WORKER_FLAG = "shepherdr-worker";
7
- export const PULSE_WORKER_FLAG = "shepherdr-pulse-worker";
8
8
  const WORKER_MARKER = "herdr-worker-v1";
9
- const LEGACY_PULSE_MARKER = "herdr-pulse-worker-v1";
10
9
  const WORKER_ROLE_CHANNEL = "shepherdr:worker-role:v1";
11
10
 
12
11
  type SessionManager = ExtensionContext["sessionManager"];
@@ -17,44 +16,25 @@ interface WorkerRoleRequest {
17
16
  reply: (worker: boolean) => void;
18
17
  }
19
18
 
20
- function markedWorker(manager: SessionManager, pulseOnly = false): boolean {
19
+ export function markedWorker(manager: SessionManager): boolean {
21
20
  const sessionId = manager.getSessionId();
22
21
  return manager.getEntries().some((entry) => {
23
- if (
24
- entry.type !== "custom" ||
25
- (entry.customType !== WORKER_MARKER &&
26
- entry.customType !== LEGACY_PULSE_MARKER)
27
- )
22
+ if (entry.type !== "custom" || entry.customType !== WORKER_MARKER)
28
23
  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
- );
24
+ const data = entry.data as { sessionId?: unknown } | undefined;
25
+ return data?.sessionId === sessionId;
38
26
  });
39
27
  }
40
28
 
41
29
  export function registerWorkerRole(pi: ExtensionAPI) {
30
+ registerSpawnAncestry(pi);
42
31
  pi.registerFlag(WORKER_FLAG, {
43
32
  type: "boolean",
44
33
  default: false,
45
34
  description: "Run as a supervised Shepherdr worker",
46
35
  });
47
- pi.registerFlag(PULSE_WORKER_FLAG, {
48
- type: "boolean",
49
- default: false,
50
- description: "Run as a detached pulse worker",
51
- });
52
36
  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);
37
+ pi.getFlag(WORKER_FLAG) === true || markedWorker(manager);
58
38
  // Read the supplied native session directly, even before our session_start.
59
39
  pi.events.on(WORKER_ROLE_CHANNEL, (request: unknown) => {
60
40
  const value = request as Partial<WorkerRoleRequest> | undefined;
@@ -66,18 +46,12 @@ export function registerWorkerRole(pi: ExtensionAPI) {
66
46
  value.reply(isWorker(value.sessionManager));
67
47
  });
68
48
  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
- ) {
49
+ if (pi.getFlag(WORKER_FLAG) === true && !markedWorker(ctx.sessionManager)) {
75
50
  // Startup entries would prevent fresh Notes family adoption before work.
76
51
  pi.appendEntry(WORKER_MARKER, {
77
52
  sessionId: ctx.sessionManager.getSessionId(),
78
- ...(pulse ? { pulse: true } : {}),
79
53
  });
80
54
  }
81
55
  });
82
- return { isWorker, isPulseWorker };
56
+ return { isWorker };
83
57
  }
@@ -3,6 +3,12 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ WORKER_PROTOCOL,
8
+ type WorkerService,
9
+ type WorkerStart,
10
+ type WorkerStatus,
11
+ } from "../worker-api.js";
6
12
  import { activityTask } from "./activity.js";
7
13
  import { dispatchAgentWork, reserveAgentName } from "./agents-work.js";
8
14
  import type { AgentBoard } from "./board/host.js";
@@ -10,6 +16,7 @@ import { sessionPath } from "./core/agents.js";
10
16
  import type { AgentFleet } from "./fleet/index.js";
11
17
  import {
12
18
  RolledBackAgentLaunchError,
19
+ resumeAgentArgs,
13
20
  rollbackStartedAgent,
14
21
  startAgent,
15
22
  UnstartedAgentLaunchError,
@@ -17,23 +24,9 @@ import {
17
24
  import { attributeAgentPrompt } from "./messages/attribution.js";
18
25
  import { loadAgentProfiles, profileAgentArgs } from "./profiles.js";
19
26
  import type { SharedAgentContext } from "./shared-context.js";
27
+ import { prepareLaunchAncestry } from "./spawn-ancestry.js";
20
28
  import { ENTRY, panelFor, records } from "./worker-ownership.js";
21
- import { PULSE_WORKER_FLAG, type registerWorkerRole } from "./worker-role.js";
22
-
23
- const RUNNER_PROTOCOL = "@howaboua/pi-pulses/runner/v1";
24
- // Structural implementation of Pulses' optional runner ABI, without a private-package dependency.
25
- interface PulseRun {
26
- taskId: string;
27
- title: string;
28
- prompt: string;
29
- cwd: string;
30
- runId: string;
31
- workerId?: string;
32
- }
33
- interface PulseWorker {
34
- workerId: string;
35
- state: "working" | "idle" | "closed";
36
- }
29
+ import type { registerWorkerRole } from "./worker-role.js";
37
30
 
38
31
  export function registerWorkerService(
39
32
  pi: ExtensionAPI,
@@ -43,13 +36,10 @@ export function registerWorkerService(
43
36
  workerRole: ReturnType<typeof registerWorkerRole>,
44
37
  ): void {
45
38
  let active: ExtensionContext | undefined;
46
- let busy = false;
47
- const isController = (ctx: ExtensionContext) =>
48
- ctx.mode === "tui" && !workerRole.isPulseWorker(ctx.sessionManager);
39
+ let busy: Pick<WorkerStart, "scope" | "key" | "requestId"> | undefined;
49
40
  function assertContext(ctx: ExtensionContext) {
50
- if (!isController(ctx))
51
- throw new Error("Detached workers cannot claim or schedule pulses");
52
41
  if (
42
+ ctx.mode !== "tui" ||
53
43
  !active ||
54
44
  !ctx.sessionManager.getSessionFile() ||
55
45
  ctx.sessionManager.getSessionFile() !==
@@ -59,9 +49,11 @@ export function registerWorkerService(
59
49
  "Worker service is unavailable for this session; retry after session startup",
60
50
  );
61
51
  }
62
- async function owned(ctx: ExtensionContext, workerId: string) {
52
+ async function owned(ctx: ExtensionContext, scope: string, workerId: string) {
63
53
  assertContext(ctx);
64
- const worker = records(ctx).find((value) => value.workerId === workerId);
54
+ const worker = records(ctx).find(
55
+ (value) => value.scope === scope && value.workerId === workerId,
56
+ );
65
57
  if (!worker) throw new Error("Worker is not owned by this session branch");
66
58
  const identity = await fleet.connected().client.machineIdentity();
67
59
  if (identity.host !== worker.host || identity.session !== worker.session)
@@ -71,9 +63,10 @@ export function registerWorkerService(
71
63
 
72
64
  async function inspect(
73
65
  ctx: ExtensionContext,
66
+ scope: string,
74
67
  workerId: string,
75
- ): Promise<PulseWorker> {
76
- const worker = await owned(ctx, workerId);
68
+ ): Promise<WorkerStatus> {
69
+ const worker = await owned(ctx, scope, workerId);
77
70
  const panel = await panelFor(fleet, worker);
78
71
  const record = fleet
79
72
  .connected()
@@ -93,18 +86,22 @@ export function registerWorkerService(
93
86
  : "idle",
94
87
  };
95
88
  }
96
- const service = {
97
- protocol: RUNNER_PROTOCOL,
98
- id: "shepherdr",
99
- isController,
89
+ const service: WorkerService = {
90
+ protocol: WORKER_PROTOCOL,
91
+ id: "shepherdr-workers-v1",
92
+ isWorker: (ctx) => workerRole.isWorker(ctx.sessionManager),
100
93
  inspect,
101
94
  subscribe: (listener: () => void) => fleet.subscribe(listener),
102
- async start(ctx: ExtensionContext, input: PulseRun) {
103
- let stage: "preflight" | "launch" | "dispatch" = "dispatch";
95
+ async start(ctx: ExtensionContext, input: WorkerStart) {
96
+ let stage: "preflight" | "launch" | "dispatch" = "preflight";
104
97
  try {
98
+ if (!input || typeof input !== "object")
99
+ throw new Error("Worker request is required");
105
100
  stage = records(ctx).some(
106
101
  (worker) =>
107
- worker.pulseId === input.taskId && worker.runId === input.runId,
102
+ worker.scope === input.scope &&
103
+ worker.key === input.key &&
104
+ worker.requestId === input.requestId,
108
105
  )
109
106
  ? "dispatch"
110
107
  : "preflight";
@@ -124,36 +121,69 @@ export function registerWorkerService(
124
121
  "Parent branch changed during worker startup; inspect before retrying",
125
122
  );
126
123
  };
127
- if (busy) throw new Error("A worker operation is already in progress");
124
+ if (busy) {
125
+ if (
126
+ busy.scope === input.scope &&
127
+ busy.key === input.key &&
128
+ busy.requestId === input.requestId
129
+ )
130
+ stage = "dispatch";
131
+ throw new Error("A worker operation is already in progress");
132
+ }
128
133
  for (const field of [
129
- "taskId",
134
+ "scope",
135
+ "key",
130
136
  "title",
131
137
  "prompt",
132
138
  "cwd",
133
- "runId",
139
+ "requestId",
134
140
  ] as const)
135
- if (!input[field]?.trim()) throw new Error(`${field} is required`);
141
+ if (typeof input[field] !== "string" || !input[field].trim())
142
+ throw new Error(`${field} is required`);
143
+ if (
144
+ input.workerId !== undefined &&
145
+ (typeof input.workerId !== "string" || !input.workerId.trim())
146
+ )
147
+ throw new Error("workerId must be a non-empty string");
148
+ if (
149
+ input.lifetime !== undefined &&
150
+ input.lifetime !== "parent" &&
151
+ input.lifetime !== "detached"
152
+ )
153
+ throw new Error("Worker lifetime must be parent or detached");
154
+ const lifetime = input.lifetime ?? "parent";
136
155
  if (!isAbsolute(input.cwd))
137
156
  throw new Error("Worker cwd must be absolute");
138
157
  if (input.prompt.trimStart().startsWith("/"))
139
- throw new Error("Scheduled work must be a task, not a slash command");
140
- busy = true;
158
+ throw new Error("Worker work must be a task, not a slash command");
159
+ busy = {
160
+ scope: input.scope,
161
+ key: input.key,
162
+ requestId: input.requestId,
163
+ };
141
164
  try {
142
165
  const runtime = fleet.connected();
143
166
  let worker = records(ctx).find(
144
- (value) => value.pulseId === input.taskId,
167
+ (value) => value.scope === input.scope && value.key === input.key,
145
168
  );
146
169
  if (input.workerId && input.workerId !== worker?.workerId)
147
- throw new Error("Worker is not owned by this pulse in this branch");
148
- if (worker) await owned(ctx, worker.workerId);
170
+ throw new Error(
171
+ "Worker is not owned by this caller in this branch",
172
+ );
173
+ if (worker) await owned(ctx, input.scope, worker.workerId);
174
+ if (worker && worker.lifetime !== lifetime)
175
+ throw new Error(
176
+ "Worker lifetime differs; use its original lifetime or another key",
177
+ );
149
178
  let panel = worker ? await panelFor(fleet, worker) : undefined;
150
- if (worker?.runId === input.runId) {
179
+ if (worker?.requestId === input.requestId) {
151
180
  stage = "dispatch";
152
- return await inspect(ctx, worker.workerId);
181
+ return await inspect(ctx, input.scope, worker.workerId);
153
182
  }
154
183
  if (
155
184
  worker &&
156
- (await inspect(ctx, worker.workerId)).state === "working"
185
+ (await inspect(ctx, input.scope, worker.workerId)).state ===
186
+ "working"
157
187
  )
158
188
  throw new Error("Worker already has active responsibility");
159
189
  if (worker && worker.cwd !== input.cwd)
@@ -164,9 +194,7 @@ export function registerWorkerService(
164
194
  const profile = (await loadAgentProfiles()).get("general");
165
195
  if (!profile)
166
196
  throw new Error("General worker profile is unavailable");
167
- const profileArgs = profileAgentArgs(profile, {
168
- includePrompt: false,
169
- });
197
+ const profileArgs = profileAgentArgs(profile);
170
198
  if (
171
199
  profileArgs.some((arg) =>
172
200
  /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
@@ -178,8 +206,7 @@ export function registerWorkerService(
178
206
  "Worker profile cannot select an existing session",
179
207
  );
180
208
  const args = [
181
- ...profileArgs,
182
- `--${PULSE_WORKER_FLAG}`,
209
+ ...(worker ? resumeAgentArgs(profileArgs) : profileArgs),
183
210
  ...(worker ? ["--session", worker.sessionPath] : []),
184
211
  ];
185
212
  const reservation = await reserveAgentName(runtime, input.title);
@@ -200,13 +227,19 @@ export function registerWorkerService(
200
227
  runtime.client,
201
228
  {
202
229
  name,
203
- label: input.title,
230
+ ...(worker ? {} : { label: input.title }),
204
231
  cwd: input.cwd,
205
232
  placement: "terminal",
233
+ ...(lifetime === "detached"
234
+ ? { outliveParent: true as const }
235
+ : {}),
206
236
  },
207
237
  runtime.fallbackCwd,
208
238
  runtime.resolveDirectory,
209
- { agentArgs: args },
239
+ {
240
+ agentArgs: args,
241
+ ancestry: await prepareLaunchAncestry(ctx, fleet),
242
+ },
210
243
  );
211
244
  try {
212
245
  const relationshipResult = await relationship?.accept(
@@ -228,8 +261,10 @@ export function registerWorkerService(
228
261
  const identity = await runtime.client.machineIdentity();
229
262
  worker = {
230
263
  workerId: worker?.workerId ?? crypto.randomUUID(),
231
- pulseId: input.taskId,
232
- runId: "",
264
+ scope: input.scope,
265
+ lifetime,
266
+ key: input.key,
267
+ requestId: worker?.requestId ?? "",
233
268
  parent: ctx.sessionManager.getSessionFile()!,
234
269
  ...identity,
235
270
  target: panel.pane_id,
@@ -252,7 +287,8 @@ export function registerWorkerService(
252
287
  }
253
288
  if (!worker) throw new Error("Worker ownership is unavailable");
254
289
  const attributed = await attributeAgentPrompt(
255
- runtime.client,
290
+ fleet.connected().client,
291
+ ctx.sessionManager.getSessionId(),
256
292
  input.prompt,
257
293
  "task",
258
294
  );
@@ -272,13 +308,13 @@ export function registerWorkerService(
272
308
  },
273
309
  { expectUserMessage: true },
274
310
  );
275
- worker = { ...worker, runId: input.runId };
311
+ worker = { ...worker, requestId: input.requestId };
276
312
  assertBranch();
277
313
  pi.appendEntry(ENTRY, worker);
278
314
  if (dispatch.warning) ctx.ui.notify(dispatch.warning, "warning");
279
- return inspect(ctx, worker.workerId);
315
+ return inspect(ctx, input.scope, worker.workerId);
280
316
  } finally {
281
- busy = false;
317
+ busy = undefined;
282
318
  }
283
319
  } catch (error) {
284
320
  if (
@@ -297,13 +333,13 @@ export function registerWorkerService(
297
333
  }
298
334
  },
299
335
  };
300
- pi.events.on(`${RUNNER_PROTOCOL}/request`, (request: unknown) => {
336
+ pi.events.on(`${WORKER_PROTOCOL}/request`, (request: unknown) => {
301
337
  const value = request as {
302
338
  protocol?: unknown;
303
339
  accept?: (value: typeof service) => void;
304
340
  };
305
341
  if (
306
- value?.protocol === RUNNER_PROTOCOL &&
342
+ value?.protocol === WORKER_PROTOCOL &&
307
343
  typeof value.accept === "function"
308
344
  )
309
345
  value.accept(service);
package/worker-api.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const WORKER_PROTOCOL = "@howaboua/pi-shepherdr/workers/v1";
4
+
5
+ export interface WorkerStart {
6
+ scope: string;
7
+ key: string;
8
+ requestId: string;
9
+ title: string;
10
+ prompt: string;
11
+ cwd: string;
12
+ workerId?: string;
13
+ lifetime?: "parent" | "detached";
14
+ }
15
+
16
+ export interface WorkerStatus {
17
+ workerId: string;
18
+ state: "working" | "idle" | "closed";
19
+ }
20
+
21
+ /** Discover through `${WORKER_PROTOCOL}/request` with { protocol, accept(service) }.
22
+ * Scheduling and controller eligibility belong to callers, not this service.
23
+ */
24
+ export interface WorkerService {
25
+ protocol: typeof WORKER_PROTOCOL;
26
+ id: string;
27
+ isWorker(ctx: ExtensionContext): boolean;
28
+ /** Admission only. Never retry an uncertain rejection, even with the same requestId.
29
+ * Only dispatched:false proves no submission. Inspection does not clear uncertainty.
30
+ */
31
+ start(ctx: ExtensionContext, input: WorkerStart): Promise<WorkerStatus>;
32
+ inspect(
33
+ ctx: ExtensionContext,
34
+ scope: string,
35
+ workerId: string,
36
+ ): Promise<WorkerStatus>;
37
+ subscribe(listener: () => void): () => void;
38
+ }
@@ -1,32 +0,0 @@
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
- }