@howaboua/pi-agent-board 0.0.3 → 0.0.5

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.
@@ -0,0 +1,278 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { recordBoardActivityMarker } from "../activity.js";
6
+ import { BoardAwareness } from "../awareness.js";
7
+ import {
8
+ type BoardScope,
9
+ writeBoardConfig,
10
+ writeBoardSummaryAutomatic,
11
+ } from "../config.js";
12
+ import { gptBoardHelp, parseBoardRequest } from "../contract.js";
13
+ import { preparePolicyMessage } from "../delivery.js";
14
+ import {
15
+ binding,
16
+ rootBoardSetting,
17
+ saveBinding,
18
+ saveBoardSetting,
19
+ setBoardDefault,
20
+ } from "../identity.js";
21
+ import type { BoardAdapter } from "../integration.js";
22
+ import { type BoardEnvelope } from "../protocol.js";
23
+ import { BoardSummarizer } from "../summarizer.js";
24
+ import { BoardCatchup } from "./catchup.js";
25
+ import { BoardOwner } from "./owner.js";
26
+ import { BoardRouting } from "./routing.js";
27
+ import { BoardTurns } from "./turns.js";
28
+
29
+ export class BoardRuntime {
30
+ gptPromptMode = false;
31
+ private preparePromptMode: ((ctx: ExtensionContext) => void) | undefined;
32
+ private readonly pi: ExtensionAPI;
33
+ private readonly routing: BoardRouting;
34
+ private readonly turns: BoardTurns;
35
+ private readonly owner: BoardOwner;
36
+ private readonly awareness: BoardAwareness;
37
+ private readonly catchup: BoardCatchup;
38
+ private readonly summarizer = new BoardSummarizer();
39
+ private refreshTools: (() => void) | undefined;
40
+ private lastSetting: { sessionId: string; enabled: boolean } | undefined;
41
+ private configError: string | undefined;
42
+ private availabilityWarning: string | undefined;
43
+ constructor(pi: ExtensionAPI) {
44
+ this.pi = pi;
45
+ const availability = (ctx: ExtensionContext, error?: unknown) =>
46
+ this.reportAvailability(ctx, error);
47
+ this.awareness = new BoardAwareness(
48
+ pi,
49
+ (ctx) => this.population(ctx),
50
+ availability,
51
+ () => this.routing.adapter?.briefing,
52
+ () => this.gptPromptMode,
53
+ );
54
+ this.catchup = new BoardCatchup(
55
+ pi,
56
+ this.awareness,
57
+ (ctx, request) => this.toOwner(ctx, request),
58
+ availability,
59
+ () => this.gptPromptMode,
60
+ );
61
+ this.turns = new BoardTurns(
62
+ pi,
63
+ (ctx, request) => this.toOwner(ctx, request),
64
+ availability,
65
+ (ctx, ids) => this.awareness.markSeen(ctx, ids),
66
+ );
67
+ this.owner = new BoardOwner(
68
+ this.turns,
69
+ this.summarizer,
70
+ () => this.routing.adapter,
71
+ () => this.routing.requireAdapter(),
72
+ (ctx, request, signal) => this.handle(ctx, request, signal),
73
+ );
74
+ this.routing = new BoardRouting(
75
+ pi,
76
+ this.turns,
77
+ this.owner,
78
+ (ctx) => this.refresh(ctx),
79
+ availability,
80
+ );
81
+ pi.on("session_start", (_event, ctx) => {
82
+ this.summarizer.cancelAll();
83
+ this.availabilityWarning = undefined;
84
+ setBoardDefault(ctx, true);
85
+ return this.refresh(ctx);
86
+ });
87
+ pi.on("session_shutdown", () => this.summarizer.cancelAll());
88
+ pi.on("before_agent_start", async (_event, ctx) => {
89
+ this.preparePromptMode?.(ctx);
90
+ // Reconcile resumed/offline children before tool/prompt preparation.
91
+ const own = binding(ctx);
92
+ if (own.upstream) {
93
+ try {
94
+ const result = await this.toOwner(ctx, {
95
+ operation: "board-call",
96
+ caller: own,
97
+ params: { action: "help" },
98
+ requestId: "status",
99
+ });
100
+ availability(ctx);
101
+ if (
102
+ typeof result === "object" &&
103
+ result !== null &&
104
+ "enabled" in result &&
105
+ typeof result.enabled === "boolean" &&
106
+ result.enabled !== own.enabled
107
+ )
108
+ saveBinding(pi, { ...own, enabled: result.enabled });
109
+ } catch (error) {
110
+ if (own.enabled) availability(ctx, error);
111
+ }
112
+ }
113
+ await this.refresh(ctx);
114
+ const catchup = await this.promptCatchup(ctx);
115
+ catchup.accepted();
116
+ if (catchup.content)
117
+ return {
118
+ message: preparePolicyMessage({
119
+ customType: "shepherdr-board-catchup",
120
+ content: catchup.content.trim(),
121
+ display: true,
122
+ }),
123
+ };
124
+ });
125
+ }
126
+ private reportAvailability(ctx: ExtensionContext, error?: unknown): void {
127
+ const own = binding(ctx);
128
+ if (error === undefined || !own.enabled) {
129
+ this.availabilityWarning = undefined;
130
+ return;
131
+ }
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ const key = JSON.stringify([
134
+ own.sessionId,
135
+ own.boardId,
136
+ own.upstream,
137
+ message,
138
+ ]);
139
+ if (this.availabilityWarning === key) return;
140
+ this.availabilityWarning = key;
141
+ ctx.ui.notify(`Board unavailable: ${message}`, "warning");
142
+ }
143
+ setToolRefresh(refresh: () => void) {
144
+ this.refreshTools = refresh;
145
+ }
146
+ setPromptModePreparation(prepare: (ctx: ExtensionContext) => void) {
147
+ this.preparePromptMode = prepare;
148
+ }
149
+ private async population(ctx: ExtensionContext) {
150
+ const own = binding(ctx);
151
+ if (own.upstream) {
152
+ const status = await this.toOwner(
153
+ ctx,
154
+ {
155
+ operation: "board-call",
156
+ caller: own,
157
+ params: { action: "help" },
158
+ requestId: "briefing-status",
159
+ },
160
+ ctx.signal,
161
+ );
162
+ if (
163
+ !status ||
164
+ typeof status !== "object" ||
165
+ !("enabled" in status) ||
166
+ typeof status.enabled !== "boolean"
167
+ )
168
+ throw new Error("Board status unavailable");
169
+ if (status.enabled !== own.enabled) {
170
+ saveBinding(this.pi, { ...own, enabled: status.enabled });
171
+ await this.refresh(ctx);
172
+ }
173
+ if (!status.enabled) return;
174
+ }
175
+ return this.execute(
176
+ ctx,
177
+ { action: "search_posts", limit: 1, max_chars_per_post: 1 },
178
+ "briefing",
179
+ );
180
+ }
181
+ enabled(ctx: ExtensionContext | undefined) {
182
+ return ctx ? binding(ctx).enabled : false;
183
+ }
184
+ async promptCatchup(ctx: ExtensionContext) {
185
+ return this.catchup.read(ctx);
186
+ }
187
+ async refresh(ctx: ExtensionContext) {
188
+ const own = binding(ctx);
189
+ this.awareness.refresh(ctx);
190
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
191
+ if (setting?.error && setting.error !== this.configError)
192
+ ctx.ui.notify(`Board disabled: ${setting.error}`, "error");
193
+ this.configError = setting?.error;
194
+ const active = this.pi.getActiveTools().filter((name) => name !== "board");
195
+ if (own.enabled) active.push("board");
196
+ this.pi.setActiveTools(active);
197
+ this.refreshTools?.();
198
+ if (!own.enabled) {
199
+ this.turns.active.clear();
200
+ this.summarizer.cancelAll();
201
+ }
202
+ const changed =
203
+ this.lastSetting?.sessionId !== own.sessionId ||
204
+ this.lastSetting.enabled !== own.enabled;
205
+ this.lastSetting = { sessionId: own.sessionId, enabled: own.enabled };
206
+ if (changed && !own.upstream)
207
+ await this.routing.propagateEnabled(ctx, own.enabled);
208
+ }
209
+ async setSetting(ctx: ExtensionContext, scope: BoardScope, enabled: boolean) {
210
+ if (!ctx.isIdle())
211
+ throw new Error("Change the board setting after this session settles");
212
+ const own = binding(ctx);
213
+ if (own.upstream)
214
+ throw new Error("Change the board setting in the owning root session");
215
+ if (scope === "session") saveBoardSetting(this.pi, ctx, enabled);
216
+ else writeBoardConfig(own.ownerFolder, scope, enabled);
217
+ await this.refresh(ctx);
218
+ }
219
+ status(ctx: ExtensionContext, includeArchive = true) {
220
+ const own = binding(ctx);
221
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
222
+ return `Board ${own.enabled ? "on" : "off"} (${setting?.source ?? "inherited from owner"})${includeArchive ? `. ${own.boardId}\nArchive: ${own.databasePath}` : ""}${setting?.error ? `\n${setting.error}` : ""}`;
223
+ }
224
+ setAutomaticSummaries(ctx: ExtensionContext, automatic: boolean) {
225
+ writeBoardSummaryAutomatic(ctx.cwd, automatic);
226
+ if (!automatic) this.summarizer.cancelAll();
227
+ }
228
+ async execute(ctx: ExtensionContext, input: unknown, requestId: string) {
229
+ const params = parseBoardRequest(input);
230
+ const caller = binding(ctx);
231
+ if (!caller.upstream) {
232
+ const setting = rootBoardSetting(ctx);
233
+ if (setting.error) throw new Error(setting.error);
234
+ }
235
+ if (!caller.enabled)
236
+ throw new Error("Board is off; the user can enable it with /board on");
237
+ const value = await this.toOwner(
238
+ ctx,
239
+ {
240
+ operation: "board-call",
241
+ caller,
242
+ params,
243
+ requestId,
244
+ },
245
+ ctx.signal,
246
+ );
247
+ if (params.action === "read_thread" || params.action === "read_post")
248
+ this.awareness.markRead(ctx, value);
249
+ try {
250
+ recordBoardActivityMarker(this.pi, ctx, params, value, requestId);
251
+ } catch {
252
+ // Presentation failure must not turn a successful operation into a retry.
253
+ ctx.ui.notify(
254
+ "Board action succeeded. Its history notice is unavailable. Do not repeat writes just to restore the notice.",
255
+ "warning",
256
+ );
257
+ }
258
+ return params.action === "help" && this.gptPromptMode
259
+ ? gptBoardHelp(value)
260
+ : value;
261
+ }
262
+ async handle(ctx: ExtensionContext, value: unknown, signal?: AbortSignal) {
263
+ return this.routing.handle(ctx, value, signal);
264
+ }
265
+ async toOwner(
266
+ ctx: ExtensionContext,
267
+ request: BoardEnvelope,
268
+ signal?: AbortSignal,
269
+ ) {
270
+ return this.routing.toOwner(ctx, request, signal);
271
+ }
272
+ attach(adapter: BoardAdapter) {
273
+ this.routing.attach(adapter);
274
+ }
275
+ get active() {
276
+ return this.turns.active;
277
+ }
278
+ }
@@ -0,0 +1,113 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { registerBoardActivityRenderer } from "../activity.js";
3
+ import { initializeDelivery, isMissingOptionalModule } from "../delivery.js";
4
+ import { createBoardTool } from "../tool.js";
5
+ import { BoardRuntime } from "./coordinator.js";
6
+
7
+ export { BoardRuntime };
8
+
9
+ const CLAIM = "@howaboua/pi-agent-board.owner/v1";
10
+ const AVAILABLE = "@howaboua/pi-agent-board.available/v1";
11
+ interface OwnerClaim {
12
+ runtime: Promise<BoardRuntime>;
13
+ }
14
+
15
+ /** Discover an explicitly loaded owner, including one loaded after this adapter. */
16
+ export function discoverBoard(
17
+ pi: ExtensionAPI,
18
+ attach: (runtime: BoardRuntime) => void,
19
+ ) {
20
+ let attached = false;
21
+ const accept = (runtime: BoardRuntime) => {
22
+ if (attached) return;
23
+ attached = true;
24
+ attach(runtime);
25
+ };
26
+ const request = () =>
27
+ pi.events.emit(CLAIM, {
28
+ accept: (claim: OwnerClaim) => {
29
+ void claim.runtime.then(accept);
30
+ },
31
+ });
32
+ const stop = pi.events.on(AVAILABLE, request);
33
+ request();
34
+ pi.on("session_shutdown", stop);
35
+ }
36
+
37
+ /** Only the standalone extension creates and registers the board engine. */
38
+ export async function acquireBoard(pi: ExtensionAPI): Promise<BoardRuntime> {
39
+ let claim: OwnerClaim | undefined;
40
+ pi.events.emit(CLAIM, {
41
+ accept(value: OwnerClaim) {
42
+ claim = value;
43
+ },
44
+ });
45
+ if (!claim) {
46
+ const created: OwnerClaim = {
47
+ runtime: createRuntime(pi),
48
+ };
49
+ claim = created;
50
+ const stop = pi.events.on(CLAIM, (value) => {
51
+ if (
52
+ value &&
53
+ typeof value === "object" &&
54
+ "accept" in value &&
55
+ typeof value.accept === "function"
56
+ )
57
+ value.accept(created);
58
+ });
59
+ pi.on("session_shutdown", stop);
60
+ }
61
+ const runtime = await claim.runtime;
62
+ pi.events.emit(AVAILABLE, undefined);
63
+ return runtime;
64
+ }
65
+
66
+ async function createRuntime(pi: ExtensionAPI) {
67
+ await initializeDelivery();
68
+ const runtime = new BoardRuntime(pi);
69
+ const tool = createBoardTool(runtime);
70
+ pi.registerTool(tool);
71
+ try {
72
+ const { registerGptPromptMode, prepareGptPromptMode } = await import(
73
+ "@howaboua/pi-codex-conversion/prompt-mode"
74
+ );
75
+ runtime.setPromptModePreparation((ctx) => prepareGptPromptMode(pi, ctx));
76
+ registerGptPromptMode(pi, (active) => {
77
+ runtime.gptPromptMode = active;
78
+ return [tool];
79
+ });
80
+ } catch (error) {
81
+ if (!isMissingOptionalModule(error, "prompt-mode")) throw error;
82
+ }
83
+ registerBoardActivityRenderer(pi);
84
+ try {
85
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
86
+ await import("@howaboua/pi-codex-conversion/code-mode");
87
+ const registration = registerCodeModeExtensionTools(
88
+ pi,
89
+ () => [
90
+ adaptToolForCodeMode(tool, {
91
+ prepareInput: (input) =>
92
+ input === undefined || input === null ? {} : input,
93
+ discovery: "help",
94
+ }),
95
+ ],
96
+ { isActive: (ctx) => runtime.enabled(ctx) },
97
+ );
98
+ runtime.setToolRefresh(() => registration.refresh());
99
+ pi.on("session_shutdown", () => registration.unregister());
100
+ } catch (error) {
101
+ if (!isMissingOptionalModule(error, "code-mode")) throw error;
102
+ if (
103
+ error instanceof Error &&
104
+ "code" in error &&
105
+ error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED"
106
+ )
107
+ throw new Error(
108
+ "Update Codex Conversion to use its Code and Notebook board tools",
109
+ { cause: error },
110
+ );
111
+ }
112
+ return runtime;
113
+ }
@@ -0,0 +1,164 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { executeArchive, readSubscribedUpdates } from "../archive.js";
3
+ import {
4
+ agentPath,
5
+ type BoardParams,
6
+ boardHelp,
7
+ parseBoardRequest,
8
+ } from "../contract.js";
9
+ import { binding, boardAliases, members } from "../identity.js";
10
+ import type { BoardAdapter } from "../integration.js";
11
+ import type { BoardEnvelope } from "../protocol.js";
12
+ import type { BoardSummarizer } from "../summarizer.js";
13
+ import type { BoardTurns } from "./turns.js";
14
+
15
+ /** Owner execution begins at membership validation; archive commit precedes delivery. */
16
+ export class BoardOwner {
17
+ private readonly turns: BoardTurns;
18
+ private readonly summarizer: BoardSummarizer;
19
+ private readonly adapterOrUndefined: () => BoardAdapter | undefined;
20
+ private readonly adapter: () => BoardAdapter;
21
+ private readonly notify: (
22
+ ctx: ExtensionContext,
23
+ request: BoardEnvelope,
24
+ signal?: AbortSignal,
25
+ ) => Promise<unknown>;
26
+ constructor(
27
+ turns: BoardTurns,
28
+ summarizer: BoardSummarizer,
29
+ adapterOrUndefined: () => BoardAdapter | undefined,
30
+ adapter: () => BoardAdapter,
31
+ notify: (
32
+ ctx: ExtensionContext,
33
+ request: BoardEnvelope,
34
+ signal?: AbortSignal,
35
+ ) => Promise<unknown>,
36
+ ) {
37
+ this.turns = turns;
38
+ this.summarizer = summarizer;
39
+ this.adapterOrUndefined = adapterOrUndefined;
40
+ this.adapter = adapter;
41
+ this.notify = notify;
42
+ }
43
+ async execute(
44
+ ctx: ExtensionContext,
45
+ request: BoardEnvelope,
46
+ ): Promise<unknown> {
47
+ const own = binding(ctx);
48
+ if (!("caller" in request)) throw new Error("Invalid board owner request");
49
+ const directory = members(ctx);
50
+ const caller = directory.find(
51
+ (member) =>
52
+ member.sessionId === request.caller.sessionId &&
53
+ member.agentName === request.caller.agentName,
54
+ );
55
+ if (
56
+ !caller ||
57
+ request.caller.boardId !== own.boardId ||
58
+ request.caller.databasePath !== own.databasePath
59
+ )
60
+ throw new Error("Caller not bound to this board");
61
+ if (
62
+ request.operation === "board-unregister" ||
63
+ request.operation === "board-register"
64
+ )
65
+ return this.adapter().commitDirectory(own, directory, caller, request);
66
+ if (request.operation === "board-active") {
67
+ if (own.enabled) this.turns.register(caller, request);
68
+ return true;
69
+ }
70
+ if (request.operation === "board-catchup")
71
+ return own.enabled
72
+ ? readSubscribedUpdates(caller, request.seen, boardAliases(ctx))
73
+ : [];
74
+ if (request.operation !== "board-call")
75
+ throw new Error("Invalid board owner operation");
76
+ const params = parseBoardRequest(request.params);
77
+ if (params.action === "help")
78
+ return {
79
+ ...boardHelp,
80
+ rules: this.adapterOrUndefined()
81
+ ? boardHelp.rules
82
+ : {
83
+ ...boardHelp.rules,
84
+ agents:
85
+ "Agent reference /<Pi session ID>; notices require registered members",
86
+ },
87
+ enabled: own.enabled,
88
+ };
89
+ if (!own.enabled)
90
+ throw new Error("Board is off; the user can enable it with /board on");
91
+ const prepared: BoardParams =
92
+ params.author === undefined
93
+ ? params
94
+ : {
95
+ ...params,
96
+ author: agentPath(
97
+ params.author,
98
+ caller.legacyAgentName ?? caller.agentName,
99
+ ),
100
+ };
101
+ const active = new Map(this.turns.active);
102
+ const result = await executeArchive(
103
+ { ...caller, enabled: own.enabled },
104
+ directory.map((member) => member.agentName),
105
+ prepared,
106
+ request.requestId,
107
+ boardAliases(ctx, params.board_id),
108
+ );
109
+ if ("notice" in result && result.notice) {
110
+ // Replayed mutations have no notice: never start or cancel twice for a retry.
111
+ if (params.action === "set_status") {
112
+ if (params.status === "open")
113
+ this.summarizer.cancel(own.boardId, result.notice.thread_id);
114
+ else
115
+ this.summarizer.start(
116
+ ctx,
117
+ own,
118
+ result.notice.thread_id,
119
+ result.notice.message_id,
120
+ );
121
+ }
122
+ for (let start = 0; start < result.recipients.length; start += 16) {
123
+ await Promise.all(
124
+ result.recipients.slice(start, start + 16).map(async (target) => {
125
+ const turn = active.get(target);
126
+ if (!turn) return;
127
+ const route: string[] = [];
128
+ let member = directory.find(
129
+ (entry) => entry.sessionId === turn.sessionId,
130
+ );
131
+ while (
132
+ member &&
133
+ member.sessionId !== own.sessionId &&
134
+ route.length < directory.length
135
+ ) {
136
+ route.unshift(member.sessionId);
137
+ member = directory.find(
138
+ (entry) => entry.sessionId === member?.parentSessionId,
139
+ );
140
+ }
141
+ if (member?.sessionId !== own.sessionId) return;
142
+ try {
143
+ await this.notify(
144
+ ctx,
145
+ {
146
+ operation: "board-notify",
147
+ boardId: own.boardId,
148
+ target,
149
+ route,
150
+ ...turn,
151
+ notice: result.notice,
152
+ },
153
+ AbortSignal.timeout(750),
154
+ );
155
+ } catch {
156
+ /* Committed posts succeed even when a running turn stops accepting. */
157
+ }
158
+ }),
159
+ );
160
+ }
161
+ }
162
+ return result.value;
163
+ }
164
+ }
@@ -0,0 +1,152 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { binding, parseBinding, saveBinding } from "../identity.js";
6
+ import type { BoardAdapter } from "../integration.js";
7
+ import { type BoardEnvelope, parseEnvelope } from "../protocol.js";
8
+ import type { BoardOwner } from "./owner.js";
9
+ import type { BoardTurns } from "./turns.js";
10
+
11
+ /** Routes membership/setting/notice envelopes; lifecycle refresh stays with the runtime. */
12
+ export class BoardRouting {
13
+ private readonly pi: ExtensionAPI;
14
+ private readonly turns: BoardTurns;
15
+ private readonly owner: BoardOwner;
16
+ private readonly refresh: (ctx: ExtensionContext) => Promise<void>;
17
+ private readonly reportAvailability: (
18
+ ctx: ExtensionContext,
19
+ error?: unknown,
20
+ ) => void;
21
+ adapter: BoardAdapter | undefined;
22
+ constructor(
23
+ pi: ExtensionAPI,
24
+ turns: BoardTurns,
25
+ owner: BoardOwner,
26
+ refresh: (ctx: ExtensionContext) => Promise<void>,
27
+ reportAvailability: (ctx: ExtensionContext, error?: unknown) => void,
28
+ ) {
29
+ this.pi = pi;
30
+ this.turns = turns;
31
+ this.owner = owner;
32
+ this.refresh = refresh;
33
+ this.reportAvailability = reportAvailability;
34
+ }
35
+ async handle(
36
+ ctx: ExtensionContext,
37
+ value: unknown,
38
+ signal?: AbortSignal,
39
+ ): Promise<unknown> {
40
+ const request = parseEnvelope(value);
41
+ const own = binding(ctx);
42
+ if (request.operation === "board-bind") {
43
+ parseBinding(request.binding);
44
+ if (own.sessionId === request.binding.sessionId)
45
+ throw new Error(
46
+ "Child and controller have the same Pi session ID; start the child with a different ID",
47
+ );
48
+ if (request.binding.agentName !== `/${request.binding.sessionId}`)
49
+ throw new Error(
50
+ "Restart the controller with updated extensions before spawning shared-board agents",
51
+ );
52
+ if (
53
+ !ctx.isIdle() ||
54
+ ctx.sessionManager
55
+ .getEntries()
56
+ .some(
57
+ (entry) =>
58
+ (entry.type === "message" &&
59
+ ["user", "assistant"].includes(entry.message.role)) ||
60
+ (entry.type === "custom" &&
61
+ entry.customType === "shepherdr-board-binding"),
62
+ )
63
+ )
64
+ throw new Error(
65
+ "Bind board identity only in a fresh idle child before its first task",
66
+ );
67
+ const { legacyAgentName: _legacy, ...proposed } = request.binding;
68
+ const adopted = {
69
+ ...proposed,
70
+ sessionId: own.sessionId,
71
+ agentName: own.agentName,
72
+ parentSessionId: request.binding.sessionId,
73
+ };
74
+ saveBinding(this.pi, adopted);
75
+ await this.refresh(ctx);
76
+ return adopted;
77
+ }
78
+ if (request.operation === "board-enabled") {
79
+ if (!own.upstream || request.boardId !== own.boardId)
80
+ throw new Error("Invalid board setting route");
81
+ saveBinding(this.pi, { ...own, enabled: request.enabled });
82
+ await this.refresh(ctx);
83
+ await this.propagateEnabled(ctx, request.enabled);
84
+ return true;
85
+ }
86
+ if (request.operation === "board-notify") {
87
+ if (!own.enabled || request.boardId !== own.boardId) return false;
88
+ if (request.target === own.agentName) return this.turns.deliver(request);
89
+ return this.routeNotice(ctx, request, signal);
90
+ }
91
+ return this.toOwner(ctx, request, signal);
92
+ }
93
+ async toOwner(
94
+ ctx: ExtensionContext,
95
+ request: BoardEnvelope,
96
+ signal?: AbortSignal,
97
+ ): Promise<unknown> {
98
+ const own = binding(ctx);
99
+ if (own.upstream) {
100
+ try {
101
+ const result = await this.requireAdapter().request(
102
+ own.upstream,
103
+ request,
104
+ signal,
105
+ );
106
+ this.reportAvailability(ctx);
107
+ return result;
108
+ } catch (error) {
109
+ if (
110
+ error instanceof Error &&
111
+ error.message.startsWith("Shared context response was lost")
112
+ )
113
+ throw new Error(
114
+ "Board response lost; a mutation may have completed. Read the channel/thread before retrying",
115
+ { cause: error },
116
+ );
117
+ if (
118
+ error instanceof Error &&
119
+ error.message.startsWith("Shared context owner is unavailable")
120
+ )
121
+ throw new Error(
122
+ "Board owner unavailable; resume its Pi session and reconnect its machine",
123
+ { cause: error },
124
+ );
125
+ throw error;
126
+ }
127
+ }
128
+ return this.owner.execute(ctx, request);
129
+ }
130
+
131
+ private async routeNotice(
132
+ ctx: ExtensionContext,
133
+ request: Extract<BoardEnvelope, { operation: "board-notify" }>,
134
+ signal?: AbortSignal,
135
+ ) {
136
+ return this.requireAdapter().routeNotice(ctx, request, signal);
137
+ }
138
+ async propagateEnabled(ctx: ExtensionContext, enabled: boolean) {
139
+ await this.adapter?.propagateEnabled(ctx, enabled);
140
+ }
141
+ attach(adapter: BoardAdapter) {
142
+ if (this.adapter) throw new Error("Board integration already attached");
143
+ this.adapter = adapter;
144
+ }
145
+ requireAdapter() {
146
+ if (!this.adapter)
147
+ throw new Error(
148
+ "Board member route unavailable; load the extension that manages this session's board membership",
149
+ );
150
+ return this.adapter;
151
+ }
152
+ }