@howaboua/pi-agent-comms 0.0.1 → 0.0.3

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 (47) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/viewer/web/app.js +6 -6
  4. package/dist/viewer/web/render.js +2 -2
  5. package/docs/BOARD.md +1 -1
  6. package/docs/NOTES.md +19 -2
  7. package/package.json +75 -74
  8. package/src/board/activity.ts +1 -0
  9. package/src/board/briefing.ts +2 -2
  10. package/src/board/delivery.ts +8 -6
  11. package/src/board/runtime/activation.ts +2 -3
  12. package/src/board/runtime/catchup.ts +1 -1
  13. package/src/board/settings/panel.ts +11 -8
  14. package/src/board/viewer/web/app.js +6 -6
  15. package/src/board/viewer/web/render.js +2 -2
  16. package/src/guidance.ts +14 -14
  17. package/src/notes/AGENTS.md +3 -3
  18. package/src/notes/activation.ts +1 -0
  19. package/src/notes/bridge.ts +4 -2
  20. package/src/notes/context-owner.ts +5 -5
  21. package/src/notes/feature.ts +67 -1
  22. package/src/notes/fresh-notes.ts +46 -5
  23. package/src/notes/history-search-pruning.mjs +110 -76
  24. package/src/notes/history-search-worker.mjs +1 -1
  25. package/src/notes/history-windows.ts +1 -1
  26. package/src/notes/index.ts +9 -3
  27. package/src/notes/integrations.ts +83 -45
  28. package/src/notes/lifecycle.ts +11 -2
  29. package/src/notes/model-roles.ts +2 -2
  30. package/src/notes/notes-lookup.ts +1 -1
  31. package/src/notes/rollover.ts +34 -5
  32. package/src/notes/session-pruning-cleanup.mjs +164 -0
  33. package/src/notes/session-pruning-exit.mjs +312 -0
  34. package/src/notes/session-pruning-screen.ts +1 -1
  35. package/src/notes/session-pruning-sparse.mjs +133 -0
  36. package/src/notes/session-pruning-state.mjs +123 -0
  37. package/src/notes/session-pruning-transaction.ts +1 -0
  38. package/src/notes/session-pruning.ts +34 -1
  39. package/src/notes/settings-controls.ts +23 -17
  40. package/src/notes/settings-screen.ts +2 -6
  41. package/src/notes/settings.ts +13 -6
  42. package/src/notes/shared-notes.ts +52 -30
  43. package/src/notes/tool-contracts.ts +24 -5
  44. package/src/notes/tools.ts +51 -29
  45. package/src/notes/tree-checkpoint.ts +12 -13
  46. package/src/notes/window-message.ts +6 -18
  47. package/src/notes/windows.ts +10 -11
@@ -54,8 +54,8 @@ export function createNotesContextOwner(
54
54
  | undefined;
55
55
  return Boolean(
56
56
  data?.version === 2 &&
57
- Array.isArray(data.agents) &&
58
- data.agents.length === 0,
57
+ Array.isArray(data.agents) &&
58
+ data.agents.length === 0,
59
59
  );
60
60
  }
61
61
  // Foreign plain custom entries may be startup metadata. Notes state
@@ -87,9 +87,9 @@ export function createNotesContextOwner(
87
87
  const details = windowDetails(entry);
88
88
  return Boolean(
89
89
  details &&
90
- details.identity.windowNumber === 0 &&
91
- !details.trim &&
92
- (details.kind === "window" || details.kind === "identity"),
90
+ details.identity.windowNumber === 0 &&
91
+ !details.trim &&
92
+ (details.kind === "window" || details.kind === "identity"),
93
93
  );
94
94
  }),
95
95
  snapshotNotes: exportNotesSnapshot,
@@ -7,6 +7,11 @@ import type {
7
7
  import type { CommsFeature } from "../guidance.js";
8
8
  import type { OpenSettings } from "../settings-navigation.js";
9
9
  import type { NotesRuntime } from "./index.js";
10
+ import {
11
+ admitSessionCleanup,
12
+ previousCleanupFailure,
13
+ } from "./session-pruning-exit.mjs";
14
+ import { cleanupStatus } from "./session-pruning-state.mjs";
10
15
  import {
11
16
  legacyNotesConfigured,
12
17
  loadNotesSettings,
@@ -53,6 +58,43 @@ export function createNotesFeature(
53
58
  let store: NotesStore | undefined;
54
59
  let storage: Promise<NotesStore> | undefined;
55
60
  let closed = false;
61
+ let staleOpening = false;
62
+ let releaseCleanupOwner: (() => void) | undefined;
63
+ const admit = async (ctx: ExtensionContext) => {
64
+ if (releaseCleanupOwner) return !staleOpening;
65
+ let reason: string | undefined;
66
+ try {
67
+ const claim = await admitSessionCleanup(
68
+ ctx.sessionManager.getSessionFile(),
69
+ ctx.sessionManager.getSessionId(),
70
+ ctx.sessionManager.getHeader(),
71
+ );
72
+ releaseCleanupOwner = claim?.release;
73
+ if (claim?.stale)
74
+ reason =
75
+ "This session was cleaned while Pi was opening it. Restart Pi to load its saved tree safely.";
76
+ } catch (error) {
77
+ reason = `Pi could not safely open this session: ${String(error)}. Resolve the problem and restart Pi.`;
78
+ }
79
+ if (!reason) return true;
80
+ staleOpening = true;
81
+ console.error(reason);
82
+ ctx.ui.notify(reason, "error");
83
+ if (ctx.mode === "rpc") {
84
+ // RPC honours startup shutdown after attaching input. Returning lets it
85
+ // reach that check before accepting normal commands.
86
+ ctx.shutdown();
87
+ return false;
88
+ }
89
+ if (ctx.mode === "tui") ctx.shutdown();
90
+ else {
91
+ // Released print/json mode installs graceful SIGTERM handling before
92
+ // session_start, but does not bind the documented ctx.shutdown action.
93
+ process.kill(process.pid, "SIGTERM");
94
+ }
95
+ // Do not finish binding or start an initial prompt/tree while exiting.
96
+ await new Promise<never>(() => {});
97
+ };
56
98
  const ensureStore = () =>
57
99
  (storage ??= (async () => {
58
100
  const { NotesStore } = await import("./store.js");
@@ -110,6 +152,22 @@ export function createNotesFeature(
110
152
  await open(ctx);
111
153
  });
112
154
  pi.on("session_start", async (_event, ctx) => {
155
+ if (!(await admit(ctx))) return;
156
+ const file = ctx.sessionManager.getSessionFile();
157
+ if (file) {
158
+ try {
159
+ const error = previousCleanupFailure(
160
+ cleanupStatus(file, dirname(notesSettingsPath())),
161
+ ctx.sessionManager.getSessionId(),
162
+ );
163
+ if (error) ctx.ui.notify(error, "warning");
164
+ } catch (error) {
165
+ ctx.ui.notify(
166
+ `Previous session cleanup status could not be read: ${String(error)}. Check Notes storage permissions and retry.`,
167
+ "warning",
168
+ );
169
+ }
170
+ }
113
171
  try {
114
172
  settings = loadNotesSettings(ctx);
115
173
  writeSettings(notesSettingsPath(), settings);
@@ -126,12 +184,20 @@ export function createNotesFeature(
126
184
  );
127
185
  }
128
186
  });
187
+ pi.on("agent_settled", async (_event, ctx) => {
188
+ // A brand-new session has no JSONL file until its first persisted turn.
189
+ await admit(ctx);
190
+ });
129
191
  pi.on("model_select", async (_event, ctx) => {
130
192
  if (!runtime && settings && modelIsActive(settings, ctx.model))
131
193
  await ensure(ctx);
132
194
  });
133
- pi.on("session_shutdown", () => {
195
+ pi.on("session_shutdown", (event) => {
134
196
  closed = true;
197
+ if (event.reason !== "quit") {
198
+ releaseCleanupOwner?.();
199
+ releaseCleanupOwner = undefined;
200
+ }
135
201
  store?.close();
136
202
  });
137
203
  pi.registerCommand("notes", {
@@ -58,17 +58,58 @@ export function hasPrecedingNoteWrite(
58
58
  windowId: string | undefined,
59
59
  runId: string,
60
60
  requestCallId: string,
61
+ parentCallId?: string,
61
62
  ): boolean {
62
63
  const { messages, receipts, outcomes } = noteEvidence(
63
64
  branch,
64
65
  windowId,
65
66
  runId,
66
67
  );
68
+ if (parentCallId) {
69
+ // The running cell has no result yet. Only Notes-owned completed write
70
+ // outcomes under its exec/wait scopes can prove a same-cell save.
71
+ const issuingCall = messages.findLastIndex(
72
+ (message) =>
73
+ message.role === "assistant" &&
74
+ message.content.some(
75
+ (block) => block.type === "toolCall" && block.id === parentCallId,
76
+ ),
77
+ );
78
+ if (issuingCall < 0) return false;
79
+ const parents = new Set([parentCallId]);
80
+ const initial = messages.find(
81
+ (message) =>
82
+ message.role === "toolResult" && message.toolCallId === parentCallId,
83
+ );
84
+ const cell = initial?.role === "toolResult" ? codeCell(initial) : undefined;
85
+ if (cell) {
86
+ for (const message of messages.slice(issuingCall)) {
87
+ if (message.role !== "assistant") continue;
88
+ for (const call of message.content) {
89
+ if (
90
+ call.type === "toolCall" &&
91
+ call.name === "wait" &&
92
+ call.arguments["cell_id"] === cell.id
93
+ )
94
+ parents.add(call.id);
95
+ }
96
+ }
97
+ }
98
+ const local = outcomes.filter(
99
+ (item) => parents.has(item.parentCallId) && item.origin !== "routed",
100
+ );
101
+ if (local.length)
102
+ return (
103
+ receipts.length > 0 &&
104
+ local.every((item) => !item.pending && item.saved)
105
+ );
106
+ }
107
+ const issuingCallId = parentCallId ?? requestCallId;
67
108
  const request = messages.findLastIndex(
68
109
  (message) =>
69
110
  message.role === "assistant" &&
70
111
  message.content.some(
71
- (block) => block.type === "toolCall" && block.id === requestCallId,
112
+ (block) => block.type === "toolCall" && block.id === issuingCallId,
72
113
  ),
73
114
  );
74
115
  if (request < 0) return false;
@@ -83,7 +124,7 @@ export function hasPrecedingNoteWrite(
83
124
  const current = groups.pop() ?? [];
84
125
  const predecessors = current.slice(
85
126
  0,
86
- current.findIndex((call) => call.id === requestCallId),
127
+ current.findIndex((call) => call.id === issuingCallId),
87
128
  );
88
129
  const calls = predecessors.length ? predecessors : (groups.at(-1) ?? []);
89
130
  const allResults = messages.flatMap((message) =>
@@ -140,9 +181,9 @@ function noteEvidence(
140
181
  .filter((receipt): receipt is NoteReceipt =>
141
182
  Boolean(
142
183
  receipt &&
143
- receipt.origin !== "routed" &&
144
- receipt.windowId === windowId &&
145
- (!runId || receipt.runId === runId),
184
+ receipt.origin !== "routed" &&
185
+ receipt.windowId === windowId &&
186
+ (!runId || receipt.runId === runId),
146
187
  ),
147
188
  );
148
189
  const messages = buildSessionProjection(run).messages;
@@ -1,6 +1,7 @@
1
1
  import { open } from "node:fs/promises";
2
+ import { StringDecoder } from "node:string_decoder";
2
3
 
3
- /** @typedef {{file:string; sessionId:string; generation:string; excluded:Set<string>}} PrunedHistory */
4
+ /** @typedef {{file:string; sessionId:string; generation:string; size:number; surviving:Set<string>; excluded:Set<string>}} PrunedHistory */
4
5
 
5
6
  /** The live SessionManager still contains old text until restart. Read the committed
6
7
  * source so later indexing, settings toggles and /reload cannot resurrect its terms.
@@ -8,11 +9,11 @@ import { open } from "node:fs/promises";
8
9
  export function createHistoryPruning() {
9
10
  /** @type {PrunedHistory | undefined} */
10
11
  let cached;
11
- const empty = new Set();
12
+ const empty = () => false;
12
13
  /** @param {import("./sqlite.mjs").Database} db
13
14
  * @param {string} sessionId
14
15
  * @param {string | undefined} file
15
- * @returns {Promise<ReadonlySet<string>>}
16
+ * @returns {Promise<(id:string) => boolean>}
16
17
  */
17
18
  return async (db, sessionId, file) => {
18
19
  if (!file) return empty;
@@ -25,92 +26,125 @@ export function createHistoryPruning() {
25
26
  return empty;
26
27
  throw error;
27
28
  }
28
- let stream;
29
29
  try {
30
30
  const { size } = await input.stat();
31
31
  if (!size) return empty;
32
- stream = input.createReadStream({
33
- start: 0,
34
- end: size - 1,
35
- autoClose: false,
36
- encoding: "utf8",
37
- });
38
- /** @type {PrunedHistory | undefined} */
39
- let source;
40
- let pending = "";
41
- for await (const chunk of stream) {
42
- pending += chunk;
43
- let start = 0;
44
- let end;
45
- while ((end = pending.indexOf("\n", start)) >= 0) {
46
- const entry = JSON.parse(pending.slice(start, end));
47
- start = end + 1;
48
- if (!source) {
49
- if (entry.type !== "session" || entry.id !== sessionId)
50
- throw new Error("History source identity changed");
51
- const marker = entry.notesPruning;
52
- if (marker === undefined) return empty;
53
- if (
54
- marker?.version !== 1 ||
55
- marker.sessionId !== sessionId ||
56
- typeof marker.generation !== "string"
57
- )
58
- throw new Error("Invalid history pruning marker");
59
- if (
60
- cached?.file === file &&
61
- cached.sessionId === sessionId &&
62
- cached.generation === marker.generation
63
- )
64
- return cached.excluded;
65
- source = {
66
- file,
67
- sessionId,
68
- generation: marker.generation,
69
- excluded: new Set(),
70
- };
71
- continue;
32
+ let header;
33
+ for await (const entry of records(input, 0, size)) {
34
+ header = entry;
35
+ break;
36
+ }
37
+ if (header?.type !== "session" || header.id !== sessionId)
38
+ throw new Error("History source identity changed");
39
+ const marker = header.notesPruning;
40
+ if (marker === undefined) return empty;
41
+ if (
42
+ marker?.version !== 1 ||
43
+ marker.sessionId !== sessionId ||
44
+ typeof marker.generation !== "string"
45
+ )
46
+ throw new Error("Invalid history pruning marker");
47
+ const previous =
48
+ cached?.file === file &&
49
+ cached.sessionId === sessionId &&
50
+ cached.generation === marker.generation &&
51
+ cached.size <= size
52
+ ? cached
53
+ : undefined;
54
+ const incremental = previous !== undefined;
55
+ if (previous?.size === size) return exclusion(previous);
56
+ /** @type {PrunedHistory} */
57
+ const source = previous ?? {
58
+ file,
59
+ sessionId,
60
+ generation: marker.generation,
61
+ size: 0,
62
+ surviving: new Set(),
63
+ excluded: new Set(),
64
+ };
65
+ // A failed suffix scan invalidates mutated cache sets. Ordinary appends
66
+ // scan only their suffix, not the full session or every indexed document.
67
+ cached = undefined;
68
+ for await (const entry of records(input, source.size, size)) {
69
+ if (!incremental && entry.type === "session") continue;
70
+ if (typeof entry.id !== "string" || source.surviving.has(entry.id))
71
+ throw new Error("Invalid history source entry identity");
72
+ source.surviving.add(entry.id);
73
+ const message = entry.type === "message" ? entry.message : undefined;
74
+ if (
75
+ (entry.type === "custom" &&
76
+ entry.customType === "notes-compaction:pruned:v1") ||
77
+ (["user", "assistant"].includes(message?.role) &&
78
+ !visibleText(message.content))
79
+ )
80
+ source.excluded.add(entry.id);
81
+ }
82
+ source.size = size;
83
+ const excluded = exclusion(source);
84
+ if (!incremental) {
85
+ const removeTerms = db.prepare(
86
+ "DELETE FROM history_terms WHERE rowid = ?",
87
+ );
88
+ const removeDocument = db.prepare(
89
+ "DELETE FROM history_documents WHERE id = ?",
90
+ );
91
+ /** @type {import("./sqlite.mjs").Statement<[string], {id:number; item_id:string}>} */
92
+ const documents = db.prepare(
93
+ "SELECT id, item_id FROM history_documents WHERE session_id = ?",
94
+ );
95
+ db.transaction(() => {
96
+ for (const row of documents.all(sessionId)) {
97
+ if (!excluded(row.item_id)) continue;
98
+ removeTerms.run(row.id);
99
+ removeDocument.run(row.id);
72
100
  }
73
- const message = entry.type === "message" ? entry.message : undefined;
74
- if (
75
- (entry.type === "custom" &&
76
- entry.customType === "notes-compaction:pruned:v1") ||
77
- (["user", "assistant"].includes(message?.role) &&
78
- !visibleText(message.content))
79
- )
80
- source.excluded.add(entry.id);
81
- }
82
- pending = pending.slice(start);
101
+ }).immediate();
83
102
  }
84
- // Only complete lines from the opened inode count. A concurrent append's
85
- // incomplete suffix is new history, never an old pruned conversation.
86
- if (!source) throw new Error("History source header is missing");
87
- const excluded = source.excluded;
88
- const removeTerms = db.prepare(
89
- "DELETE FROM history_terms WHERE rowid = ?",
90
- );
91
- const removeDocument = db.prepare(
92
- "DELETE FROM history_documents WHERE id = ?",
93
- );
94
- /** @type {import("./sqlite.mjs").Statement<[string], {id:number; item_id:string}>} */
95
- const documents = db.prepare(
96
- "SELECT id, item_id FROM history_documents WHERE session_id = ?",
97
- );
98
- db.transaction(() => {
99
- for (const row of documents.all(sessionId)) {
100
- if (!excluded.has(row.item_id)) continue;
101
- removeTerms.run(row.id);
102
- removeDocument.run(row.id);
103
- }
104
- }).immediate();
105
103
  cached = source;
106
104
  return excluded;
107
105
  } finally {
108
- stream?.destroy();
109
106
  await input.close();
110
107
  }
111
108
  };
112
109
  }
113
110
 
111
+ /** @param {import("node:fs/promises").FileHandle} input @param {number} start @param {number} size */
112
+ async function* records(input, start, size) {
113
+ const buffer = Buffer.alloc(64 * 1024);
114
+ const decoder = new StringDecoder("utf8");
115
+ let pending = "";
116
+ for (let position = start; position < size;) {
117
+ const { bytesRead } = await input.read(
118
+ buffer,
119
+ 0,
120
+ Math.min(buffer.length, size - position),
121
+ position,
122
+ );
123
+ if (!bytesRead)
124
+ throw new Error("History source changed during reconciliation");
125
+ position += bytesRead;
126
+ pending += decoder.write(buffer.subarray(0, bytesRead));
127
+ let offset = 0;
128
+ let end;
129
+ while ((end = pending.indexOf("\n", offset)) >= 0) {
130
+ yield JSON.parse(pending.slice(offset, end));
131
+ offset = end + 1;
132
+ }
133
+ pending = pending.slice(offset);
134
+ }
135
+ pending += decoder.end();
136
+ if (pending.length)
137
+ throw new Error(
138
+ "History source has an incomplete record; retry after the turn completes",
139
+ );
140
+ }
141
+
142
+ /** @param {PrunedHistory} source */
143
+ function exclusion(source) {
144
+ /** @param {string} id */
145
+ return (id) => !source.surviving.has(id) || source.excluded.has(id);
146
+ }
147
+
114
148
  /** @param {unknown} content */
115
149
  function visibleText(content) {
116
150
  return typeof content === "string"
@@ -97,7 +97,7 @@ async function index(request) {
97
97
  }
98
98
  }
99
99
  for (const item of request.items) {
100
- if (excluded.has(item.item_id)) continue;
100
+ if (excluded(item.item_id)) continue;
101
101
  const fingerprint = createHash("sha256")
102
102
  .update(item.content)
103
103
  .digest("hex");
@@ -36,7 +36,7 @@ function customHistoryRole(
36
36
  "codex-toolkit-update",
37
37
  "codex-notebook-status",
38
38
  "codex-context-briefing",
39
- ].includes(entry.customType)
39
+ ].includes(entry.customType)
40
40
  ? details
41
41
  : undefined;
42
42
  return metadata &&
@@ -32,13 +32,17 @@ export async function createNotesRuntime(pi: ExtensionAPI, store: NotesStore) {
32
32
  lifecycle.windows.projectBranch(entries),
33
33
  );
34
34
  let refreshNested = () => {};
35
+ let refreshTools = () => {};
35
36
  const activation = createNotesActivation(
36
37
  pi,
37
38
  store,
38
39
  search,
39
40
  lifecycle,
40
41
  settingsPath,
41
- () => refreshNested(),
42
+ () => {
43
+ refreshTools();
44
+ refreshNested();
45
+ },
42
46
  );
43
47
  const stopAdmission = pi.events.on(
44
48
  "pi-notes-compaction:custom-turn-admission:v1",
@@ -59,12 +63,14 @@ export async function createNotesRuntime(pi: ExtensionAPI, store: NotesStore) {
59
63
  },
60
64
  );
61
65
  const roles = createModelRoles(pi, activation, lifecycle);
62
- const tools = createTools(pi, store, lifecycle, search, roles);
66
+ const toolRegistration = createTools(pi, store, lifecycle, search, roles);
67
+ const { tools } = toolRegistration;
68
+ refreshTools = toolRegistration.refresh;
63
69
  refreshNested = await registerNotesToolIntegrations(
64
70
  pi,
65
71
  lifecycle,
66
72
  activation,
67
- tools,
73
+ toolRegistration,
68
74
  );
69
75
  for (const tool of tools) pi.registerTool(tool);
70
76
  const owner = createNotesContextOwner(pi, store, lifecycle, search);
@@ -22,12 +22,12 @@ export async function registerNotesToolIntegrations(
22
22
  pi: ExtensionAPI,
23
23
  lifecycle: NotesLifecycle,
24
24
  activation: NotesActivation,
25
- tools: ReturnType<typeof createTools>,
25
+ registration: ReturnType<typeof createTools>,
26
26
  ) {
27
+ const { tools, requestContext } = registration;
27
28
  try {
28
- const { registerGptPromptMode } = await import(
29
- "@howaboua/pi-codex-conversion/prompt-mode"
30
- );
29
+ const { registerGptPromptMode } =
30
+ await import("@howaboua/pi-codex-conversion/prompt-mode");
31
31
  const registration = registerGptPromptMode(pi, (active, ctx) => {
32
32
  if (ctx) activation.refreshActivation(ctx);
33
33
  const tool = tools.find((tool) => tool.name === "new_context");
@@ -59,42 +59,82 @@ export async function registerNotesToolIntegrations(
59
59
  try {
60
60
  const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
61
61
  await import("@howaboua/pi-codex-conversion/code-mode");
62
+ const rollover: ReturnType<typeof adaptToolForCodeMode> = {
63
+ name: "new_context",
64
+ topLevelName: "new_context",
65
+ usage: "tools.new_context(args)",
66
+ description: "",
67
+ kind: "function",
68
+ inputOptional: true,
69
+ deferLoading: true,
70
+ discoverWhenDeferred: false,
71
+ propagateTermination: true,
72
+ executionMode: "sequential",
73
+ inputSchema: tools.find((tool) => tool.name === "new_context")!
74
+ .parameters,
75
+ async invoke(input, context, signal) {
76
+ if (
77
+ !context.extensionContext ||
78
+ !context.originalExecCallId ||
79
+ !context.toolCallId
80
+ )
81
+ throw new Error(
82
+ "Context rollover is unavailable in this call. Save notes and call new_context directly.",
83
+ );
84
+ const output = await requestContext(
85
+ context.toolCallId,
86
+ input,
87
+ signal,
88
+ context.extensionContext,
89
+ context.originalExecCallId,
90
+ );
91
+ context.captureResult?.(output);
92
+ const part = output.content[0];
93
+ return part?.type === "text" ? JSON.parse(part.text) : undefined;
94
+ },
95
+ };
62
96
  const registration = registerCodeModeExtensionTools(
63
97
  pi,
64
- () =>
65
- tools
66
- .filter((tool) => tool.name === "notes" || tool.name === "history")
67
- .map((tool) => ({
68
- ...adaptToolForCodeMode(tool, {
69
- discovery: "help",
70
- usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
71
- deferLoading: tool.name !== "notes",
72
- opaqueResult: tool.name === "notes",
73
- ...(tool.name === "history"
74
- ? { resultValue: historyResultValue }
75
- : {}),
76
- }),
77
- // Code checks inputs before Pi can normalise these aliases.
78
- ...(tool.name === "notes"
79
- ? {
80
- inputSchema: {
81
- ...NOTES_SCHEMA,
82
- properties: {
83
- ...noteProperties,
84
- content: noteProperties["text"],
85
- end_line: noteProperties["stop_line"],
98
+ () => {
99
+ rollover.inputSchema = tools.find(
100
+ (tool) => tool.name === "new_context",
101
+ )!.parameters;
102
+ return [
103
+ rollover,
104
+ ...tools
105
+ .filter((tool) => tool.name === "notes" || tool.name === "history")
106
+ .map((tool) => ({
107
+ ...adaptToolForCodeMode(tool, {
108
+ discovery: "help",
109
+ usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
110
+ deferLoading: tool.name !== "notes",
111
+ opaqueResult: tool.name === "notes",
112
+ ...(tool.name === "history"
113
+ ? { resultValue: historyResultValue }
114
+ : {}),
115
+ }),
116
+ // Code checks inputs before Pi can normalise these aliases.
117
+ ...(tool.name === "notes"
118
+ ? {
119
+ inputSchema: {
120
+ ...NOTES_SCHEMA,
121
+ properties: {
122
+ ...noteProperties,
123
+ content: noteProperties["text"],
124
+ end_line: noteProperties["stop_line"],
125
+ },
86
126
  },
87
- },
88
- }
89
- : {}),
90
- })),
127
+ }
128
+ : {}),
129
+ })),
130
+ ];
131
+ },
91
132
  { isActive: () => lifecycle.active },
92
133
  );
93
134
  refreshNested = registration.refresh;
94
135
  pi.on("session_shutdown", () => registration.unregister());
95
- const { withCodexDeveloperMessageDetails } = await import(
96
- "@howaboua/pi-codex-conversion/developer-messages"
97
- );
136
+ const { withCodexDeveloperMessageDetails } =
137
+ await import("@howaboua/pi-codex-conversion/developer-messages");
98
138
  lifecycle.prepareReminder = withCodexDeveloperMessageDetails;
99
139
  } catch (error) {
100
140
  if (!optionalPccMissing(error)) throw error;
@@ -138,19 +178,17 @@ export async function registerNotesCompactionIntegration(
138
178
  } = await import("@howaboua/pi-codex-conversion/compaction");
139
179
  prepareProviderWindow = (ctx) => prepareContextWindow(pi, ctx);
140
180
  const registration = registerCompactionPreparation(pi, prepareCompaction);
141
- const stopProjection = registerContextBranchProjection(
142
- pi,
143
- (entries, ctx) =>
144
- activation.available
145
- ? projectTreeHandoffBranch(
146
- lifecycle.windows.projectBranch(
147
- projectTreeCheckpointBranch(
148
- entries,
149
- ctx.sessionManager.getEntries(),
150
- ),
181
+ const stopProjection = registerContextBranchProjection(pi, (entries, ctx) =>
182
+ activation.available
183
+ ? projectTreeHandoffBranch(
184
+ lifecycle.windows.projectBranch(
185
+ projectTreeCheckpointBranch(
186
+ entries,
187
+ ctx.sessionManager.getEntries(),
151
188
  ),
152
- )
153
- : entries,
189
+ ),
190
+ )
191
+ : entries,
154
192
  );
155
193
  pi.on("session_shutdown", stopProjection);
156
194
  pi.on("session_before_compact", registration.prepare);