@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.
@@ -14,7 +14,13 @@ import {
14
14
  sharedNotesUnavailable,
15
15
  } from "./shared-notes.js";
16
16
  import type { NotesStore } from "./store.js";
17
- import { queryArguments, queryHelp, result } from "./tool-contracts.js";
17
+ import {
18
+ prepareHistoryArguments,
19
+ prepareNotesArguments,
20
+ queryArguments,
21
+ queryHelp,
22
+ result,
23
+ } from "./tool-contracts.js";
18
24
 
19
25
  export function createQueryExecutor(
20
26
  pi: ExtensionAPI,
@@ -35,7 +41,8 @@ export function createQueryExecutor(
35
41
  signal: AbortSignal | undefined,
36
42
  ctx: ExtensionContext,
37
43
  ): Promise<AgentToolResult<unknown>> {
38
- const help = queryHelp("notes", input);
44
+ input = prepareNotesArguments(input, true);
45
+ const help = queryHelp("notes", input, false, lifecycle.gptPromptMode());
39
46
  if (help) return help;
40
47
  assertActive();
41
48
  const raw = queryArguments("notes", input);
@@ -127,6 +134,7 @@ export function createQueryExecutor(
127
134
  signal: AbortSignal | undefined,
128
135
  ctx: ExtensionContext,
129
136
  ): Promise<AgentToolResult<unknown>> {
137
+ input = prepareHistoryArguments(input);
130
138
  const help = queryHelp(
131
139
  "history",
132
140
  input,
@@ -0,0 +1,115 @@
1
+ import type { LookupQuery } from "./bridge.js";
2
+
3
+ const ACTIONS: Record<LookupQuery["namespace"], Record<string, string>> = {
4
+ notes: {
5
+ list_files_by_prefix: "list",
6
+ read_file: "read",
7
+ search_contents: "search",
8
+ append_to_file: "append",
9
+ write_file: "write",
10
+ },
11
+ history: { list_items: "list", read_item: "read", search_contents: "search" },
12
+ };
13
+ const HINTS = [
14
+ "limit",
15
+ "max_results",
16
+ "max_files",
17
+ "max_matches_per_file",
18
+ "file_order",
19
+ "file_order_by",
20
+ "recent_file_first",
21
+ "recent_first",
22
+ "limit_chars",
23
+ "max_chars_per_item",
24
+ ];
25
+ const PRESENTATION: Record<string, readonly string[]> = {
26
+ "notes:list": ["limit", "file_order", "file_order_by"],
27
+ "notes:search": ["limit", "max_matches_per_file", "recent_file_first"],
28
+ "notes:read": ["start_line", "stop_line"],
29
+ "history:list_windows": ["limit", "recent_first"],
30
+ "history:list": ["limit", "recent_first", "max_chars_per_item"],
31
+ "history:search": ["limit", "recent_first"],
32
+ "history:read": ["limit_chars", "offset_chars"],
33
+ };
34
+
35
+ function alias(params: Record<string, unknown>, from: string, to: string) {
36
+ if (!(from in params)) return;
37
+ if (to in params && params[to] !== params[from])
38
+ throw new Error(`Conflicting ${to} and ${from}; supply only ${to}`);
39
+ params[to] = params[from];
40
+ delete params[from];
41
+ }
42
+
43
+ /** Accept familiar spellings without adding competing names to discovery. */
44
+ export function normalizeQueryInput(
45
+ namespace: LookupQuery["namespace"],
46
+ input: unknown,
47
+ ): Record<string, unknown> {
48
+ if (input === undefined) return {};
49
+ if (typeof input === "string") {
50
+ try {
51
+ input = JSON.parse(input);
52
+ } catch {
53
+ throw new Error(
54
+ "Supply an action object or valid JSON object; use {} for help",
55
+ );
56
+ }
57
+ }
58
+ if (!input || typeof input !== "object" || Array.isArray(input))
59
+ throw new Error("Supply an action object; use {} for help");
60
+ const params = { ...input } as Record<string, unknown>;
61
+ const action =
62
+ ACTIONS[namespace][String(params["action"])] ?? params["action"];
63
+ if (action !== undefined) params["action"] = action;
64
+ if (namespace === "notes") {
65
+ if (action === "write" || action === "append")
66
+ alias(params, "content", "text");
67
+ if (action === "list" || action === "search") {
68
+ alias(params, "prefix", "path");
69
+ alias(params, "path_prefix", "path");
70
+ alias(params, "max_results", "limit");
71
+ alias(params, "max_files", "limit");
72
+ if (action === "search")
73
+ alias(params, "recent_first", "recent_file_first");
74
+ }
75
+ } else if (["list", "search", "list_windows"].includes(String(action))) {
76
+ alias(params, "max_results", "limit");
77
+ }
78
+ const used = PRESENTATION[`${namespace}:${String(action)}`] ?? [];
79
+ for (const hint of HINTS) if (!used.includes(hint)) delete params[hint];
80
+ return params;
81
+ }
82
+
83
+ /** Keep persisted sharing requests and backend endpoint names unchanged. */
84
+ export function internalQueryArguments(
85
+ namespace: LookupQuery["namespace"],
86
+ input: Record<string, unknown>,
87
+ ) {
88
+ const params = { ...input };
89
+ const action = params["action"];
90
+ params["action"] =
91
+ Object.entries(ACTIONS[namespace]).find(
92
+ ([, value]) => value === action,
93
+ )?.[0] ?? action;
94
+ if (namespace === "notes") {
95
+ if (action === "list" || action === "search") {
96
+ alias(params, "path", action === "list" ? "prefix" : "path_prefix");
97
+ alias(params, "limit", action === "list" ? "max_results" : "max_files");
98
+ }
99
+ }
100
+ return params;
101
+ }
102
+
103
+ export function isNoteWrite(input: unknown): boolean {
104
+ try {
105
+ if (typeof input === "string") input = JSON.parse(input);
106
+ if (!input || typeof input !== "object" || !("action" in input))
107
+ return false;
108
+ // Failed write attempts still invalidate freshness; do not validate their fields here.
109
+ return ["write", "append", "write_file", "append_to_file"].includes(
110
+ String(input.action),
111
+ );
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
@@ -0,0 +1,103 @@
1
+ import { type Static, Type } from "typebox";
2
+ import { Check } from "typebox/value";
3
+ import type { SavedNotesSession } from "./saved-session.js";
4
+
5
+ const Agent = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
6
+ export const Identity = Type.Object({
7
+ protocol: Type.Literal(1),
8
+ sessionId: Type.String(),
9
+ threadId: Type.String(),
10
+ agentName: Agent,
11
+ storage: Type.Optional(
12
+ Type.Union([Type.Literal("session"), Type.Literal("remote")]),
13
+ ),
14
+ routing: Type.Optional(Type.Unknown()),
15
+ });
16
+ export const Member = Type.Object({
17
+ threadId: Type.String(),
18
+ sessionId: Type.String(),
19
+ agentName: Agent,
20
+ machine: Type.String(),
21
+ sessionFile: Type.String(),
22
+ });
23
+ export const Plan = Type.Object({
24
+ controllerSessionId: Type.String(),
25
+ targetSessionId: Type.String(),
26
+ context: Type.Optional(
27
+ Type.Object({
28
+ controller: Identity,
29
+ target: Identity,
30
+ alias: Agent,
31
+ controllerAlias: Agent,
32
+ controllerFile: Type.Optional(Type.String()),
33
+ controllerNotes: Type.Unknown(),
34
+ targetNotes: Type.Unknown(),
35
+ }),
36
+ ),
37
+ });
38
+ export const Route = Type.Object({
39
+ plan: Plan,
40
+ machine: Type.String(),
41
+ sessionFile: Type.String(),
42
+ phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
43
+ detached: Type.Optional(
44
+ Type.Object({ context: Type.Optional(Type.Unknown()) }),
45
+ ),
46
+ });
47
+ export const Detachment = Type.Object({
48
+ plan: Plan,
49
+ context: Type.Optional(Type.Unknown()),
50
+ });
51
+ export const Snapshot = Type.Object({
52
+ protocol: Type.Literal(1),
53
+ timestamp: Type.Number(),
54
+ files: Type.Array(
55
+ Type.Object({
56
+ path: Type.String(),
57
+ text: Type.String(),
58
+ createdAt: Type.Number(),
59
+ updatedAt: Type.Number(),
60
+ operation: Type.Union([
61
+ Type.Literal("local_append_overlay"),
62
+ Type.Literal("local_replacement"),
63
+ ]),
64
+ }),
65
+ ),
66
+ });
67
+ export const Parent = Type.Object({
68
+ transport: Type.Literal("shepherdr"),
69
+ parent: Type.String(),
70
+ });
71
+ export type Identity = Static<typeof Identity>;
72
+
73
+ /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
74
+ export function savedNotesIdentity(
75
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
76
+ ): Identity {
77
+ let found: Identity | undefined;
78
+ for (const entry of session.entries) {
79
+ if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
80
+ continue;
81
+ if (!Check(Identity, entry.data))
82
+ throw new Error("Invalid saved notes identity");
83
+ if (entry.data.threadId !== session.threadId) continue;
84
+ if (found) throw new Error("Conflicting saved notes identities");
85
+ found = entry.data;
86
+ }
87
+ return (
88
+ found ?? {
89
+ protocol: 1,
90
+ threadId: session.threadId,
91
+ sessionId: session.threadId,
92
+ agentName: "/root",
93
+ }
94
+ );
95
+ }
96
+
97
+ export function sameOwner(a: Identity, b: Identity): boolean {
98
+ return (
99
+ a.threadId === b.threadId &&
100
+ a.sessionId === b.sessionId &&
101
+ a.agentName === b.agentName
102
+ );
103
+ }
@@ -1,7 +1,11 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionCommandContext,
4
+ } from "@earendil-works/pi-coding-agent";
2
5
  import type { NotesActivation } from "./activation.js";
3
6
  import type { HistorySearch } from "./history-search.js";
4
7
  import type { NotesLifecycle } from "./lifecycle.js";
8
+ import type { createModelRoles } from "./model-roles.js";
5
9
  import { sessionRef } from "./notes.js";
6
10
  import type { SessionPruning } from "./session-pruning.js";
7
11
  import type { NotesSettings } from "./settings.js";
@@ -16,13 +20,17 @@ export function registerNotesSettingsCommand(
16
20
  search: HistorySearch,
17
21
  settingsPath: string,
18
22
  sessionPruning: SessionPruning,
23
+ roles: ReturnType<typeof createModelRoles>,
19
24
  ): void {
20
- pi.registerCommand("notes", {
21
- description: "Manage local notes and context rollover",
22
- handler: async (args, ctx) => {
23
- if (args.trim()) {
24
- ctx.ui.notify("Use /notes to open settings.", "info");
25
- return;
25
+ const open = async (
26
+ ctx: ExtensionCommandContext,
27
+ initial: "notes" | "roles",
28
+ ) => {
29
+ let tab = initial;
30
+ while (true) {
31
+ if (tab === "roles") {
32
+ if ((await roles.command("", ctx)) !== "notes") return;
33
+ tab = "notes";
26
34
  }
27
35
  if (!ctx.hasUI) {
28
36
  ctx.ui.notify("Notes settings require interactive Pi.", "warning");
@@ -44,7 +52,7 @@ export function registerNotesSettingsCommand(
44
52
  );
45
53
  };
46
54
  try {
47
- await openNotesSettings(ctx, {
55
+ const next = await openNotesSettings(ctx, {
48
56
  settings: () => activation.settings,
49
57
  save,
50
58
  settingsPath,
@@ -69,9 +77,32 @@ export function registerNotesSettingsCommand(
69
77
  ];
70
78
  },
71
79
  });
80
+ if (next !== "roles") return;
81
+ tab = "roles";
72
82
  } catch (error) {
73
83
  ctx.ui.notify(`Notes settings failed: ${String(error)}`, "error");
84
+ return;
85
+ }
86
+ }
87
+ };
88
+ pi.registerCommand("notes", {
89
+ description: "Manage local notes and context rollover",
90
+ handler: async (args, ctx) => {
91
+ if (args.trim()) {
92
+ ctx.ui.notify("Use /notes to open settings.", "info");
93
+ return;
94
+ }
95
+ await open(ctx, "notes");
96
+ },
97
+ });
98
+ pi.registerCommand("roles", {
99
+ description: "Configure model roles and in-conversation handoffs",
100
+ handler: async (args, ctx) => {
101
+ if (args.trim()) {
102
+ await roles.command(args, ctx);
103
+ return;
74
104
  }
105
+ await open(ctx, "roles");
75
106
  },
76
107
  });
77
108
  }
@@ -0,0 +1,209 @@
1
+ import {
2
+ type ExtensionContext,
3
+ getSettingsListTheme,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { SettingsList } from "@earendil-works/pi-tui";
6
+ import {
7
+ IDLE_MINUTES,
8
+ NEW_WINDOW_REQUESTS,
9
+ type NotesSettings,
10
+ } from "./settings.js";
11
+ import { TASK_BOUNDARY_PRESETS, taskBoundaryLabel } from "./task-boundary.js";
12
+
13
+ export function createNotesSettingsControls(
14
+ ctx: ExtensionContext,
15
+ options: {
16
+ settings: () => NotesSettings;
17
+ settingsPath: string;
18
+ save: (settings: NotesSettings) => void;
19
+ },
20
+ done: (action: "close" | "prune" | "sessionPruning") => void,
21
+ requestRender: () => void,
22
+ ) {
23
+ const settings = options.settings();
24
+ const idleValue = (minutes: number) =>
25
+ minutes === 0
26
+ ? "Off"
27
+ : minutes < 60
28
+ ? `${minutes}m`
29
+ : `${Math.ceil(minutes / 60)}h`;
30
+ const list = new SettingsList(
31
+ [
32
+ {
33
+ id: "sessionPruning",
34
+ label: "Session auto-pruning",
35
+ currentValue: "select…",
36
+ values: ["select…", "settings…"],
37
+ description:
38
+ "Per-session history limits and Run now. Memory savings require restarting Pi.",
39
+ },
40
+ {
41
+ id: "active",
42
+ label: "Active",
43
+ description: `Whitelist matches exact model IDs from any provider. Edit modelWhitelist in ${options.settingsPath}, then reload Pi. Example: ["gpt-6-luna", "gpt-6.1-sol"].`,
44
+ currentValue: settings.active === "all" ? "All models" : "Whitelist",
45
+ values: ["All models", "Whitelist"],
46
+ },
47
+ {
48
+ id: "sharing",
49
+ label: "Share subagent context",
50
+ description:
51
+ "Let new child agents share notes and history. Existing families remain connected when off.",
52
+ currentValue: settings.shareSubagentContext ? "on" : "off",
53
+ values: ["off", "on"],
54
+ },
55
+ {
56
+ id: "rankedHistorySearch",
57
+ label: "Ranked history search",
58
+ description:
59
+ "BM25 for earlier user messages and assistant replies. Skips current context and tool activity.",
60
+ currentValue: settings.rankedHistorySearch ? "on" : "off",
61
+ values: ["off", "on"],
62
+ },
63
+ {
64
+ id: "noteSaveMarkers",
65
+ label: "Note-save markers",
66
+ currentValue: settings.noteSaveMarkers ? "on" : "off",
67
+ values: ["off", "on"],
68
+ },
69
+ {
70
+ id: "compact",
71
+ label: "Normal compaction",
72
+ description:
73
+ "Use Pi/PCC compaction for /compact and new_context. Off uses notes-only rollover; /compact then waits for your next prompt.",
74
+ currentValue: settings.normalCompaction ? "on" : "off",
75
+ values: ["off", "on"],
76
+ },
77
+ {
78
+ id: "newWindowRequests",
79
+ label: "New window requests",
80
+ description:
81
+ "Off disables new_context. Pi-limits keeps the current window when Pi finds too little history to compact. Unrestricted accepts requests at any size. Normal compaction still chooses how windows roll over. Manual /compact and idle rollover are separate.",
82
+ currentValue: settings.newWindowRequests,
83
+ values: [...NEW_WINDOW_REQUESTS],
84
+ },
85
+ {
86
+ id: "taskBoundaryReminder",
87
+ label: "Task-boundary reminder",
88
+ description:
89
+ "Suggest a separate-task rollover after this many used tokens, only with active capacity above 272k. Custom: edit taskBoundaryReminder in the notes settings JSON (whole tokens); 0 is off.",
90
+ currentValue: taskBoundaryLabel(settings.taskBoundaryReminder),
91
+ values: [
92
+ ...TASK_BOUNDARY_PRESETS.map(taskBoundaryLabel),
93
+ "custom (edit JSON)",
94
+ ],
95
+ },
96
+ {
97
+ id: "idle",
98
+ label: "Idle rollover",
99
+ description:
100
+ "Roll over before the next input only with fresh notes from a completed turn. Not a cache-expiry guarantee.",
101
+ currentValue: idleValue(settings.idleMinutes),
102
+ values: IDLE_MINUTES.map(idleValue),
103
+ },
104
+ {
105
+ id: "prune",
106
+ label: "Prune missing sessions",
107
+ description:
108
+ "Remove notes, cached responses and history index entries for missing session files. Keeps the active session, unknown paths and inaccessible files. Confirmation required.",
109
+ currentValue: "select…",
110
+ values: ["select…", "prune…"],
111
+ },
112
+ ],
113
+ 5,
114
+ getSettingsListTheme(),
115
+ (id, value) => {
116
+ if (id === "sessionPruning") {
117
+ done("sessionPruning");
118
+ return;
119
+ }
120
+ if (id === "prune") {
121
+ done("prune");
122
+ return;
123
+ }
124
+ const current = options.settings();
125
+ if (id === "taskBoundaryReminder" && value === "custom (edit JSON)") {
126
+ ctx.ui.notify(
127
+ `Set taskBoundaryReminder to a positive whole token count in ${options.settingsPath}, then reload Pi. 0 is off.`,
128
+ "info",
129
+ );
130
+ list.updateValue(id, taskBoundaryLabel(current.taskBoundaryReminder));
131
+ return;
132
+ }
133
+ try {
134
+ if (id === "active")
135
+ options.save({
136
+ ...current,
137
+ active: value === "All models" ? "all" : "whitelist",
138
+ });
139
+ else if (id === "sharing")
140
+ options.save({
141
+ ...current,
142
+ shareSubagentContext: value === "on",
143
+ });
144
+ else if (id === "noteSaveMarkers")
145
+ options.save({ ...current, noteSaveMarkers: value === "on" });
146
+ else if (id === "rankedHistorySearch")
147
+ options.save({
148
+ ...current,
149
+ rankedHistorySearch: value === "on",
150
+ });
151
+ else if (id === "compact")
152
+ options.save({ ...current, normalCompaction: value === "on" });
153
+ else if (id === "newWindowRequests") {
154
+ const newWindowRequests = NEW_WINDOW_REQUESTS.find(
155
+ (mode) => mode === value,
156
+ );
157
+ if (newWindowRequests)
158
+ options.save({ ...current, newWindowRequests });
159
+ } else if (id === "taskBoundaryReminder")
160
+ options.save({
161
+ ...current,
162
+ taskBoundaryReminder:
163
+ TASK_BOUNDARY_PRESETS.find(
164
+ (tokens) => taskBoundaryLabel(tokens) === value,
165
+ ) ?? current.taskBoundaryReminder,
166
+ });
167
+ else {
168
+ const idleMinutes = IDLE_MINUTES.find(
169
+ (minutes) => idleValue(minutes) === value,
170
+ );
171
+ if (idleMinutes !== undefined)
172
+ options.save({ ...current, idleMinutes });
173
+ }
174
+ } catch (error) {
175
+ if (id === "rankedHistorySearch") {
176
+ list.updateValue(id, current.rankedHistorySearch ? "on" : "off");
177
+ } else
178
+ list.updateValue(
179
+ id,
180
+ id === "active"
181
+ ? current.active === "all"
182
+ ? "All models"
183
+ : "Whitelist"
184
+ : id === "taskBoundaryReminder"
185
+ ? taskBoundaryLabel(current.taskBoundaryReminder)
186
+ : id === "newWindowRequests"
187
+ ? current.newWindowRequests
188
+ : id === "noteSaveMarkers"
189
+ ? current.noteSaveMarkers
190
+ ? "on"
191
+ : "off"
192
+ : id === "compact"
193
+ ? current.normalCompaction
194
+ ? "on"
195
+ : "off"
196
+ : idleValue(current.idleMinutes),
197
+ );
198
+ ctx.ui.notify(
199
+ `Could not save notes settings: ${String(error)}`,
200
+ "error",
201
+ );
202
+ }
203
+ requestRender();
204
+ },
205
+ () => done("close"),
206
+ { enableSearch: false },
207
+ );
208
+ return list;
209
+ }