@howaboua/pi-notes-compaction 0.0.10 → 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,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),
@@ -0,0 +1,179 @@
1
+ import type {
2
+ CustomMessageEntryDraft,
3
+ ExtensionAPI,
4
+ SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { keyHint } from "@earendil-works/pi-coding-agent";
7
+ import { Box, Text, TruncatedText } from "@earendil-works/pi-tui";
8
+ import type { WindowIdentity } from "./bridge.js";
9
+
10
+ export const WINDOW_MESSAGE = "notes-compaction:window:v1";
11
+ export const SETTLEMENT_ENTRY = "notes-compaction:settled:v1";
12
+ export interface WindowDetails {
13
+ protocol: 1;
14
+ kind: "window" | "identity" | "reminder" | "urgent" | "task-boundary";
15
+ identity: WindowIdentity;
16
+ trim: boolean;
17
+ }
18
+ const GUIDANCE = `<context_window_guidance>
19
+ Notes are recovery state, not a diary. Write checkpoints and reports to relative paths in your own notes. Delegates do likewise and return their note paths. Keep one concise, authoritative note per task or topic at a stable path. Task checkpoints cover request, constraints, decisions, status, next steps and history IDs. Use write to replace stale state and mark completion. Link to existing notes instead of copying or summarising their contents. Recording isn't permission to implement.
20
+
21
+ You must maintain a task checkpoint, updating it at each meaningful milestone and on completion or before switching substantive tasks, even with context room. Don't save every reply or intermediate step. Before new_context or handoff, save current state and wait for success; include the checkpoint path in handoffs. After rollover, read the checkpoint, then only needed links. Don't reread notes still in context unless they may have changed. Use history for missing details.
22
+
23
+ Previous skill reads don’t carry into this window. Read the skills needed for the current task.
24
+ </context_window_guidance>`;
25
+
26
+ const GPT_GUIDANCE = `<context_window_guidance>
27
+ Notes=recovery state≠diary. Checkpoints/reports→write relative paths in own notes. Delegates→same→return note paths. One concise authoritative note per task/topic, stable path. Task checkpoint=request/constraints/decisions/status/next steps/history IDs. write→replace stale state; mark completion. Existing notes→link≠copy/summarise. Recording≠implementation permission.
28
+
29
+ Must maintain task checkpoint→update@each meaningful milestone + completion/before switching substantive tasks, even with context room. Not every reply/step. Before new_context/handoff: save current state→await success; handoff includes checkpoint path. Post-rollover: read checkpoint→needed links only. In-context notes: reread only if possibly changed. Missing details→history.
30
+
31
+ Prior skill reads≠current context. Read task-relevant skills.
32
+ </context_window_guidance>`;
33
+
34
+ export function registerWindowRenderer(pi: ExtensionAPI): void {
35
+ pi.registerMessageRenderer(
36
+ WINDOW_MESSAGE,
37
+ (message, { expanded, outputPad }, theme) => {
38
+ const details = parseWindowDetails(message.details);
39
+ if (!details || typeof message.content !== "string") return undefined;
40
+ const title =
41
+ details.kind === "task-boundary"
42
+ ? "Task-boundary reminder"
43
+ : details.kind === "urgent"
44
+ ? "Context nearly full · Save notes and start a new window now"
45
+ : details.kind === "reminder"
46
+ ? "Context checkpoint reminder · Save notes and start a new window"
47
+ : `Context window ${details.identity.windowNumber + 1} · Notes and history`;
48
+ const box = new Box(outputPad, 1, (text) =>
49
+ theme.bg("customMessageBg", text),
50
+ );
51
+ box.addChild(
52
+ expanded
53
+ ? new Text(theme.fg("customMessageText", message.content), 0, 0)
54
+ : new TruncatedText(
55
+ theme.fg(
56
+ details.kind === "urgent" ? "warning" : "customMessageLabel",
57
+ title,
58
+ ) +
59
+ theme.fg(
60
+ "dim",
61
+ ` (${keyHint("app.tools.expand", "to expand")})`,
62
+ ),
63
+ 0,
64
+ 0,
65
+ ),
66
+ );
67
+ return box;
68
+ },
69
+ );
70
+ }
71
+
72
+ function identity(value: unknown): WindowIdentity | undefined {
73
+ if (!value || typeof value !== "object") return;
74
+ const data = value as Partial<WindowIdentity>;
75
+ if (
76
+ typeof data.firstWindowId !== "string" ||
77
+ !data.firstWindowId ||
78
+ typeof data.currentWindowId !== "string" ||
79
+ !data.currentWindowId ||
80
+ !Number.isInteger(data.windowNumber) ||
81
+ data.windowNumber! < 0 ||
82
+ (data.previousWindowId !== undefined &&
83
+ typeof data.previousWindowId !== "string")
84
+ )
85
+ return;
86
+ return data as WindowIdentity;
87
+ }
88
+
89
+ function parseWindowDetails(value: unknown): WindowDetails | undefined {
90
+ if (!value || typeof value !== "object") return;
91
+ const details = value as Partial<WindowDetails>;
92
+ const ids = identity(details.identity);
93
+ if (
94
+ details.protocol !== 1 ||
95
+ !ids ||
96
+ !["window", "identity", "reminder", "urgent", "task-boundary"].includes(
97
+ details.kind ?? "",
98
+ ) ||
99
+ typeof details.trim !== "boolean"
100
+ )
101
+ return;
102
+ return {
103
+ protocol: 1,
104
+ kind: details.kind!,
105
+ identity: ids,
106
+ trim: details.trim,
107
+ };
108
+ }
109
+
110
+ /** Understand previous PCC window IDs for familiar history lookup, without importing its runtime. */
111
+ export function windowDetails(
112
+ entry: SessionEntry | CustomMessageEntryDraft,
113
+ ): WindowDetails | undefined {
114
+ if (entry.type !== "custom_message") return;
115
+ return messageWindowDetails(entry.customType, entry.details);
116
+ }
117
+
118
+ export function messageWindowDetails(
119
+ customType: string,
120
+ data: unknown,
121
+ ): WindowDetails | undefined {
122
+ if (customType === WINDOW_MESSAGE) return parseWindowDetails(data);
123
+ if (
124
+ customType !== "codex-context-window" ||
125
+ !data ||
126
+ typeof data !== "object" ||
127
+ !("contextManagement" in data)
128
+ )
129
+ return;
130
+ const details = data.contextManagement;
131
+ if (
132
+ !details ||
133
+ typeof details !== "object" ||
134
+ !("kind" in details) ||
135
+ (details.kind !== "window" && details.kind !== "task-boundary")
136
+ )
137
+ return;
138
+ const ids = identity(details);
139
+ return ids
140
+ ? {
141
+ protocol: 1,
142
+ kind: details.kind,
143
+ identity: ids,
144
+ trim:
145
+ "trimPreviousWindow" in details &&
146
+ details.trimPreviousWindow === true,
147
+ }
148
+ : undefined;
149
+ }
150
+
151
+ export function windowMessage(
152
+ ids: WindowIdentity,
153
+ agent: string,
154
+ hint: string,
155
+ trim: boolean,
156
+ kind: "window" | "identity" = "window",
157
+ gpt = false,
158
+ ): CustomMessageEntryDraft {
159
+ const lines = [
160
+ `Agent name: ${agent}`,
161
+ `First context window id: ${ids.firstWindowId}`,
162
+ `Current context window id: ${ids.currentWindowId}`,
163
+ ];
164
+ if (ids.previousWindowId)
165
+ lines.push(`Previous context window id: ${ids.previousWindowId}`);
166
+ if (hint) lines.push(hint);
167
+ return {
168
+ type: "custom_message",
169
+ customType: WINDOW_MESSAGE,
170
+ content: `${gpt ? GPT_GUIDANCE : GUIDANCE}\n\n<context_window>\n${lines.join("\n")}\n</context_window>`,
171
+ display: true,
172
+ details: {
173
+ protocol: 1,
174
+ kind,
175
+ identity: ids,
176
+ trim,
177
+ } satisfies WindowDetails,
178
+ };
179
+ }