@howaboua/pi-agent-board 0.0.3 → 0.0.4

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.
@@ -3,6 +3,7 @@ import {
3
3
  buildSessionContext,
4
4
  type ExtensionAPI,
5
5
  type ExtensionContext,
6
+ type SessionEntry,
6
7
  } from "@earendil-works/pi-coding-agent";
7
8
  import type {
8
9
  CODEX_CONTEXT_BRIEFING_TYPE,
@@ -61,47 +62,64 @@ export function contextBriefingWindow(
61
62
  entry.details.strategy === "codex-context-window"
62
63
  ),
63
64
  );
64
- const boundary = branch.findLastIndex(
65
- (entry) =>
66
- entry.type === "custom_message" &&
67
- entry.customType === "codex-context-window" &&
68
- entry.details &&
69
- typeof entry.details === "object" &&
70
- "contextManagement" in entry.details &&
71
- entry.details.contextManagement &&
72
- typeof entry.details.contextManagement === "object" &&
73
- "kind" in entry.details.contextManagement &&
74
- entry.details.contextManagement.kind === "window",
75
- );
65
+ const boundary = branch.findLastIndex((entry) => briefingIdentity(entry));
76
66
  return compaction > boundary
77
67
  ? branch[compaction]!.id
78
- : (windowId ?? ctx.sessionManager.getSessionId());
68
+ : (windowId ??
69
+ (boundary >= 0
70
+ ? briefingIdentity(branch[boundary]!)?.currentWindowId
71
+ : undefined) ??
72
+ ctx.sessionManager.getSessionId());
79
73
  }
80
74
 
81
75
  export function hasContextRollover(ctx: ExtensionContext): boolean {
82
76
  return ctx.sessionManager.getBranch().some((entry) => {
83
77
  if (entry.type === "compaction") return true;
84
- if (
85
- entry.type !== "custom_message" ||
86
- entry.customType !== "codex-context-window" ||
87
- !entry.details ||
88
- typeof entry.details !== "object" ||
89
- !("contextManagement" in entry.details)
90
- )
91
- return false;
92
- const window = entry.details.contextManagement;
93
- return Boolean(
94
- window &&
95
- typeof window === "object" &&
96
- "kind" in window &&
97
- window.kind === "window" &&
98
- "windowNumber" in window &&
99
- typeof window.windowNumber === "number" &&
100
- window.windowNumber > 0,
101
- );
78
+ return (briefingIdentity(entry)?.windowNumber ?? 0) > 0;
102
79
  });
103
80
  }
104
81
 
82
+ /** Consume owner-authored identities without depending on an optional runtime. */
83
+ function briefingIdentity(entry: SessionEntry) {
84
+ if (entry.type !== "custom_message") return;
85
+ const details = entry.details;
86
+ if (!details || typeof details !== "object") return;
87
+ let identity: unknown;
88
+ if (
89
+ entry.customType === "notes-compaction:window:v1" &&
90
+ "protocol" in details &&
91
+ details.protocol === 1 &&
92
+ "kind" in details &&
93
+ details.kind === "window" &&
94
+ "identity" in details
95
+ )
96
+ identity = details.identity;
97
+ else if (
98
+ entry.customType === "codex-context-window" &&
99
+ "contextManagement" in details &&
100
+ details.contextManagement &&
101
+ typeof details.contextManagement === "object" &&
102
+ "kind" in details.contextManagement &&
103
+ details.contextManagement.kind === "window"
104
+ )
105
+ identity = details.contextManagement;
106
+ if (
107
+ identity &&
108
+ typeof identity === "object" &&
109
+ "currentWindowId" in identity &&
110
+ typeof identity.currentWindowId === "string" &&
111
+ identity.currentWindowId &&
112
+ "windowNumber" in identity &&
113
+ typeof identity.windowNumber === "number" &&
114
+ Number.isInteger(identity.windowNumber) &&
115
+ identity.windowNumber >= 0
116
+ )
117
+ return {
118
+ currentWindowId: identity.currentWindowId,
119
+ windowNumber: identity.windowNumber,
120
+ };
121
+ }
122
+
105
123
  export async function recordContextBriefing(
106
124
  pi: ExtensionAPI,
107
125
  ctx: ExtensionContext,
package/src/contract.ts CHANGED
@@ -214,23 +214,25 @@ export function gptBoardHelp(value: unknown): unknown {
214
214
  return value;
215
215
  const compact: typeof boardHelp.rules = {
216
216
  scope:
217
- "Default: your tree. board_id browses saved history only, never writes. Discover via list_boards",
218
- post: "text required. Exactly one: channel_name, new_channel_name, thread_id. Thread ID=first post ID. New channel subscribes author to first posts",
219
- set_status: boardHelp.rules.set_status,
217
+ "Default=your tree; board_id→saved history READONLY; discover→list_boards",
218
+ post: "text required; EXACTLY one: channel_name|new_channel_name|thread_id. thread_id=first post ID; new channel→author subscribed to first posts",
219
+ set_status:
220
+ "Parent session ONLY; completed=user confirms done; abandoned=user drops it; NOT agents finish. Closed→reopen BEFORE reply",
220
221
  subscriptions:
221
- "Exactly one: channel_name/thread_id. Channel=first posts, thread=replies. target_agent defaults to you. Posting subscribes author to thread unless explicitly unsubscribed",
222
+ "EXACTLY one: channel_name|thread_id; channel=first posts, thread=replies; target_agent=you by default; posting→subscribe author UNLESS explicitly unsubscribed",
222
223
  notify:
223
- "agents_to_notify: one-time, excludes author. Running turns only, no waking/offline notices",
224
+ "agents_to_notify=once, excludes author; running turns ONLY; NO waking/offline notices",
224
225
  agents:
225
- "Use spawn's boardAgent, absolute /root/... or relative child path. Never pane/contextAgent",
226
+ "spawn's boardAgent: absolute /root/... OR relative child path; NOT pane/contextAgent",
226
227
  paging:
227
- "limit default20 cap50. Opaque cursor, unchanged query/sort/full. Concurrent changes may shift pages",
228
- summaries: boardHelp.rules.summaries,
228
+ "limit default20 cap50; opaque cursor→unchanged query/sort/full; concurrent changes MAY shift pages",
229
+ summaries:
230
+ "Closing MAY summarise IF enabled; summarised threads return/search summaries ONLY; full=true reads/searches originals; summary author filters=participants; read_post=originals ALWAYS",
229
231
  order:
230
- "Newest first. get_channels: activity. list_threads sort=created|activity. read_thread: newest replies, root repeated each page",
231
- text: "Case-insensitive substring search. max_chars_per_post default1000. read_post: Unicode-character offsets, limit_chars default20000. Continue at next_offset_chars<n_chars",
232
+ "Newest first; get_channels→activity; list_threads sort=created|activity; read_thread→newest replies+root EVERY page",
233
+ text: "Case-insensitive substring; max_chars_per_post default1000; read_post→Unicode-char offsets, limit_chars default20000; next_offset_chars<n_chars→continue",
232
234
  budget:
233
- "Post cap64KiB. Channel: 1-128 UTF-8 bytes, no edge whitespace/control characters. Results cap8000 serialized UTF-8 bytes. Reads may reduce limits; continue returned cursor/offset",
235
+ "Post≤64KiB; channel=1-128 UTF-8 bytes, NO edge whitespace/control chars; results≤8000 serialized UTF-8 bytes; reads MAY lower limits; continue returned cursor/offset",
234
236
  };
235
237
  return {
236
238
  ...value,
package/src/queries.ts CHANGED
@@ -25,14 +25,13 @@ export function queryBoard(
25
25
  if (params.action === "list_boards") {
26
26
  const rows = store.all<{
27
27
  board_id: string;
28
- root_session_id: string;
29
28
  owner_folder: string;
30
29
  created_at: string;
31
30
  last_activity_at: string;
32
31
  channel_count: number;
33
32
  message_count: number;
34
33
  }>(
35
- `SELECT b.*,
34
+ `SELECT b.board_id,b.owner_folder,b.created_at,
36
35
  COALESCE((SELECT MAX(created_at) FROM posts p WHERE p.board_id=b.board_id),(SELECT MAX(created_at) FROM channels c WHERE c.board_id=b.board_id),b.created_at) AS last_activity_at,
37
36
  (SELECT COUNT(*) FROM channels c WHERE c.board_id=b.board_id) AS channel_count,
38
37
  (SELECT COUNT(*) FROM posts p WHERE p.board_id=b.board_id) AS message_count
@@ -0,0 +1,96 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { BoardAwareness } from "../awareness.js";
6
+ import { binding } from "../identity.js";
7
+ import type { BoardEnvelope } from "../protocol.js";
8
+
9
+ /** Validates unread responses against the still-selected membership before acceptance. */
10
+ export class BoardCatchup {
11
+ private readonly pi: ExtensionAPI;
12
+ private readonly awareness: BoardAwareness;
13
+ private readonly request: (
14
+ ctx: ExtensionContext,
15
+ request: BoardEnvelope,
16
+ ) => Promise<unknown>;
17
+ private readonly availability: (
18
+ ctx: ExtensionContext,
19
+ error?: unknown,
20
+ ) => void;
21
+ private readonly gpt: () => boolean;
22
+ constructor(
23
+ pi: ExtensionAPI,
24
+ awareness: BoardAwareness,
25
+ request: (
26
+ ctx: ExtensionContext,
27
+ request: BoardEnvelope,
28
+ ) => Promise<unknown>,
29
+ availability: (ctx: ExtensionContext, error?: unknown) => void,
30
+ gpt: () => boolean,
31
+ ) {
32
+ this.pi = pi;
33
+ this.awareness = awareness;
34
+ this.request = request;
35
+ this.availability = availability;
36
+ this.gpt = gpt;
37
+ }
38
+ async read(
39
+ ctx: ExtensionContext,
40
+ ): Promise<{ content: string; accepted: () => void }> {
41
+ const empty = { content: "", accepted: () => {} };
42
+ const own = binding(ctx);
43
+ if (!own.enabled) return empty;
44
+ try {
45
+ const result = await this.request(ctx, {
46
+ operation: "board-catchup",
47
+ caller: own,
48
+ seen: this.awareness.seen(ctx),
49
+ });
50
+ if (
51
+ !Array.isArray(result) ||
52
+ !result.every(
53
+ (post) =>
54
+ post &&
55
+ typeof post.message_id === "string" &&
56
+ typeof post.thread_id === "string",
57
+ )
58
+ )
59
+ throw new Error("Invalid board catch-up response");
60
+ if (
61
+ !binding(ctx).enabled ||
62
+ binding(ctx).sessionId !== own.sessionId ||
63
+ binding(ctx).boardId !== own.boardId ||
64
+ binding(ctx).agentName !== own.agentName
65
+ )
66
+ return empty;
67
+ this.availability(ctx);
68
+ const nested = this.pi
69
+ .getActiveTools()
70
+ .some((tool) => ["exec", "code", "notebook"].includes(tool));
71
+ return {
72
+ content: result.length
73
+ ? `\n\n${this.gpt() ? "Unread board updates→read task-relevant threads:" : "Unread board updates available; read if relevant to the current task:"} ${[
74
+ ...new Set(result.map((post) => post.thread_id)),
75
+ ]
76
+ .map((thread_id) => {
77
+ const args = JSON.stringify({
78
+ action: "read_thread",
79
+ thread_id,
80
+ });
81
+ return nested ? `await tools.board(${args})` : `board ${args}`;
82
+ })
83
+ .join("; ")}`
84
+ : "",
85
+ accepted: () =>
86
+ this.awareness.markSeen(
87
+ ctx,
88
+ result.map((post) => post.message_id),
89
+ ),
90
+ };
91
+ } catch (error) {
92
+ this.availability(ctx, error);
93
+ return empty;
94
+ }
95
+ }
96
+ }
@@ -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
+ }