@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,55 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { BoardBinding } from "./identity.js";
3
+ import type { BoardEnvelope } from "./protocol.js";
4
+
5
+ /** Optional membership transport. The runtime owns storage, settings and delivery. */
6
+ export interface BoardAdapter {
7
+ briefing?(
8
+ member: boolean,
9
+ population: "empty" | "populated" | "unavailable",
10
+ ): string;
11
+ request(
12
+ route: string,
13
+ request: BoardEnvelope,
14
+ signal?: AbortSignal,
15
+ ): Promise<unknown>;
16
+ commitDirectory(
17
+ own: BoardBinding,
18
+ directory: BoardBinding[],
19
+ caller: BoardBinding,
20
+ request: Extract<
21
+ BoardEnvelope,
22
+ { operation: "board-register" | "board-unregister" }
23
+ >,
24
+ ): unknown;
25
+ routeNotice(
26
+ ctx: ExtensionContext,
27
+ request: Extract<BoardEnvelope, { operation: "board-notify" }>,
28
+ signal?: AbortSignal,
29
+ ): Promise<unknown>;
30
+ propagateEnabled(ctx: ExtensionContext, enabled: boolean): Promise<void>;
31
+ }
32
+
33
+ export type { BoardScope } from "./config.js";
34
+ export {
35
+ contextBriefingWindow,
36
+ hasContextRollover,
37
+ recordContextBriefing,
38
+ registerContextBriefing,
39
+ } from "./context-briefing.js";
40
+ export type { BoardBinding } from "./identity.js";
41
+ export {
42
+ BindingSchema,
43
+ binding,
44
+ children,
45
+ members,
46
+ parseBinding,
47
+ parseBinding as canonicalBoardBinding,
48
+ removeMember,
49
+ rootBoardSetting,
50
+ saveBinding,
51
+ saveChild,
52
+ saveMember,
53
+ } from "./identity.js";
54
+ export type { BoardEnvelope } from "./protocol.js";
55
+ export { isBoardEnvelope } from "./protocol.js";
@@ -0,0 +1,54 @@
1
+ import type { BoardParams } from "./contract.js";
2
+
3
+ export interface PostRecord {
4
+ message_id: string;
5
+ channel_name: string;
6
+ author: string;
7
+ thread_id: string;
8
+ created_at: string;
9
+ text: string;
10
+ }
11
+ export const POST_COLUMNS =
12
+ "id AS message_id,channel AS channel_name,author,root AS thread_id,created_at,text";
13
+ export function metadata({ text: _text, ...value }: PostRecord) {
14
+ return value;
15
+ }
16
+ export function preview(post: PostRecord, chars: number) {
17
+ const text = Array.from(post.text);
18
+ return {
19
+ ...metadata(post),
20
+ text_preview: text.slice(0, chars).join(""),
21
+ n_chars: text.length,
22
+ truncated: text.length > chars,
23
+ };
24
+ }
25
+ export function window(params: BoardParams) {
26
+ const limit = Math.min(params.limit ?? 20, 50);
27
+ let offset = 0;
28
+ if (params.cursor !== undefined) {
29
+ const bytes = Buffer.from(params.cursor, "base64url");
30
+ if (bytes.length !== 4 || bytes.toString("base64url") !== params.cursor)
31
+ throw new Error("Invalid cursor");
32
+ offset = bytes.readUInt32BE();
33
+ }
34
+ return { limit, offset };
35
+ }
36
+ export function page<T>(values: T[], params: BoardParams) {
37
+ const { limit, offset } = window(params);
38
+ const has_more = values.length > limit;
39
+ const results = values.slice(0, limit);
40
+ const next_cursor = has_more ? cursor(offset + results.length) : null;
41
+ return { results, n_returned: results.length, has_more, next_cursor };
42
+ }
43
+ export function cursor(offset: number) {
44
+ if (offset > 0xffffffff) throw new Error("Cursor exceeds board limit");
45
+ const bytes = Buffer.alloc(4);
46
+ bytes.writeUInt32BE(offset);
47
+ return bytes.toString("base64url");
48
+ }
49
+ export function budget(params: BoardParams, count: number) {
50
+ return Math.min(
51
+ params.max_chars_per_post ?? 1000,
52
+ Math.floor(20000 / Math.max(1, count)),
53
+ );
54
+ }
@@ -0,0 +1,78 @@
1
+ import { type Static, Type } from "typebox";
2
+ import { Check } from "typebox/value";
3
+ import { BindingSchema } from "./identity.js";
4
+
5
+ const NoticeSchema = Type.Object(
6
+ {
7
+ message_id: Type.String(),
8
+ channel_name: Type.String(),
9
+ author: Type.String(),
10
+ thread_id: Type.String(),
11
+ created_at: Type.String(),
12
+ text_preview: Type.String({ maxLength: 300 }),
13
+ n_chars: Type.Integer({ minimum: 0 }),
14
+ truncated: Type.Boolean(),
15
+ },
16
+ { additionalProperties: false },
17
+ );
18
+ const Protocol = Type.Union([
19
+ Type.Object({
20
+ operation: Type.Literal("board-catchup"),
21
+ caller: BindingSchema,
22
+ seen: Type.Array(Type.String()),
23
+ }),
24
+ Type.Object({
25
+ operation: Type.Literal("board-bind"),
26
+ binding: BindingSchema,
27
+ }),
28
+ Type.Object({
29
+ operation: Type.Literal("board-register"),
30
+ caller: BindingSchema,
31
+ member: BindingSchema,
32
+ }),
33
+ Type.Object({
34
+ operation: Type.Literal("board-unregister"),
35
+ caller: BindingSchema,
36
+ member: BindingSchema,
37
+ }),
38
+ Type.Object({
39
+ operation: Type.Literal("board-enabled"),
40
+ boardId: Type.String(),
41
+ enabled: Type.Boolean(),
42
+ }),
43
+ Type.Object({
44
+ operation: Type.Literal("board-active"),
45
+ caller: BindingSchema,
46
+ turnId: Type.Union([Type.String(), Type.Null()]),
47
+ previousTurnId: Type.Optional(Type.String()),
48
+ }),
49
+ Type.Object({
50
+ operation: Type.Literal("board-call"),
51
+ caller: BindingSchema,
52
+ params: Type.Unknown(),
53
+ requestId: Type.String(),
54
+ }),
55
+ Type.Object({
56
+ operation: Type.Literal("board-notify"),
57
+ boardId: Type.String(),
58
+ target: Type.String(),
59
+ route: Type.Optional(Type.Array(Type.String())),
60
+ sessionId: Type.String(),
61
+ turnId: Type.String(),
62
+ notice: NoticeSchema,
63
+ }),
64
+ ]);
65
+ export type BoardEnvelope = Static<typeof Protocol>;
66
+ export function parseEnvelope(value: unknown): BoardEnvelope {
67
+ if (!Check(Protocol, value)) throw new Error("Invalid board host request");
68
+ return value as BoardEnvelope;
69
+ }
70
+ export function isBoardEnvelope(value: unknown): boolean {
71
+ return (
72
+ !!value &&
73
+ typeof value === "object" &&
74
+ "operation" in value &&
75
+ typeof value.operation === "string" &&
76
+ value.operation.startsWith("board-")
77
+ );
78
+ }
@@ -0,0 +1,168 @@
1
+ import { caseFold } from "unicode-case-folding";
2
+ import { type BoardParams, required } from "./contract.js";
3
+ import {
4
+ budget,
5
+ cursor,
6
+ metadata,
7
+ POST_COLUMNS,
8
+ type PostRecord,
9
+ page,
10
+ preview,
11
+ window,
12
+ } from "./paging.js";
13
+ import { searchBoard } from "./search.js";
14
+ import type { BoardStore } from "./store.js";
15
+ import { summaryPreview } from "./summaries.js";
16
+
17
+ export function queryBoard(
18
+ store: BoardStore,
19
+ ownBoard: string,
20
+ params: BoardParams,
21
+ ): Record<string, unknown> {
22
+ const board = params.board_id ?? ownBoard;
23
+ const { limit, offset } = window(params);
24
+ const order = params.recent_first === false ? "ASC" : "DESC";
25
+ if (params.action === "list_boards") {
26
+ const rows = store.all<{
27
+ board_id: string;
28
+ owner_folder: string;
29
+ created_at: string;
30
+ last_activity_at: string;
31
+ channel_count: number;
32
+ message_count: number;
33
+ }>(
34
+ `SELECT b.board_id,b.owner_folder,b.created_at,
35
+ COALESCE((SELECT created_at FROM posts p WHERE p.board_id=b.board_id ORDER BY seq DESC LIMIT 1),(SELECT created_at FROM channels c WHERE c.board_id=b.board_id ORDER BY substr(created_at,1,16) DESC,name DESC LIMIT 1),b.created_at) AS last_activity_at,
36
+ (SELECT COUNT(*) FROM channels c WHERE c.board_id=b.board_id) AS channel_count,
37
+ (SELECT COUNT(*) FROM posts p WHERE p.board_id=b.board_id) AS message_count
38
+ FROM boards b ORDER BY substr(last_activity_at,1,16) DESC,(SELECT MAX(seq) FROM posts p WHERE p.board_id=b.board_id) DESC,board_id DESC LIMIT ? OFFSET ?`,
39
+ limit + 1,
40
+ offset,
41
+ );
42
+ return page(
43
+ rows.map((row) => ({ ...row, current: row.board_id === ownBoard })),
44
+ params,
45
+ );
46
+ }
47
+ if (params.action === "get_channels") {
48
+ const rows = store.all<{ name: string }>(
49
+ `SELECT name FROM channels c WHERE board_id=? AND instr(name_search,?)>0 ORDER BY
50
+ COALESCE((SELECT substr(created_at,1,16) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name ORDER BY seq DESC LIMIT 1),substr(c.created_at,1,16)) ${order},
51
+ (SELECT MAX(seq) FROM posts p WHERE p.board_id=c.board_id AND p.channel=c.name) ${order},name ${order} LIMIT ? OFFSET ?`,
52
+ board,
53
+ caseFold(params.query ?? ""),
54
+ limit + 1,
55
+ offset,
56
+ );
57
+ return page(
58
+ rows.map(({ name }) => store.channel(board, name)),
59
+ params,
60
+ );
61
+ }
62
+ if (params.action === "read_post") {
63
+ const post = store.post(board, required(params.message_id, "message_id"));
64
+ const chars = Array.from(post.text);
65
+ const offset = Math.min(params.offset_chars ?? 0, chars.length);
66
+ const text = chars
67
+ .slice(offset, offset + Math.min(params.limit_chars ?? 20000, 20000))
68
+ .join("");
69
+ return {
70
+ ...metadata(post),
71
+ text,
72
+ n_chars: chars.length,
73
+ next_offset_chars: offset + Array.from(text).length,
74
+ };
75
+ }
76
+ if (params.action === "read_thread") {
77
+ const root = store.root(board, required(params.thread_id, "thread_id"));
78
+ const summary = params.full
79
+ ? undefined
80
+ : store.summaries.get(board, root.thread_id);
81
+ if (summary) {
82
+ const points = Array.from(summary.text);
83
+ const start = Math.min(offset, points.length);
84
+ const text = points.slice(start, start + budget(params, 1)).join("");
85
+ const next = start + Array.from(text).length;
86
+ return {
87
+ view: "summary",
88
+ root_post: metadata(root),
89
+ ...store.threadStatus(board, root.thread_id),
90
+ summary: {
91
+ ...summaryPreview(summary, 0),
92
+ text_preview: text,
93
+ offset_chars: start,
94
+ truncated: next < points.length,
95
+ },
96
+ has_more: next < points.length,
97
+ next_cursor: next < points.length ? cursor(next) : null,
98
+ };
99
+ }
100
+ const replies = store.all<PostRecord>(
101
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY seq DESC LIMIT ? OFFSET ?`,
102
+ board,
103
+ root.message_id,
104
+ limit + 1,
105
+ offset,
106
+ );
107
+ const chars = budget(params, Math.min(replies.length, limit) + 1);
108
+ return {
109
+ view: "full",
110
+ root_post: preview(root, chars),
111
+ ...store.threadStatus(board, root.thread_id),
112
+ ...page(
113
+ replies.map((post) => preview(post, chars)),
114
+ params,
115
+ ),
116
+ };
117
+ }
118
+ if (params.action === "list_threads") {
119
+ const channel = store.channel(
120
+ board,
121
+ required(params.channel_name, "channel_name"),
122
+ );
123
+ const sort =
124
+ params.sort === "activity"
125
+ ? "(SELECT MAX(seq) FROM posts r WHERE r.board_id=p.board_id AND r.root=p.id)"
126
+ : "p.seq";
127
+ const roots = store.all<PostRecord>(
128
+ `SELECT ${POST_COLUMNS} FROM posts p WHERE board_id=? AND channel=? AND id=root ORDER BY ${sort} ${order},seq ${order} LIMIT ? OFFSET ?`,
129
+ board,
130
+ channel.channel_name,
131
+ limit + 1,
132
+ offset,
133
+ );
134
+ const chars = budget(params, 2 * Math.min(roots.length, limit));
135
+ return page(
136
+ roots.map((root) => {
137
+ const summary = store.summaries.get(board, root.thread_id);
138
+ const reply = store.one<PostRecord>(
139
+ `SELECT ${POST_COLUMNS} FROM posts WHERE board_id=? AND root=? AND id<>root ORDER BY seq DESC LIMIT 1`,
140
+ board,
141
+ root.message_id,
142
+ );
143
+ const count =
144
+ store.one<{ n: number }>(
145
+ "SELECT COUNT(*) AS n FROM posts WHERE board_id=? AND root=? AND id<>root",
146
+ board,
147
+ root.message_id,
148
+ )?.n ?? 0;
149
+ return {
150
+ thread_id: root.message_id,
151
+ ...store.threadStatus(board, root.message_id),
152
+ ...(summary
153
+ ? { summary: summaryPreview(summary, chars) }
154
+ : { root_post: preview(root, chars) }),
155
+ reply_count: count,
156
+ last_activity_at: reply?.created_at ?? root.created_at,
157
+ ...(summary
158
+ ? {}
159
+ : { latest_reply: reply ? preview(reply, chars) : null }),
160
+ };
161
+ }),
162
+ params,
163
+ );
164
+ }
165
+ if (params.action === "search_posts")
166
+ return searchBoard(store, board, params);
167
+ throw new Error(`Unsupported board read: ${params.action}`);
168
+ }
@@ -0,0 +1,82 @@
1
+ import { minuteTimestamp } from "../timestamps.js";
2
+ import type { BoardParams } from "./contract.js";
3
+
4
+ // Includes UTF-8 text, JSON escaping and metadata, in every tool mode.
5
+ const MAX_RESPONSE_BYTES = 8000;
6
+
7
+ export function serializeBoardResult(value: unknown): string {
8
+ const text = JSON.stringify(value, (key, entry) =>
9
+ (key === "created_at" || key === "last_activity_at") &&
10
+ typeof entry === "string"
11
+ ? minuteTimestamp(entry)
12
+ : entry,
13
+ );
14
+ if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
15
+ throw new Error(
16
+ "Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
17
+ );
18
+ return text;
19
+ }
20
+
21
+ /** Keep the runtime's full acknowledgements out of native and nested tool output. */
22
+ export function serializeBoardToolResult(
23
+ value: unknown,
24
+ action: BoardParams["action"] | undefined,
25
+ ): string {
26
+ if (!value || typeof value !== "object" || Array.isArray(value))
27
+ return serializeBoardResult(value);
28
+ const result: Record<string, unknown> = { ...value };
29
+ if (action === "post" || action === "set_status") {
30
+ delete result["author"];
31
+ delete result["created_at"];
32
+ } else if (action === "create_channel") {
33
+ delete result["created_at"];
34
+ delete result["created_by"];
35
+ delete result["message_count"];
36
+ delete result["last_message_id"];
37
+ }
38
+ return serializeBoardResult(result);
39
+ }
40
+
41
+ export function checkMutationBudget(caller: string, params: BoardParams) {
42
+ // Native acknowledgement reserve, checked before opening or creating storage.
43
+ const target = params.target_agent ?? "";
44
+ if (
45
+ 2048 + Buffer.byteLength(caller) + Buffer.byteLength(target) >
46
+ MAX_RESPONSE_BYTES
47
+ )
48
+ throw new Error(
49
+ "Output budget is too small to acknowledge a message-board mutation; no change was made.",
50
+ );
51
+ }
52
+
53
+ export function boundedBoardRead<T extends { value: unknown }>(
54
+ params: BoardParams,
55
+ fetch: (request: BoardParams) => T,
56
+ ): T {
57
+ const limit = Math.min(params.limit ?? 20, 50);
58
+ const chars = Math.min(params.max_chars_per_post ?? 1000, 20000);
59
+ const postChars = Math.min(params.limit_chars ?? 20000, 20000);
60
+ const previews = ["list_threads", "search_posts", "read_thread"].includes(
61
+ params.action,
62
+ );
63
+ const post = params.action === "read_post";
64
+ const largest = post ? postChars : previews ? Math.max(limit, chars) : limit;
65
+ for (let scale = 1; ; scale *= 2) {
66
+ const reduced = (value: number) => Math.max(1, Math.floor(value / scale));
67
+ // Reissue the original cursor/offset so continuation matches the reduced page.
68
+ const result = fetch({
69
+ ...params,
70
+ ...(post
71
+ ? { limit_chars: reduced(postChars) }
72
+ : { limit: reduced(limit) }),
73
+ ...(previews ? { max_chars_per_post: reduced(chars) } : {}),
74
+ });
75
+ if (Buffer.byteLength(JSON.stringify(result.value)) <= MAX_RESPONSE_BYTES)
76
+ return result;
77
+ if (Math.floor(largest / scale) <= 1)
78
+ throw new Error(
79
+ "The output budget is too small for this result's metadata.",
80
+ );
81
+ }
82
+ }
@@ -0,0 +1,50 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { initializeDelivery, isMissingOptionalModule } from "../delivery.js";
3
+ import { createBoardTool } from "../tool.js";
4
+ import type { BoardRuntime } from "./coordinator.js";
5
+
6
+ export async function activateBoard(pi: ExtensionAPI, runtime: BoardRuntime) {
7
+ await initializeDelivery();
8
+ const tool = createBoardTool(runtime);
9
+ pi.registerTool(tool);
10
+ try {
11
+ const { registerGptPromptMode, prepareGptPromptMode } = await import(
12
+ "@howaboua/pi-codex-conversion/prompt-mode"
13
+ );
14
+ runtime.setPromptModePreparation((ctx) => prepareGptPromptMode(pi, ctx));
15
+ registerGptPromptMode(pi, (active) => {
16
+ runtime.gptPromptMode = active;
17
+ return [tool];
18
+ });
19
+ } catch (error) {
20
+ if (!isMissingOptionalModule(error, "prompt-mode")) throw error;
21
+ }
22
+ try {
23
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
24
+ await import("@howaboua/pi-codex-conversion/code-mode");
25
+ const registration = registerCodeModeExtensionTools(
26
+ pi,
27
+ () => [
28
+ adaptToolForCodeMode(tool, {
29
+ prepareInput: (input) =>
30
+ input === undefined || input === null ? {} : input,
31
+ discovery: "help",
32
+ }),
33
+ ],
34
+ { isActive: (ctx) => runtime.enabled(ctx) },
35
+ );
36
+ runtime.setToolRefresh(() => registration.refresh());
37
+ pi.on("session_shutdown", () => registration.unregister());
38
+ } catch (error) {
39
+ if (!isMissingOptionalModule(error, "code-mode")) throw error;
40
+ if (
41
+ error instanceof Error &&
42
+ "code" in error &&
43
+ error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED"
44
+ )
45
+ throw new Error(
46
+ "Update Codex Conversion to use its Code and Notebook board tools",
47
+ { cause: error },
48
+ );
49
+ }
50
+ }
@@ -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
+ }