@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.
- package/CHANGELOG.md +12 -0
- package/README.md +28 -0
- package/package.json +3 -3
- package/src/attachment-sharing.ts +134 -0
- package/src/context-owner.ts +15 -19
- package/src/extension-hooks.ts +2 -2
- package/src/fresh-notes.ts +5 -11
- package/src/history-search-pruning.mjs +2 -2
- package/src/history-search-worker.mjs +13 -11
- package/src/history-search.ts +1 -1
- package/src/history-windows.ts +223 -0
- package/src/history.ts +4 -222
- package/src/index.ts +27 -2
- package/src/integrations.ts +3 -1
- package/src/model-role-config.ts +99 -0
- package/src/model-role-editor.ts +40 -0
- package/src/model-role-screen.ts +58 -0
- package/src/model-roles.ts +363 -0
- package/src/note-query.ts +150 -0
- package/src/notes-lookup.ts +1 -1
- package/src/notes.ts +3 -145
- package/src/query-executor.ts +10 -2
- package/src/query-input.ts +115 -0
- package/src/saved-sharing-records.ts +103 -0
- package/src/session-pruning-screen.ts +168 -94
- package/src/session-pruning.ts +15 -2
- package/src/settings-command.ts +41 -10
- package/src/settings-controls.ts +209 -0
- package/src/settings-screen.ts +23 -211
- package/src/shared-notes.ts +20 -203
- package/src/shared-session-reader.ts +132 -0
- package/src/sharing-service.ts +2 -116
- package/src/sqlite.mjs +33 -0
- package/src/store.ts +15 -13
- package/src/tool-contracts.ts +121 -80
- package/src/tools.ts +46 -6
- package/src/window-message.ts +179 -0
- package/src/windows.ts +13 -172
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionCommandContext,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { NotesActivation } from "./activation.js";
|
|
7
|
+
import type { NotesLifecycle } from "./lifecycle.js";
|
|
8
|
+
import {
|
|
9
|
+
type ModelRole,
|
|
10
|
+
type RoleConfig,
|
|
11
|
+
readRoleConfig,
|
|
12
|
+
writeRoleConfig,
|
|
13
|
+
} from "./model-role-config.js";
|
|
14
|
+
import { editModelRole } from "./model-role-editor.js";
|
|
15
|
+
import { openModelRoleScreen } from "./model-role-screen.js";
|
|
16
|
+
import { modelIsActive } from "./settings.js";
|
|
17
|
+
|
|
18
|
+
export function createModelRoles(
|
|
19
|
+
pi: ExtensionAPI,
|
|
20
|
+
activation: NotesActivation,
|
|
21
|
+
lifecycle: NotesLifecycle,
|
|
22
|
+
refresh: () => void,
|
|
23
|
+
) {
|
|
24
|
+
let config: RoleConfig = { enabled: false, roles: [] };
|
|
25
|
+
let configError: string | undefined;
|
|
26
|
+
try {
|
|
27
|
+
config = readRoleConfig();
|
|
28
|
+
} catch (error) {
|
|
29
|
+
configError = String(error);
|
|
30
|
+
}
|
|
31
|
+
type Recommendation = {
|
|
32
|
+
role: ModelRole;
|
|
33
|
+
reason: string;
|
|
34
|
+
continuity: string;
|
|
35
|
+
session: string;
|
|
36
|
+
provider: string | undefined;
|
|
37
|
+
model: string | undefined;
|
|
38
|
+
reasoning: string;
|
|
39
|
+
settled: boolean;
|
|
40
|
+
};
|
|
41
|
+
let pending: Recommendation | undefined;
|
|
42
|
+
let selectedRole: string | undefined;
|
|
43
|
+
let completed = false;
|
|
44
|
+
let generation = 0;
|
|
45
|
+
const enabled = () => lifecycle.active && config.enabled;
|
|
46
|
+
const reset = () => {
|
|
47
|
+
generation++;
|
|
48
|
+
pending = undefined;
|
|
49
|
+
completed = false;
|
|
50
|
+
};
|
|
51
|
+
const save = (value: RoleConfig) => {
|
|
52
|
+
writeRoleConfig(value);
|
|
53
|
+
config = value;
|
|
54
|
+
selectedRole = undefined;
|
|
55
|
+
configError = undefined;
|
|
56
|
+
reset();
|
|
57
|
+
refresh();
|
|
58
|
+
pi.sendMessage(
|
|
59
|
+
{
|
|
60
|
+
customType: "model-role-update",
|
|
61
|
+
display: false,
|
|
62
|
+
content: config.enabled
|
|
63
|
+
? "Role preferences updated. Discover current preferences with notes action=roles before recommending a handoff"
|
|
64
|
+
: "Role recommendations disabled. Keep the current model unless the user directs a switch",
|
|
65
|
+
},
|
|
66
|
+
{ deliverAs: "nextTurn" },
|
|
67
|
+
);
|
|
68
|
+
};
|
|
69
|
+
const query = async (
|
|
70
|
+
args: { role?: string; reason?: string; continuity?: string },
|
|
71
|
+
ctx: ExtensionContext,
|
|
72
|
+
) => {
|
|
73
|
+
if (!enabled())
|
|
74
|
+
throw new Error(
|
|
75
|
+
"Role recommendations are off. The user can enable them with /roles",
|
|
76
|
+
);
|
|
77
|
+
let result: unknown;
|
|
78
|
+
if (!args.role) {
|
|
79
|
+
if (args.reason || args.continuity)
|
|
80
|
+
throw new Error(
|
|
81
|
+
"Supply role, reason and continuity together, or use notes action=roles to discover preferences",
|
|
82
|
+
);
|
|
83
|
+
result = {
|
|
84
|
+
current: {
|
|
85
|
+
provider: ctx.model?.provider,
|
|
86
|
+
model: ctx.model?.id,
|
|
87
|
+
reasoning: pi.getThinkingLevel(),
|
|
88
|
+
selectedRole: selectedRole ?? null,
|
|
89
|
+
matchingRoles: config.roles
|
|
90
|
+
.filter(
|
|
91
|
+
(role) =>
|
|
92
|
+
role.provider === ctx.model?.provider &&
|
|
93
|
+
role.model === ctx.model?.id,
|
|
94
|
+
)
|
|
95
|
+
.map((role) => role.id),
|
|
96
|
+
},
|
|
97
|
+
roles: config.roles,
|
|
98
|
+
pending,
|
|
99
|
+
};
|
|
100
|
+
} else {
|
|
101
|
+
const role = config.roles.find((role) => role.id === args.role);
|
|
102
|
+
if (!role)
|
|
103
|
+
throw new Error(
|
|
104
|
+
"Unknown role. Use notes action=roles for configured roles",
|
|
105
|
+
);
|
|
106
|
+
if (!args.reason?.trim() || !args.continuity?.trim())
|
|
107
|
+
throw new Error("A recommendation needs reason and continuity");
|
|
108
|
+
if (
|
|
109
|
+
selectedRole === role.id &&
|
|
110
|
+
role.provider === ctx.model?.provider &&
|
|
111
|
+
role.model === ctx.model.id
|
|
112
|
+
)
|
|
113
|
+
throw new Error(
|
|
114
|
+
"Already using this role's model and reasoning; continue here",
|
|
115
|
+
);
|
|
116
|
+
pending = {
|
|
117
|
+
role: { ...role },
|
|
118
|
+
reason: args.reason.trim(),
|
|
119
|
+
continuity: args.continuity.trim(),
|
|
120
|
+
session: ctx.sessionManager.getSessionId(),
|
|
121
|
+
provider: ctx.model?.provider,
|
|
122
|
+
model: ctx.model?.id,
|
|
123
|
+
reasoning: pi.getThinkingLevel(),
|
|
124
|
+
settled: false,
|
|
125
|
+
};
|
|
126
|
+
result = {
|
|
127
|
+
recommendation: role.id,
|
|
128
|
+
reason: pending.reason,
|
|
129
|
+
continuity: pending.continuity,
|
|
130
|
+
status:
|
|
131
|
+
"Awaiting run settlement and user action: /roles accept. Continue here unless accepted",
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
content: [{ type: "text" as const, text: JSON.stringify(result) }],
|
|
136
|
+
details: {},
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
140
|
+
activation.refreshActivation(ctx);
|
|
141
|
+
refresh();
|
|
142
|
+
reset();
|
|
143
|
+
if (!enabled()) return;
|
|
144
|
+
const content =
|
|
145
|
+
"Model role preferences are enabled. Discover current model and configured preferences with notes action=roles. Use notes action=recommend_handoff with role, evidence in reason, and continuity when accumulated conversation favours a different role, never after fixed turns. Keep the current model until the user accepts.";
|
|
146
|
+
const present = ctx.sessionManager
|
|
147
|
+
.buildContextEntries()
|
|
148
|
+
.some(
|
|
149
|
+
(entry) =>
|
|
150
|
+
entry.type === "message" &&
|
|
151
|
+
entry.message.role === "custom" &&
|
|
152
|
+
entry.message.customType === "model-role-guidance" &&
|
|
153
|
+
entry.message.content === content,
|
|
154
|
+
);
|
|
155
|
+
if (!present)
|
|
156
|
+
return {
|
|
157
|
+
message: { customType: "model-role-guidance", content, display: false },
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
pi.on("model_select", () => {
|
|
161
|
+
reset();
|
|
162
|
+
selectedRole = undefined;
|
|
163
|
+
});
|
|
164
|
+
pi.on("thinking_level_select", () => {
|
|
165
|
+
reset();
|
|
166
|
+
selectedRole = undefined;
|
|
167
|
+
});
|
|
168
|
+
const navigation = () => {
|
|
169
|
+
selectedRole = undefined;
|
|
170
|
+
reset();
|
|
171
|
+
};
|
|
172
|
+
pi.on("session_before_switch", navigation);
|
|
173
|
+
pi.on("session_before_fork", navigation);
|
|
174
|
+
pi.on("session_before_tree", navigation);
|
|
175
|
+
pi.on("session_tree", reset);
|
|
176
|
+
pi.on("agent_before_settle", (event) => {
|
|
177
|
+
completed = event.outcome === "completed";
|
|
178
|
+
});
|
|
179
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
180
|
+
if (!pending) {
|
|
181
|
+
completed = false;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (!enabled() || pending.settled || _event.aborted || !completed) {
|
|
185
|
+
reset();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
pending.settled = true;
|
|
189
|
+
ctx.ui.notify(
|
|
190
|
+
`Recommended role: ${pending.role.id} (${pending.role.provider}/${pending.role.model})\n${pending.reason}\n/roles accept to switch in this conversation; /roles dismiss to keep the current model`,
|
|
191
|
+
"info",
|
|
192
|
+
);
|
|
193
|
+
});
|
|
194
|
+
pi.on("session_start", (_event, ctx) => {
|
|
195
|
+
reset();
|
|
196
|
+
selectedRole = undefined;
|
|
197
|
+
if (configError)
|
|
198
|
+
ctx.ui.notify(`Role recommendations are off: ${configError}`, "error");
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
async function switchRole(
|
|
202
|
+
role: ModelRole,
|
|
203
|
+
ctx: ExtensionCommandContext,
|
|
204
|
+
recommendation?: Recommendation,
|
|
205
|
+
) {
|
|
206
|
+
const session = ctx.sessionManager.getSessionId();
|
|
207
|
+
const provider = ctx.model?.provider;
|
|
208
|
+
const modelId = ctx.model?.id;
|
|
209
|
+
const reasoning = pi.getThinkingLevel();
|
|
210
|
+
const version = generation;
|
|
211
|
+
await ctx.waitForIdle();
|
|
212
|
+
if (
|
|
213
|
+
!ctx.isIdle() ||
|
|
214
|
+
generation !== version ||
|
|
215
|
+
ctx.sessionManager.getSessionId() !== session ||
|
|
216
|
+
ctx.model?.provider !== provider ||
|
|
217
|
+
ctx.model?.id !== modelId ||
|
|
218
|
+
pi.getThinkingLevel() !== reasoning ||
|
|
219
|
+
(recommendation &&
|
|
220
|
+
(pending !== recommendation ||
|
|
221
|
+
!recommendation.settled ||
|
|
222
|
+
recommendation.session !== session ||
|
|
223
|
+
recommendation.provider !== provider ||
|
|
224
|
+
recommendation.model !== modelId ||
|
|
225
|
+
recommendation.reasoning !== reasoning))
|
|
226
|
+
) {
|
|
227
|
+
ctx.ui.notify(
|
|
228
|
+
"The conversation or model changed. Keep the current model; request a new recommendation or choose a role with /roles",
|
|
229
|
+
"warning",
|
|
230
|
+
);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const model = ctx.modelRegistry.find(role.provider, role.model);
|
|
234
|
+
if (!model)
|
|
235
|
+
throw new Error(
|
|
236
|
+
`Model unavailable: ${role.provider}/${role.model}. Choose another model with /roles`,
|
|
237
|
+
);
|
|
238
|
+
if (!lifecycle.active || !modelIsActive(activation.settings, model))
|
|
239
|
+
throw new Error(
|
|
240
|
+
"Notes must be active for both models. Check Active and model whitelist in /notes before switching",
|
|
241
|
+
);
|
|
242
|
+
// Use Pi's existing session and replay projection; never recreate messages or tool pairs.
|
|
243
|
+
if (provider !== model.provider || modelId !== model.id) {
|
|
244
|
+
if (!(await pi.setModel(model)))
|
|
245
|
+
throw new Error(
|
|
246
|
+
`Could not select ${role.provider}/${role.model}; check provider authentication or choose another role with /roles`,
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
pi.setThinkingLevel(role.reasoning);
|
|
250
|
+
selectedRole = role.id;
|
|
251
|
+
reset();
|
|
252
|
+
pi.sendMessage(
|
|
253
|
+
{
|
|
254
|
+
customType: "model-role-handoff",
|
|
255
|
+
display: true,
|
|
256
|
+
content: `Using role ${role.id}: ${role.description}\nModel: ${role.provider}/${role.model}; reasoning: ${pi.getThinkingLevel()}. Conversation retained.${recommendation ? `\nReason: ${recommendation.reason}\nContinuity: ${recommendation.continuity}` : ""}`,
|
|
257
|
+
},
|
|
258
|
+
{ deliverAs: "nextTurn" },
|
|
259
|
+
);
|
|
260
|
+
ctx.ui.notify(
|
|
261
|
+
`Using ${role.id}: ${role.provider}/${role.model} (${pi.getThinkingLevel()}). Conversation retained`,
|
|
262
|
+
"info",
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const command = async (args: string, ctx: ExtensionCommandContext) => {
|
|
267
|
+
try {
|
|
268
|
+
const input = args.trim();
|
|
269
|
+
if (input === "dismiss") {
|
|
270
|
+
reset();
|
|
271
|
+
ctx.ui.notify(
|
|
272
|
+
"Recommendation dismissed; current model retained",
|
|
273
|
+
"info",
|
|
274
|
+
);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (input === "accept") {
|
|
278
|
+
if (!pending) {
|
|
279
|
+
ctx.ui.notify(
|
|
280
|
+
"No current recommendation. Use /roles to choose a role",
|
|
281
|
+
"info",
|
|
282
|
+
);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
await switchRole(pending.role, ctx, pending);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (input) {
|
|
289
|
+
ctx.ui.notify("Usage: /roles [accept|dismiss]", "error");
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (!ctx.hasUI)
|
|
293
|
+
throw new Error(
|
|
294
|
+
"Role configuration needs interactive Pi. /roles accept and /roles dismiss remain available",
|
|
295
|
+
);
|
|
296
|
+
while (true) {
|
|
297
|
+
const choice = await openModelRoleScreen(
|
|
298
|
+
ctx,
|
|
299
|
+
[
|
|
300
|
+
...(pending
|
|
301
|
+
? ["Accept recommendation", "Dismiss recommendation"]
|
|
302
|
+
: []),
|
|
303
|
+
"Switch role",
|
|
304
|
+
"Add or replace role",
|
|
305
|
+
"Remove role",
|
|
306
|
+
config.enabled
|
|
307
|
+
? "Disable recommendations"
|
|
308
|
+
: "Enable recommendations",
|
|
309
|
+
],
|
|
310
|
+
config.roles,
|
|
311
|
+
);
|
|
312
|
+
if (!choice) return;
|
|
313
|
+
if (choice === "notes-tab") return "notes" as const;
|
|
314
|
+
if (choice === "Accept recommendation" && pending)
|
|
315
|
+
await switchRole(pending.role, ctx, pending);
|
|
316
|
+
else if (choice === "Dismiss recommendation") reset();
|
|
317
|
+
else if (choice === "Switch role") {
|
|
318
|
+
const id = await ctx.ui.select(
|
|
319
|
+
"Switch role (conversation retained)",
|
|
320
|
+
config.roles.map((role) => role.id),
|
|
321
|
+
);
|
|
322
|
+
const role = config.roles.find((role) => role.id === id);
|
|
323
|
+
if (role) await switchRole(role, ctx);
|
|
324
|
+
} else if (choice === "Add or replace role") {
|
|
325
|
+
const role = await editModelRole(ctx);
|
|
326
|
+
if (role)
|
|
327
|
+
save({
|
|
328
|
+
...config,
|
|
329
|
+
roles: [
|
|
330
|
+
...config.roles.filter((existing) => existing.id !== role.id),
|
|
331
|
+
role,
|
|
332
|
+
],
|
|
333
|
+
});
|
|
334
|
+
} else if (choice === "Remove role") {
|
|
335
|
+
const id = await ctx.ui.select(
|
|
336
|
+
"Remove role",
|
|
337
|
+
config.roles.map((role) => role.id),
|
|
338
|
+
);
|
|
339
|
+
if (!id) return;
|
|
340
|
+
save({
|
|
341
|
+
...config,
|
|
342
|
+
roles: config.roles.filter((role) => role.id !== id),
|
|
343
|
+
});
|
|
344
|
+
} else if (
|
|
345
|
+
choice === "Enable recommendations" ||
|
|
346
|
+
choice === "Disable recommendations"
|
|
347
|
+
) {
|
|
348
|
+
save({ ...config, enabled: choice === "Enable recommendations" });
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
} catch (error) {
|
|
352
|
+
ctx.ui.notify(
|
|
353
|
+
error instanceof Error ? error.message : String(error),
|
|
354
|
+
"error",
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
return {
|
|
359
|
+
enabled,
|
|
360
|
+
command,
|
|
361
|
+
query,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { NoteRevision } from "./store.js";
|
|
2
|
+
|
|
3
|
+
export function canonicalPath(
|
|
4
|
+
path: unknown,
|
|
5
|
+
agent: string,
|
|
6
|
+
required = true,
|
|
7
|
+
): string {
|
|
8
|
+
if (path === undefined || path === null || path === "") {
|
|
9
|
+
if (required) throw new Error("Note file path is required");
|
|
10
|
+
return "";
|
|
11
|
+
}
|
|
12
|
+
if (typeof path !== "string")
|
|
13
|
+
throw new Error(
|
|
14
|
+
required ? "Note file path is required" : "Note prefix must be a string",
|
|
15
|
+
);
|
|
16
|
+
const root = `${agent}/notes`;
|
|
17
|
+
let value = path;
|
|
18
|
+
if (value === root) {
|
|
19
|
+
if (required)
|
|
20
|
+
throw new Error("Absolute note paths must use <agent>/notes/<path>");
|
|
21
|
+
value = "";
|
|
22
|
+
} else if (value.startsWith(`${root}/`)) value = value.slice(root.length + 1);
|
|
23
|
+
else if (value.startsWith("/"))
|
|
24
|
+
throw new Error(
|
|
25
|
+
"That agent's notes are not available here. Use a relative path for this agent.",
|
|
26
|
+
);
|
|
27
|
+
if (
|
|
28
|
+
(required && !value) ||
|
|
29
|
+
(value !== "" &&
|
|
30
|
+
value.split("/").some((part) => !part || part === ".." || part === "."))
|
|
31
|
+
)
|
|
32
|
+
throw new Error(
|
|
33
|
+
required
|
|
34
|
+
? "Note paths cannot contain empty, . or .. components"
|
|
35
|
+
: "Note prefixes cannot contain empty, . or .. components",
|
|
36
|
+
);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function normalizeNoteParams(
|
|
41
|
+
params: Record<string, unknown>,
|
|
42
|
+
agent: string,
|
|
43
|
+
): Record<string, unknown> {
|
|
44
|
+
const result = { ...params };
|
|
45
|
+
for (const field of ["path", "prefix", "path_prefix"])
|
|
46
|
+
if (field in params)
|
|
47
|
+
result[field] = canonicalPath(params[field], agent, field === "path");
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readNotes(
|
|
52
|
+
notes: ReadonlyMap<string, NoteRevision>,
|
|
53
|
+
params: Record<string, unknown>,
|
|
54
|
+
agent: string,
|
|
55
|
+
): Record<string, unknown> {
|
|
56
|
+
const action = params["action"];
|
|
57
|
+
const root = `${agent}/notes/`;
|
|
58
|
+
if (action === "read_file") {
|
|
59
|
+
const path = params["path"] as string;
|
|
60
|
+
const note = notes.get(path);
|
|
61
|
+
if (!note) return { file: null };
|
|
62
|
+
const lines = note.text.split("\n");
|
|
63
|
+
const start = lineIndex(params["start_line"], lines.length, 0);
|
|
64
|
+
const stop = lineIndex(params["stop_line"], lines.length, lines.length - 1);
|
|
65
|
+
return {
|
|
66
|
+
file: {
|
|
67
|
+
path: `${root}${note.path}`,
|
|
68
|
+
content: start <= stop ? lines.slice(start, stop + 1).join("\n") : "",
|
|
69
|
+
start_line: start + 1,
|
|
70
|
+
stop_line: Math.max(start, stop) + 1,
|
|
71
|
+
total_lines: lines.length,
|
|
72
|
+
...(note.mode === "append" ? { append_only: true } : {}),
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (action === "list_files_by_prefix") {
|
|
77
|
+
const by = params["file_order_by"];
|
|
78
|
+
const direction = params["file_order"] === "descending" ? -1 : 1;
|
|
79
|
+
const files = [...notes.values()]
|
|
80
|
+
.filter((note) => note.path.startsWith(String(params["prefix"] ?? "")))
|
|
81
|
+
.sort(
|
|
82
|
+
(a, b) =>
|
|
83
|
+
(by === "created_at"
|
|
84
|
+
? a.createdAt - b.createdAt
|
|
85
|
+
: by === "updated_at"
|
|
86
|
+
? a.updatedAt - b.updatedAt
|
|
87
|
+
: a.path.localeCompare(b.path)) * direction,
|
|
88
|
+
)
|
|
89
|
+
.map((note) => ({
|
|
90
|
+
path: `${root}${note.path}`,
|
|
91
|
+
updated_at: new Date(note.updatedAt).toISOString(),
|
|
92
|
+
...(by === "created_at"
|
|
93
|
+
? { created_at: new Date(note.createdAt).toISOString() }
|
|
94
|
+
: {}),
|
|
95
|
+
}));
|
|
96
|
+
const limit = integer(params["max_results"], 20, 100);
|
|
97
|
+
return {
|
|
98
|
+
files: files.slice(0, limit),
|
|
99
|
+
...(files.length > limit ? { truncated: true } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (action !== "search_contents")
|
|
103
|
+
throw new Error("notes requires a supported action");
|
|
104
|
+
const query = params["query"];
|
|
105
|
+
if (typeof query !== "string" || !query)
|
|
106
|
+
throw new Error("notes search_contents requires query");
|
|
107
|
+
const files = [...notes.values()].filter((note) =>
|
|
108
|
+
note.path.startsWith(String(params["path_prefix"] ?? "")),
|
|
109
|
+
);
|
|
110
|
+
files.sort(
|
|
111
|
+
params["recent_file_first"] === true
|
|
112
|
+
? (a, b) => b.createdAt - a.createdAt
|
|
113
|
+
: (a, b) => a.path.localeCompare(b.path),
|
|
114
|
+
);
|
|
115
|
+
const found: Record<string, unknown>[] = [];
|
|
116
|
+
const fileLimit = integer(params["max_files"], 20, 100);
|
|
117
|
+
const matchLimit = integer(params["max_matches_per_file"], 20, 100);
|
|
118
|
+
for (const note of files) {
|
|
119
|
+
const matches = note.text
|
|
120
|
+
.split("\n")
|
|
121
|
+
.map((line, index) => ({ line_number: index + 1, line }))
|
|
122
|
+
.filter(({ line }) => line.includes(query));
|
|
123
|
+
if (!matches.length) continue;
|
|
124
|
+
if (found.length === fileLimit) return { files: found, truncated: true };
|
|
125
|
+
found.push({
|
|
126
|
+
path: `${root}${note.path}`,
|
|
127
|
+
matches: matches.slice(0, matchLimit),
|
|
128
|
+
...(matches.length > matchLimit ? { truncated: true } : {}),
|
|
129
|
+
...(note.mode === "append" ? { append_only: true } : {}),
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return { files: found };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function lineIndex(
|
|
136
|
+
value: unknown,
|
|
137
|
+
lineCount: number,
|
|
138
|
+
fallback: number,
|
|
139
|
+
): number {
|
|
140
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value === 0)
|
|
141
|
+
return fallback;
|
|
142
|
+
const index = value > 0 ? value - 1 : lineCount + value;
|
|
143
|
+
return Math.max(0, Math.min(index, Math.max(0, lineCount - 1)));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function integer(value: unknown, fallback: number, max: number): number {
|
|
147
|
+
return typeof value === "number" && Number.isInteger(value)
|
|
148
|
+
? Math.max(1, Math.min(value, max))
|
|
149
|
+
: fallback;
|
|
150
|
+
}
|
package/src/notes-lookup.ts
CHANGED
|
@@ -83,7 +83,7 @@ export async function lookupNotes(
|
|
|
83
83
|
);
|
|
84
84
|
if (responses.length && canProject && replacementsInScope)
|
|
85
85
|
warnings.push(
|
|
86
|
-
"Older matches may refer to replaced notes. Read a note before relying on its excerpt;
|
|
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
88
|
const output = result({ ...local, ...(warnings.length ? { warnings } : {}) });
|
|
89
89
|
if (shared)
|
package/src/notes.ts
CHANGED
|
@@ -4,8 +4,11 @@ import type {
|
|
|
4
4
|
SessionEntry,
|
|
5
5
|
} from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import type { NoteSnapshotData } from "./bridge.js";
|
|
7
|
+
import { canonicalPath, readNotes } from "./note-query.js";
|
|
7
8
|
import { type NoteRevision, NotesStore, type SessionRef } from "./store.js";
|
|
8
9
|
|
|
10
|
+
export { normalizeNoteParams, readNotes } from "./note-query.js";
|
|
11
|
+
|
|
9
12
|
export const NOTE_RECEIPT = "notes-compaction:note:v1";
|
|
10
13
|
export const CACHE_RECEIPT = "notes-compaction:cache:v1";
|
|
11
14
|
export interface NoteReceipt {
|
|
@@ -215,50 +218,6 @@ export function exportNotesSnapshot(
|
|
|
215
218
|
return snapshot;
|
|
216
219
|
}
|
|
217
220
|
|
|
218
|
-
function canonicalPath(path: unknown, agent: string, required = true): string {
|
|
219
|
-
if (path === undefined || path === null || path === "") {
|
|
220
|
-
if (required) throw new Error("Note file path is required");
|
|
221
|
-
return "";
|
|
222
|
-
}
|
|
223
|
-
if (typeof path !== "string")
|
|
224
|
-
throw new Error(
|
|
225
|
-
required ? "Note file path is required" : "Note prefix must be a string",
|
|
226
|
-
);
|
|
227
|
-
const root = `${agent}/notes`;
|
|
228
|
-
let value = path;
|
|
229
|
-
if (value === root) {
|
|
230
|
-
if (required)
|
|
231
|
-
throw new Error("Absolute note paths must use <agent>/notes/<path>");
|
|
232
|
-
value = "";
|
|
233
|
-
} else if (value.startsWith(`${root}/`)) value = value.slice(root.length + 1);
|
|
234
|
-
else if (value.startsWith("/"))
|
|
235
|
-
throw new Error(
|
|
236
|
-
"That agent's notes are not available here. Use a relative path for this agent.",
|
|
237
|
-
);
|
|
238
|
-
if (
|
|
239
|
-
(required && !value) ||
|
|
240
|
-
(value !== "" &&
|
|
241
|
-
value.split("/").some((part) => !part || part === ".." || part === "."))
|
|
242
|
-
)
|
|
243
|
-
throw new Error(
|
|
244
|
-
required
|
|
245
|
-
? "Note paths cannot contain empty, . or .. components"
|
|
246
|
-
: "Note prefixes cannot contain empty, . or .. components",
|
|
247
|
-
);
|
|
248
|
-
return value;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
export function normalizeNoteParams(
|
|
252
|
-
params: Record<string, unknown>,
|
|
253
|
-
agent: string,
|
|
254
|
-
): Record<string, unknown> {
|
|
255
|
-
const result = { ...params };
|
|
256
|
-
for (const field of ["path", "prefix", "path_prefix"])
|
|
257
|
-
if (field in params)
|
|
258
|
-
result[field] = canonicalPath(params[field], agent, field === "path");
|
|
259
|
-
return result;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
221
|
export function noteHints(
|
|
263
222
|
store: NotesStore,
|
|
264
223
|
ctx: ExtensionContext,
|
|
@@ -336,104 +295,3 @@ export function useNotes(
|
|
|
336
295
|
}
|
|
337
296
|
return readNotes(notes, params, agent);
|
|
338
297
|
}
|
|
339
|
-
|
|
340
|
-
export function readNotes(
|
|
341
|
-
notes: ReadonlyMap<string, NoteRevision>,
|
|
342
|
-
params: Record<string, unknown>,
|
|
343
|
-
agent: string,
|
|
344
|
-
): Record<string, unknown> {
|
|
345
|
-
const action = params["action"];
|
|
346
|
-
const root = `${agent}/notes/`;
|
|
347
|
-
if (action === "read_file") {
|
|
348
|
-
const path = params["path"] as string;
|
|
349
|
-
const note = notes.get(path);
|
|
350
|
-
if (!note) return { file: null };
|
|
351
|
-
const lines = note.text.split("\n");
|
|
352
|
-
const start = lineIndex(params["start_line"], lines.length, 0);
|
|
353
|
-
const stop = lineIndex(params["stop_line"], lines.length, lines.length - 1);
|
|
354
|
-
return {
|
|
355
|
-
file: {
|
|
356
|
-
path: `${root}${note.path}`,
|
|
357
|
-
content: start <= stop ? lines.slice(start, stop + 1).join("\n") : "",
|
|
358
|
-
start_line: start + 1,
|
|
359
|
-
stop_line: Math.max(start, stop) + 1,
|
|
360
|
-
total_lines: lines.length,
|
|
361
|
-
...(note.mode === "append" ? { append_only: true } : {}),
|
|
362
|
-
},
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
if (action === "list_files_by_prefix") {
|
|
366
|
-
const by = params["file_order_by"];
|
|
367
|
-
const direction = params["file_order"] === "descending" ? -1 : 1;
|
|
368
|
-
const files = [...notes.values()]
|
|
369
|
-
.filter((note) => note.path.startsWith(String(params["prefix"] ?? "")))
|
|
370
|
-
.sort(
|
|
371
|
-
(a, b) =>
|
|
372
|
-
(by === "created_at"
|
|
373
|
-
? a.createdAt - b.createdAt
|
|
374
|
-
: by === "updated_at"
|
|
375
|
-
? a.updatedAt - b.updatedAt
|
|
376
|
-
: a.path.localeCompare(b.path)) * direction,
|
|
377
|
-
)
|
|
378
|
-
.map((note) => ({
|
|
379
|
-
path: `${root}${note.path}`,
|
|
380
|
-
updated_at: new Date(note.updatedAt).toISOString(),
|
|
381
|
-
...(by === "created_at"
|
|
382
|
-
? { created_at: new Date(note.createdAt).toISOString() }
|
|
383
|
-
: {}),
|
|
384
|
-
}));
|
|
385
|
-
const limit = integer(params["max_results"], 20, 100);
|
|
386
|
-
return {
|
|
387
|
-
files: files.slice(0, limit),
|
|
388
|
-
...(files.length > limit ? { truncated: true } : {}),
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
if (action !== "search_contents")
|
|
392
|
-
throw new Error("notes requires a supported action");
|
|
393
|
-
const query = params["query"];
|
|
394
|
-
if (typeof query !== "string" || !query)
|
|
395
|
-
throw new Error("notes search_contents requires query");
|
|
396
|
-
const files = [...notes.values()].filter((note) =>
|
|
397
|
-
note.path.startsWith(String(params["path_prefix"] ?? "")),
|
|
398
|
-
);
|
|
399
|
-
files.sort(
|
|
400
|
-
params["recent_file_first"] === true
|
|
401
|
-
? (a, b) => b.createdAt - a.createdAt
|
|
402
|
-
: (a, b) => a.path.localeCompare(b.path),
|
|
403
|
-
);
|
|
404
|
-
const found: Record<string, unknown>[] = [];
|
|
405
|
-
const fileLimit = integer(params["max_files"], 20, 100);
|
|
406
|
-
const matchLimit = integer(params["max_matches_per_file"], 20, 100);
|
|
407
|
-
for (const note of files) {
|
|
408
|
-
const matches = note.text
|
|
409
|
-
.split("\n")
|
|
410
|
-
.map((line, index) => ({ line_number: index + 1, line }))
|
|
411
|
-
.filter(({ line }) => line.includes(query));
|
|
412
|
-
if (!matches.length) continue;
|
|
413
|
-
if (found.length === fileLimit) return { files: found, truncated: true };
|
|
414
|
-
found.push({
|
|
415
|
-
path: `${root}${note.path}`,
|
|
416
|
-
matches: matches.slice(0, matchLimit),
|
|
417
|
-
...(matches.length > matchLimit ? { truncated: true } : {}),
|
|
418
|
-
...(note.mode === "append" ? { append_only: true } : {}),
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
return { files: found };
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
function lineIndex(
|
|
425
|
-
value: unknown,
|
|
426
|
-
lineCount: number,
|
|
427
|
-
fallback: number,
|
|
428
|
-
): number {
|
|
429
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value === 0)
|
|
430
|
-
return fallback;
|
|
431
|
-
const index = value > 0 ? value - 1 : lineCount + value;
|
|
432
|
-
return Math.max(0, Math.min(index, Math.max(0, lineCount - 1)));
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
function integer(value: unknown, fallback: number, max: number): number {
|
|
436
|
-
return typeof value === "number" && Number.isInteger(value)
|
|
437
|
-
? Math.max(1, Math.min(value, max))
|
|
438
|
-
: fallback;
|
|
439
|
-
}
|