@howaboua/pi-notes-compaction 0.0.4 → 0.0.6

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.
package/src/settings.ts CHANGED
@@ -3,9 +3,25 @@ import { dirname } from "node:path";
3
3
 
4
4
  export const IDLE_MINUTES = [0, 5, 15, 25, 55] as const;
5
5
  export type IdleMinutes = (typeof IDLE_MINUTES)[number];
6
+ export const NEW_WINDOW_REQUESTS = [
7
+ "off",
8
+ "pi-limits",
9
+ "unrestricted",
10
+ ] as const;
11
+ export type NewWindowRequests = (typeof NEW_WINDOW_REQUESTS)[number];
12
+ export const DEFAULT_MODEL_WHITELIST = [
13
+ "gpt-6-astra",
14
+ "gpt-6-sol",
15
+ "gpt-6-luna",
16
+ "gpt-6.1-sol",
17
+ ];
6
18
  export interface NotesSettings {
19
+ active: "all" | "whitelist";
20
+ modelWhitelist: string[];
7
21
  normalCompaction: boolean;
22
+ newWindowRequests: NewWindowRequests;
8
23
  idleMinutes: IdleMinutes;
24
+ taskBoundaryReminder: number;
9
25
  }
10
26
 
11
27
  export function readSettings(path: string): NotesSettings {
@@ -14,7 +30,14 @@ export function readSettings(path: string): NotesSettings {
14
30
  source = readFileSync(path, "utf8");
15
31
  } catch (error) {
16
32
  if ((error as NodeJS.ErrnoException).code === "ENOENT")
17
- return { normalCompaction: false, idleMinutes: 0 };
33
+ return {
34
+ active: "all",
35
+ modelWhitelist: [...DEFAULT_MODEL_WHITELIST],
36
+ normalCompaction: false,
37
+ newWindowRequests: "unrestricted",
38
+ idleMinutes: 0,
39
+ taskBoundaryReminder: 0,
40
+ };
18
41
  throw error;
19
42
  }
20
43
  const settings: unknown = JSON.parse(source);
@@ -27,17 +50,65 @@ export function readSettings(path: string): NotesSettings {
27
50
  throw new Error(
28
51
  "Invalid notes settings. Save a setting in /notes, then reload Pi.",
29
52
  );
53
+ const active = "active" in settings ? settings.active : "all";
54
+ if (active !== "all" && active !== "whitelist")
55
+ throw new Error(
56
+ `Invalid active setting in ${path}. Use "all" or "whitelist", then reload Pi.`,
57
+ );
58
+ const modelWhitelist =
59
+ "modelWhitelist" in settings
60
+ ? settings.modelWhitelist
61
+ : [...DEFAULT_MODEL_WHITELIST];
62
+ if (
63
+ !Array.isArray(modelWhitelist) ||
64
+ !modelWhitelist.every((id): id is string => typeof id === "string")
65
+ )
66
+ throw new Error(
67
+ `Invalid modelWhitelist in ${path}. Use an array of model ID strings, then reload Pi.`,
68
+ );
30
69
  const idleMinutes = "idleMinutes" in settings ? settings.idleMinutes : 0;
70
+ const newWindowRequests =
71
+ "newWindowRequests" in settings
72
+ ? settings.newWindowRequests
73
+ : "unrestricted";
74
+ if (!NEW_WINDOW_REQUESTS.some((value) => value === newWindowRequests))
75
+ throw new Error(
76
+ "Invalid new window requests setting. Choose off, pi-limits or unrestricted in /notes.",
77
+ );
78
+ const taskBoundaryReminder =
79
+ "taskBoundaryReminder" in settings ? settings.taskBoundaryReminder : 0;
80
+ if (
81
+ typeof taskBoundaryReminder !== "number" ||
82
+ !Number.isSafeInteger(taskBoundaryReminder) ||
83
+ taskBoundaryReminder < 0
84
+ )
85
+ throw new Error(
86
+ "Invalid task-boundary reminder setting. Save a setting in /notes, then reload Pi.",
87
+ );
31
88
  if (!IDLE_MINUTES.some((value) => value === idleMinutes))
32
89
  throw new Error(
33
90
  "Invalid idle rollover interval. Choose off, 5, 15, 25 or 55 minutes.",
34
91
  );
35
92
  return {
93
+ active,
94
+ modelWhitelist,
36
95
  normalCompaction: settings.normalCompaction,
96
+ newWindowRequests: newWindowRequests as NewWindowRequests,
37
97
  idleMinutes: idleMinutes as IdleMinutes,
98
+ taskBoundaryReminder,
38
99
  };
39
100
  }
40
101
 
102
+ export function modelIsActive(
103
+ settings: NotesSettings,
104
+ model?: { id: string },
105
+ ): boolean {
106
+ return (
107
+ settings.active === "all" ||
108
+ Boolean(model && settings.modelWhitelist.includes(model.id))
109
+ );
110
+ }
111
+
41
112
  export function writeSettings(path: string, settings: NotesSettings): void {
42
113
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
43
114
  const temporary = `${path}.${process.pid}.tmp`;
@@ -0,0 +1,377 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type {
3
+ ExtensionContext,
4
+ SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { type Static, Type } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { collectNotes, normalizeNoteParams, readNotes } from "./notes.js";
9
+ import {
10
+ readSavedNotesSession,
11
+ type SavedNotesSession,
12
+ } from "./saved-session.js";
13
+ import type { NotesStore } from "./store.js";
14
+
15
+ const Agent = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
16
+ const Identity = Type.Object({
17
+ protocol: Type.Literal(1),
18
+ sessionId: Type.String(),
19
+ threadId: Type.String(),
20
+ agentName: Agent,
21
+ storage: Type.Optional(
22
+ Type.Union([Type.Literal("session"), Type.Literal("remote")]),
23
+ ),
24
+ routing: Type.Optional(Type.Unknown()),
25
+ });
26
+ const Member = Type.Object({
27
+ threadId: Type.String(),
28
+ sessionId: Type.String(),
29
+ agentName: Agent,
30
+ machine: Type.String(),
31
+ sessionFile: Type.String(),
32
+ });
33
+ const Plan = Type.Object({
34
+ controllerSessionId: Type.String(),
35
+ targetSessionId: Type.String(),
36
+ context: Type.Optional(
37
+ Type.Object({
38
+ controller: Identity,
39
+ target: Identity,
40
+ alias: Agent,
41
+ controllerAlias: Agent,
42
+ controllerFile: Type.Optional(Type.String()),
43
+ controllerNotes: Type.Unknown(),
44
+ targetNotes: Type.Unknown(),
45
+ }),
46
+ ),
47
+ });
48
+ const Route = Type.Object({
49
+ plan: Plan,
50
+ machine: Type.String(),
51
+ sessionFile: Type.String(),
52
+ phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
53
+ detached: Type.Optional(
54
+ Type.Object({ context: Type.Optional(Type.Unknown()) }),
55
+ ),
56
+ });
57
+ const Detachment = Type.Object({
58
+ plan: Plan,
59
+ context: Type.Optional(Type.Unknown()),
60
+ });
61
+ const Snapshot = Type.Object({
62
+ protocol: Type.Literal(1),
63
+ timestamp: Type.Number(),
64
+ files: Type.Array(
65
+ Type.Object({
66
+ path: Type.String(),
67
+ text: Type.String(),
68
+ createdAt: Type.Number(),
69
+ updatedAt: Type.Number(),
70
+ operation: Type.Union([
71
+ Type.Literal("local_append_overlay"),
72
+ Type.Literal("local_replacement"),
73
+ ]),
74
+ }),
75
+ ),
76
+ });
77
+ const Parent = Type.Object({
78
+ transport: Type.Literal("shepherdr"),
79
+ parent: Type.String(),
80
+ });
81
+ type Identity = Static<typeof Identity>;
82
+
83
+ function records(session: SavedNotesSession, kind: string): unknown[] {
84
+ return session.entries.flatMap((entry) =>
85
+ entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
86
+ );
87
+ }
88
+
89
+ /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
90
+ export function savedNotesIdentity(
91
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
92
+ ): Identity {
93
+ let found: Identity | undefined;
94
+ for (const entry of session.entries) {
95
+ if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
96
+ continue;
97
+ if (!Check(Identity, entry.data))
98
+ throw new Error("Invalid saved notes identity");
99
+ if (entry.data.threadId !== session.threadId) continue;
100
+ if (found) throw new Error("Conflicting saved notes identities");
101
+ found = entry.data;
102
+ }
103
+ return (
104
+ found ?? {
105
+ protocol: 1,
106
+ threadId: session.threadId,
107
+ sessionId: session.threadId,
108
+ agentName: "/root",
109
+ }
110
+ );
111
+ }
112
+
113
+ function sameOwner(a: Identity, b: Identity): boolean {
114
+ return (
115
+ a.threadId === b.threadId &&
116
+ a.sessionId === b.sessionId &&
117
+ a.agentName === b.agentName
118
+ );
119
+ }
120
+ function inside(path: string, root: string): boolean {
121
+ return path === root || path.startsWith(`${root}/`);
122
+ }
123
+ function remap(
124
+ params: Record<string, unknown>,
125
+ from: string,
126
+ to: string,
127
+ ): Record<string, unknown> {
128
+ return Object.fromEntries(
129
+ Object.entries(params).map(([key, value]) => [
130
+ key,
131
+ ["path", "prefix", "path_prefix"].includes(key) &&
132
+ typeof value === "string" &&
133
+ inside(value, from)
134
+ ? `${to}${value.slice(from.length)}`
135
+ : value,
136
+ ]),
137
+ );
138
+ }
139
+
140
+ export function sharedNotesUnavailable(error: unknown): boolean {
141
+ return (
142
+ error instanceof Error &&
143
+ /^(Cross-agent (?:context requires an available context router|notes (?:are unavailable here|owner is unavailable))|Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
144
+ error.message,
145
+ )
146
+ );
147
+ }
148
+
149
+ /** Saved local notes do not need PCC, a router, or a running owner. Writes still belong to the live session. */
150
+ export async function readSharedNotes(
151
+ ctx: ExtensionContext,
152
+ store: Pick<NotesStore, "read">,
153
+ params: Record<string, unknown>,
154
+ signal?: AbortSignal,
155
+ ): Promise<Record<string, unknown> | undefined> {
156
+ if (
157
+ !["read_file", "list_files_by_prefix", "search_contents"].includes(
158
+ String(params["action"]),
159
+ )
160
+ )
161
+ return;
162
+ const path = params["path"] ?? params["prefix"] ?? params["path_prefix"];
163
+ if (typeof path !== "string" || !path.startsWith("/")) return;
164
+ const target = /^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(
165
+ path,
166
+ )?.[1];
167
+ if (!target) return;
168
+ const outputAgent = target;
169
+ const current: SavedNotesSession = {
170
+ threadId: ctx.sessionManager.getSessionId(),
171
+ entries: ctx.sessionManager.getEntries(),
172
+ branch: ctx.sessionManager.getBranch(),
173
+ };
174
+ if (savedNotesIdentity(current).agentName === target) return;
175
+ const visited = new Set<string>();
176
+
177
+ function read(
178
+ session: SavedNotesSession,
179
+ query: Record<string, unknown>,
180
+ native: string,
181
+ ) {
182
+ return {
183
+ ...readNotes(
184
+ collectNotes(store, session.branch),
185
+ normalizeNoteParams(query, native),
186
+ outputAgent,
187
+ ),
188
+ source: "saved-session",
189
+ read_only: true,
190
+ remote: { state: "not_fetched" },
191
+ ...(session.savedAt === undefined
192
+ ? {}
193
+ : { saved_at: new Date(session.savedAt).toISOString() }),
194
+ };
195
+ }
196
+ async function reference(
197
+ identity: Identity,
198
+ destination: string,
199
+ query: Record<string, unknown>,
200
+ file: string | undefined,
201
+ retained?: unknown,
202
+ detached = false,
203
+ ): Promise<Record<string, unknown> | undefined> {
204
+ if (file && !detached) {
205
+ let saved: SavedNotesSession | undefined;
206
+ try {
207
+ saved = await readSavedNotesSession(file, signal);
208
+ } catch (error) {
209
+ signal?.throwIfAborted();
210
+ if (
211
+ !(
212
+ error instanceof Error &&
213
+ "code" in error &&
214
+ error.code === "ENOENT" &&
215
+ retained !== undefined
216
+ )
217
+ )
218
+ throw error;
219
+ }
220
+ if (saved) {
221
+ if (!sameOwner(savedNotesIdentity(saved), identity))
222
+ throw new Error("Saved shared notes belong to a different session");
223
+ return resolve(saved, destination, query);
224
+ }
225
+ }
226
+ if (destination !== identity.agentName || !Check(Snapshot, retained))
227
+ return;
228
+ const entry: SessionEntry = {
229
+ type: "custom",
230
+ id: "retained",
231
+ parentId: null,
232
+ timestamp: new Date(retained.timestamp).toISOString(),
233
+ customType: "codex-context-note-snapshot",
234
+ data: {
235
+ ...retained,
236
+ files: retained.files.filter((file) =>
237
+ file.path.startsWith(`${identity.agentName}/notes/`),
238
+ ),
239
+ },
240
+ };
241
+ return {
242
+ ...read(
243
+ { threadId: identity.threadId, entries: [], branch: [entry] },
244
+ query,
245
+ identity.agentName,
246
+ ),
247
+ source: "retained-checkpoints",
248
+ captured_at: new Date(retained.timestamp).toISOString(),
249
+ ...(detached ? { detached: true } : { stale: true }),
250
+ };
251
+ }
252
+ async function resolve(
253
+ session: SavedNotesSession,
254
+ destination: string,
255
+ query: Record<string, unknown>,
256
+ ): Promise<Record<string, unknown> | undefined> {
257
+ signal?.throwIfAborted();
258
+ if (visited.has(session.threadId)) return;
259
+ visited.add(session.threadId);
260
+ const identity = savedNotesIdentity(session);
261
+ if (identity.agentName === destination) {
262
+ if (
263
+ identity.storage === "remote" &&
264
+ !session.branch.some(
265
+ (entry) =>
266
+ entry.type === "custom" &&
267
+ entry.customType === "notes-compaction:note:v1",
268
+ )
269
+ )
270
+ return;
271
+ return read(session, query, identity.agentName);
272
+ }
273
+ const routes = new Map<string, Static<typeof Route>>();
274
+ for (const value of records(session, "shepherdr-attachment-route"))
275
+ if (
276
+ Check(Route, value) &&
277
+ value.plan.controllerSessionId === identity.threadId
278
+ )
279
+ routes.set(`${value.machine}\0${value.sessionFile}`, value);
280
+ for (const route of routes.values()) {
281
+ const link = route.plan.context;
282
+ if (route.phase !== "ready" || !link || !inside(destination, link.alias))
283
+ continue;
284
+ if (!sameOwner(identity, link.controller))
285
+ throw new Error("Saved shared notes identity changed");
286
+ return reference(
287
+ link.target,
288
+ `${link.target.agentName}${destination.slice(link.alias.length)}`,
289
+ remap(query, link.alias, link.target.agentName),
290
+ route.machine === "local" ? route.sessionFile : undefined,
291
+ route.detached?.context ?? link.targetNotes,
292
+ route.detached?.context !== undefined,
293
+ );
294
+ }
295
+ const owner = records(session, "shepherdr-attachment-owner").findLast(
296
+ (value) =>
297
+ Check(Plan, value) && value.targetSessionId === identity.threadId,
298
+ );
299
+ if (
300
+ Check(Plan, owner) &&
301
+ owner.context &&
302
+ inside(destination, owner.context.controllerAlias)
303
+ ) {
304
+ const link = owner.context;
305
+ if (!sameOwner(identity, link.target))
306
+ throw new Error("Saved shared notes identity changed");
307
+ const detached = records(
308
+ session,
309
+ "shepherdr-attachment-detached",
310
+ ).findLast(
311
+ (value) =>
312
+ Check(Detachment, value) && isDeepStrictEqual(value.plan, owner),
313
+ );
314
+ const snapshot = Check(Detachment, detached)
315
+ ? detached.context
316
+ : undefined;
317
+ return reference(
318
+ link.controller,
319
+ `${link.controller.agentName}${destination.slice(link.controllerAlias.length)}`,
320
+ remap(query, link.controllerAlias, link.controller.agentName),
321
+ link.controllerFile,
322
+ snapshot ?? link.controllerNotes,
323
+ snapshot !== undefined,
324
+ );
325
+ }
326
+ const member = records(session, "herdr-context-child").findLast(
327
+ (value) =>
328
+ Check(Member, value) &&
329
+ value.threadId === identity.threadId &&
330
+ value.sessionId === identity.sessionId &&
331
+ inside(destination, value.agentName),
332
+ );
333
+ if (Check(Member, member)) {
334
+ if (member.machine !== "local") return;
335
+ const saved = await readSavedNotesSession(member.sessionFile, signal);
336
+ const child = savedNotesIdentity(saved);
337
+ if (
338
+ child.sessionId !== identity.sessionId ||
339
+ child.agentName !== member.agentName
340
+ )
341
+ throw new Error(
342
+ "Saved shared notes belong to a different agent family",
343
+ );
344
+ return resolve(saved, destination, query);
345
+ }
346
+ const routing = identity.routing;
347
+ const suffix = ".jsonl.shepherdr-context.json";
348
+ if (Check(Parent, routing) && routing.parent.endsWith(suffix)) {
349
+ const saved = await readSavedNotesSession(
350
+ routing.parent.slice(0, -".shepherdr-context.json".length),
351
+ signal,
352
+ );
353
+ const parent = savedNotesIdentity(saved);
354
+ if (
355
+ parent.sessionId !== identity.sessionId ||
356
+ !identity.agentName.startsWith(`${parent.agentName}/`)
357
+ )
358
+ throw new Error("Saved shared notes parent identity changed");
359
+ return resolve(saved, destination, query);
360
+ }
361
+ return undefined;
362
+ }
363
+ try {
364
+ return await resolve(current, target, params);
365
+ } catch (error) {
366
+ if (
367
+ error instanceof Error &&
368
+ "code" in error &&
369
+ ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
370
+ )
371
+ throw new Error(
372
+ "Saved shared notes are unavailable on this machine. Restore access to the saved session, then retry.",
373
+ { cause: error },
374
+ );
375
+ throw error;
376
+ }
377
+ }
@@ -0,0 +1,32 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export function renderTaskBoundaryReminder(remainingPercent: number): string {
4
+ return `<context_window_reminder>\nSuggested context budget reached; ${remainingPercent}% remains. For a sequence of tasks, finish the current task, save notes and call new_context before the next. Otherwise, continue here.\n</context_window_reminder>`;
5
+ }
6
+
7
+ export const TASK_BOUNDARY_PRESETS = [
8
+ 0, 250_000, 300_000, 400_000, 450_000,
9
+ ] as const;
10
+ export function taskBoundaryLabel(tokens: number): string {
11
+ return tokens === 0
12
+ ? "off"
13
+ : TASK_BOUNDARY_PRESETS.some((value) => value === tokens)
14
+ ? `${tokens / 1000}k`
15
+ : "custom (edit JSON)";
16
+ }
17
+ export function taskBoundaryEligible(
18
+ ctx: ExtensionContext,
19
+ threshold: number,
20
+ tokens = ctx.getContextUsage()?.tokens,
21
+ ): boolean {
22
+ const capacity =
23
+ ctx.getContextUsage()?.contextWindow ?? ctx.model?.contextWindow ?? 0;
24
+ return (
25
+ threshold > 0 &&
26
+ Number.isFinite(capacity) &&
27
+ capacity > 272_000 &&
28
+ typeof tokens === "number" &&
29
+ Number.isFinite(tokens) &&
30
+ tokens >= threshold
31
+ );
32
+ }
package/src/tools.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  sourceSessionIds,
25
25
  useNotes,
26
26
  } from "./notes.js";
27
+ import { readSharedNotes, sharedNotesUnavailable } from "./shared-notes.js";
27
28
  import type { NotesStore } from "./store.js";
28
29
 
29
30
  const NOTES_ACTIONS = [
@@ -41,7 +42,8 @@ const HISTORY_ACTIONS = [
41
42
  "read_item",
42
43
  "search_contents",
43
44
  ] as const;
44
- export const NOTES_USAGE = "await tools.notes() // help";
45
+ export const NOTES_USAGE =
46
+ "await tools.notes({ action, ...args }) // no args: help; actions(required args): list_files_by_prefix(); read_file(path); search_contents(query); append_to_file(path,text); write_file(path,text)";
45
47
  export const HISTORY_USAGE = "await tools.history() // help";
46
48
  const STRING = Type.Optional(Type.String());
47
49
  const INTEGER = Type.Optional(Type.Integer({ minimum: 1 }));
@@ -222,8 +224,7 @@ function discovery(
222
224
  ),
223
225
  ...(namespace === "notes"
224
226
  ? {
225
- usage:
226
- 'await tools.notes({ action: "read_file", path: "checkpoint" })',
227
+ usage: '{ "action": "read_file", "path": "checkpoint" }',
227
228
  ranges:
228
229
  "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",
229
230
  defaults:
@@ -347,7 +348,9 @@ function createQueryExecutor(
347
348
  ) {
348
349
  const assertActive = () => {
349
350
  if (!lifecycle.active)
350
- throw new Error("Notes continuity is unavailable in this session");
351
+ throw new Error(
352
+ "Notes tools are inactive. Ask the user to check /notes.",
353
+ );
351
354
  };
352
355
  async function notes(
353
356
  callId: string,
@@ -359,15 +362,25 @@ function createQueryExecutor(
359
362
  if (help) return help;
360
363
  assertActive();
361
364
  const raw = relevant("notes", input);
362
- const routed =
363
- !shared &&
364
- (await lifecycle.bridge?.route?.(
365
- { namespace: "notes", params: raw },
366
- callId,
367
- ctx,
368
- signal,
369
- ));
370
- if (routed) return routed;
365
+ if (!shared) {
366
+ try {
367
+ const routed = await lifecycle.bridge?.route?.(
368
+ { namespace: "notes", params: raw },
369
+ callId,
370
+ ctx,
371
+ signal,
372
+ );
373
+ if (routed) return routed;
374
+ } catch (error) {
375
+ signal?.throwIfAborted();
376
+ if (!sharedNotesUnavailable(error)) throw error;
377
+ const saved = await readSharedNotes(ctx, store, raw, signal);
378
+ if (saved) return result(saved);
379
+ throw error;
380
+ }
381
+ const saved = await readSharedNotes(ctx, store, raw, signal);
382
+ if (saved) return result(saved);
383
+ }
371
384
  const params = relevant(
372
385
  "notes",
373
386
  normalizeNoteParams(raw, lifecycle.agent(ctx)),
@@ -508,7 +521,9 @@ export function createTools(
508
521
  ): ToolDefinition[] {
509
522
  const assertActive = () => {
510
523
  if (!lifecycle.active)
511
- throw new Error("Notes continuity is unavailable in this session");
524
+ throw new Error(
525
+ "Notes tools are inactive. Ask the user to check /notes.",
526
+ );
512
527
  };
513
528
  const queries = createQueryExecutor(pi, store, lifecycle);
514
529
  return [
@@ -516,16 +531,24 @@ export function createTools(
516
531
  name: "notes",
517
532
  label: "notes",
518
533
  description:
519
- "Cross-window notes. write_file replaces; append_to_file adds. Virtual paths: relative uses current agent; cross-agent uses <agent>/notes[/path].",
534
+ "Persistent notes. write_file replaces; append_to_file adds. Virtual paths: relative uses current agent; cross-agent uses <agent>/notes[/path].",
520
535
  parameters: NOTES_SCHEMA,
521
536
  executionMode: "sequential",
522
537
  prepareArguments(args) {
523
538
  if (args === undefined) return {};
524
539
  if (!args || typeof args !== "object" || Array.isArray(args))
525
540
  throw new Error(
526
- 'Supply an action object: await tools.notes({ action: "read_file", path: "checkpoint" }); tools.notes() returns help',
541
+ 'Supply an action object, e.g. { "action": "read_file", "path": "checkpoint" }. Use {} for help',
527
542
  );
528
543
  const params = { ...args } as Record<string, unknown>;
544
+ if (
545
+ (params["action"] === "write_file" ||
546
+ params["action"] === "append_to_file") &&
547
+ "content" in params
548
+ ) {
549
+ if (!("text" in params)) params["text"] = params["content"];
550
+ delete params["content"];
551
+ }
529
552
  if (
530
553
  params["action"] === "list_files_by_prefix" &&
531
554
  params["max_files"] !== undefined
@@ -542,7 +565,7 @@ export function createTools(
542
565
  ];
543
566
  if (!schema || !Check(schema, value))
544
567
  throw new Error(
545
- `Invalid notes ${field}; call tools.notes() for exact arguments`,
568
+ `Invalid notes ${field}; use {} for exact arguments`,
546
569
  );
547
570
  }
548
571
  return params;
@@ -554,7 +577,7 @@ export function createTools(
554
577
  name: "history",
555
578
  label: "history",
556
579
  description:
557
- "Prior-window detail. Pass IDs unchanged. Search, never browse",
580
+ "Search earlier conversation, don't browse it. Pass returned IDs unchanged",
558
581
  parameters: HISTORY_SCHEMA,
559
582
  prepareArguments(args) {
560
583
  return args === undefined ? {} : args;
@@ -565,22 +588,23 @@ export function createTools(
565
588
  {
566
589
  name: "new_context",
567
590
  label: "new_context",
568
- description: "Start a new context window",
591
+ description:
592
+ "Start fresh from saved notes; recover earlier conversation through history",
569
593
  parameters: Type.Object({}, { additionalProperties: false }),
570
594
  exposure: "model-only",
571
595
  executionMode: "sequential",
572
- async execute(_id, _input, signal, _update, ctx) {
596
+ async execute(id, _input, signal, _update, ctx) {
573
597
  assertActive();
574
598
  if (signal?.aborted) throw new Error("Rollover cancelled");
575
- const started = lifecycle.requestRollover(ctx);
599
+ const started = lifecycle.requestRollover(ctx, id);
576
600
  if (started) ctx.abort();
577
601
  return {
578
602
  ...result({
579
603
  started,
580
604
  message: started
581
- ? lifecycle.normalCompaction
582
- ? "Normal compaction will run before the new window opens"
583
- : "A new window will continue from your notes after this run settles"
605
+ ? lifecycle.newWindowRequests === "pi-limits"
606
+ ? "Window request queued. Pi will check whether enough history can be compacted"
607
+ : "A new window will open after this run settles"
584
608
  : "A checkpoint or rollover is already pending. Save notes and finish your response",
585
609
  }),
586
610
  ...(started ? { terminate: true } : {}),