@howaboua/pi-notes-compaction 0.0.11 → 0.0.12

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.
@@ -3,7 +3,6 @@ import { isDeepStrictEqual } from "node:util";
3
3
  import type {
4
4
  ExtensionAPI,
5
5
  ExtensionContext,
6
- SessionEntry,
7
6
  } from "@earendil-works/pi-coding-agent";
8
7
  import {
9
8
  CONTEXT_AGENT_ENTRY,
@@ -11,10 +10,7 @@ import {
11
10
  contextTargetAgent,
12
11
  parseContextAgentBinding,
13
12
  } from "./agent-identity.js";
14
- import {
15
- readAttachmentSnapshot,
16
- readRemoteNoteReference,
17
- } from "./attachment-snapshot.js";
13
+ import { createAttachmentSharing } from "./attachment-sharing.js";
18
14
  import { bindingStartupEntries } from "./binding-startup.js";
19
15
  import type { NotesOwner } from "./bridge.js";
20
16
  import {
@@ -25,7 +21,6 @@ import {
25
21
  type SharedContextRequest,
26
22
  type SharedContextResult,
27
23
  } from "./context-sharing.js";
28
- import { exportNotesSnapshot } from "./notes.js";
29
24
 
30
25
  export function registerContextSharingService(
31
26
  pi: ExtensionAPI,
@@ -199,116 +194,7 @@ export function registerContextSharingService(
199
194
  );
200
195
  return config.execute(ctx, request, signal);
201
196
  },
202
- exportAttachmentNotes(ctx) {
203
- const identity = describe(ctx);
204
- if (!identity)
205
- throw new Error("Checkpoint export requires notes-based continuity");
206
- if (identity.storage === "remote") {
207
- if (!identity.backendUrl)
208
- throw new Error("Saved remote context has no backend address");
209
- return {
210
- protocol: 1,
211
- storage: "remote",
212
- timestamp: Date.now(),
213
- identity,
214
- baseUrl: identity.backendUrl,
215
- };
216
- }
217
-
218
- const snapshot = exportNotesSnapshot(
219
- ctx.sessionManager.getBranch(),
220
- identity.agentName,
221
- );
222
- return {
223
- ...snapshot,
224
- files: snapshot.files.filter(
225
- (file) =>
226
- contextTargetAgent(
227
- "notes",
228
- { path: file.path },
229
- identity.agentName,
230
- ) === identity.agentName,
231
- ),
232
- };
233
- },
234
- validateAttachmentNotes(snapshot, identity) {
235
- if (identity.storage === "remote") {
236
- if (
237
- !isDeepStrictEqual(
238
- readRemoteNoteReference(snapshot).identity,
239
- identity,
240
- )
241
- )
242
- throw new Error("Remote checkpoint owner changed");
243
- } else
244
- readAttachmentSnapshot(snapshot, {
245
- action: "list_files_by_prefix",
246
- prefix: `${identity.agentName}/notes`,
247
- });
248
- },
249
- async verifyAttachmentAccess(ctx, snapshot) {
250
- if (
251
- !snapshot ||
252
- typeof snapshot !== "object" ||
253
- !("storage" in snapshot) ||
254
- snapshot.storage !== "remote"
255
- )
256
- return;
257
- const { verifyRemoteReference } = await import("./remote.js");
258
- await verifyRemoteReference(ctx, readRemoteNoteReference(snapshot));
259
- },
260
- async executeRemoteAttachment(ctx, snapshot, request, signal) {
261
- if (request.namespace === "history")
262
- throw new Error(
263
- "History is unavailable from a saved remote notes attachment. Open its saved Pi JSONL session on this machine, then retry.",
264
- );
265
- const { executeRemoteAttachment } = await import("./remote.js");
266
- return executeRemoteAttachment(
267
- ctx,
268
- readRemoteNoteReference(snapshot),
269
- request,
270
- signal,
271
- );
272
- },
273
- parseAttachmentNotes(input, identity) {
274
- if (!Array.isArray(input))
275
- throw new Error("Invalid persisted checkpoint entries");
276
- const entries: SessionEntry[] = input.map((entry: unknown) => {
277
- if (
278
- !entry ||
279
- typeof entry !== "object" ||
280
- !("type" in entry) ||
281
- !(
282
- (entry.type === "custom" &&
283
- "customType" in entry &&
284
- typeof entry.customType === "string" &&
285
- "data" in entry) ||
286
- (entry.type === "branch_summary" && "details" in entry)
287
- )
288
- )
289
- throw new Error("Invalid persisted checkpoint entry");
290
- return entry as SessionEntry;
291
- });
292
- const snapshot = exportNotesSnapshot(entries, identity.agentName);
293
- return {
294
- ...snapshot,
295
- files: snapshot.files.filter(
296
- (file) =>
297
- contextTargetAgent(
298
- "notes",
299
- { path: file.path },
300
- identity.agentName,
301
- ) === identity.agentName,
302
- ),
303
- };
304
- },
305
- readAttachmentNotes(snapshot, params) {
306
- const details = readAttachmentSnapshot(snapshot, params);
307
- return {
308
- content: [{ type: "text", text: JSON.stringify(details) }],
309
- details: { codexHistoryNotes: details },
310
- };
311
- },
197
+ ...createAttachmentSharing(describe),
312
198
  registerRouter(next) {
313
199
  if (router && router !== next)
314
200
  throw new Error("A context router is already registered");
@@ -3,21 +3,22 @@ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
4
  import { Check } from "typebox/value";
5
5
  import type { LookupQuery } from "./bridge.js";
6
+ import { internalQueryArguments, normalizeQueryInput } from "./query-input.js";
6
7
 
7
8
  const NOTES_ACTIONS = [
8
9
  "help",
9
- "list_files_by_prefix",
10
- "read_file",
11
- "search_contents",
12
- "append_to_file",
13
- "write_file",
10
+ "list",
11
+ "read",
12
+ "search",
13
+ "append",
14
+ "write",
14
15
  ] as const;
15
16
  const HISTORY_ACTIONS = [
16
17
  "help",
17
18
  "list_windows",
18
- "list_items",
19
- "read_item",
20
- "search_contents",
19
+ "list",
20
+ "read",
21
+ "search",
21
22
  ] as const;
22
23
  export const NOTES_USAGE = "await tools.notes()";
23
24
  export const HISTORY_USAGE = "await tools.history()";
@@ -31,20 +32,20 @@ export const GPT_NEW_CONTEXT_DESCRIPTION =
31
32
  "Saved notes→fresh context; earlier conversation→history";
32
33
  const STRING = Type.Optional(Type.String());
33
34
  const INTEGER = Type.Optional(Type.Integer({ minimum: 1 }));
34
- const NULLABLE_STRING = Type.Optional(Type.Union([Type.String(), Type.Null()]));
35
35
  const LINE = Type.Optional(Type.Union([Type.Integer(), Type.Null()]));
36
- export const NOTES_SCHEMA = Type.Object(
36
+ const NOTES_SCHEMA = Type.Object(
37
37
  {
38
- action: Type.Optional(StringEnum([...NOTES_ACTIONS, "read"])),
39
- path: STRING,
38
+ action: Type.Optional(StringEnum(NOTES_ACTIONS)),
39
+ path: Type.Optional(
40
+ Type.Union([Type.String(), Type.Null()], {
41
+ description: "File for read/write/append; prefix for list/search",
42
+ }),
43
+ ),
40
44
  text: STRING,
41
- prefix: NULLABLE_STRING,
42
45
  query: STRING,
43
- path_prefix: NULLABLE_STRING,
44
46
  start_line: LINE,
45
47
  stop_line: LINE,
46
- max_results: INTEGER,
47
- max_files: INTEGER,
48
+ limit: INTEGER,
48
49
  max_matches_per_file: INTEGER,
49
50
  file_order: Type.Optional(StringEnum(["ascending", "descending"])),
50
51
  file_order_by: Type.Optional(
@@ -54,6 +55,31 @@ export const NOTES_SCHEMA = Type.Object(
54
55
  },
55
56
  { additionalProperties: false },
56
57
  );
58
+ export function notesSchema(roles: boolean) {
59
+ if (!roles) return NOTES_SCHEMA;
60
+ return Type.Object(
61
+ {
62
+ ...NOTES_SCHEMA.properties,
63
+ action: Type.Optional(
64
+ StringEnum([...NOTES_ACTIONS, "roles", "recommend_handoff"]),
65
+ ),
66
+ role: STRING,
67
+ reason: Type.Optional(
68
+ Type.String({
69
+ minLength: 1,
70
+ description: "Conversation evidence this role fits better now",
71
+ }),
72
+ ),
73
+ continuity: Type.Optional(
74
+ Type.String({
75
+ minLength: 1,
76
+ description: "Goal, decisions, unfinished work and next step",
77
+ }),
78
+ ),
79
+ },
80
+ { additionalProperties: false },
81
+ );
82
+ }
57
83
  export const HISTORY_SCHEMA = Type.Object(
58
84
  {
59
85
  action: Type.Optional(StringEnum(HISTORY_ACTIONS)),
@@ -61,7 +87,7 @@ export const HISTORY_SCHEMA = Type.Object(
61
87
  item_id: STRING,
62
88
  window_id: Type.Optional(
63
89
  Type.Union([Type.String(), Type.Null()], {
64
- description: "Required with item_id for read_item",
90
+ description: "Required with item_id for read",
65
91
  }),
66
92
  ),
67
93
  query: STRING,
@@ -83,6 +109,8 @@ export const HISTORY_SCHEMA = Type.Object(
83
109
  );
84
110
 
85
111
  const FIELDS: Record<string, readonly string[]> = {
112
+ roles: [],
113
+ recommend_handoff: ["role", "reason", "continuity"],
86
114
  list_files_by_prefix: [
87
115
  "prefix",
88
116
  "file_order",
@@ -134,8 +162,10 @@ export function queryArguments(
134
162
  ): Record<string, unknown> {
135
163
  if (!input || typeof input !== "object" || Array.isArray(input))
136
164
  throw new Error("Supply an action object");
137
- const params = input as Record<string, unknown>;
165
+ const normalized = normalizeQueryInput(namespace, input);
166
+ const params = internalQueryArguments(namespace, normalized);
138
167
  const action = params["action"];
168
+ const publicAction = normalized["action"];
139
169
  const key =
140
170
  action === "search_contents" ? `search_${namespace}` : String(action);
141
171
  const fields = FIELDS[key];
@@ -145,31 +175,27 @@ export function queryArguments(
145
175
  ? "notes requires a supported action"
146
176
  : "Unknown action",
147
177
  );
148
- if (namespace === "notes") {
149
- for (const field of Object.keys(params))
150
- if (field !== "action" && !fields.includes(field))
151
- throw new Error(`notes ${String(action)} does not accept ${field}`);
152
- if (
153
- ["read_file", "write_file", "append_to_file"].includes(String(action)) &&
154
- (typeof params["path"] !== "string" || !params["path"])
155
- )
156
- throw new Error(`notes ${String(action)} requires path`);
157
- if (
158
- action === "search_contents" &&
159
- (typeof params["query"] !== "string" || !params["query"])
160
- )
161
- throw new Error("notes search_contents requires query");
162
- if (
163
- ["write_file", "append_to_file"].includes(String(action)) &&
164
- typeof params["text"] !== "string"
165
- )
166
- throw new Error(`notes ${String(action)} requires text`);
167
- }
168
- return Object.fromEntries(
169
- Object.entries(params).filter(
170
- ([key]) => key === "action" || fields.includes(key),
171
- ),
172
- );
178
+ for (const field of Object.keys(params))
179
+ if (field !== "action" && !fields.includes(field))
180
+ throw new Error(
181
+ `${namespace} ${String(publicAction)} does not accept ${field}; use {} for help`,
182
+ );
183
+ if (
184
+ ["read_file", "write_file", "append_to_file"].includes(String(action)) &&
185
+ (typeof params["path"] !== "string" || !params["path"])
186
+ )
187
+ throw new Error(`notes ${String(publicAction)} requires path`);
188
+ if (
189
+ action === "search_contents" &&
190
+ (typeof params["query"] !== "string" || !params["query"])
191
+ )
192
+ throw new Error(`${namespace} search requires query`);
193
+ if (
194
+ ["write_file", "append_to_file"].includes(String(action)) &&
195
+ typeof params["text"] !== "string"
196
+ )
197
+ throw new Error(`notes ${String(publicAction)} requires text`);
198
+ return params;
173
199
  }
174
200
 
175
201
  export function result(payload: unknown): AgentToolResult<unknown> {
@@ -202,31 +228,31 @@ export function queryHelp(
202
228
  action,
203
229
  action === "help"
204
230
  ? ""
205
- : FIELDS[
206
- action === "search_contents" ? `search_${namespace}` : action
207
- ]!.map((field) =>
231
+ : FIELDS[helpKey(namespace, action)]!.map((field) =>
208
232
  ["path", "text", "query", "item_id"].includes(field) ||
209
- (action === "read_item" && field === "window_id")
233
+ (action === "read" && field === "window_id")
210
234
  ? field
211
235
  : `${field}?`,
212
- ).join(" "),
236
+ )
237
+ .map((field) => publicField(namespace, field))
238
+ .join(" "),
213
239
  ]),
214
240
  ),
215
241
  ...(namespace === "notes"
216
242
  ? {
217
243
  writes: gpt
218
- ? "write_file=replace; append_to_file=add"
219
- : "write_file replaces; append_to_file adds",
244
+ ? "write=replace; append=add"
245
+ : "write replaces; append adds",
220
246
  paths: gpt
221
247
  ? "Relative=current agent; cross-agent=<agent>/notes[/path]"
222
248
  : "Relative uses current agent; cross-agent uses <agent>/notes[/path]",
223
- usage: '{ "action": "read_file", "path": "checkpoint" }',
249
+ usage: '{ "action": "read", "path": "checkpoint" }',
224
250
  ranges: gpt
225
251
  ? "start_line/stop_line=1-based inclusive; negative=from end; 0/null/omitted=first/last; out-of-range→clamp; reversed→empty"
226
252
  : "start_line/stop_line inclusive, 1-based; negative counts from end; 0/null/omitted uses first/last line; out-of-range clamps; reversed range returns empty content",
227
253
  defaults: gpt
228
- ? "list max_results=20; search max_files/max_matches_per_file=20; limits clamp 1..100; list/search name ascending; recent_file_first→created_at descending"
229
- : "list max_results 20; search max_files/max_matches_per_file 20; limits clamp to 1..100; list name ascending; search name ascending, recent_file_first sorts created_at descending",
254
+ ? "list limit=20; search limit/max_matches_per_file=20; limits clamp 1..100; list/search name ascending; recent_file_first→created_at descending"
255
+ : "list limit 20; search limit/max_matches_per_file 20; limits clamp to 1..100; list name ascending; search name ascending, recent_file_first sorts created_at descending",
230
256
  }
231
257
  : {
232
258
  usage: gpt
@@ -245,35 +271,50 @@ export function queryHelp(
245
271
  return undefined;
246
272
  }
247
273
 
248
- export function prepareNotesArguments(args: unknown) {
249
- if (args === undefined) return {};
250
- if (!args || typeof args !== "object" || Array.isArray(args))
274
+ export function prepareNotesArguments(args: unknown, roles = false) {
275
+ const params = normalizeQueryInput("notes", args);
276
+ if (
277
+ !roles &&
278
+ ["roles", "recommend_handoff"].includes(String(params["action"]))
279
+ )
251
280
  throw new Error(
252
- 'Supply an action object, e.g. { "action": "read_file", "path": "checkpoint" }. Use {} for help',
281
+ "Role recommendations are off. The user can enable them with /roles",
253
282
  );
254
- const params = { ...args } as Record<string, unknown>;
255
- if (params["action"] === "read") params["action"] = "read_file";
256
- if (
257
- (params["action"] === "write_file" ||
258
- params["action"] === "append_to_file") &&
259
- "content" in params
260
- ) {
261
- if (!("text" in params)) params["text"] = params["content"];
262
- delete params["content"];
263
- }
264
- if (
265
- params["action"] === "list_files_by_prefix" &&
266
- params["max_files"] !== undefined
267
- ) {
268
- if (!("max_results" in params)) params["max_results"] = params["max_files"];
269
- delete params["max_files"];
270
- }
271
- if (!queryHelp("notes", params)) queryArguments("notes", params);
283
+ validateArguments("notes", params, notesSchema(roles));
284
+ return params;
285
+ }
286
+
287
+ export function prepareHistoryArguments(args: unknown) {
288
+ const params = normalizeQueryInput("history", args);
289
+ validateArguments("history", params, HISTORY_SCHEMA);
290
+ return params;
291
+ }
292
+
293
+ function validateArguments(
294
+ namespace: LookupQuery["namespace"],
295
+ params: Record<string, unknown>,
296
+ schema: import("typebox").TObject,
297
+ ) {
298
+ if (!queryHelp(namespace, params)) queryArguments(namespace, params);
272
299
  for (const [field, value] of Object.entries(params)) {
273
- const schema =
274
- NOTES_SCHEMA.properties[field as keyof typeof NOTES_SCHEMA.properties];
275
- if (!schema || !Check(schema, value))
276
- throw new Error(`Invalid notes ${field}; use {} for exact arguments`);
300
+ const property = schema.properties[field];
301
+ if (!property || !Check(property, value))
302
+ throw new Error(
303
+ `Invalid ${namespace} ${field}; use {} for exact arguments`,
304
+ );
277
305
  }
278
- return params;
306
+ }
307
+
308
+ function helpKey(namespace: LookupQuery["namespace"], action: string) {
309
+ const internal = internalQueryArguments(namespace, { action })["action"];
310
+ return internal === "search_contents"
311
+ ? `search_${namespace}`
312
+ : String(internal);
313
+ }
314
+
315
+ function publicField(namespace: LookupQuery["namespace"], field: string) {
316
+ if (namespace !== "notes") return field;
317
+ return field
318
+ .replace(/^(prefix|path_prefix)(\?)?$/, "path$2")
319
+ .replace(/^(max_results|max_files)(\?)?$/, "limit$2");
279
320
  }
package/src/tools.ts CHANGED
@@ -8,13 +8,15 @@ import { Type } from "typebox";
8
8
  import type { LookupQuery, SharedNotesDetails } from "./bridge.js";
9
9
  import type { HistorySearch } from "./history-search.js";
10
10
  import type { NotesLifecycle } from "./lifecycle.js";
11
+ import type { createModelRoles } from "./model-roles.js";
11
12
  import { createQueryExecutor } from "./query-executor.js";
12
13
  import type { NotesStore } from "./store.js";
13
14
  import {
14
15
  HISTORY_SCHEMA,
15
16
  NEW_CONTEXT_DESCRIPTION,
16
17
  NOTES_DESCRIPTION,
17
- NOTES_SCHEMA,
18
+ notesSchema,
19
+ prepareHistoryArguments,
18
20
  prepareNotesArguments,
19
21
  result,
20
22
  } from "./tool-contracts.js";
@@ -50,6 +52,7 @@ export function createTools(
50
52
  store: NotesStore,
51
53
  lifecycle: NotesLifecycle,
52
54
  search: HistorySearch,
55
+ roles: ReturnType<typeof createModelRoles>,
53
56
  ): ToolDefinition[] {
54
57
  const assertActive = () => {
55
58
  if (!lifecycle.active)
@@ -63,11 +66,48 @@ export function createTools(
63
66
  name: "notes",
64
67
  label: "notes",
65
68
  description: NOTES_DESCRIPTION,
66
- parameters: NOTES_SCHEMA,
69
+ parameters: notesSchema(roles.enabled()),
67
70
  executionMode: "sequential",
68
- prepareArguments: prepareNotesArguments,
69
- execute: (callId, input, signal, _update, ctx) =>
70
- queries.notes(callId, input, signal, ctx),
71
+ prepareArguments: (args) => prepareNotesArguments(args, roles.enabled()),
72
+ execute: async (callId, input, signal, _update, ctx) => {
73
+ const params = prepareNotesArguments(input, roles.enabled());
74
+ if (
75
+ params["action"] === "roles" ||
76
+ params["action"] === "recommend_handoff"
77
+ ) {
78
+ assertActive();
79
+ if (signal?.aborted)
80
+ throw new Error("Handoff recommendation cancelled");
81
+ if (params["action"] === "roles") return roles.query({}, ctx);
82
+ const role = params["role"],
83
+ reason = params["reason"],
84
+ continuity = params["continuity"];
85
+ if (
86
+ typeof role !== "string" ||
87
+ !role.trim() ||
88
+ typeof reason !== "string" ||
89
+ typeof continuity !== "string"
90
+ )
91
+ throw new Error(
92
+ "recommend_handoff requires role, reason and continuity; use notes action=roles to discover preferences",
93
+ );
94
+ return roles.query({ role, reason, continuity }, ctx);
95
+ }
96
+ const output = await queries.notes(callId, params, signal, ctx);
97
+ if (
98
+ roles.enabled() &&
99
+ (!params["action"] || params["action"] === "help")
100
+ ) {
101
+ const part = output.content[0];
102
+ if (part?.type === "text") {
103
+ const help = JSON.parse(part.text);
104
+ help.actions.roles = "";
105
+ help.actions.recommend_handoff = "role reason continuity";
106
+ return result(help);
107
+ }
108
+ }
109
+ return output;
110
+ },
71
111
  },
72
112
  {
73
113
  name: "history",
@@ -75,7 +115,7 @@ export function createTools(
75
115
  description: "Search earlier conversation",
76
116
  parameters: HISTORY_SCHEMA,
77
117
  prepareArguments(args) {
78
- return args === undefined ? {} : args;
118
+ return prepareHistoryArguments(args);
79
119
  },
80
120
  execute: (callId, input, signal, _update, ctx) =>
81
121
  queries.history(callId, input, signal, ctx),