@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,302 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { isContextAgentName } from "./agent-identity.js";
7
+ import type { NoteSnapshotData } from "./bridge.js";
8
+ import { canonicalPath, readNotes } from "./note-query.js";
9
+ import { type NoteRevision, NotesStore, type SessionRef } from "./store.js";
10
+
11
+ export { normalizeNoteParams, readNotes } from "./note-query.js";
12
+
13
+ export const NOTE_RECEIPT = "notes-compaction:note:v1";
14
+ export const CACHE_RECEIPT = "notes-compaction:cache:v1";
15
+ export interface NoteReceipt {
16
+ protocol: 1;
17
+ sessionId: string;
18
+ windowId: string;
19
+ runId: string;
20
+ origin?: "routed";
21
+ /** Model-invisible recovery snapshot follows native fork and branch projections. */
22
+ revision: NoteRevision;
23
+ }
24
+
25
+ export function sessionRef(ctx: ExtensionContext): SessionRef {
26
+ return {
27
+ id: ctx.sessionManager.getSessionId(),
28
+ file: ctx.sessionManager.getSessionFile(),
29
+ };
30
+ }
31
+
32
+ export function sourceSessionIds(ctx: ExtensionContext): string[] {
33
+ const ids = new Set([ctx.sessionManager.getSessionId()]);
34
+ for (const entry of ctx.sessionManager.getBranch())
35
+ if (
36
+ entry.type === "custom" &&
37
+ entry.customType === CACHE_RECEIPT &&
38
+ entry.data &&
39
+ typeof entry.data === "object" &&
40
+ "protocol" in entry.data &&
41
+ entry.data.protocol === 1 &&
42
+ "sessionId" in entry.data &&
43
+ typeof entry.data.sessionId === "string"
44
+ )
45
+ ids.add(entry.data.sessionId);
46
+ return [...ids];
47
+ }
48
+
49
+ export function noteReceipt(data: unknown): NoteReceipt | undefined {
50
+ if (
51
+ !data ||
52
+ typeof data !== "object" ||
53
+ !("protocol" in data) ||
54
+ data.protocol !== 1 ||
55
+ !("revision" in data)
56
+ )
57
+ return;
58
+ const record = data as Partial<NoteReceipt>;
59
+ const revision = record.revision;
60
+ if (
61
+ typeof record.sessionId !== "string" ||
62
+ typeof record.windowId !== "string" ||
63
+ typeof record.runId !== "string" ||
64
+ (record.origin !== undefined && record.origin !== "routed") ||
65
+ !revision ||
66
+ typeof revision.id !== "string" ||
67
+ typeof revision.path !== "string" ||
68
+ typeof revision.text !== "string" ||
69
+ !["replace", "append"].includes(revision.mode) ||
70
+ !Number.isFinite(revision.createdAt) ||
71
+ !Number.isFinite(revision.updatedAt)
72
+ )
73
+ return;
74
+ return record as NoteReceipt;
75
+ }
76
+
77
+ function relativeLegacyPath(path: string): string {
78
+ // Legacy canonical paths use the first notes component as the agent-root boundary.
79
+ const components = path.split("/");
80
+ const boundary = components.indexOf("notes");
81
+ return components[0] === "" &&
82
+ isContextAgentName(components.slice(0, boundary).join("/")) &&
83
+ boundary > 1
84
+ ? components.slice(boundary + 1).join("/")
85
+ : path;
86
+ }
87
+
88
+ function snapshotNotes(data: unknown, id: string): NoteRevision[] | undefined {
89
+ if (
90
+ !data ||
91
+ typeof data !== "object" ||
92
+ !("protocol" in data) ||
93
+ data.protocol !== 1 ||
94
+ !("files" in data) ||
95
+ !Array.isArray(data.files)
96
+ )
97
+ return;
98
+ const result: NoteRevision[] = [];
99
+ for (const file of data.files) {
100
+ if (
101
+ !file ||
102
+ typeof file !== "object" ||
103
+ typeof file.path !== "string" ||
104
+ typeof file.text !== "string" ||
105
+ !Number.isFinite(file.createdAt) ||
106
+ !Number.isFinite(file.updatedAt)
107
+ )
108
+ return;
109
+ result.push({
110
+ id,
111
+ path: relativeLegacyPath(file.path),
112
+ text: file.text,
113
+ mode: file.operation === "local_append_overlay" ? "append" : "replace",
114
+ createdAt: file.createdAt,
115
+ updatedAt: file.updatedAt,
116
+ });
117
+ }
118
+ return result;
119
+ }
120
+
121
+ /** Only selected-branch receipts choose visible revisions. Sibling writes never leak. */
122
+ export function collectNotes(
123
+ store: Pick<NotesStore, "read">,
124
+ entries: readonly SessionEntry[],
125
+ ): Map<string, NoteRevision> {
126
+ const notes = new Map<string, NoteRevision>();
127
+ for (const entry of entries) {
128
+ if (
129
+ entry.type === "branch_summary" &&
130
+ entry.details &&
131
+ typeof entry.details === "object" &&
132
+ "codexContextNoteHandoff" in entry.details
133
+ ) {
134
+ for (const note of snapshotNotes(
135
+ entry.details.codexContextNoteHandoff,
136
+ entry.id,
137
+ ) ?? [])
138
+ notes.set(note.path, note);
139
+ continue;
140
+ }
141
+ if (entry.type !== "custom") continue;
142
+ if (entry.customType === NOTE_RECEIPT) {
143
+ const receipt = noteReceipt(entry.data);
144
+ if (!receipt)
145
+ throw new Error(
146
+ "A saved note could not be read. Open an intact session branch to recover it.",
147
+ );
148
+ // A fork carries the receipt even when its source session was explicitly pruned.
149
+ const revision = store.read(receipt.revision.id) ?? receipt.revision;
150
+ notes.set(revision.path, revision);
151
+ } else if (entry.customType === "codex-context-note") {
152
+ const data = entry.data as
153
+ | {
154
+ protocol?: unknown;
155
+ path?: unknown;
156
+ text?: unknown;
157
+ action?: unknown;
158
+ timestamp?: unknown;
159
+ }
160
+ | undefined;
161
+ if (
162
+ data?.protocol !== 1 ||
163
+ typeof data.path !== "string" ||
164
+ typeof data.text !== "string" ||
165
+ (data.action !== "write" && data.action !== "append")
166
+ )
167
+ continue;
168
+ const path = relativeLegacyPath(data.path);
169
+ const previous = notes.get(path);
170
+ const time = typeof data.timestamp === "number" ? data.timestamp : 0;
171
+ notes.set(path, {
172
+ id: entry.id,
173
+ path,
174
+ text:
175
+ data.action === "append"
176
+ ? (previous?.text ?? "") + data.text
177
+ : data.text,
178
+ mode: "replace",
179
+ createdAt: previous?.createdAt ?? time,
180
+ updatedAt: time,
181
+ });
182
+ } else if (entry.customType === "codex-context-note-snapshot") {
183
+ const snapshot = snapshotNotes(entry.data, entry.id);
184
+ if (!snapshot) continue;
185
+ notes.clear();
186
+ for (const note of snapshot) notes.set(note.path, note);
187
+ }
188
+ }
189
+ return notes;
190
+ }
191
+
192
+ /** Receipts carry recovery text, so detached reads need neither a database nor another process. */
193
+ export function exportNotesSnapshot(
194
+ entries: readonly SessionEntry[],
195
+ agentName: string,
196
+ ): NoteSnapshotData {
197
+ if (!isContextAgentName(agentName))
198
+ throw new Error("Invalid notes agent identity");
199
+ const notes = collectNotes({ read: () => undefined }, entries);
200
+ const snapshot: NoteSnapshotData = {
201
+ protocol: 1,
202
+ timestamp: Date.now(),
203
+ files: [...notes.values()]
204
+ .sort((a, b) => a.path.localeCompare(b.path))
205
+ .map((note) => ({
206
+ path: `${agentName}/notes/${canonicalPath(note.path, agentName)}`,
207
+ text: note.text,
208
+ createdAt: note.createdAt,
209
+ updatedAt: note.updatedAt,
210
+ operation:
211
+ note.mode === "append" ? "local_append_overlay" : "local_replacement",
212
+ })),
213
+ };
214
+ if (
215
+ snapshot.files.some((file) => Buffer.byteLength(file.text) > 1_000_000) ||
216
+ Buffer.byteLength(JSON.stringify(snapshot)) > 10_000_000
217
+ )
218
+ throw new Error(
219
+ "Notes snapshot exceeds the retained checkpoint size limit",
220
+ );
221
+ return snapshot;
222
+ }
223
+
224
+ export function noteHints(
225
+ store: NotesStore,
226
+ ctx: ExtensionContext,
227
+ agent: string,
228
+ ): string {
229
+ const notes = [
230
+ ...collectNotes(store, ctx.sessionManager.getBranch()).values(),
231
+ ]
232
+ .sort((a, b) => b.updatedAt - a.updatedAt)
233
+ .map((note) => `${agent}/notes/${note.path}`);
234
+ const paths = [
235
+ ...new Set([...notes, ...store.cachedPaths(sourceSessionIds(ctx))]),
236
+ ].slice(0, 5);
237
+ return paths.length
238
+ ? `Recent notes in virtual filesystem: ${paths.join(", ")}`.slice(0, 4000)
239
+ : "";
240
+ }
241
+
242
+ export function useNotes(
243
+ pi: ExtensionAPI,
244
+ store: NotesStore,
245
+ params: Record<string, unknown>,
246
+ ctx: ExtensionContext,
247
+ agent: string,
248
+ windowId: string,
249
+ runId: string,
250
+ routed = false,
251
+ ): Record<string, unknown> {
252
+ const notes = collectNotes(store, ctx.sessionManager.getBranch());
253
+ const action = params["action"];
254
+ const root = `${agent}/notes/`;
255
+ if (action === "write_file" || action === "append_to_file") {
256
+ const path = params["path"] as string;
257
+ const text = params["text"];
258
+ if (typeof text !== "string")
259
+ throw new Error(`notes ${action} requires text`);
260
+ const previous = notes.get(path);
261
+ const next =
262
+ action === "append_to_file" ? (previous?.text ?? "") + text : text;
263
+ if (Buffer.byteLength(next) > 1_000_000)
264
+ throw new Error("Note file exceeds the 1,000,000-byte limit");
265
+ const now = Date.now();
266
+ // Append never pretends to decode a remote base. The remote fragment remains separate.
267
+ const mode =
268
+ action === "write_file" ? "replace" : (previous?.mode ?? "append");
269
+ let revision: NoteRevision;
270
+ try {
271
+ revision = store.write(sessionRef(ctx), {
272
+ path,
273
+ text: next,
274
+ mode,
275
+ createdAt: previous?.createdAt ?? now,
276
+ updatedAt: now,
277
+ });
278
+ } catch {
279
+ throw new Error(
280
+ "Local note could not be saved. The selected branch remains unchanged. Retry after local storage is available.",
281
+ );
282
+ }
283
+ try {
284
+ pi.appendEntry(NOTE_RECEIPT, {
285
+ protocol: 1,
286
+ sessionId: ctx.sessionManager.getSessionId(),
287
+ windowId,
288
+ runId,
289
+ ...(routed ? { origin: "routed" as const } : {}),
290
+ revision,
291
+ } satisfies NoteReceipt);
292
+ } catch {
293
+ throw new Error(
294
+ `Note ${root}${path} was stored but not attached to this session. Read it before retrying the write.`,
295
+ );
296
+ }
297
+ return {
298
+ file: { path: `${root}${path}` },
299
+ };
300
+ }
301
+ return readNotes(notes, params, agent);
302
+ }
@@ -0,0 +1,242 @@
1
+ import type {
2
+ AgentToolResult,
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ contextAgentIdentity,
8
+ contextAgentNames,
9
+ contextStorageAgentName,
10
+ } from "./agent-identity.js";
11
+ import { useHistory } from "./history.js";
12
+ import type { HistorySearch } from "./history-search.js";
13
+ import type { NotesLifecycle } from "./lifecycle.js";
14
+ import { noteResult } from "./note-result.js";
15
+ import { collectNotes, normalizeNoteParams, useNotes } from "./notes.js";
16
+ import { lookupNotes } from "./notes-lookup.js";
17
+ import {
18
+ readSharedHistory,
19
+ readSharedNotes,
20
+ sharedNotesUnavailable,
21
+ } from "./shared-notes.js";
22
+ import type { NotesStore } from "./store.js";
23
+ import {
24
+ prepareHistoryArguments,
25
+ prepareNotesArguments,
26
+ queryArguments,
27
+ queryHelp,
28
+ result,
29
+ } from "./tool-contracts.js";
30
+
31
+ export function createQueryExecutor(
32
+ pi: ExtensionAPI,
33
+ store: NotesStore,
34
+ lifecycle: NotesLifecycle,
35
+ search: HistorySearch,
36
+ shared = false,
37
+ ) {
38
+ const assertActive = () => {
39
+ if (!lifecycle.active && !shared)
40
+ throw new Error(
41
+ "Notes tools are inactive. Ask the user to check /notes.",
42
+ );
43
+ };
44
+ async function notes(
45
+ callId: string,
46
+ input: unknown,
47
+ signal: AbortSignal | undefined,
48
+ ctx: ExtensionContext,
49
+ ): Promise<AgentToolResult<unknown>> {
50
+ input = prepareNotesArguments(input);
51
+ const help = queryHelp("notes", input, lifecycle.gptPromptMode());
52
+ if (help) return help;
53
+ assertActive();
54
+ const raw = queryArguments("notes", input);
55
+ if (!shared) {
56
+ let unavailable: unknown;
57
+ try {
58
+ const saved = await readSharedNotes(
59
+ ctx,
60
+ store,
61
+ raw,
62
+ signal,
63
+ lifecycle.bridge?.loadSavedSession,
64
+ );
65
+ if (saved) return noteResult(saved);
66
+ } catch (error) {
67
+ signal?.throwIfAborted();
68
+ if (!sharedNotesUnavailable(error)) throw error;
69
+ unavailable = error;
70
+ }
71
+ try {
72
+ const routed = await lifecycle.bridge?.route?.(
73
+ { namespace: "notes", params: raw },
74
+ callId,
75
+ ctx,
76
+ signal,
77
+ );
78
+ if (routed)
79
+ return {
80
+ ...routed,
81
+ ...noteResult(routed.structuredContent),
82
+ details: routed.details,
83
+ };
84
+ } catch (error) {
85
+ signal?.throwIfAborted();
86
+ if (!unavailable || !sharedNotesUnavailable(error)) throw error;
87
+ throw unavailable;
88
+ }
89
+ if (unavailable) throw unavailable;
90
+ }
91
+ const identity = contextAgentIdentity(ctx);
92
+ const storageAgent = contextStorageAgentName(identity);
93
+ const localRaw = { ...raw };
94
+ for (const key of ["path", "prefix", "path_prefix"]) {
95
+ const value = localRaw[key];
96
+ if (typeof value !== "string") continue;
97
+ const alias = contextAgentNames(identity).find(
98
+ (name) =>
99
+ value === `${name}/notes` || value.startsWith(`${name}/notes/`),
100
+ );
101
+ if (alias)
102
+ localRaw[key] = `${identity.agentName}${value.slice(alias.length)}`;
103
+ }
104
+ const params = queryArguments(
105
+ "notes",
106
+ normalizeNoteParams(localRaw, lifecycle.agent(ctx)),
107
+ );
108
+ if (signal?.aborted) throw new Error("Note operation cancelled");
109
+ const local = useNotes(
110
+ pi,
111
+ store,
112
+ params,
113
+ ctx,
114
+ lifecycle.agent(ctx),
115
+ lifecycle.windows.current?.currentWindowId ?? "",
116
+ lifecycle.runId,
117
+ shared,
118
+ );
119
+ if (
120
+ params["action"] === "write_file" ||
121
+ params["action"] === "append_to_file"
122
+ )
123
+ return {
124
+ ...noteResult(local),
125
+ details: {
126
+ ...(shared
127
+ ? { codexHistoryNotes: {}, notesCompactionRouted: true }
128
+ : {
129
+ notesCompaction: {
130
+ protocol: 1,
131
+ saved: true,
132
+ runId: lifecycle.runId,
133
+ },
134
+ }),
135
+ },
136
+ };
137
+ const notes = collectNotes(store, ctx.sessionManager.getBranch());
138
+ if (
139
+ params["action"] === "read_file" &&
140
+ notes.get(params["path"] as string)?.mode === "replace"
141
+ )
142
+ return noteResult(local);
143
+ const prefix = String(params["prefix"] ?? params["path_prefix"] ?? "");
144
+ const replacementsInScope =
145
+ params["action"] !== "read_file" &&
146
+ [...notes.values()].some(
147
+ (note) => note.mode === "replace" && note.path.startsWith(prefix),
148
+ );
149
+ const remoteParams = { ...params };
150
+ for (const field of ["path", "prefix", "path_prefix"])
151
+ if (typeof remoteParams[field] === "string")
152
+ remoteParams[field] =
153
+ `${storageAgent}/notes${remoteParams[field] ? `/${remoteParams[field]}` : ""}`;
154
+ return lookupNotes(
155
+ pi,
156
+ store,
157
+ lifecycle,
158
+ { namespace: "notes", params: remoteParams },
159
+ local,
160
+ callId,
161
+ ctx,
162
+ signal,
163
+ shared,
164
+ replacementsInScope,
165
+ );
166
+ }
167
+ async function history(
168
+ callId: string,
169
+ input: unknown,
170
+ signal: AbortSignal | undefined,
171
+ ctx: ExtensionContext,
172
+ ): Promise<AgentToolResult<unknown>> {
173
+ input = prepareHistoryArguments(input);
174
+ const help = queryHelp("history", input, lifecycle.gptPromptMode());
175
+ if (help) return help;
176
+ assertActive();
177
+ const params = queryArguments("history", input);
178
+ if (!shared) {
179
+ try {
180
+ const routed = await lifecycle.bridge?.route?.(
181
+ { namespace: "history", params },
182
+ callId,
183
+ ctx,
184
+ signal,
185
+ );
186
+ if (routed) return routed;
187
+ } catch (error) {
188
+ signal?.throwIfAborted();
189
+ if (
190
+ !sharedNotesUnavailable(error) &&
191
+ !(
192
+ error instanceof Error &&
193
+ error.message ===
194
+ "Counterpart history requires its live attached owner; native history is unchanged"
195
+ )
196
+ )
197
+ throw error;
198
+ const saved = await readSharedHistory(
199
+ ctx,
200
+ store,
201
+ search,
202
+ params,
203
+ signal,
204
+ lifecycle.bridge?.loadSavedSession,
205
+ );
206
+ if (saved) return result(saved);
207
+ throw error;
208
+ }
209
+ const saved = await readSharedHistory(
210
+ ctx,
211
+ store,
212
+ search,
213
+ params,
214
+ signal,
215
+ lifecycle.bridge?.loadSavedSession,
216
+ );
217
+ if (saved) return result(saved);
218
+ }
219
+ if (
220
+ params["agent_name"] &&
221
+ !contextAgentNames(contextAgentIdentity(ctx)).includes(
222
+ String(params["agent_name"]),
223
+ )
224
+ )
225
+ throw new Error(
226
+ "That agent's history is unavailable here. Omit agent_name to search this session, or request an accessible handoff from its owner.",
227
+ );
228
+ signal?.throwIfAborted();
229
+ return result(
230
+ await useHistory(
231
+ ctx.sessionManager.getBranch(),
232
+ params,
233
+ ctx.sessionManager.getSessionId(),
234
+ search,
235
+ ctx.sessionManager.getEntries(),
236
+ signal,
237
+ shared,
238
+ ),
239
+ );
240
+ }
241
+ return { notes, history };
242
+ }
@@ -0,0 +1,126 @@
1
+ import type { LookupQuery } from "./bridge.js";
2
+
3
+ const ACTIONS: Record<LookupQuery["namespace"], Record<string, string>> = {
4
+ notes: {
5
+ list_files_by_prefix: "list",
6
+ read_file: "read",
7
+ search_contents: "search",
8
+ append_to_file: "append",
9
+ write_file: "write",
10
+ },
11
+ history: { list_items: "list", read_item: "read", search_contents: "search" },
12
+ };
13
+ const HINTS = [
14
+ "limit",
15
+ "max_results",
16
+ "max_files",
17
+ "max_matches_per_file",
18
+ "file_order",
19
+ "file_order_by",
20
+ "recent_file_first",
21
+ "recent_first",
22
+ "limit_chars",
23
+ "max_chars_per_item",
24
+ ];
25
+ const PRESENTATION: Record<string, readonly string[]> = {
26
+ "notes:list": ["limit", "file_order", "file_order_by"],
27
+ "notes:search": ["limit", "max_matches_per_file", "recent_file_first"],
28
+ "notes:read": ["start_line", "stop_line"],
29
+ "history:list_windows": ["limit", "recent_first"],
30
+ "history:list": ["limit", "recent_first", "max_chars_per_item"],
31
+ "history:search": ["limit", "recent_first"],
32
+ "history:read": ["limit_chars", "offset_chars"],
33
+ };
34
+
35
+ function alias(params: Record<string, unknown>, from: string, to: string) {
36
+ if (!(from in params)) return;
37
+ if (to in params && params[to] !== params[from])
38
+ throw new Error(`Conflicting ${to} and ${from}; supply only ${to}`);
39
+ params[to] = params[from];
40
+ delete params[from];
41
+ }
42
+
43
+ /** Accept familiar spellings without adding competing names to discovery. */
44
+ export function normalizeQueryInput(
45
+ namespace: LookupQuery["namespace"],
46
+ input: unknown,
47
+ ): Record<string, unknown> {
48
+ if (input === undefined) return {};
49
+ if (typeof input === "string") {
50
+ try {
51
+ input = JSON.parse(input);
52
+ } catch {
53
+ throw new Error(
54
+ "Supply an action object or valid JSON object; use {} for help",
55
+ );
56
+ }
57
+ }
58
+ if (!input || typeof input !== "object" || Array.isArray(input))
59
+ throw new Error("Supply an action object; use {} for help");
60
+ const params = { ...input } as Record<string, unknown>;
61
+ if (
62
+ namespace === "history" &&
63
+ params["action"] === undefined &&
64
+ "query" in params
65
+ )
66
+ params["action"] = "search";
67
+ const action =
68
+ ACTIONS[namespace][String(params["action"])] ?? params["action"];
69
+ if (action !== undefined) params["action"] = action;
70
+ if (namespace === "notes") {
71
+ alias(params, "address", "path");
72
+ if (action === "write" || action === "append") {
73
+ alias(params, "content", "text");
74
+ alias(params, "body", "text");
75
+ }
76
+ if (action === "list" || action === "search") {
77
+ alias(params, "prefix", "path");
78
+ alias(params, "path_prefix", "path");
79
+ alias(params, "max_results", "limit");
80
+ alias(params, "max_files", "limit");
81
+ if (action === "search")
82
+ alias(params, "recent_first", "recent_file_first");
83
+ }
84
+ } else if (["list", "search", "list_windows"].includes(String(action))) {
85
+ alias(params, "max_results", "limit");
86
+ }
87
+ const used = PRESENTATION[`${namespace}:${String(action)}`] ?? [];
88
+ if (namespace === "history" && action !== "read")
89
+ delete params["offset_chars"];
90
+ for (const hint of HINTS) if (!used.includes(hint)) delete params[hint];
91
+ return params;
92
+ }
93
+
94
+ /** Keep persisted sharing requests and backend endpoint names unchanged. */
95
+ export function internalQueryArguments(
96
+ namespace: LookupQuery["namespace"],
97
+ input: Record<string, unknown>,
98
+ ) {
99
+ const params = { ...input };
100
+ const action = params["action"];
101
+ params["action"] =
102
+ Object.entries(ACTIONS[namespace]).find(
103
+ ([, value]) => value === action,
104
+ )?.[0] ?? action;
105
+ if (namespace === "notes") {
106
+ if (action === "list" || action === "search") {
107
+ alias(params, "path", action === "list" ? "prefix" : "path_prefix");
108
+ alias(params, "limit", action === "list" ? "max_results" : "max_files");
109
+ }
110
+ }
111
+ return params;
112
+ }
113
+
114
+ export function isNoteWrite(input: unknown): boolean {
115
+ try {
116
+ if (typeof input === "string") input = JSON.parse(input);
117
+ if (!input || typeof input !== "object" || !("action" in input))
118
+ return false;
119
+ // Failed write attempts still invalidate freshness; do not validate their fields here.
120
+ return ["write", "append", "write_file", "append_to_file"].includes(
121
+ String(input.action),
122
+ );
123
+ } catch {
124
+ return false;
125
+ }
126
+ }