@howaboua/pi-notes-compaction 0.0.13 → 0.0.14

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.
@@ -7,15 +7,14 @@ import { NOTE_RECEIPT, type NoteReceipt, noteReceipt } from "./notes.js";
7
7
  import { isNoteWrite } from "./query-input.js";
8
8
 
9
9
  export const NESTED_NOTE_OUTCOME = "notes-compaction:nested-write:v1";
10
- export interface NestedNoteOutcome {
10
+ export type NestedNoteOutcome = {
11
11
  protocol: 1;
12
12
  runId: string;
13
13
  windowId: string;
14
14
  callId: string;
15
15
  parentCallId: string;
16
- saved: boolean;
17
16
  origin?: "routed";
18
- }
17
+ } & ({ pending: true; saved: false } | { pending: false; saved: boolean });
19
18
  export const NOTES_RUN_ENTRY = "notes-compaction:run:v1";
20
19
 
21
20
  /** A receipt proves persistence. Current-run tool outcomes prove the checkpoint actually completed. */
@@ -53,7 +52,7 @@ export function hasFreshNotes(
53
52
  );
54
53
  }
55
54
 
56
- /** The current request is already in history; only its preceding completed invocation qualifies. */
55
+ /** Only the preceding tool-call group (or completed same-group predecessors) qualifies. */
57
56
  export function hasPrecedingNoteWrite(
58
57
  branch: readonly SessionEntry[],
59
58
  windowId: string | undefined,
@@ -73,33 +72,34 @@ export function hasPrecedingNoteWrite(
73
72
  ),
74
73
  );
75
74
  if (request < 0) return false;
76
- const calls = messages
75
+ const groups = messages
77
76
  .slice(0, request + 1)
78
77
  .flatMap((message) =>
79
78
  message.role === "assistant"
80
- ? message.content.filter((block) => block.type === "toolCall")
79
+ ? [message.content.filter((block) => block.type === "toolCall")]
81
80
  : [],
82
- );
83
- const call =
84
- calls[calls.findLastIndex((call) => call.id === requestCallId) - 1];
85
- if (!call) return false;
86
- const previous = messages.findLast(
87
- (message) =>
88
- message.role === "toolResult" &&
89
- message.toolCallId === call.id &&
90
- message.toolName === call.name,
81
+ )
82
+ .filter((calls) => calls.length > 0);
83
+ const current = groups.pop() ?? [];
84
+ const predecessors = current.slice(
85
+ 0,
86
+ current.findIndex((call) => call.id === requestCallId),
87
+ );
88
+ const calls = predecessors.length ? predecessors : (groups.at(-1) ?? []);
89
+ const allResults = messages.flatMap((message) =>
90
+ message.role === "toolResult" ? [message] : [],
91
+ );
92
+ const results = allResults.filter((result) =>
93
+ calls.some(
94
+ (call) => call.id === result.toolCallId && call.name === result.toolName,
95
+ ),
91
96
  );
92
97
  return (
93
- previous?.role === "toolResult" &&
94
- completedWrites(
95
- [call],
96
- [previous],
97
- receipts,
98
- outcomes,
99
- messages.flatMap((message) =>
100
- message.role === "toolResult" ? [message] : [],
101
- ),
102
- )
98
+ calls.length > 0 &&
99
+ calls.every((call) =>
100
+ results.some((result) => result.toolCallId === call.id),
101
+ ) &&
102
+ completedWrites(calls, results, receipts, outcomes, allResults)
103
103
  );
104
104
  }
105
105
 
@@ -156,11 +156,16 @@ function noteEvidence(
156
156
  typeof value.callId === "string" &&
157
157
  typeof value.parentCallId === "string" &&
158
158
  (value.origin === undefined || value.origin === "routed") &&
159
+ typeof value.pending === "boolean" &&
160
+ (!value.pending || value.saved === false) &&
159
161
  typeof value.saved === "boolean"
160
162
  ? [value as NestedNoteOutcome]
161
163
  : [];
162
164
  });
163
- return { messages, receipts, outcomes };
165
+ // Starts remain failed proof until their matching completion replaces them.
166
+ const latest = new Map<string, NestedNoteOutcome>();
167
+ for (const outcome of outcomes) latest.set(outcome.callId, outcome);
168
+ return { messages, receipts, outcomes: [...latest.values()] };
164
169
  }
165
170
 
166
171
  function completedWrites(
@@ -268,16 +273,22 @@ function completedWrites(
268
273
  : noteCalls.filter(
269
274
  (call) => !outcomes.some((item) => item.callId === call.id),
270
275
  );
276
+ const untrackedWrites = uncovered.filter(
277
+ (call) => !call.arguments || isNoteWrite(call.arguments),
278
+ );
279
+ // Pi also marks argument omission as incomplete. Notes' start/end ledger
280
+ // proves write completion even when that bounded record loses arguments or calls.
281
+ const tracked =
282
+ completed.length > 0 && completed.every((item) => item.pending === false);
271
283
  if (
272
- uncovered.some(
273
- (call) =>
274
- call.status !== "ok" &&
275
- (!call.arguments || isNoteWrite(call.arguments)),
276
- ) ||
277
- (uncovered.length && !nested?.complete)
284
+ untrackedWrites.some((call) => call.status !== "ok") ||
285
+ (nested?.complete === false &&
286
+ (noteCalls.length > 0 || completed.length > 0) &&
287
+ !(legacy === true && !completed.length) &&
288
+ (!tracked || untrackedWrites.length > 0))
278
289
  )
279
290
  return false;
280
- const nestedWrites = uncovered.filter((call) =>
291
+ const nestedWrites = untrackedWrites.filter((call) =>
281
292
  isNoteWrite(call.arguments),
282
293
  );
283
294
  if (
@@ -8,7 +8,7 @@ import type {
8
8
  } from "./history-search-protocol.js";
9
9
 
10
10
  const UNAVAILABLE =
11
- "Ranked history search is unavailable. list and read still work. Ask the user to check local storage or turn off Ranked history search in /notes.";
11
+ "History request failed. Use list/read or ask user to check /notes.";
12
12
 
13
13
  /** Worker owns derived storage; JSONL and the caller own content and scope. */
14
14
  export class HistorySearch {
@@ -91,13 +91,23 @@ export async function historyWindows(
91
91
  });
92
92
  let windowId = `session:${sessionId}`;
93
93
  let activeStart = 0;
94
+ let hasWindowBoundary = false;
94
95
  const positions = new Map(
95
96
  entries.map((entry, position) => [entry.id, position]),
96
97
  );
97
98
  for (const [position, entry] of entries.entries()) {
98
99
  const boundary = windowDetails(entry);
99
- if (boundary?.kind === "window" && boundary.trim)
100
- activeStart = position + 1;
100
+ if (boundary?.kind === "window") {
101
+ // Pi persists the initial kickoff before the returned window message.
102
+ if (
103
+ !hasWindowBoundary &&
104
+ !boundary.trim &&
105
+ boundary.identity.windowNumber === 0
106
+ )
107
+ windowId = boundary.identity.currentWindowId;
108
+ hasWindowBoundary = true;
109
+ if (boundary.trim) activeStart = position + 1;
110
+ }
101
111
  if (entry.type === "compaction") {
102
112
  const kept = positions.get(entry.firstKeptEntryId);
103
113
  if (kept !== undefined && kept <= position)
package/src/history.ts CHANGED
@@ -62,7 +62,13 @@ export async function useHistory(
62
62
  throw new Error(
63
63
  `history read requires ${typeof windowId !== "string" ? "window_id" : "item_id"} as a string. Copy window_id and item_id from the same search or list result`,
64
64
  );
65
- const item = windows.get(windowId)?.find((item) => item.item_id === itemId);
65
+ // Keep exact pre-initialisation references saved by earlier releases readable.
66
+ const items =
67
+ windows.get(windowId) ??
68
+ (windowId === `session:${sessionId}`
69
+ ? windows.values().next().value
70
+ : undefined);
71
+ const item = items?.find((item) => item.item_id === itemId);
66
72
  if (!item) return { item: null };
67
73
  const offset = integer(params["offset_chars"], 0, item.content.length);
68
74
  const limit = integer(params["limit_chars"], 8000, 8000);
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { createNotesActivation } from "./activation.js";
7
7
  import { createNotesContextOwner } from "./context-owner.js";
8
8
  import { registerNotesHooks } from "./extension-hooks.js";
9
9
  import { registerNotesSharing } from "./extension-sharing.js";
10
+ import { registerCheckpointRenderer } from "./fresh-checkpoint.js";
10
11
  import { HistorySearch } from "./history-search.js";
11
12
  import { registerNotesToolIntegrations } from "./integrations.js";
12
13
  import { NotesLifecycle } from "./lifecycle.js";
@@ -21,6 +22,7 @@ import { registerWindowRenderer } from "./windows.js";
21
22
 
22
23
  export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
23
24
  registerWindowRenderer(pi);
25
+ registerCheckpointRenderer(pi);
24
26
  const dir = join(getAgentDir(), "notes-compaction");
25
27
  const settingsPath = join(dir, "settings.json");
26
28
  const store = new NotesStore(join(dir, "notes.sqlite"));
@@ -75,6 +77,7 @@ export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
75
77
  const markers = registerNoteSaveMarkers(
76
78
  pi,
77
79
  () => lifecycle.active && activation.settings.noteSaveMarkers,
80
+ () => lifecycle.windows.current?.currentWindowId,
78
81
  );
79
82
  await registerNotesHooks(
80
83
  pi,
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ AgentToolResult,
2
3
  ExtensionAPI,
3
4
  ExtensionContext,
4
5
  } from "@earendil-works/pi-coding-agent";
@@ -6,10 +7,8 @@ import type { NotesActivation } from "./activation.js";
6
7
  import type { NotesLifecycle } from "./lifecycle.js";
7
8
  import {
8
9
  GPT_NEW_CONTEXT_DESCRIPTION,
9
- GPT_NOTES_DESCRIPTION,
10
10
  HISTORY_USAGE,
11
11
  NEW_CONTEXT_DESCRIPTION,
12
- NOTES_DESCRIPTION,
13
12
  NOTES_USAGE,
14
13
  } from "./tool-contracts.js";
15
14
  import type { createTools } from "./tools.js";
@@ -29,16 +28,13 @@ export async function registerNotesToolIntegrations(
29
28
  );
30
29
  const registration = registerGptPromptMode(pi, (active, ctx) => {
31
30
  if (ctx) activation.refreshActivation(ctx);
32
- for (const [name, normal, gpt] of [
33
- ["notes", NOTES_DESCRIPTION, GPT_NOTES_DESCRIPTION],
34
- ["new_context", NEW_CONTEXT_DESCRIPTION, GPT_NEW_CONTEXT_DESCRIPTION],
35
- ] as const) {
36
- const tool = tools.find((tool) => tool.name === name);
37
- const description = active ? gpt : normal;
38
- if (tool && tool.description !== description) {
39
- tool.description = description;
40
- pi.registerTool(tool);
41
- }
31
+ const tool = tools.find((tool) => tool.name === "new_context");
32
+ const description = active
33
+ ? GPT_NEW_CONTEXT_DESCRIPTION
34
+ : NEW_CONTEXT_DESCRIPTION;
35
+ if (tool && tool.description !== description) {
36
+ tool.description = description;
37
+ pi.registerTool(tool);
42
38
  }
43
39
  return lifecycle.active ? tools : [];
44
40
  });
@@ -69,19 +65,11 @@ export async function registerNotesToolIntegrations(
69
65
  adaptToolForCodeMode(tool, {
70
66
  discovery: "help",
71
67
  usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
72
- deferLoading: true,
68
+ deferLoading: tool.name !== "notes",
73
69
  opaqueResult: tool.name === "notes",
74
- resultValue(result) {
75
- const [part] = result.content;
76
- if (result.content.length === 1 && part?.type === "text") {
77
- try {
78
- return JSON.parse(part.text);
79
- } catch {
80
- return part.text;
81
- }
82
- }
83
- return { content: result.content };
84
- },
70
+ ...(tool.name === "history"
71
+ ? { resultValue: historyResultValue }
72
+ : {}),
85
73
  }),
86
74
  ),
87
75
  { isActive: () => lifecycle.active },
@@ -98,6 +86,18 @@ export async function registerNotesToolIntegrations(
98
86
  return refreshNested;
99
87
  }
100
88
 
89
+ function historyResultValue(result: AgentToolResult<unknown>): unknown {
90
+ const [part] = result.content;
91
+ if (result.content.length === 1 && part?.type === "text") {
92
+ try {
93
+ return JSON.parse(part.text);
94
+ } catch {
95
+ return part.text;
96
+ }
97
+ }
98
+ return { content: result.content };
99
+ }
100
+
101
101
  export async function registerNotesCompactionIntegration(
102
102
  pi: ExtensionAPI,
103
103
  activation: NotesActivation,
@@ -29,6 +29,7 @@ export function createModelRoles(
29
29
  ) {
30
30
  let config: RoleConfig = { roles: [] };
31
31
  let configError: string | undefined;
32
+ let roleIdsChanged: ((ids: string[]) => void) | undefined;
32
33
  const load = () => {
33
34
  try {
34
35
  config = readRoleConfig();
@@ -37,6 +38,7 @@ export function createModelRoles(
37
38
  config = { roles: [] };
38
39
  configError = error instanceof Error ? error.message : String(error);
39
40
  }
41
+ roleIdsChanged?.(config.roles.map((role) => role.id).sort());
40
42
  };
41
43
  pi.on("before_agent_start", (event, ctx) => {
42
44
  activation.refreshActivation(ctx);
@@ -56,14 +58,30 @@ export function createModelRoles(
56
58
  entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE,
57
59
  );
58
60
  if (!config.roles.length && !previous) return;
61
+ const reasoning = pi.getThinkingLevel();
62
+ const matching = config.roles
63
+ .filter(
64
+ (role) =>
65
+ role.provider === ctx.model?.provider &&
66
+ role.model === ctx.model?.id &&
67
+ role.reasoning === reasoning,
68
+ )
69
+ .map((role) => role.id);
70
+ const currentRole =
71
+ matching.length === 0
72
+ ? "none (no matching preset)"
73
+ : matching.length === 1
74
+ ? matching.join(", ")
75
+ : `ambiguous (${matching.join(", ")})`;
59
76
  const content = config.roles.length
60
77
  ? [
78
+ `Current role: ${currentRole}`,
61
79
  lifecycle.gptPromptMode()
62
- ? 'Roles=user preferences, not capability limits. Switch only for clear, sustained task/scope change, not one specialised prompt. Any model can do general work. Bounded specialist detour→consider available subagent. Save notes→new_context({role: "name"}); omit role→keep model.'
63
- : 'Roles are user preferences, not capability limits. Switch only for a clear, sustained change of task or scope, not a single specialised prompt. Any model can do general work. Consider an available subagent for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current model.',
80
+ ? 'Roles=user preferences, not capability limits. Switch for clear, sustained task/scope change, not one specialised prompt. Any role can do general work. Bounded specialist detour→consider subagent. Save notes→new_context({role: "name"}); omit role→keep role.'
81
+ : 'Roles are user preferences, not capability limits. Switch for clear, sustained change of task or scope, not single specialised prompt. Any role can do general work. Consider subagents for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current role.',
64
82
  ...config.roles.map((role) => `- ${role.id}: ${role.description}`),
65
83
  ].join("\n")
66
- : "No model roles are available. Call new_context without role.";
84
+ : "No model roles available. Call new_context without role.";
67
85
  if (
68
86
  startingWindow?.kind !== "window" &&
69
87
  previous?.type === "custom_message" &&
@@ -197,5 +215,11 @@ export function createModelRoles(
197
215
  ? ("notes" as const)
198
216
  : undefined;
199
217
  }
200
- return { prepare, command };
218
+ return {
219
+ prepare,
220
+ command,
221
+ onRoleIdsChanged(listener: (ids: string[]) => void) {
222
+ roleIdsChanged = listener;
223
+ },
224
+ };
201
225
  }
@@ -0,0 +1,70 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { Check } from "typebox/value";
4
+
5
+ const OPTIONAL_STRING = Type.Optional(Type.String());
6
+ const OPTIONAL_BOOLEAN = Type.Optional(Type.Boolean());
7
+ const MATCH = Type.Object({ line_number: Type.Integer(), line: Type.String() });
8
+
9
+ // Pi codemode needs this declaration to return structuredContent rather than text.
10
+ export const NOTES_OUTPUT_SCHEMA = Type.Object(
11
+ {},
12
+ { additionalProperties: true },
13
+ );
14
+
15
+ const NOTES_RESULT_SCHEMA = Type.Object(
16
+ {
17
+ file: Type.Optional(
18
+ Type.Union([
19
+ Type.Object({
20
+ path: Type.String(),
21
+ content: OPTIONAL_STRING,
22
+ start_line: Type.Optional(Type.Integer()),
23
+ stop_line: Type.Optional(Type.Integer()),
24
+ total_lines: Type.Optional(Type.Integer()),
25
+ append_only: OPTIONAL_BOOLEAN,
26
+ }),
27
+ Type.Null(),
28
+ ]),
29
+ ),
30
+ files: Type.Optional(
31
+ Type.Array(
32
+ Type.Object({
33
+ path: Type.String(),
34
+ updated_at: OPTIONAL_STRING,
35
+ created_at: OPTIONAL_STRING,
36
+ matches: Type.Optional(Type.Array(MATCH)),
37
+ truncated: OPTIONAL_BOOLEAN,
38
+ append_only: OPTIONAL_BOOLEAN,
39
+ }),
40
+ ),
41
+ ),
42
+ usage: OPTIONAL_STRING,
43
+ warnings: Type.Optional(Type.Array(Type.String())),
44
+ warning: OPTIONAL_STRING,
45
+ truncated: OPTIONAL_BOOLEAN,
46
+ read_only: OPTIONAL_BOOLEAN,
47
+ saved_at: OPTIONAL_STRING,
48
+ captured_at: OPTIONAL_STRING,
49
+ results: OPTIONAL_STRING,
50
+ actions: Type.Optional(Type.Record(Type.String(), Type.String())),
51
+ writes: OPTIONAL_STRING,
52
+ paths: OPTIONAL_STRING,
53
+ ranges: OPTIONAL_STRING,
54
+ defaults: OPTIONAL_STRING,
55
+ },
56
+ { additionalProperties: false },
57
+ );
58
+
59
+ /** One canonical payload for native text and every programmatic caller. */
60
+ export function noteResult(payload: unknown): AgentToolResult<unknown> {
61
+ if (!Check(NOTES_RESULT_SCHEMA, payload))
62
+ throw new Error(
63
+ "Notes returned invalid data. Read the note before retrying a write.",
64
+ );
65
+ return {
66
+ content: [{ type: "text", text: JSON.stringify(payload) }],
67
+ structuredContent: payload,
68
+ details: {},
69
+ };
70
+ }
@@ -11,9 +11,16 @@ const NOTE_SAVE_MARKER = "codex-note-save-marker";
11
11
  export function registerNoteSaveMarkers(
12
12
  pi: ExtensionAPI,
13
13
  enabled: () => boolean,
14
+ currentWindowId: () => string | undefined,
14
15
  ) {
15
16
  let manager: ExtensionContext["sessionManager"] | undefined;
16
- let cached: { leaf: string | null; id: string | undefined } | undefined;
17
+ let cached:
18
+ | {
19
+ leaf: string | null;
20
+ windowId: string | undefined;
21
+ id: string | undefined;
22
+ }
23
+ | undefined;
17
24
  const restore = (_event: unknown, ctx: ExtensionContext) => {
18
25
  manager = ctx.sessionManager;
19
26
  cached = undefined;
@@ -31,17 +38,24 @@ export function registerNoteSaveMarkers(
31
38
  return new (class extends Text {
32
39
  override render(width: number): string[] {
33
40
  const leaf = manager?.getLeafId();
34
- if (manager && (!cached || cached.leaf !== leaf))
41
+ const windowId = currentWindowId();
42
+ if (
43
+ manager &&
44
+ (!cached || cached.leaf !== leaf || cached.windowId !== windowId)
45
+ ) {
46
+ const branch = manager.getBranch();
35
47
  cached = {
36
48
  leaf: manager.getLeafId(),
37
- id: manager
38
- .getBranch()
39
- .findLast(
40
- (item) =>
41
- item.type === "custom" &&
42
- item.customType === NOTE_SAVE_MARKER,
43
- )?.id,
49
+ windowId,
50
+ id: hasFreshNotes(branch, windowId)
51
+ ? branch.findLast(
52
+ (item) =>
53
+ item.type === "custom" &&
54
+ item.customType === NOTE_SAVE_MARKER,
55
+ )?.id
56
+ : undefined,
44
57
  };
58
+ }
45
59
  const visible = manager && enabled() && cached?.id === entry.id;
46
60
  this.setText(visible ? content : "");
47
61
  return visible ? super.render(width) : [];
@@ -10,9 +10,9 @@ import type {
10
10
  } from "./bridge.js";
11
11
  import { queryKey } from "./bridge.js";
12
12
  import type { NotesLifecycle } from "./lifecycle.js";
13
+ import { noteResult } from "./note-result.js";
13
14
  import { CACHE_RECEIPT, sessionRef, sourceSessionIds } from "./notes.js";
14
15
  import type { NotesStore } from "./store.js";
15
- import { result } from "./tool-contracts.js";
16
16
 
17
17
  export async function lookupNotes(
18
18
  pi: ExtensionAPI,
@@ -85,7 +85,10 @@ export async function lookupNotes(
85
85
  warnings.push(
86
86
  "Older matches may refer to replaced notes. Read a note before relying on its excerpt; read returns the current saved version.",
87
87
  );
88
- const output = result({ ...local, ...(warnings.length ? { warnings } : {}) });
88
+ const output = noteResult({
89
+ ...local,
90
+ ...(warnings.length ? { warnings } : {}),
91
+ });
89
92
  if (shared)
90
93
  return {
91
94
  ...output,
package/src/notes.ts CHANGED
@@ -3,6 +3,7 @@ import type {
3
3
  ExtensionContext,
4
4
  SessionEntry,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import { isContextAgentName } from "./agent-identity.js";
6
7
  import type { NoteSnapshotData } from "./bridge.js";
7
8
  import { canonicalPath, readNotes } from "./note-query.js";
8
9
  import { type NoteRevision, NotesStore, type SessionRef } from "./store.js";
@@ -77,7 +78,9 @@ function relativeLegacyPath(path: string): string {
77
78
  // Legacy canonical paths use the first notes component as the agent-root boundary.
78
79
  const components = path.split("/");
79
80
  const boundary = components.indexOf("notes");
80
- return components[0] === "" && components[1] === "root" && boundary > 1
81
+ return components[0] === "" &&
82
+ isContextAgentName(components.slice(0, boundary).join("/")) &&
83
+ boundary > 1
81
84
  ? components.slice(boundary + 1).join("/")
82
85
  : path;
83
86
  }
@@ -191,7 +194,7 @@ export function exportNotesSnapshot(
191
194
  entries: readonly SessionEntry[],
192
195
  agentName: string,
193
196
  ): NoteSnapshotData {
194
- if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(agentName))
197
+ if (!isContextAgentName(agentName))
195
198
  throw new Error("Invalid notes agent identity");
196
199
  const notes = collectNotes({ read: () => undefined }, entries);
197
200
  const snapshot: NoteSnapshotData = {
@@ -231,7 +234,9 @@ export function noteHints(
231
234
  const paths = [
232
235
  ...new Set([...notes, ...store.cachedPaths(sourceSessionIds(ctx))]),
233
236
  ].slice(0, 5);
234
- return paths.length ? `Recent notes: ${paths.join(", ")}`.slice(0, 4000) : "";
237
+ return paths.length
238
+ ? `Recent notes in virtual filesystem: ${paths.join(", ")}`.slice(0, 4000)
239
+ : "";
235
240
  }
236
241
 
237
242
  export function useNotes(
@@ -3,9 +3,15 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ contextAgentIdentity,
8
+ contextAgentNames,
9
+ contextStorageAgentName,
10
+ } from "./agent-identity.js";
6
11
  import { useHistory } from "./history.js";
7
12
  import type { HistorySearch } from "./history-search.js";
8
13
  import type { NotesLifecycle } from "./lifecycle.js";
14
+ import { noteResult } from "./note-result.js";
9
15
  import { collectNotes, normalizeNoteParams, useNotes } from "./notes.js";
10
16
  import { lookupNotes } from "./notes-lookup.js";
11
17
  import {
@@ -42,7 +48,7 @@ export function createQueryExecutor(
42
48
  ctx: ExtensionContext,
43
49
  ): Promise<AgentToolResult<unknown>> {
44
50
  input = prepareNotesArguments(input);
45
- const help = queryHelp("notes", input, false, lifecycle.gptPromptMode());
51
+ const help = queryHelp("notes", input, lifecycle.gptPromptMode());
46
52
  if (help) return help;
47
53
  assertActive();
48
54
  const raw = queryArguments("notes", input);
@@ -59,15 +65,28 @@ export function createQueryExecutor(
59
65
  signal?.throwIfAborted();
60
66
  if (!sharedNotesUnavailable(error)) throw error;
61
67
  const saved = await readSharedNotes(ctx, store, raw, signal);
62
- if (saved) return result(saved);
68
+ if (saved) return noteResult(saved);
63
69
  throw error;
64
70
  }
65
71
  const saved = await readSharedNotes(ctx, store, raw, signal);
66
- if (saved) return result(saved);
72
+ if (saved) return noteResult(saved);
73
+ }
74
+ const identity = contextAgentIdentity(ctx);
75
+ const storageAgent = contextStorageAgentName(identity);
76
+ const localRaw = { ...raw };
77
+ for (const key of ["path", "prefix", "path_prefix"]) {
78
+ const value = localRaw[key];
79
+ if (typeof value !== "string") continue;
80
+ const alias = contextAgentNames(identity).find(
81
+ (name) =>
82
+ value === `${name}/notes` || value.startsWith(`${name}/notes/`),
83
+ );
84
+ if (alias)
85
+ localRaw[key] = `${identity.agentName}${value.slice(alias.length)}`;
67
86
  }
68
87
  const params = queryArguments(
69
88
  "notes",
70
- normalizeNoteParams(raw, lifecycle.agent(ctx)),
89
+ normalizeNoteParams(localRaw, lifecycle.agent(ctx)),
71
90
  );
72
91
  if (signal?.aborted) throw new Error("Note operation cancelled");
73
92
  const local = useNotes(
@@ -85,7 +104,7 @@ export function createQueryExecutor(
85
104
  params["action"] === "append_to_file"
86
105
  )
87
106
  return {
88
- ...result(local),
107
+ ...noteResult(local),
89
108
  details: {
90
109
  ...(shared
91
110
  ? { codexHistoryNotes: {}, notesCompactionRouted: true }
@@ -103,7 +122,7 @@ export function createQueryExecutor(
103
122
  params["action"] === "read_file" &&
104
123
  notes.get(params["path"] as string)?.mode === "replace"
105
124
  )
106
- return result(local);
125
+ return noteResult(local);
107
126
  const prefix = String(params["prefix"] ?? params["path_prefix"] ?? "");
108
127
  const replacementsInScope =
109
128
  params["action"] !== "read_file" &&
@@ -114,7 +133,7 @@ export function createQueryExecutor(
114
133
  for (const field of ["path", "prefix", "path_prefix"])
115
134
  if (typeof remoteParams[field] === "string")
116
135
  remoteParams[field] =
117
- `${lifecycle.agent(ctx)}/notes${remoteParams[field] ? `/${remoteParams[field]}` : ""}`;
136
+ `${storageAgent}/notes${remoteParams[field] ? `/${remoteParams[field]}` : ""}`;
118
137
  return lookupNotes(
119
138
  pi,
120
139
  store,
@@ -135,12 +154,7 @@ export function createQueryExecutor(
135
154
  ctx: ExtensionContext,
136
155
  ): Promise<AgentToolResult<unknown>> {
137
156
  input = prepareHistoryArguments(input);
138
- const help = queryHelp(
139
- "history",
140
- input,
141
- search.isEnabled(ctx.sessionManager.getSessionId()),
142
- lifecycle.gptPromptMode(),
143
- );
157
+ const help = queryHelp("history", input, lifecycle.gptPromptMode());
144
158
  if (help) return help;
145
159
  assertActive();
146
160
  const params = queryArguments("history", input);
@@ -177,7 +191,12 @@ export function createQueryExecutor(
177
191
  const saved = await readSharedHistory(ctx, store, search, params, signal);
178
192
  if (saved) return result(saved);
179
193
  }
180
- if (params["agent_name"] && params["agent_name"] !== lifecycle.agent(ctx))
194
+ if (
195
+ params["agent_name"] &&
196
+ !contextAgentNames(contextAgentIdentity(ctx)).includes(
197
+ String(params["agent_name"]),
198
+ )
199
+ )
181
200
  throw new Error(
182
201
  "That agent's Pi session history is unavailable on this machine. Restore access to its saved JSONL session, or omit agent_name to search this session.",
183
202
  );