@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,312 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
+ import { Type } from "typebox";
4
+ import { Check } from "typebox/value";
5
+ import type { LookupQuery } from "./bridge.js";
6
+ import { noteResult } from "./note-result.js";
7
+ import { internalQueryArguments, normalizeQueryInput } from "./query-input.js";
8
+
9
+ const NOTES_ACTIONS = [
10
+ "help",
11
+ "list",
12
+ "read",
13
+ "search",
14
+ "append",
15
+ "write",
16
+ ] as const;
17
+ const HISTORY_ACTIONS = [
18
+ "help",
19
+ "list_windows",
20
+ "list",
21
+ "read",
22
+ "search",
23
+ ] as const;
24
+ export const NOTES_USAGE = "await tools.notes()";
25
+ export const HISTORY_USAGE = "await tools.history()";
26
+ export const NOTES_DESCRIPTION = "Virtual filesystem task checkpoints";
27
+ export const NOTES_ROUTING_GUIDELINE =
28
+ "notes: task checkpoints and internal handoffs. MUST revise via write/append actions. Paths are virtual: read/write only through notes, never shell/filesystem tools. MUST NOT store project files or deliverables";
29
+ export const NEW_CONTEXT_DESCRIPTION =
30
+ "Start fresh context window. MUST save notes before calling";
31
+ export const GPT_NEW_CONTEXT_DESCRIPTION = "Save notes→fresh context";
32
+ const STRING = Type.Optional(Type.String());
33
+ const INTEGER = Type.Optional(Type.Integer({ minimum: 1 }));
34
+ const LINE = Type.Optional(Type.Union([Type.Integer(), Type.Null()]));
35
+ export const NOTES_SCHEMA = Type.Object(
36
+ {
37
+ action: Type.Optional(StringEnum(NOTES_ACTIONS)),
38
+ path: Type.Optional(
39
+ Type.Union([Type.String(), Type.Null()], {
40
+ description:
41
+ "File for read/write/append; prefix for list/search; virtual filesystem, not files in the project",
42
+ }),
43
+ ),
44
+ text: STRING,
45
+ query: STRING,
46
+ start_line: LINE,
47
+ stop_line: LINE,
48
+ limit: INTEGER,
49
+ max_matches_per_file: INTEGER,
50
+ file_order: Type.Optional(StringEnum(["ascending", "descending"])),
51
+ file_order_by: Type.Optional(
52
+ StringEnum(["name", "created_at", "updated_at"]),
53
+ ),
54
+ recent_file_first: Type.Optional(Type.Boolean()),
55
+ },
56
+ { additionalProperties: false },
57
+ );
58
+ const NEW_CONTEXT_SCHEMA = Type.Object(
59
+ {
60
+ role: Type.Optional(
61
+ Type.String({
62
+ minLength: 1,
63
+ description:
64
+ "Configured model-role ID, not an agent name or handoff text",
65
+ }),
66
+ ),
67
+ },
68
+ { additionalProperties: false },
69
+ );
70
+
71
+ export function newContextSchema(roleIds: string[]) {
72
+ return Type.Object(
73
+ roleIds.length ? { role: Type.Optional(StringEnum(roleIds)) } : {},
74
+ { additionalProperties: false },
75
+ );
76
+ }
77
+
78
+ export function prepareNewContextArguments(input: unknown) {
79
+ const args = input ?? {};
80
+ if (!Check(NEW_CONTEXT_SCHEMA, args))
81
+ throw new Error(
82
+ 'Use {} to keep the current model, or {role: "name"} for a configured role.',
83
+ );
84
+ return args;
85
+ }
86
+ export const HISTORY_SCHEMA = Type.Object(
87
+ {
88
+ action: Type.Optional(StringEnum(HISTORY_ACTIONS)),
89
+ agent_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
90
+ item_id: Type.Optional(Type.String()),
91
+ window_id: Type.Optional(
92
+ Type.Union([Type.String(), Type.Null()], {
93
+ description: "Required with item_id for read",
94
+ }),
95
+ ),
96
+ query: STRING,
97
+ limit: INTEGER,
98
+ limit_chars: INTEGER,
99
+ max_chars_per_item: INTEGER,
100
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
101
+ recent_first: Type.Optional(Type.Boolean()),
102
+ role: Type.Optional(
103
+ Type.Union([
104
+ StringEnum(["user", "assistant", "tool", "system", "developer"]),
105
+ Type.Null(),
106
+ ]),
107
+ ),
108
+ tool_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
109
+ tool_namespace: Type.Optional(Type.Union([Type.String(), Type.Null()])),
110
+ },
111
+ { additionalProperties: false },
112
+ );
113
+
114
+ const FIELDS: Record<string, readonly string[]> = {
115
+ list_files_by_prefix: [
116
+ "prefix",
117
+ "file_order",
118
+ "file_order_by",
119
+ "max_results",
120
+ ],
121
+ read_file: ["path", "start_line", "stop_line"],
122
+ search_notes: [
123
+ "query",
124
+ "path_prefix",
125
+ "max_files",
126
+ "max_matches_per_file",
127
+ "recent_file_first",
128
+ ],
129
+ append_to_file: ["path", "text"],
130
+ write_file: ["path", "text"],
131
+ list_windows: ["agent_name", "limit", "recent_first"],
132
+ list_items: [
133
+ "agent_name",
134
+ "window_id",
135
+ "role",
136
+ "tool_name",
137
+ "tool_namespace",
138
+ "limit",
139
+ "max_chars_per_item",
140
+ "recent_first",
141
+ ],
142
+ read_item: [
143
+ "agent_name",
144
+ "window_id",
145
+ "item_id",
146
+ "offset_chars",
147
+ "limit_chars",
148
+ ],
149
+ search_history: [
150
+ "agent_name",
151
+ "window_id",
152
+ "role",
153
+ "tool_name",
154
+ "tool_namespace",
155
+ "query",
156
+ "limit",
157
+ "recent_first",
158
+ ],
159
+ };
160
+ export function queryArguments(
161
+ namespace: LookupQuery["namespace"],
162
+ input: unknown,
163
+ ): Record<string, unknown> {
164
+ if (!input || typeof input !== "object" || Array.isArray(input))
165
+ throw new Error("Supply an action object");
166
+ const normalized = normalizeQueryInput(namespace, input);
167
+ const params = internalQueryArguments(namespace, normalized);
168
+ const action = params["action"];
169
+ const publicAction = normalized["action"];
170
+ const key =
171
+ action === "search_contents" ? `search_${namespace}` : String(action);
172
+ const fields = FIELDS[key];
173
+ if (!fields)
174
+ throw new Error(
175
+ namespace === "notes"
176
+ ? "notes requires a supported action"
177
+ : "Unknown action",
178
+ );
179
+ for (const field of Object.keys(params))
180
+ if (field !== "action" && !fields.includes(field))
181
+ throw new Error(
182
+ `${namespace} ${String(publicAction)} does not accept ${field}; use {} for help`,
183
+ );
184
+ if (
185
+ ["read_file", "write_file", "append_to_file"].includes(String(action)) &&
186
+ (typeof params["path"] !== "string" || !params["path"])
187
+ )
188
+ throw new Error(`notes ${String(publicAction)} requires path`);
189
+ if (
190
+ action === "search_contents" &&
191
+ (typeof params["query"] !== "string" || !params["query"])
192
+ )
193
+ throw new Error(`${namespace} search requires query`);
194
+ if (
195
+ ["write_file", "append_to_file"].includes(String(action)) &&
196
+ typeof params["text"] !== "string"
197
+ )
198
+ throw new Error(`notes ${String(publicAction)} requires text`);
199
+ return params;
200
+ }
201
+
202
+ export function result(payload: unknown): AgentToolResult<unknown> {
203
+ return {
204
+ content: [{ type: "text", text: JSON.stringify(payload) }],
205
+ details: {},
206
+ };
207
+ }
208
+
209
+ export function queryHelp(
210
+ namespace: LookupQuery["namespace"],
211
+ input: unknown,
212
+ gpt = false,
213
+ ): AgentToolResult<unknown> | undefined {
214
+ const params = input === undefined ? {} : input;
215
+ if (!params || typeof params !== "object" || Array.isArray(params))
216
+ throw new Error("Supply an action object, or omit arguments for help");
217
+ const entries = Object.entries(params);
218
+ if (
219
+ !entries.length ||
220
+ (params as Record<string, unknown>)["action"] === "help"
221
+ ) {
222
+ if (entries.some(([key]) => key !== "action"))
223
+ throw new Error("Help accepts only action: help");
224
+ const actions = namespace === "notes" ? NOTES_ACTIONS : HISTORY_ACTIONS;
225
+ return (namespace === "notes" ? noteResult : result)({
226
+ ...(namespace === "notes"
227
+ ? { results: "read: file.content; write/append: file.path" }
228
+ : {}),
229
+ actions: Object.fromEntries(
230
+ actions.map((action) => [
231
+ action,
232
+ action === "help"
233
+ ? ""
234
+ : FIELDS[helpKey(namespace, action)]!.map((field) =>
235
+ ["path", "text", "query", "item_id"].includes(field) ||
236
+ (action === "read" && field === "window_id")
237
+ ? field
238
+ : `${field}?`,
239
+ )
240
+ .map((field) => publicField(namespace, field))
241
+ .join(" "),
242
+ ]),
243
+ ),
244
+ ...(namespace === "notes"
245
+ ? {
246
+ writes: gpt
247
+ ? "write=replace; append=add"
248
+ : "write replaces; append adds",
249
+ paths: gpt
250
+ ? "Virtual≠disk; own list/search→omit path; relative=current agent; absolute=/<session ID>/notes[/path], not the agent ID alone"
251
+ : "Virtual note paths, not disk files. Omit path to list/search your notes. Relative paths use your agent; absolute paths require /<session ID>/notes[/path], not the agent ID alone",
252
+ usage: 'notes: {"action":"read","path":"checkpoint"}',
253
+ ranges: gpt
254
+ ? "start_line/stop_line=1-based inclusive; negative=from end; 0/null/omitted=first/last; out-of-range→clamp; reversed→empty"
255
+ : "start_line/stop_line inclusive, 1-based; negative from end; 0/null/omitted uses first/last line; out-of-range clamps; reversed returns empty content",
256
+ defaults: gpt
257
+ ? "list limit=20; search limit/max_matches_per_file=20; limits clamp 1..100; list/search name ascending; recent_file_first→created_at descending"
258
+ : "list limit 20; search limit/max_matches_per_file 20; limits clamp 1..100; list/search name ascending; recent_file_first sorts created_at descending",
259
+ }
260
+ : {
261
+ usage: gpt
262
+ ? "query→search default; past chat→search≠browse; returned IDs unchanged"
263
+ : "With query, action defaults to search. Search past chat, don't browse it. Pass returned IDs unchanged",
264
+ search: gpt
265
+ ? "recent_first=true→newest first"
266
+ : "recent_first=true uses newest first",
267
+ }),
268
+ });
269
+ }
270
+ return undefined;
271
+ }
272
+
273
+ export function prepareNotesArguments(args: unknown) {
274
+ const params = normalizeQueryInput("notes", args);
275
+ validateArguments("notes", params, NOTES_SCHEMA);
276
+ return params;
277
+ }
278
+
279
+ export function prepareHistoryArguments(args: unknown) {
280
+ const params = normalizeQueryInput("history", args);
281
+ validateArguments("history", params, HISTORY_SCHEMA);
282
+ return params;
283
+ }
284
+
285
+ function validateArguments(
286
+ namespace: LookupQuery["namespace"],
287
+ params: Record<string, unknown>,
288
+ schema: import("typebox").TObject,
289
+ ) {
290
+ if (!queryHelp(namespace, params)) queryArguments(namespace, params);
291
+ for (const [field, value] of Object.entries(params)) {
292
+ const property = schema.properties[field];
293
+ if (!property || !Check(property, value))
294
+ throw new Error(
295
+ `Invalid ${namespace} ${field}; use {} for exact arguments`,
296
+ );
297
+ }
298
+ }
299
+
300
+ function helpKey(namespace: LookupQuery["namespace"], action: string) {
301
+ const internal = internalQueryArguments(namespace, { action })["action"];
302
+ return internal === "search_contents"
303
+ ? `search_${namespace}`
304
+ : String(internal);
305
+ }
306
+
307
+ function publicField(namespace: LookupQuery["namespace"], field: string) {
308
+ if (namespace !== "notes") return field;
309
+ return field
310
+ .replace(/^(prefix|path_prefix)(\?)?$/, "path$2")
311
+ .replace(/^(max_results|max_files)(\?)?$/, "limit$2");
312
+ }
@@ -0,0 +1,148 @@
1
+ import type {
2
+ AgentToolResult,
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ ToolDefinition,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import type { LookupQuery, SharedNotesDetails } from "./bridge.js";
9
+ import type { HistorySearch } from "./history-search.js";
10
+ import type { NotesLifecycle } from "./lifecycle.js";
11
+ import type { createModelRoles } from "./model-roles.js";
12
+ import { NOTES_OUTPUT_SCHEMA } from "./note-result.js";
13
+ import { createQueryExecutor } from "./query-executor.js";
14
+ import type { NotesStore } from "./store.js";
15
+ import {
16
+ HISTORY_SCHEMA,
17
+ NEW_CONTEXT_DESCRIPTION,
18
+ NOTES_DESCRIPTION,
19
+ NOTES_ROUTING_GUIDELINE,
20
+ NOTES_SCHEMA,
21
+ newContextSchema,
22
+ prepareHistoryArguments,
23
+ prepareNewContextArguments,
24
+ prepareNotesArguments,
25
+ result,
26
+ } from "./tool-contracts.js";
27
+
28
+ export function createSharedExecutor(
29
+ pi: ExtensionAPI,
30
+ store: NotesStore,
31
+ lifecycle: NotesLifecycle,
32
+ search: HistorySearch,
33
+ ) {
34
+ const queries = createQueryExecutor(pi, store, lifecycle, search, true);
35
+ return async (
36
+ query: LookupQuery,
37
+ callId: string,
38
+ ctx: ExtensionContext,
39
+ signal?: AbortSignal,
40
+ ): Promise<AgentToolResult<SharedNotesDetails>> => {
41
+ const output = await queries[query.namespace](
42
+ callId,
43
+ query.params,
44
+ signal,
45
+ ctx,
46
+ );
47
+ return {
48
+ ...output,
49
+ details: { codexHistoryNotes: {}, ...(output.details as object) },
50
+ };
51
+ };
52
+ }
53
+
54
+ export function createTools(
55
+ pi: ExtensionAPI,
56
+ store: NotesStore,
57
+ lifecycle: NotesLifecycle,
58
+ search: HistorySearch,
59
+ roles: ReturnType<typeof createModelRoles>,
60
+ ): ToolDefinition[] {
61
+ const assertActive = () => {
62
+ if (!lifecycle.active)
63
+ throw new Error(
64
+ "Notes tools are inactive. Ask the user to check /notes.",
65
+ );
66
+ };
67
+ const queries = createQueryExecutor(pi, store, lifecycle, search);
68
+ const tools: ToolDefinition[] = [
69
+ {
70
+ name: "notes",
71
+ label: "notes",
72
+ description: NOTES_DESCRIPTION,
73
+ promptGuidelines: [NOTES_ROUTING_GUIDELINE],
74
+ parameters: NOTES_SCHEMA,
75
+ outputSchema: NOTES_OUTPUT_SCHEMA,
76
+ executionMode: "sequential",
77
+ prepareArguments: prepareNotesArguments,
78
+ execute: (callId, input, signal, _update, ctx) =>
79
+ queries.notes(callId, input, signal, ctx),
80
+ },
81
+ {
82
+ name: "history",
83
+ label: "history",
84
+ description: "Search past chat",
85
+ parameters: HISTORY_SCHEMA,
86
+ prepareArguments(args) {
87
+ return prepareHistoryArguments(args);
88
+ },
89
+ execute: (callId, input, signal, _update, ctx) =>
90
+ queries.history(callId, input, signal, ctx),
91
+ },
92
+ {
93
+ name: "new_context",
94
+ label: "new_context",
95
+ description: NEW_CONTEXT_DESCRIPTION,
96
+ parameters: newContextSchema([]),
97
+ prepareArguments: prepareNewContextArguments,
98
+ exposure: "model-only",
99
+ executionMode: "sequential",
100
+ async execute(id, input, signal, _update, ctx) {
101
+ assertActive();
102
+ if (signal?.aborted) throw new Error("Rollover cancelled");
103
+ const { role } = prepareNewContextArguments(input);
104
+ const handoff =
105
+ role === undefined ? undefined : await roles.prepare(role, ctx);
106
+ if (signal?.aborted) throw new Error("Rollover cancelled");
107
+ const started = lifecycle.requestRollover(ctx, id, handoff);
108
+ if (started) ctx.abort();
109
+ return {
110
+ ...result({
111
+ started,
112
+ message: started
113
+ ? lifecycle.newWindowRequests === "pi-limits"
114
+ ? "Window request queued"
115
+ : "New window queued"
116
+ : "Checkpoint or rollover is already pending. Save notes and finish your response",
117
+ }),
118
+ ...(started ? { terminate: true } : {}),
119
+ };
120
+ },
121
+ },
122
+ {
123
+ name: "get_context_remaining",
124
+ label: "get_context_remaining",
125
+ description: "Remaining context tokens",
126
+ parameters: Type.Object({}, { additionalProperties: false }),
127
+ async execute(_id, _input, _signal, _update, ctx) {
128
+ assertActive();
129
+ const remaining = lifecycle.windows.remaining(ctx);
130
+ return result({
131
+ contextWindow: remaining.contextWindow,
132
+ remainingTokens: remaining.remainingTokens ?? null,
133
+ remainingPercent: remaining.remainingPercent ?? null,
134
+ });
135
+ },
136
+ },
137
+ ];
138
+ const newContext = tools.find((tool) => tool.name === "new_context")!;
139
+ let advertisedRoles = "[]";
140
+ roles.onRoleIdsChanged((ids) => {
141
+ const key = JSON.stringify(ids);
142
+ if (key === advertisedRoles) return;
143
+ advertisedRoles = key;
144
+ newContext.parameters = newContextSchema(ids);
145
+ pi.registerTool(newContext);
146
+ });
147
+ return tools;
148
+ }
@@ -0,0 +1,27 @@
1
+ /** @typedef {import("./tree-archive.js").TreeArchiveManifestData} TreeArchiveManifestData */
2
+ export const TREE_ARCHIVE_ENTRY_TYPE = "codex-context-tree-archive";
3
+ const TREE_ARCHIVE_PROTOCOL = 1;
4
+ export const MAX_ARCHIVE_DEPTH = 50_000;
5
+
6
+ /** @param {unknown} value @returns {value is TreeArchiveManifestData} */
7
+ export function isTreeArchiveManifestData(value) {
8
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9
+ const manifest = /** @type {Record<string, unknown>} */ (value);
10
+ return (
11
+ manifest["protocol"] === TREE_ARCHIVE_PROTOCOL &&
12
+ manifest["strategy"] === "codex-context-tree" &&
13
+ nonEmptyString(manifest["windowId"]) &&
14
+ nonEmptyString(manifest["boundaryEntryId"]) &&
15
+ nonEmptyString(manifest["summaryEntryId"]) &&
16
+ nonEmptyString(manifest["archivedLeafId"]) &&
17
+ (manifest["compactionEntryId"] === undefined ||
18
+ nonEmptyString(manifest["compactionEntryId"])) &&
19
+ (manifest["branchBaseId"] === null ||
20
+ nonEmptyString(manifest["branchBaseId"]))
21
+ );
22
+ }
23
+
24
+ /** @param {unknown} value @returns {value is string} */
25
+ function nonEmptyString(value) {
26
+ return typeof value === "string" && value !== "";
27
+ }
@@ -0,0 +1,129 @@
1
+ import type {
2
+ BranchSummaryEntry,
3
+ SessionEntry,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ isTreeArchiveManifestData,
7
+ MAX_ARCHIVE_DEPTH,
8
+ TREE_ARCHIVE_ENTRY_TYPE,
9
+ } from "./tree-archive-manifest.mjs";
10
+ import { windowDetails } from "./windows.js";
11
+
12
+ export { TREE_ARCHIVE_ENTRY_TYPE } from "./tree-archive-manifest.mjs";
13
+
14
+ export interface TreeArchiveManifestData {
15
+ protocol: 1;
16
+ strategy: "codex-context-tree";
17
+ windowId: string;
18
+ boundaryEntryId: string;
19
+ summaryEntryId: string;
20
+ archivedLeafId: string;
21
+ branchBaseId: string | null;
22
+ compactionEntryId?: string;
23
+ }
24
+
25
+ interface TreeArchive {
26
+ manifest: TreeArchiveManifestData;
27
+ summary: BranchSummaryEntry;
28
+ // Pi forks copy the active branch, not the archived paths it references.
29
+ entries: SessionEntry[] | undefined;
30
+ }
31
+
32
+ export interface TreeArchiveIndex {
33
+ archives: TreeArchive[];
34
+ invalidManifest: boolean;
35
+ }
36
+
37
+ export function buildTreeArchiveIndex(
38
+ allEntries: readonly SessionEntry[],
39
+ activeBranch: readonly SessionEntry[],
40
+ ): TreeArchiveIndex {
41
+ const byId = new Map(allEntries.map((entry) => [entry.id, entry]));
42
+ const archives: TreeArchive[] = [];
43
+ const seenSummaries = new Set<string>();
44
+ const seenWindows = new Set<string>();
45
+ let invalidManifest = false;
46
+ for (const entry of activeBranch) {
47
+ if (entry.type !== "custom" || entry.customType !== TREE_ARCHIVE_ENTRY_TYPE)
48
+ continue;
49
+ if (!isTreeArchiveManifestData(entry.data)) {
50
+ invalidManifest = true;
51
+ continue;
52
+ }
53
+ const manifest = entry.data;
54
+ if (
55
+ seenSummaries.has(manifest.summaryEntryId) ||
56
+ seenWindows.has(manifest.windowId)
57
+ ) {
58
+ invalidManifest = true;
59
+ continue;
60
+ }
61
+ const summary = byId.get(manifest.summaryEntryId);
62
+ if (
63
+ !summary ||
64
+ summary.type !== "branch_summary" ||
65
+ entry.parentId !== summary.id ||
66
+ summary.fromId !== manifest.archivedLeafId ||
67
+ summary.parentId !== manifest.branchBaseId
68
+ ) {
69
+ invalidManifest = true;
70
+ continue;
71
+ }
72
+ const archivedEntries = archivedPath(manifest, byId);
73
+ if (
74
+ archivedEntries &&
75
+ manifest.compactionEntryId !== undefined &&
76
+ !archivedEntries.some(
77
+ (entry) =>
78
+ entry.id === manifest.compactionEntryId &&
79
+ entry.type === "compaction",
80
+ )
81
+ ) {
82
+ invalidManifest = true;
83
+ continue;
84
+ }
85
+ seenSummaries.add(summary.id);
86
+ seenWindows.add(manifest.windowId);
87
+ archives.push({ manifest, summary, entries: archivedEntries });
88
+ }
89
+ return { archives, invalidManifest };
90
+ }
91
+
92
+ function archivedPath(
93
+ manifest: TreeArchiveManifestData,
94
+ byId: ReadonlyMap<string, SessionEntry>,
95
+ ): SessionEntry[] | undefined {
96
+ const reverse: SessionEntry[] = [];
97
+ const visited = new Set<string>();
98
+ let currentId: string | null = manifest.archivedLeafId;
99
+ let foundBoundary = false;
100
+ while (currentId !== manifest.branchBaseId) {
101
+ if (
102
+ currentId === null ||
103
+ visited.has(currentId) ||
104
+ reverse.length >= MAX_ARCHIVE_DEPTH
105
+ )
106
+ return undefined;
107
+ visited.add(currentId);
108
+ const entry = byId.get(currentId);
109
+ if (!entry) return undefined;
110
+ reverse.push(entry);
111
+ if (entry.id === manifest.boundaryEntryId) foundBoundary = true;
112
+ currentId = entry.parentId;
113
+ }
114
+ if (!foundBoundary) return undefined;
115
+ return reverse.reverse();
116
+ }
117
+
118
+ export function hasTreeArchiveSuccessor(
119
+ entries: readonly SessionEntry[],
120
+ windowId: string,
121
+ ): boolean {
122
+ return entries.some((entry) => {
123
+ const details = windowDetails(entry);
124
+ return (
125
+ details?.kind === "window" &&
126
+ details.identity.previousWindowId === windowId
127
+ );
128
+ });
129
+ }