@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa

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 (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -0,0 +1,311 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ recordBoardActivityMarker,
7
+ registerBoardActivityRenderer,
8
+ } from "../activity.js";
9
+ import {
10
+ type BoardScope,
11
+ writeBoardConfig,
12
+ writeBoardSummaryAutomatic,
13
+ } from "../config.js";
14
+ import { gptBoardHelp, parseBoardRequest } from "../contract.js";
15
+ import { preparePolicyMessage } from "../delivery.js";
16
+ import {
17
+ binding,
18
+ rootBoardSetting,
19
+ saveBinding,
20
+ saveBoardSetting,
21
+ setBoardDefault,
22
+ } from "../identity.js";
23
+ import type { BoardAdapter } from "../integration.js";
24
+ import { type BoardEnvelope } from "../protocol.js";
25
+ import type { BoardEngine } from "./engine.js";
26
+ import { BoardOwner } from "./owner.js";
27
+ import { BoardRouting } from "./routing.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 owner: BoardOwner;
35
+ private engine: BoardEngine | undefined;
36
+ private engineReady: Promise<BoardEngine> | undefined;
37
+ private briefingReady: Promise<void> | undefined;
38
+ private refreshTools: (() => void) | undefined;
39
+ private lastSetting: { sessionId: string; enabled: boolean } | undefined;
40
+ private configError: string | undefined;
41
+ private availabilityWarning: string | undefined;
42
+ constructor(pi: ExtensionAPI) {
43
+ this.pi = pi;
44
+ registerBoardActivityRenderer(pi);
45
+ const availability = (ctx: ExtensionContext, error?: unknown) =>
46
+ this.reportAvailability(ctx, error);
47
+ this.owner = new BoardOwner(
48
+ () => this.requireEngine().turns,
49
+ () => this.requireEngine().summarizer,
50
+ () => this.routing.adapter,
51
+ () => this.routing.requireAdapter(),
52
+ (ctx, request, signal) => this.handle(ctx, request, signal),
53
+ );
54
+ this.routing = new BoardRouting(
55
+ pi,
56
+ { deliver: (request) => this.engine?.turns.deliver(request) ?? false },
57
+ this.owner,
58
+ (ctx) => this.refresh(ctx),
59
+ availability,
60
+ );
61
+ pi.on("session_start", (_event, ctx) => {
62
+ this.engine?.summarizer.cancelAll();
63
+ this.availabilityWarning = undefined;
64
+ setBoardDefault(ctx, true);
65
+ return this.refresh(ctx);
66
+ });
67
+ pi.on("session_shutdown", () => this.engine?.summarizer.cancelAll());
68
+ pi.on("before_agent_start", async (_event, ctx) => {
69
+ const prepared = this.preparePromptMode;
70
+ this.preparePromptMode?.(ctx);
71
+ // Reconcile resumed/offline children before tool/prompt preparation.
72
+ const own = binding(ctx);
73
+ if (own.upstream) {
74
+ try {
75
+ const result = await this.toOwner(ctx, {
76
+ operation: "board-call",
77
+ caller: own,
78
+ params: { action: "help" },
79
+ requestId: "status",
80
+ });
81
+ availability(ctx);
82
+ if (
83
+ typeof result === "object" &&
84
+ result !== null &&
85
+ "enabled" in result &&
86
+ typeof result.enabled === "boolean" &&
87
+ result.enabled !== own.enabled
88
+ )
89
+ saveBinding(pi, { ...own, enabled: result.enabled });
90
+ } catch (error) {
91
+ if (own.enabled) availability(ctx, error);
92
+ }
93
+ }
94
+ await this.refresh(ctx);
95
+ if (this.preparePromptMode !== prepared) this.preparePromptMode?.(ctx);
96
+ const catchup = await this.promptCatchup(ctx);
97
+ catchup.accepted();
98
+ if (catchup.content)
99
+ return {
100
+ message: preparePolicyMessage({
101
+ customType: "shepherdr-board-catchup",
102
+ content: catchup.content.trim(),
103
+ display: true,
104
+ }),
105
+ };
106
+ });
107
+ }
108
+ reportAvailability(ctx: ExtensionContext, error?: unknown): void {
109
+ const own = binding(ctx);
110
+ if (error === undefined || !own.enabled) {
111
+ this.availabilityWarning = undefined;
112
+ return;
113
+ }
114
+ const message = error instanceof Error ? error.message : String(error);
115
+ const key = JSON.stringify([
116
+ own.sessionId,
117
+ own.boardId,
118
+ own.upstream,
119
+ message,
120
+ ]);
121
+ if (this.availabilityWarning === key) return;
122
+ this.availabilityWarning = key;
123
+ ctx.ui.notify(`Board unavailable: ${message}`, "warning");
124
+ }
125
+ setToolRefresh(refresh: () => void) {
126
+ this.refreshTools = refresh;
127
+ }
128
+ setPromptModePreparation(prepare: (ctx: ExtensionContext) => void) {
129
+ this.preparePromptMode = prepare;
130
+ }
131
+ async population(ctx: ExtensionContext) {
132
+ const own = binding(ctx);
133
+ if (own.upstream) {
134
+ const status = await this.toOwner(
135
+ ctx,
136
+ {
137
+ operation: "board-call",
138
+ caller: own,
139
+ params: { action: "help" },
140
+ requestId: "briefing-status",
141
+ },
142
+ ctx.signal,
143
+ );
144
+ if (
145
+ !status ||
146
+ typeof status !== "object" ||
147
+ !("enabled" in status) ||
148
+ typeof status.enabled !== "boolean"
149
+ )
150
+ throw new Error("Board status unavailable");
151
+ if (status.enabled !== own.enabled) {
152
+ saveBinding(this.pi, { ...own, enabled: status.enabled });
153
+ await this.refresh(ctx);
154
+ }
155
+ if (!status.enabled) return;
156
+ }
157
+ return this.execute(
158
+ ctx,
159
+ { action: "search_posts", limit: 1, max_chars_per_post: 1 },
160
+ "briefing",
161
+ );
162
+ }
163
+ enabled(ctx: ExtensionContext | undefined) {
164
+ return ctx ? binding(ctx).enabled : false;
165
+ }
166
+ async promptCatchup(ctx: ExtensionContext) {
167
+ return this.enabled(ctx)
168
+ ? (await this.ensureEngine()).catchup.read(ctx)
169
+ : { content: "", accepted() {} };
170
+ }
171
+ async refresh(ctx: ExtensionContext) {
172
+ const own = binding(ctx);
173
+ if (own.enabled) await this.ensureEngine();
174
+ // Native Pi also needs projection of saved briefings while Board is off.
175
+ if (
176
+ own.enabled ||
177
+ ctx.sessionManager
178
+ .getEntries()
179
+ .some(
180
+ (entry) =>
181
+ entry.type === "custom" &&
182
+ entry.customType === "codex-context-briefing",
183
+ )
184
+ )
185
+ await this.ensureBriefing();
186
+ this.engine?.awareness.refresh(ctx);
187
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
188
+ if (setting?.error && setting.error !== this.configError)
189
+ ctx.ui.notify(`Board disabled: ${setting.error}`, "error");
190
+ this.configError = setting?.error;
191
+ const active = this.pi.getActiveTools().filter((name) => name !== "board");
192
+ if (own.enabled) active.push("board");
193
+ this.pi.setActiveTools(active);
194
+ this.refreshTools?.();
195
+ if (!own.enabled) {
196
+ this.engine?.turns.active.clear();
197
+ this.engine?.summarizer.cancelAll();
198
+ }
199
+ const changed =
200
+ this.lastSetting?.sessionId !== own.sessionId ||
201
+ this.lastSetting.enabled !== own.enabled;
202
+ this.lastSetting = { sessionId: own.sessionId, enabled: own.enabled };
203
+ if (changed && !own.upstream)
204
+ await this.routing.propagateEnabled(ctx, own.enabled);
205
+ }
206
+ async setSetting(ctx: ExtensionContext, scope: BoardScope, enabled: boolean) {
207
+ if (!ctx.isIdle())
208
+ throw new Error("Change the board setting after this session settles");
209
+ const own = binding(ctx);
210
+ if (own.upstream)
211
+ throw new Error("Change the board setting in the owning root session");
212
+ if (scope === "session") saveBoardSetting(this.pi, ctx, enabled);
213
+ else writeBoardConfig(own.ownerFolder, scope, enabled);
214
+ await this.refresh(ctx);
215
+ }
216
+ status(ctx: ExtensionContext, includeArchive = true) {
217
+ const own = binding(ctx);
218
+ const setting = own.upstream ? undefined : rootBoardSetting(ctx);
219
+ return `Board ${own.enabled ? "on" : "off"} (${setting?.source ?? "inherited from owner"})${includeArchive ? `. ${own.boardId}\nArchive: ${own.databasePath}` : ""}${setting?.error ? `\n${setting.error}` : ""}`;
220
+ }
221
+ setAutomaticSummaries(ctx: ExtensionContext, automatic: boolean) {
222
+ writeBoardSummaryAutomatic(ctx.cwd, automatic);
223
+ if (!automatic) this.engine?.summarizer.cancelAll();
224
+ }
225
+ async execute(ctx: ExtensionContext, input: unknown, requestId: string) {
226
+ const params = parseBoardRequest(input);
227
+ const caller = binding(ctx);
228
+ if (!caller.upstream) {
229
+ const setting = rootBoardSetting(ctx);
230
+ if (setting.error) throw new Error(setting.error);
231
+ }
232
+ if (!caller.enabled)
233
+ throw new Error("Board is off; the user can enable it with /board on");
234
+ const value = await this.toOwner(
235
+ ctx,
236
+ {
237
+ operation: "board-call",
238
+ caller,
239
+ params,
240
+ requestId,
241
+ },
242
+ ctx.signal,
243
+ );
244
+ if (params.action === "read_thread" || params.action === "read_post")
245
+ this.engine?.awareness.markRead(ctx, value);
246
+ try {
247
+ recordBoardActivityMarker(this.pi, ctx, params, value, requestId);
248
+ } catch {
249
+ // Presentation failure must not turn a successful operation into a retry.
250
+ ctx.ui.notify(
251
+ "Board action succeeded. Its history notice is unavailable. Do not repeat writes just to restore the notice.",
252
+ "warning",
253
+ );
254
+ }
255
+ return params.action === "help" && this.gptPromptMode
256
+ ? gptBoardHelp(value)
257
+ : value;
258
+ }
259
+ async handle(ctx: ExtensionContext, value: unknown, signal?: AbortSignal) {
260
+ if (this.enabled(ctx)) await this.ensureEngine();
261
+ return this.routing.handle(ctx, value, signal);
262
+ }
263
+ async toOwner(
264
+ ctx: ExtensionContext,
265
+ request: BoardEnvelope,
266
+ signal?: AbortSignal,
267
+ ) {
268
+ if (this.enabled(ctx)) await this.ensureEngine();
269
+ return this.routing.toOwner(ctx, request, signal);
270
+ }
271
+ private ensureEngine() {
272
+ return (this.engineReady ??= import("./engine.js").then(
273
+ async ({ createBoardEngine }) => {
274
+ const engine = await createBoardEngine(this.pi, this);
275
+ this.engine = engine;
276
+ return engine;
277
+ },
278
+ ));
279
+ }
280
+ private ensureBriefing() {
281
+ return (this.briefingReady ??= import("../context-briefing.js").then(
282
+ ({ registerContextBriefing }) => {
283
+ registerContextBriefing(
284
+ this.pi,
285
+ "board",
286
+ (ctx) => this.enabled(ctx),
287
+ async (ctx, windowId) => {
288
+ if (!this.enabled(ctx)) return;
289
+ return (await this.ensureEngine()).awareness.record(ctx, windowId);
290
+ },
291
+ );
292
+ },
293
+ ));
294
+ }
295
+ private requireEngine() {
296
+ if (!this.engine) throw new Error("Board is not ready");
297
+ return this.engine;
298
+ }
299
+ get adapter() {
300
+ return this.routing.adapter;
301
+ }
302
+ attach(adapter: BoardAdapter) {
303
+ this.routing.attach(adapter);
304
+ }
305
+ get active() {
306
+ return (
307
+ this.engine?.turns.active ??
308
+ new Map<string, { sessionId: string; turnId: string }>()
309
+ );
310
+ }
311
+ }
@@ -0,0 +1,40 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { BoardAwareness } from "../awareness.js";
3
+ import { BoardSummarizer } from "../summarizer.js";
4
+ import { activateBoard } from "./activation.js";
5
+ import { BoardCatchup } from "./catchup.js";
6
+ import type { BoardRuntime } from "./coordinator.js";
7
+ import { BoardTurns } from "./turns.js";
8
+
9
+ /** Optional inference, turn delivery and summary machinery, loaded only when on. */
10
+ export async function createBoardEngine(
11
+ pi: ExtensionAPI,
12
+ runtime: BoardRuntime,
13
+ ) {
14
+ const availability = runtime.reportAvailability.bind(runtime);
15
+ const awareness = new BoardAwareness(
16
+ pi,
17
+ (ctx) => runtime.population(ctx),
18
+ availability,
19
+ () => runtime.adapter?.briefing,
20
+ () => runtime.gptPromptMode,
21
+ );
22
+ const catchup = new BoardCatchup(
23
+ pi,
24
+ awareness,
25
+ (ctx, request) => runtime.toOwner(ctx, request),
26
+ availability,
27
+ () => runtime.gptPromptMode,
28
+ );
29
+ const turns = new BoardTurns(
30
+ pi,
31
+ (ctx, request) => runtime.toOwner(ctx, request),
32
+ availability,
33
+ (ctx, ids) => awareness.markSeen(ctx, ids),
34
+ );
35
+ const summarizer = new BoardSummarizer();
36
+ await activateBoard(pi, runtime);
37
+ return { awareness, catchup, turns, summarizer };
38
+ }
39
+
40
+ export type BoardEngine = Awaited<ReturnType<typeof createBoardEngine>>;
@@ -0,0 +1,63 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { BoardRuntime } from "./coordinator.js";
3
+
4
+ export type { BoardRuntime };
5
+
6
+ const CLAIM = "@howaboua/pi-agent-board.owner/v1";
7
+ const AVAILABLE = "@howaboua/pi-agent-board.available/v1";
8
+ interface OwnerClaim {
9
+ runtime: Promise<BoardRuntime>;
10
+ }
11
+
12
+ /** Discover an explicitly loaded owner, including one loaded after this adapter. */
13
+ export function discoverBoard(
14
+ pi: ExtensionAPI,
15
+ attach: (runtime: BoardRuntime) => void,
16
+ ) {
17
+ let attached = false;
18
+ const accept = (runtime: BoardRuntime) => {
19
+ if (attached) return;
20
+ attached = true;
21
+ attach(runtime);
22
+ };
23
+ const request = () =>
24
+ pi.events.emit(CLAIM, {
25
+ accept: (claim: OwnerClaim) => {
26
+ void claim.runtime.then(accept);
27
+ },
28
+ });
29
+ const stop = pi.events.on(AVAILABLE, request);
30
+ request();
31
+ pi.on("session_shutdown", stop);
32
+ }
33
+
34
+ /** Only an explicitly loaded Board extension claims the owner; its engine stays lazy. */
35
+ export async function acquireBoard(pi: ExtensionAPI): Promise<BoardRuntime> {
36
+ let claim: OwnerClaim | undefined;
37
+ pi.events.emit(CLAIM, {
38
+ accept(value: OwnerClaim) {
39
+ claim = value;
40
+ },
41
+ });
42
+ if (!claim) {
43
+ const created: OwnerClaim = {
44
+ runtime: import("./coordinator.js").then(
45
+ ({ BoardRuntime }) => new BoardRuntime(pi),
46
+ ),
47
+ };
48
+ claim = created;
49
+ const stop = pi.events.on(CLAIM, (value) => {
50
+ if (
51
+ value &&
52
+ typeof value === "object" &&
53
+ "accept" in value &&
54
+ typeof value.accept === "function"
55
+ )
56
+ value.accept(created);
57
+ });
58
+ pi.on("session_shutdown", stop);
59
+ }
60
+ const runtime = await claim.runtime;
61
+ pi.events.emit(AVAILABLE, undefined);
62
+ return runtime;
63
+ }
@@ -0,0 +1,168 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ agentPath,
4
+ type BoardParams,
5
+ boardHelp,
6
+ parseBoardRequest,
7
+ } from "../contract.js";
8
+ import { binding, boardAliases, members } from "../identity.js";
9
+ import type { BoardAdapter } from "../integration.js";
10
+ import type { BoardEnvelope } from "../protocol.js";
11
+ import type { BoardSummarizer } from "../summarizer.js";
12
+ import type { BoardTurns } from "./turns.js";
13
+
14
+ /** Owner execution begins at membership validation; archive commit precedes delivery. */
15
+ export class BoardOwner {
16
+ private readonly getTurns: () => BoardTurns;
17
+ private readonly getSummarizer: () => BoardSummarizer;
18
+ private readonly adapterOrUndefined: () => BoardAdapter | undefined;
19
+ private readonly adapter: () => BoardAdapter;
20
+ private readonly notify: (
21
+ ctx: ExtensionContext,
22
+ request: BoardEnvelope,
23
+ signal?: AbortSignal,
24
+ ) => Promise<unknown>;
25
+ constructor(
26
+ turns: () => BoardTurns,
27
+ summarizer: () => BoardSummarizer,
28
+ adapterOrUndefined: () => BoardAdapter | undefined,
29
+ adapter: () => BoardAdapter,
30
+ notify: (
31
+ ctx: ExtensionContext,
32
+ request: BoardEnvelope,
33
+ signal?: AbortSignal,
34
+ ) => Promise<unknown>,
35
+ ) {
36
+ this.getTurns = turns;
37
+ this.getSummarizer = summarizer;
38
+ this.adapterOrUndefined = adapterOrUndefined;
39
+ this.adapter = adapter;
40
+ this.notify = notify;
41
+ }
42
+ async execute(
43
+ ctx: ExtensionContext,
44
+ request: BoardEnvelope,
45
+ ): Promise<unknown> {
46
+ const own = binding(ctx);
47
+ if (!("caller" in request)) throw new Error("Invalid board owner request");
48
+ const directory = members(ctx);
49
+ const caller = directory.find(
50
+ (member) =>
51
+ member.sessionId === request.caller.sessionId &&
52
+ member.agentName === request.caller.agentName,
53
+ );
54
+ if (
55
+ !caller ||
56
+ request.caller.boardId !== own.boardId ||
57
+ request.caller.databasePath !== own.databasePath
58
+ )
59
+ throw new Error("Caller not bound to this board");
60
+ if (
61
+ request.operation === "board-unregister" ||
62
+ request.operation === "board-register"
63
+ )
64
+ return this.adapter().commitDirectory(own, directory, caller, request);
65
+ if (request.operation === "board-active") {
66
+ if (own.enabled) this.getTurns().register(caller, request);
67
+ return true;
68
+ }
69
+ if (request.operation === "board-catchup")
70
+ return own.enabled
71
+ ? (await import("../archive.js")).readSubscribedUpdates(
72
+ caller,
73
+ request.seen,
74
+ boardAliases(ctx),
75
+ )
76
+ : [];
77
+ if (request.operation !== "board-call")
78
+ throw new Error("Invalid board owner operation");
79
+ const params = parseBoardRequest(request.params);
80
+ if (params.action === "help")
81
+ return {
82
+ ...boardHelp,
83
+ rules: this.adapterOrUndefined()
84
+ ? boardHelp.rules
85
+ : {
86
+ ...boardHelp.rules,
87
+ agents:
88
+ "Agent reference /<Pi session ID>; notices require registered members",
89
+ },
90
+ enabled: own.enabled,
91
+ };
92
+ if (!own.enabled)
93
+ throw new Error("Board is off; the user can enable it with /board on");
94
+ const prepared: BoardParams =
95
+ params.author === undefined
96
+ ? params
97
+ : {
98
+ ...params,
99
+ author: agentPath(
100
+ params.author,
101
+ caller.legacyAgentName ?? caller.agentName,
102
+ ),
103
+ };
104
+ const active = new Map(this.getTurns().active);
105
+ const { executeArchive } = await import("../archive.js");
106
+ const result = await executeArchive(
107
+ { ...caller, enabled: own.enabled },
108
+ directory.map((member) => member.agentName),
109
+ prepared,
110
+ request.requestId,
111
+ boardAliases(ctx, params.board_id),
112
+ );
113
+ if ("notice" in result && result.notice) {
114
+ // Replayed mutations have no notice: never start or cancel twice for a retry.
115
+ if (params.action === "set_status") {
116
+ if (params.status === "open")
117
+ this.getSummarizer().cancel(own.boardId, result.notice.thread_id);
118
+ else
119
+ this.getSummarizer().start(
120
+ ctx,
121
+ own,
122
+ result.notice.thread_id,
123
+ result.notice.message_id,
124
+ );
125
+ }
126
+ for (let start = 0; start < result.recipients.length; start += 16) {
127
+ await Promise.all(
128
+ result.recipients.slice(start, start + 16).map(async (target) => {
129
+ const turn = active.get(target);
130
+ if (!turn) return;
131
+ const route: string[] = [];
132
+ let member = directory.find(
133
+ (entry) => entry.sessionId === turn.sessionId,
134
+ );
135
+ while (
136
+ member &&
137
+ member.sessionId !== own.sessionId &&
138
+ route.length < directory.length
139
+ ) {
140
+ route.unshift(member.sessionId);
141
+ member = directory.find(
142
+ (entry) => entry.sessionId === member?.parentSessionId,
143
+ );
144
+ }
145
+ if (member?.sessionId !== own.sessionId) return;
146
+ try {
147
+ await this.notify(
148
+ ctx,
149
+ {
150
+ operation: "board-notify",
151
+ boardId: own.boardId,
152
+ target,
153
+ route,
154
+ ...turn,
155
+ notice: result.notice,
156
+ },
157
+ AbortSignal.timeout(750),
158
+ );
159
+ } catch {
160
+ /* Committed posts succeed even when a running turn stops accepting. */
161
+ }
162
+ }),
163
+ );
164
+ }
165
+ }
166
+ return result.value;
167
+ }
168
+ }