@howaboua/pi-shepherdr 0.2.15 → 0.2.17

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 (51) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +42 -33
  3. package/index.ts +16 -26
  4. package/package.json +11 -11
  5. package/src/agents-contract.ts +36 -8
  6. package/src/agents-discovery.ts +23 -7
  7. package/src/agents-focus.ts +242 -0
  8. package/src/agents-spawn.ts +23 -0
  9. package/src/agents-tool.ts +46 -6
  10. package/src/attachment-protocol.ts +7 -3
  11. package/src/attachment-target.ts +3 -1
  12. package/src/attachment.ts +3 -1
  13. package/src/board/host.ts +98 -366
  14. package/src/board/membership.ts +14 -8
  15. package/src/command-config.ts +51 -0
  16. package/src/control-panel-actions.ts +0 -20
  17. package/src/control-panel-items.ts +8 -36
  18. package/src/control-panel-view.ts +2 -11
  19. package/src/control-panel.ts +2 -11
  20. package/src/controller.ts +5 -5
  21. package/src/delivery.ts +0 -33
  22. package/src/herdr-client.ts +52 -6
  23. package/src/messages.ts +61 -61
  24. package/src/monitor-events.ts +24 -2
  25. package/src/monitor-questions.ts +12 -3
  26. package/src/monitor.ts +2 -2
  27. package/src/peer-channel.ts +39 -0
  28. package/src/peer-commands.ts +187 -0
  29. package/src/peer-inbox.ts +232 -55
  30. package/src/remote/shepherdr-channel.mjs +225 -0
  31. package/src/remote/shepherdr-checkpoints.mjs +5 -3
  32. package/src/remote/shepherdr-peer.mjs +198 -22
  33. package/src/remote/shepherdr.mjs +63 -8
  34. package/src/remote-client.ts +121 -11
  35. package/src/settlement.ts +1 -0
  36. package/src/shared-context.ts +104 -1
  37. package/src/types.ts +29 -0
  38. package/src/voice-handoff.ts +177 -0
  39. package/src/board/archive.ts +0 -77
  40. package/src/board/awareness.ts +0 -115
  41. package/src/board/config.ts +0 -121
  42. package/src/board/contract.ts +0 -181
  43. package/src/board/identity.ts +0 -169
  44. package/src/board/paging.ts +0 -55
  45. package/src/board/protocol.ts +0 -73
  46. package/src/board/queries.ts +0 -176
  47. package/src/board/response.ts +0 -56
  48. package/src/board/store.ts +0 -327
  49. package/src/board/tool.ts +0 -23
  50. package/src/board/turns.ts +0 -100
  51. package/src/context-briefing.ts +0 -226
package/src/board/host.ts CHANGED
@@ -3,221 +3,131 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import type { AgentFleet, ConnectedMachine } from "../fleet.js";
7
- import { sessionPath } from "../herdr.js";
8
- import { recordBoardPostMarker } from "../messages.js";
9
- import {
10
- requestContext,
11
- sessionContextPath,
12
- } from "../remote/shepherdr-context.mjs";
13
- import { executeArchive } from "./archive.js";
14
- import { BoardAwareness } from "./awareness.js";
15
- import {
16
- type BoardScope,
17
- readBoardConfig,
18
- writeBoardConfig,
19
- } from "./config.js";
20
- import {
21
- agentPath,
22
- type BoardParams,
23
- boardHelp,
24
- parseBoardRequest,
25
- } from "./contract.js";
26
6
  import {
27
7
  binding,
28
8
  children,
29
- members,
30
9
  parseBinding,
31
10
  rootBoardSetting,
32
11
  saveBinding,
33
- saveBoardSetting,
34
12
  saveChild,
35
- sessionBoardSetting,
36
- } from "./identity.js";
13
+ } from "@howaboua/pi-agent-board/integration";
14
+ import {
15
+ type BoardRuntime,
16
+ discoverBoard,
17
+ } from "@howaboua/pi-agent-board/runtime";
18
+ import type { AgentFleet, ConnectedMachine } from "../fleet.js";
19
+ import { sessionPath } from "../herdr.js";
20
+ import { boardBriefing, boardMigrationWarning } from "../messages.js";
21
+ import {
22
+ requestContext,
23
+ sessionContextPath,
24
+ } from "../remote/shepherdr-context.mjs";
37
25
  import { BoardMembership } from "./membership.js";
38
- import { type BoardEnvelope, parseEnvelope } from "./protocol.js";
39
- import { BoardTurns } from "./turns.js";
40
26
 
27
+ /** Private fleet adapter: spawning and attachment policy never enters the shared engine. */
41
28
  export class AgentBoard {
42
- private readonly listeners = new Set<() => void>();
43
- subscribe(listener: () => void): () => void {
44
- this.listeners.add(listener);
45
- return () => {
46
- this.listeners.delete(listener);
47
- };
48
- }
49
- private changed() {
50
- for (const listener of this.listeners) listener();
51
- }
52
29
  readonly membership: BoardMembership;
53
30
  private readonly pi: ExtensionAPI;
54
- private readonly fleet: AgentFleet;
55
- private readonly turns: BoardTurns;
56
- private readonly awareness: BoardAwareness;
57
- private refreshTools: (() => void) | undefined;
58
- private lastSetting: { sessionId: string; enabled: boolean } | undefined;
59
- private configError: string | undefined;
60
- constructor(pi: ExtensionAPI, fleet: AgentFleet) {
31
+ private runtime: BoardRuntime | undefined;
32
+ private constructor(pi: ExtensionAPI, fleet: AgentFleet) {
61
33
  this.pi = pi;
62
- this.fleet = fleet;
63
- this.awareness = new BoardAwareness(pi, (ctx) => this.population(ctx));
64
- this.turns = new BoardTurns(pi, (ctx, request) =>
65
- this.toOwner(ctx, request),
66
- );
67
34
  this.membership = new BoardMembership(
68
35
  pi,
69
- (ctx, request) => this.toOwner(ctx, request),
70
- this.turns.active,
36
+ (ctx, request) => this.owner().toOwner(ctx, request),
37
+ () => this.owner().active,
71
38
  );
72
- pi.on("session_start", (_event, ctx) => this.refresh(ctx));
73
- pi.on("before_agent_start", async (_event, ctx) => {
74
- // Reconcile resumed/offline children before tool/prompt preparation.
75
- const own = binding(ctx);
76
- if (own.upstream) {
77
- try {
78
- const result = await this.toOwner(ctx, {
79
- operation: "board-call",
80
- caller: own,
81
- params: { action: "help" },
82
- requestId: "status",
83
- });
84
- if (
85
- typeof result === "object" &&
86
- result !== null &&
87
- "enabled" in result &&
88
- typeof result.enabled === "boolean" &&
89
- result.enabled !== own.enabled
90
- )
91
- saveBinding(pi, { ...own, enabled: result.enabled });
92
- } catch (error) {
93
- if (own.enabled)
94
- ctx.ui.notify(
95
- `Board owner unavailable: ${String(error)}`,
96
- "warning",
97
- );
39
+ const warned = new Set<string>();
40
+ pi.on("session_start", (_event, ctx) => {
41
+ const sessionId = ctx.sessionManager.getSessionId();
42
+ if (this.runtime || warned.has(sessionId)) return;
43
+ try {
44
+ const setting = rootBoardSetting(ctx);
45
+ if (setting.error) throw new Error(setting.error);
46
+ if (binding(ctx).enabled) {
47
+ warned.add(sessionId);
48
+ ctx.ui.notify(boardMigrationWarning(), "warning");
98
49
  }
50
+ } catch (error) {
51
+ ctx.ui.notify(
52
+ `Could not restore saved board settings: ${String(error)}`,
53
+ "error",
54
+ );
99
55
  }
100
- await this.refresh(ctx);
56
+ });
57
+ discoverBoard(pi, (runtime) => {
58
+ this.runtime = runtime;
59
+ runtime.attach({
60
+ briefing: boardBriefing,
61
+ request: requestContext,
62
+ commitDirectory: (own, directory, caller, request) =>
63
+ this.membership.commitDirectory(own, directory, caller, request),
64
+ routeNotice: (ctx, request, signal) => {
65
+ const child = children(ctx).find(
66
+ (entry) =>
67
+ request.target === entry.binding.agentName ||
68
+ request.target.startsWith(`${entry.binding.agentName}/`),
69
+ );
70
+ if (!child) return Promise.resolve(false);
71
+ return fleet
72
+ .connected(child.machine)
73
+ .client.requestContext(
74
+ sessionContextPath(child.sessionFile),
75
+ request,
76
+ signal,
77
+ );
78
+ },
79
+ propagateEnabled: async (ctx, enabled) => {
80
+ await Promise.all(
81
+ children(ctx).map(async (child) => {
82
+ try {
83
+ await fleet.connected(child.machine).client.requestContext(
84
+ sessionContextPath(child.sessionFile),
85
+ {
86
+ operation: "board-enabled",
87
+ boardId: binding(ctx).boardId,
88
+ enabled,
89
+ },
90
+ AbortSignal.timeout(750),
91
+ );
92
+ } catch {
93
+ /* Resumed children reconcile before their next user turn. */
94
+ }
95
+ }),
96
+ );
97
+ },
98
+ });
101
99
  });
102
100
  }
103
- setToolRefresh(refresh: () => void) {
104
- this.refreshTools = refresh;
101
+ static create(pi: ExtensionAPI, fleet: AgentFleet) {
102
+ return new AgentBoard(pi, fleet);
105
103
  }
106
- private async population(ctx: ExtensionContext) {
107
- const own = binding(ctx);
108
- if (own.upstream) {
109
- const status = await this.toOwner(
110
- ctx,
111
- {
112
- operation: "board-call",
113
- caller: own,
114
- params: { action: "help" },
115
- requestId: "briefing-status",
116
- },
117
- ctx.signal,
104
+ private owner() {
105
+ if (!this.runtime)
106
+ throw new Error(
107
+ "Shared boards are unavailable; use agents for coordination",
118
108
  );
119
- if (
120
- !status ||
121
- typeof status !== "object" ||
122
- !("enabled" in status) ||
123
- typeof status.enabled !== "boolean"
124
- )
125
- throw new Error("Board status unavailable");
126
- if (status.enabled !== own.enabled) {
127
- saveBinding(this.pi, { ...own, enabled: status.enabled });
128
- await this.refresh(ctx);
129
- }
130
- if (!status.enabled) return;
131
- }
132
- return this.execute(
133
- ctx,
134
- { action: "search_posts", limit: 1, max_chars_per_post: 1 },
135
- "briefing",
136
- );
109
+ return this.runtime;
110
+ }
111
+ requireAvailable() {
112
+ this.owner();
137
113
  }
138
114
  enabled(ctx: ExtensionContext | undefined) {
139
- return ctx ? binding(ctx).enabled : false;
115
+ return this.runtime?.enabled(ctx) ?? false;
140
116
  }
141
- async refresh(ctx: ExtensionContext) {
142
- const own = binding(ctx);
143
- this.awareness.refresh(ctx);
144
- const setting = own.upstream ? undefined : rootBoardSetting(ctx);
145
- if (setting?.error && setting.error !== this.configError)
146
- ctx.ui.notify(`Board disabled: ${setting.error}`, "error");
147
- this.configError = setting?.error;
148
- const active = this.pi.getActiveTools().filter((name) => name !== "board");
149
- if (own.enabled) active.push("board");
150
- this.pi.setActiveTools(active);
151
- this.refreshTools?.();
152
- if (!own.enabled) this.turns.active.clear();
153
- const changed =
154
- this.lastSetting?.sessionId !== own.sessionId ||
155
- this.lastSetting.enabled !== own.enabled;
156
- this.lastSetting = { sessionId: own.sessionId, enabled: own.enabled };
157
- this.changed();
158
- if (changed && !own.upstream) await this.propagateEnabled(ctx, own.enabled);
117
+ refresh(ctx: ExtensionContext) {
118
+ return this.owner().refresh(ctx);
159
119
  }
160
- settings(ctx: ExtensionContext) {
161
- const own = binding(ctx);
162
- if (own.upstream)
163
- throw new Error("Change the board setting in the owning root session");
164
- return {
165
- ...readBoardConfig(own.ownerFolder),
166
- session: sessionBoardSetting(ctx),
167
- };
168
- }
169
- async setSetting(
170
- ctx: ExtensionContext,
171
- scope: BoardScope,
172
- enabled: boolean | undefined,
173
- ) {
174
- if (!ctx.isIdle())
175
- throw new Error("Change the board setting after this session settles");
176
- const own = binding(ctx);
177
- if (own.upstream)
178
- throw new Error("Change the board setting in the owning root session");
179
- if (scope === "session") saveBoardSetting(this.pi, ctx, enabled);
180
- else writeBoardConfig(own.ownerFolder, scope, enabled);
181
- await this.refresh(ctx);
120
+ execute(ctx: ExtensionContext, input: unknown, requestId: string) {
121
+ return this.owner().execute(ctx, input, requestId);
182
122
  }
183
- status(ctx: ExtensionContext, includeArchive = true) {
184
- const own = binding(ctx);
185
- const setting = own.upstream ? undefined : rootBoardSetting(ctx);
186
- return `Board ${own.enabled ? "on" : "off"} (${setting?.source ?? "inherited from owner"})${includeArchive ? `. ${own.boardId}\nArchive: ${own.databasePath}` : ""}${setting?.error ? `\n${setting.error}` : ""}`;
123
+ handle(ctx: ExtensionContext, value: unknown, signal?: AbortSignal) {
124
+ return this.owner().handle(ctx, value, signal);
187
125
  }
188
- async execute(ctx: ExtensionContext, input: unknown, requestId: string) {
189
- const params = parseBoardRequest(input);
190
- const caller = binding(ctx);
191
- if (!caller.upstream) {
192
- const setting = rootBoardSetting(ctx);
193
- if (setting.error) throw new Error(setting.error);
194
- }
195
- if (!caller.enabled)
196
- throw new Error(
197
- "Board is off; the user can enable it in /herdr → Settings",
198
- );
199
- const value = await this.toOwner(
200
- ctx,
201
- {
202
- operation: "board-call",
203
- caller,
204
- params,
205
- requestId,
206
- },
207
- ctx.signal,
126
+ promptCatchup(ctx: ExtensionContext) {
127
+ return (
128
+ this.runtime?.promptCatchup(ctx) ??
129
+ Promise.resolve({ content: "", accepted() {} })
208
130
  );
209
- if (params.action === "post") {
210
- try {
211
- recordBoardPostMarker(this.pi, ctx, value);
212
- } catch {
213
- // Presentation failure must not turn a committed post into a retry.
214
- ctx.ui.notify(
215
- "Posted to board. Its history notice is unavailable. Read the board to check the post; do not repost.",
216
- "warning",
217
- );
218
- }
219
- }
220
- return value;
221
131
  }
222
132
  async prepare(
223
133
  ctx: ExtensionContext,
@@ -225,8 +135,8 @@ export class AgentBoard {
225
135
  name: string,
226
136
  args: readonly string[],
227
137
  ) {
138
+ if (!this.enabled(ctx)) return undefined;
228
139
  const own = binding(ctx);
229
- if (!own.enabled) return undefined;
230
140
  if (
231
141
  args.some((arg) =>
232
142
  /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
@@ -272,7 +182,7 @@ export class AgentBoard {
272
182
  throw new Error("Spawned agent did not adopt its board binding");
273
183
  if (ctx.sessionManager.getSessionId() !== own.sessionId)
274
184
  throw new Error("Controller session changed during board binding");
275
- await this.toOwner(ctx, {
185
+ await this.owner().toOwner(ctx, {
276
186
  operation: "board-register",
277
187
  caller: own,
278
188
  member: adopted,
@@ -287,182 +197,4 @@ export class AgentBoard {
287
197
  },
288
198
  };
289
199
  }
290
- async handle(
291
- ctx: ExtensionContext,
292
- value: unknown,
293
- signal?: AbortSignal,
294
- ): Promise<unknown> {
295
- const request = parseEnvelope(value);
296
- const own = binding(ctx);
297
- if (request.operation === "board-bind") {
298
- if (
299
- !ctx.isIdle() ||
300
- ctx.sessionManager
301
- .getEntries()
302
- .some(
303
- (entry) =>
304
- (entry.type === "message" &&
305
- ["user", "assistant"].includes(entry.message.role)) ||
306
- (entry.type === "custom" &&
307
- entry.customType === "shepherdr-board-binding"),
308
- )
309
- )
310
- throw new Error(
311
- "Bind board identity only in a fresh idle child before its first task",
312
- );
313
- const adopted = { ...request.binding, sessionId: own.sessionId };
314
- saveBinding(this.pi, adopted);
315
- await this.refresh(ctx);
316
- return adopted;
317
- }
318
- if (request.operation === "board-enabled") {
319
- if (!own.upstream || request.boardId !== own.boardId)
320
- throw new Error("Invalid board setting route");
321
- saveBinding(this.pi, { ...own, enabled: request.enabled });
322
- await this.refresh(ctx);
323
- await this.propagateEnabled(ctx, request.enabled);
324
- return true;
325
- }
326
- if (request.operation === "board-notify") {
327
- if (!own.enabled || request.boardId !== own.boardId) return false;
328
- if (request.target === own.agentName) return this.turns.deliver(request);
329
- return this.routeNotice(ctx, request, signal);
330
- }
331
- return this.toOwner(ctx, request, signal);
332
- }
333
- private async toOwner(
334
- ctx: ExtensionContext,
335
- request: BoardEnvelope,
336
- signal?: AbortSignal,
337
- ): Promise<unknown> {
338
- const own = binding(ctx);
339
- if (own.upstream) {
340
- try {
341
- return await requestContext(own.upstream, request, signal);
342
- } catch (error) {
343
- if (
344
- error instanceof Error &&
345
- error.message.startsWith("Shared context response was lost")
346
- )
347
- throw new Error(
348
- "Board response lost; a mutation may have completed. Read the channel/thread before retrying",
349
- { cause: error },
350
- );
351
- if (
352
- error instanceof Error &&
353
- error.message.startsWith("Shared context owner is unavailable")
354
- )
355
- throw new Error(
356
- "Board owner unavailable; resume its Pi session and reconnect its machine",
357
- { cause: error },
358
- );
359
- throw error;
360
- }
361
- }
362
- if (!("caller" in request)) throw new Error("Invalid board owner request");
363
- const directory = members(ctx);
364
- const caller = directory.find(
365
- (member) =>
366
- member.sessionId === request.caller.sessionId &&
367
- member.agentName === request.caller.agentName,
368
- );
369
- if (
370
- !caller ||
371
- request.caller.boardId !== own.boardId ||
372
- request.caller.databasePath !== own.databasePath
373
- )
374
- throw new Error("Caller not bound to this board");
375
- if (
376
- request.operation === "board-unregister" ||
377
- request.operation === "board-register"
378
- )
379
- return this.membership.commitDirectory(own, directory, caller, request);
380
- if (request.operation === "board-active") {
381
- if (own.enabled) this.turns.register(caller, request);
382
- return true;
383
- }
384
- if (request.operation !== "board-call")
385
- throw new Error("Invalid board owner operation");
386
- const params = parseBoardRequest(request.params);
387
- if (params.action === "help") return { ...boardHelp, enabled: own.enabled };
388
- if (!own.enabled)
389
- throw new Error(
390
- "Board is off; the user can enable it in /herdr → Settings",
391
- );
392
- const prepared: BoardParams =
393
- params.author === undefined
394
- ? params
395
- : { ...params, author: agentPath(params.author, caller.agentName) };
396
- const active = new Map(this.turns.active);
397
- const result = await executeArchive(
398
- { ...caller, enabled: own.enabled },
399
- directory.map((member) => member.agentName),
400
- prepared,
401
- request.requestId,
402
- );
403
- if ("notice" in result && result.notice) {
404
- for (let start = 0; start < result.recipients.length; start += 16) {
405
- await Promise.all(
406
- result.recipients.slice(start, start + 16).map(async (target) => {
407
- const turn = active.get(target);
408
- if (!turn) return;
409
- try {
410
- await this.handle(
411
- ctx,
412
- {
413
- operation: "board-notify",
414
- boardId: own.boardId,
415
- target,
416
- ...turn,
417
- notice: result.notice,
418
- },
419
- AbortSignal.timeout(750),
420
- );
421
- } catch {
422
- /* Committed posts succeed even when a running turn stops accepting. */
423
- }
424
- }),
425
- );
426
- }
427
- }
428
- return result.value;
429
- }
430
- private async routeNotice(
431
- ctx: ExtensionContext,
432
- request: Extract<BoardEnvelope, { operation: "board-notify" }>,
433
- signal?: AbortSignal,
434
- ) {
435
- const child = children(ctx).find(
436
- (entry) =>
437
- request.target === entry.binding.agentName ||
438
- request.target.startsWith(`${entry.binding.agentName}/`),
439
- );
440
- if (!child) return false;
441
- return this.fleet
442
- .connected(child.machine)
443
- .client.requestContext(
444
- sessionContextPath(child.sessionFile),
445
- request,
446
- signal,
447
- );
448
- }
449
- private async propagateEnabled(ctx: ExtensionContext, enabled: boolean) {
450
- await Promise.all(
451
- children(ctx).map(async (child) => {
452
- try {
453
- await this.fleet.connected(child.machine).client.requestContext(
454
- sessionContextPath(child.sessionFile),
455
- {
456
- operation: "board-enabled",
457
- boardId: binding(ctx).boardId,
458
- enabled,
459
- },
460
- AbortSignal.timeout(750),
461
- );
462
- } catch {
463
- /* Resumed children reconcile with their owner before the next user turn. */
464
- }
465
- }),
466
- );
467
- }
468
200
  }
@@ -3,7 +3,7 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import type { ConnectedMachine } from "../fleet.js";
6
+ import type { BoardEnvelope } from "@howaboua/pi-agent-board/integration";
7
7
  import {
8
8
  type BoardBinding,
9
9
  binding,
@@ -13,8 +13,8 @@ import {
13
13
  saveBinding,
14
14
  saveChild,
15
15
  saveMember,
16
- } from "./identity.js";
17
- import type { BoardEnvelope } from "./protocol.js";
16
+ } from "@howaboua/pi-agent-board/integration";
17
+ import type { ConnectedMachine } from "../fleet.js";
18
18
 
19
19
  function sameMembership(left: BoardBinding, right: BoardBinding) {
20
20
  return isDeepStrictEqual(
@@ -30,26 +30,28 @@ export class BoardMembership {
30
30
  ctx: ExtensionContext,
31
31
  request: BoardEnvelope,
32
32
  ) => Promise<unknown>;
33
- private readonly active: Map<string, unknown>;
33
+ private readonly getActive: () => Map<string, unknown>;
34
34
  constructor(
35
35
  pi: ExtensionAPI,
36
36
  toOwner: (
37
37
  ctx: ExtensionContext,
38
38
  request: BoardEnvelope,
39
39
  ) => Promise<unknown>,
40
- active: Map<string, unknown>,
40
+ getActive: () => Map<string, unknown>,
41
41
  ) {
42
42
  this.pi = pi;
43
43
  this.toOwner = toOwner;
44
- this.active = active;
44
+ this.getActive = getActive;
45
45
  }
46
46
  inspectAttachment(ctx: ExtensionContext) {
47
+ this.getActive();
47
48
  const own = binding(ctx);
48
49
  if (own.upstream || children(ctx).length || members(ctx).length > 1)
49
50
  throw new Error("Target already owns or belongs to a board family");
50
51
  return own;
51
52
  }
52
53
  prepareAttachment(ctx: ExtensionContext, upstream: string, name: string) {
54
+ this.getActive();
53
55
  const own = binding(ctx);
54
56
  if (!own.enabled)
55
57
  throw new Error(
@@ -64,6 +66,7 @@ export class BoardMembership {
64
66
  expected: BoardBinding,
65
67
  desired: BoardBinding,
66
68
  ) {
69
+ this.getActive();
67
70
  if (!ctx.isIdle())
68
71
  throw new Error("Attach a board only after the target settles");
69
72
  const own = binding(ctx);
@@ -83,6 +86,7 @@ export class BoardMembership {
83
86
  adopted: BoardBinding,
84
87
  expected: BoardBinding,
85
88
  ) {
89
+ this.getActive();
86
90
  if (!isDeepStrictEqual(binding(ctx), expected))
87
91
  throw new Error("Controller board changed during attachment");
88
92
  saveBinding(this.pi, expected);
@@ -105,6 +109,7 @@ export class BoardMembership {
105
109
  desired: BoardBinding,
106
110
  previous: BoardBinding,
107
111
  ) {
112
+ this.getActive();
108
113
  if (children(ctx).length)
109
114
  throw new Error(
110
115
  "Detach a board member only when it has no board children",
@@ -117,9 +122,10 @@ export class BoardMembership {
117
122
  )
118
123
  throw new Error("Target board changed before detach");
119
124
  saveBinding(this.pi, previous);
120
- this.active.clear();
125
+ this.getActive().clear();
121
126
  }
122
127
  async unregisterAttachment(ctx: ExtensionContext, member: BoardBinding) {
128
+ this.getActive();
123
129
  const own = binding(ctx);
124
130
  await this.toOwner(ctx, {
125
131
  operation: "board-unregister",
@@ -161,7 +167,7 @@ export class BoardMembership {
161
167
  if (existing && !sameMembership(existing, member))
162
168
  throw new Error("Board member changed before detach");
163
169
  removeMember(this.pi, member);
164
- this.active.delete(member.agentName);
170
+ this.getActive().delete(member.agentName);
165
171
  return true;
166
172
  }
167
173
  if (request.operation === "board-register") {
@@ -0,0 +1,51 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ export function commandConfigPath(): string {
6
+ return resolve(getAgentDir(), "pi-shepherdr.json");
7
+ }
8
+
9
+ function object(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+
13
+ export function readExtensionCommands(): Record<string, string> {
14
+ const path = commandConfigPath();
15
+ let source: string;
16
+ try {
17
+ source = readFileSync(path, "utf8");
18
+ } catch (error) {
19
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
20
+ return {};
21
+ throw new Error(`Could not read ${path}: ${String(error)}`, {
22
+ cause: error,
23
+ });
24
+ }
25
+ try {
26
+ const document: unknown = JSON.parse(source);
27
+ if (!object(document)) throw new Error("configuration must be an object");
28
+ const commands = document["extensionCommands"];
29
+ if (commands === undefined) return {};
30
+ if (!object(commands))
31
+ throw new Error("extensionCommands must be an object");
32
+ const entries = Object.entries(commands);
33
+ const validated: [string, string][] = [];
34
+ for (const [name, description] of entries) {
35
+ if (!/^[^\s/]+$/.test(name))
36
+ throw new Error(
37
+ "extension command names must be nonempty, without slashes or whitespace",
38
+ );
39
+ if (typeof description !== "string" || !description.trim())
40
+ throw new Error(
41
+ `extensionCommands.${name} must be a nonempty description`,
42
+ );
43
+ validated.push([name, description]);
44
+ }
45
+ return Object.fromEntries(validated);
46
+ } catch (error) {
47
+ throw new Error(`Could not read ${path}: ${String(error)}`, {
48
+ cause: error,
49
+ });
50
+ }
51
+ }