@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa
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/INTEGRATION.md +31 -0
- package/LICENSE +21 -0
- package/PCC-INTEGRATION.md +17 -0
- package/README.md +53 -2
- package/dist/viewer/archive.js +249 -0
- package/dist/viewer/config.js +85 -0
- package/dist/viewer/contracts.js +1 -0
- package/dist/viewer/server.js +177 -0
- package/dist/viewer/source.js +29 -0
- package/dist/viewer/web/app.js +88 -0
- package/dist/viewer/web/index.html +41 -0
- package/dist/viewer/web/navigation.js +72 -0
- package/dist/viewer/web/posts.js +105 -0
- package/dist/viewer/web/render.js +147 -0
- package/dist/viewer/web/session.js +86 -0
- package/dist/viewer/web/style.css +517 -0
- package/dist/viewer/web/updates.js +106 -0
- package/docs/BOARD-CHANGELOG.md +49 -0
- package/docs/BOARD.md +124 -0
- package/docs/NOTES-CHANGELOG.md +127 -0
- package/docs/NOTES.md +122 -0
- package/index.ts +21 -0
- package/package.json +75 -5
- package/src/board/AGENTS.md +12 -0
- package/src/board/activity.ts +274 -0
- package/src/board/archive.ts +118 -0
- package/src/board/awareness.ts +179 -0
- package/src/board/briefing.ts +25 -0
- package/src/board/config.ts +192 -0
- package/src/board/consolidation.ts +32 -0
- package/src/board/context-briefing.ts +245 -0
- package/src/board/contract.ts +254 -0
- package/src/board/delivery.ts +85 -0
- package/src/board/feature.ts +91 -0
- package/src/board/identity.ts +238 -0
- package/src/board/integration.ts +55 -0
- package/src/board/paging.ts +54 -0
- package/src/board/protocol.ts +78 -0
- package/src/board/queries.ts +168 -0
- package/src/board/response.ts +82 -0
- package/src/board/runtime/activation.ts +50 -0
- package/src/board/runtime/catchup.ts +96 -0
- package/src/board/runtime/coordinator.ts +311 -0
- package/src/board/runtime/engine.ts +40 -0
- package/src/board/runtime/index.ts +63 -0
- package/src/board/runtime/owner.ts +168 -0
- package/src/board/runtime/routing.ts +152 -0
- package/src/board/runtime/turns.ts +109 -0
- package/src/board/search.ts +95 -0
- package/src/board/settings/panel.ts +193 -0
- package/src/board/store.ts +427 -0
- package/src/board/summaries.ts +124 -0
- package/src/board/summarizer.ts +201 -0
- package/src/board/tool.ts +27 -0
- package/src/board/viewer/AGENTS.md +1 -0
- package/src/board/viewer/archive.ts +308 -0
- package/src/board/viewer/config.ts +111 -0
- package/src/board/viewer/contracts.ts +98 -0
- package/src/board/viewer/index.ts +162 -0
- package/src/board/viewer/server.ts +204 -0
- package/src/board/viewer/source.ts +33 -0
- package/src/board/viewer/web/app.js +88 -0
- package/src/board/viewer/web/index.html +41 -0
- package/src/board/viewer/web/navigation.js +72 -0
- package/src/board/viewer/web/posts.js +105 -0
- package/src/board/viewer/web/render.js +147 -0
- package/src/board/viewer/web/session.js +86 -0
- package/src/board/viewer/web/style.css +517 -0
- package/src/board/viewer/web/updates.js +106 -0
- package/src/guidance.ts +121 -0
- package/src/notes/AGENTS.md +27 -0
- package/src/notes/activation.ts +150 -0
- package/src/notes/agent-identity.ts +221 -0
- package/src/notes/attachment-sharing.ts +165 -0
- package/src/notes/attachment-snapshot.ts +113 -0
- package/src/notes/binding-startup.ts +30 -0
- package/src/notes/bridge.ts +130 -0
- package/src/notes/compaction-projection.ts +88 -0
- package/src/notes/context-owner.ts +99 -0
- package/src/notes/context-sharing.ts +178 -0
- package/src/notes/extension-hooks.ts +200 -0
- package/src/notes/extension-sharing.ts +133 -0
- package/src/notes/feature.ts +168 -0
- package/src/notes/fresh-checkpoint.ts +143 -0
- package/src/notes/fresh-notes.ts +323 -0
- package/src/notes/history-search-protocol.ts +39 -0
- package/src/notes/history-search-pruning.mjs +120 -0
- package/src/notes/history-search-worker.mjs +258 -0
- package/src/notes/history-search.ts +269 -0
- package/src/notes/history-windows.ts +221 -0
- package/src/notes/history.ts +158 -0
- package/src/notes/idle-admission.ts +201 -0
- package/src/notes/index.ts +125 -0
- package/src/notes/integrations.ts +174 -0
- package/src/notes/lifecycle.ts +308 -0
- package/src/notes/model-role-config.ts +79 -0
- package/src/notes/model-role-screen.ts +74 -0
- package/src/notes/model-roles.ts +225 -0
- package/src/notes/note-query.ts +148 -0
- package/src/notes/note-result.ts +88 -0
- package/src/notes/note-save-marker.ts +128 -0
- package/src/notes/notes-lookup.ts +115 -0
- package/src/notes/notes.ts +302 -0
- package/src/notes/query-executor.ts +242 -0
- package/src/notes/query-input.ts +126 -0
- package/src/notes/remote.ts +376 -0
- package/src/notes/rollover.ts +224 -0
- package/src/notes/saved-session-access.ts +117 -0
- package/src/notes/saved-session-index.mjs +83 -0
- package/src/notes/saved-session.mjs +241 -0
- package/src/notes/saved-session.ts +51 -0
- package/src/notes/saved-sharing-records.ts +135 -0
- package/src/notes/session-pruning-content.ts +237 -0
- package/src/notes/session-pruning-plan.ts +243 -0
- package/src/notes/session-pruning-policy.ts +20 -0
- package/src/notes/session-pruning-screen.ts +204 -0
- package/src/notes/session-pruning-source.ts +44 -0
- package/src/notes/session-pruning-transaction.ts +141 -0
- package/src/notes/session-pruning.ts +155 -0
- package/src/notes/settings-command.ts +95 -0
- package/src/notes/settings-controls.ts +199 -0
- package/src/notes/settings-screen.ts +113 -0
- package/src/notes/settings.ts +287 -0
- package/src/notes/shared-notes.ts +411 -0
- package/src/notes/shared-session-reader.ts +143 -0
- package/src/notes/sharing-service.ts +282 -0
- package/src/notes/sqlite.mjs +33 -0
- package/src/notes/store.ts +283 -0
- package/src/notes/task-boundary.ts +37 -0
- package/src/notes/tool-contracts.ts +312 -0
- package/src/notes/tools.ts +148 -0
- package/src/notes/tree-archive-manifest.mjs +27 -0
- package/src/notes/tree-archive.ts +129 -0
- package/src/notes/tree-checkpoint.ts +170 -0
- package/src/notes/tree-handoff-read.ts +192 -0
- package/src/notes/window-checkpoint.ts +105 -0
- package/src/notes/window-message.ts +185 -0
- package/src/notes/windows.ts +272 -0
- package/src/settings-navigation.ts +11 -0
- package/src/timestamps.ts +3 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CustomMessageEntryDraft,
|
|
3
|
+
ExtensionAPI,
|
|
4
|
+
ExtensionCommandContext,
|
|
5
|
+
ExtensionContext,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import type { NotesActivation } from "./activation.js";
|
|
8
|
+
import type { NotesLifecycle } from "./lifecycle.js";
|
|
9
|
+
import {
|
|
10
|
+
type RoleConfig,
|
|
11
|
+
readRoleConfig,
|
|
12
|
+
roleConfigPath,
|
|
13
|
+
} from "./model-role-config.js";
|
|
14
|
+
import { openModelRoleScreen } from "./model-role-screen.js";
|
|
15
|
+
import { modelIsActive } from "./settings.js";
|
|
16
|
+
import { windowDetails } from "./windows.js";
|
|
17
|
+
|
|
18
|
+
const GUIDANCE_TYPE = "notes-compaction:roles";
|
|
19
|
+
|
|
20
|
+
export interface ModelRoleHandoff {
|
|
21
|
+
id: string;
|
|
22
|
+
activate(ctx: ExtensionContext): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createModelRoles(
|
|
26
|
+
pi: ExtensionAPI,
|
|
27
|
+
activation: NotesActivation,
|
|
28
|
+
lifecycle: NotesLifecycle,
|
|
29
|
+
) {
|
|
30
|
+
let config: RoleConfig = { roles: [] };
|
|
31
|
+
let configError: string | undefined;
|
|
32
|
+
let roleIdsChanged: ((ids: string[]) => void) | undefined;
|
|
33
|
+
const load = () => {
|
|
34
|
+
try {
|
|
35
|
+
config = readRoleConfig();
|
|
36
|
+
configError = undefined;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
config = { roles: [] };
|
|
39
|
+
configError = error instanceof Error ? error.message : String(error);
|
|
40
|
+
}
|
|
41
|
+
roleIdsChanged?.(config.roles.map((role) => role.id).sort());
|
|
42
|
+
};
|
|
43
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
44
|
+
activation.refreshActivation(ctx);
|
|
45
|
+
if (!lifecycle.active) return;
|
|
46
|
+
const previousError = configError;
|
|
47
|
+
load();
|
|
48
|
+
if (configError && configError !== previousError)
|
|
49
|
+
ctx.ui.notify(`Model roles unavailable: ${configError}`, "error");
|
|
50
|
+
const startingWindow =
|
|
51
|
+
event.messageType === "custom"
|
|
52
|
+
? windowDetails({ ...event.message, type: "custom_message" })
|
|
53
|
+
: undefined;
|
|
54
|
+
const previous = lifecycle.windows
|
|
55
|
+
.projectBranch(ctx.sessionManager.buildContextEntries())
|
|
56
|
+
.findLast(
|
|
57
|
+
(entry) =>
|
|
58
|
+
entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE,
|
|
59
|
+
);
|
|
60
|
+
if (!config.roles.length && !previous) return;
|
|
61
|
+
const reasoning = pi.getThinkingLevel();
|
|
62
|
+
const matching = config.roles
|
|
63
|
+
.filter(
|
|
64
|
+
(role) =>
|
|
65
|
+
role.provider === ctx.model?.provider &&
|
|
66
|
+
role.model === ctx.model?.id &&
|
|
67
|
+
role.reasoning === reasoning,
|
|
68
|
+
)
|
|
69
|
+
.map((role) => role.id);
|
|
70
|
+
const currentRole =
|
|
71
|
+
matching.length === 0
|
|
72
|
+
? "none (no matching preset)"
|
|
73
|
+
: matching.length === 1
|
|
74
|
+
? matching.join(", ")
|
|
75
|
+
: `ambiguous (${matching.join(", ")})`;
|
|
76
|
+
const content = config.roles.length
|
|
77
|
+
? [
|
|
78
|
+
`Current role: ${currentRole}`,
|
|
79
|
+
lifecycle.gptPromptMode()
|
|
80
|
+
? 'Roles=user preferences, not capability limits. Switch for clear, sustained task/scope change, not one specialised prompt. Any role can do general work. Bounded specialist detour→consider subagent. Save notes→new_context({role: "name"}); omit role→keep role.'
|
|
81
|
+
: 'Roles are user preferences, not capability limits. Switch for clear, sustained change of task or scope, not single specialised prompt. Any role can do general work. Consider subagents for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current role.',
|
|
82
|
+
...config.roles.map((role) => `- ${role.id}: ${role.description}`),
|
|
83
|
+
].join("\n")
|
|
84
|
+
: "No model roles available. Call new_context without role.";
|
|
85
|
+
if (
|
|
86
|
+
startingWindow?.kind !== "window" &&
|
|
87
|
+
previous?.type === "custom_message" &&
|
|
88
|
+
previous.content === content
|
|
89
|
+
)
|
|
90
|
+
return;
|
|
91
|
+
const message: CustomMessageEntryDraft = {
|
|
92
|
+
type: "custom_message",
|
|
93
|
+
customType: GUIDANCE_TYPE,
|
|
94
|
+
content,
|
|
95
|
+
display: false,
|
|
96
|
+
details: {},
|
|
97
|
+
};
|
|
98
|
+
return { message: lifecycle.prepareReminder?.(message) ?? message };
|
|
99
|
+
});
|
|
100
|
+
pi.on("context", (event, ctx) => {
|
|
101
|
+
if (
|
|
102
|
+
!lifecycle.active ||
|
|
103
|
+
event.messages.some(
|
|
104
|
+
(message) =>
|
|
105
|
+
message.role === "custom" && message.customType === GUIDANCE_TYPE,
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
return;
|
|
109
|
+
const summary = event.messages.findIndex(
|
|
110
|
+
(message) => message.role === "compactionSummary",
|
|
111
|
+
);
|
|
112
|
+
if (summary < 0) return;
|
|
113
|
+
const previous = ctx.sessionManager
|
|
114
|
+
.getBranch()
|
|
115
|
+
.findLast(
|
|
116
|
+
(entry) =>
|
|
117
|
+
entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE,
|
|
118
|
+
);
|
|
119
|
+
if (previous?.type !== "custom_message") return;
|
|
120
|
+
// In-run compaction has no new kickoff. Restore the owned entry before its summary.
|
|
121
|
+
return {
|
|
122
|
+
messages: [
|
|
123
|
+
...event.messages.slice(0, summary),
|
|
124
|
+
{
|
|
125
|
+
role: "custom" as const,
|
|
126
|
+
customType: previous.customType,
|
|
127
|
+
content: previous.content,
|
|
128
|
+
display: false,
|
|
129
|
+
details: previous.details,
|
|
130
|
+
timestamp: Date.parse(previous.timestamp),
|
|
131
|
+
},
|
|
132
|
+
...event.messages.slice(summary),
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
async function prepare(
|
|
138
|
+
id: string,
|
|
139
|
+
ctx: ExtensionContext,
|
|
140
|
+
): Promise<ModelRoleHandoff> {
|
|
141
|
+
load();
|
|
142
|
+
if (configError)
|
|
143
|
+
throw new Error(
|
|
144
|
+
"Model roles are unavailable. Continue here and ask the user to check /roles.",
|
|
145
|
+
);
|
|
146
|
+
const role = config.roles.find((candidate) => candidate.id === id);
|
|
147
|
+
if (!role)
|
|
148
|
+
throw new Error(
|
|
149
|
+
`Unknown role ${JSON.stringify(id)}. Use a configured role or omit role to keep the current model.`,
|
|
150
|
+
);
|
|
151
|
+
const model = ctx.modelRegistry.find(role.provider, role.model);
|
|
152
|
+
if (!model)
|
|
153
|
+
throw new Error(
|
|
154
|
+
`Role ${id} is unavailable. Continue here and ask the user to check its model in /roles.`,
|
|
155
|
+
);
|
|
156
|
+
if (!lifecycle.active || !modelIsActive(activation.settings, model))
|
|
157
|
+
throw new Error(
|
|
158
|
+
`Notes must be active for this session and role ${id}. Ask the user to check /notes before switching.`,
|
|
159
|
+
);
|
|
160
|
+
const session = ctx.sessionManager.getSessionId();
|
|
161
|
+
const source = ctx.model;
|
|
162
|
+
const reasoning = pi.getThinkingLevel();
|
|
163
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
164
|
+
if (!auth.ok)
|
|
165
|
+
throw new Error(
|
|
166
|
+
`Role ${id} has no usable provider access. Continue here and ask the user to check its login or API configuration.`,
|
|
167
|
+
);
|
|
168
|
+
return {
|
|
169
|
+
id,
|
|
170
|
+
async activate(current) {
|
|
171
|
+
if (
|
|
172
|
+
current.sessionManager.getSessionId() !== session ||
|
|
173
|
+
current.model?.provider !== source?.provider ||
|
|
174
|
+
current.model?.id !== source?.id ||
|
|
175
|
+
pi.getThinkingLevel() !== reasoning ||
|
|
176
|
+
!lifecycle.active ||
|
|
177
|
+
!modelIsActive(activation.settings, model)
|
|
178
|
+
)
|
|
179
|
+
throw new Error(
|
|
180
|
+
"The session or model settings changed. Continue here and request a new role handoff if still needed.",
|
|
181
|
+
);
|
|
182
|
+
if (source?.provider !== model.provider || source?.id !== model.id) {
|
|
183
|
+
if (!(await pi.setModel(model)))
|
|
184
|
+
throw new Error(
|
|
185
|
+
`Could not start role ${id}. Check provider access in /roles and retry.`,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
pi.setThinkingLevel(role.reasoning);
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function command(args: string, ctx: ExtensionCommandContext) {
|
|
194
|
+
if (args.trim()) {
|
|
195
|
+
ctx.ui.notify(
|
|
196
|
+
"Use /roles to view roles and JSON configuration guidance.",
|
|
197
|
+
"info",
|
|
198
|
+
);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (!ctx.hasUI) {
|
|
202
|
+
ctx.ui.notify(
|
|
203
|
+
`Configure model roles in ${roleConfigPath()}. Open /roles in interactive Pi for guidance.`,
|
|
204
|
+
"info",
|
|
205
|
+
);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
load();
|
|
209
|
+
return (await openModelRoleScreen(
|
|
210
|
+
ctx,
|
|
211
|
+
config.roles,
|
|
212
|
+
roleConfigPath(),
|
|
213
|
+
configError,
|
|
214
|
+
)) === "notes-tab"
|
|
215
|
+
? ("notes" as const)
|
|
216
|
+
: undefined;
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
prepare,
|
|
220
|
+
command,
|
|
221
|
+
onRoleIdsChanged(listener: (ids: string[]) => void) {
|
|
222
|
+
roleIdsChanged = listener;
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { minuteTimestamp } from "../timestamps.js";
|
|
2
|
+
import type { NoteRevision } from "./store.js";
|
|
3
|
+
|
|
4
|
+
export function canonicalPath(
|
|
5
|
+
path: unknown,
|
|
6
|
+
agent: string,
|
|
7
|
+
required = true,
|
|
8
|
+
): string {
|
|
9
|
+
if (path === undefined || path === null || path === "") {
|
|
10
|
+
if (required) throw new Error("Note file path is required");
|
|
11
|
+
return "";
|
|
12
|
+
}
|
|
13
|
+
if (typeof path !== "string")
|
|
14
|
+
throw new Error(
|
|
15
|
+
required ? "Note file path is required" : "Note prefix must be a string",
|
|
16
|
+
);
|
|
17
|
+
const root = `${agent}/notes`;
|
|
18
|
+
let value = path;
|
|
19
|
+
if (value === root) {
|
|
20
|
+
if (required)
|
|
21
|
+
throw new Error("Absolute note paths must use <agent>/notes/<path>");
|
|
22
|
+
value = "";
|
|
23
|
+
} else if (value.startsWith(`${root}/`)) value = value.slice(root.length + 1);
|
|
24
|
+
else if (value.startsWith("/"))
|
|
25
|
+
throw new Error(
|
|
26
|
+
"That agent's notes are not available here. Use a relative path for this agent.",
|
|
27
|
+
);
|
|
28
|
+
if (
|
|
29
|
+
(required && !value) ||
|
|
30
|
+
(value !== "" &&
|
|
31
|
+
value.split("/").some((part) => !part || part === ".." || part === "."))
|
|
32
|
+
)
|
|
33
|
+
throw new Error(
|
|
34
|
+
required
|
|
35
|
+
? "Note paths cannot contain empty, . or .. components"
|
|
36
|
+
: "Note prefixes cannot contain empty, . or .. components",
|
|
37
|
+
);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function normalizeNoteParams(
|
|
42
|
+
params: Record<string, unknown>,
|
|
43
|
+
agent: string,
|
|
44
|
+
): Record<string, unknown> {
|
|
45
|
+
const result = { ...params };
|
|
46
|
+
for (const field of ["path", "prefix", "path_prefix"])
|
|
47
|
+
if (field in params)
|
|
48
|
+
result[field] = canonicalPath(params[field], agent, field === "path");
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function readNotes(
|
|
53
|
+
notes: ReadonlyMap<string, NoteRevision>,
|
|
54
|
+
params: Record<string, unknown>,
|
|
55
|
+
agent: string,
|
|
56
|
+
): Record<string, unknown> {
|
|
57
|
+
const action = params["action"];
|
|
58
|
+
const root = `${agent}/notes/`;
|
|
59
|
+
if (action === "read_file") {
|
|
60
|
+
const path = params["path"] as string;
|
|
61
|
+
const note = notes.get(path);
|
|
62
|
+
if (!note) return { file: null };
|
|
63
|
+
const lines = note.text.split("\n");
|
|
64
|
+
const start = lineIndex(params["start_line"], lines.length, 0);
|
|
65
|
+
const stop = lineIndex(params["stop_line"], lines.length, lines.length - 1);
|
|
66
|
+
return {
|
|
67
|
+
file: {
|
|
68
|
+
path: `${root}${note.path}`,
|
|
69
|
+
content: start <= stop ? lines.slice(start, stop + 1).join("\n") : "",
|
|
70
|
+
...(note.mode === "append" ? { append_only: true } : {}),
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
if (action === "list_files_by_prefix") {
|
|
75
|
+
const by = params["file_order_by"];
|
|
76
|
+
const direction = params["file_order"] === "descending" ? -1 : 1;
|
|
77
|
+
const files = [...notes.values()]
|
|
78
|
+
.filter((note) => note.path.startsWith(String(params["prefix"] ?? "")))
|
|
79
|
+
.sort(
|
|
80
|
+
(a, b) =>
|
|
81
|
+
(by === "created_at"
|
|
82
|
+
? a.createdAt - b.createdAt
|
|
83
|
+
: by === "updated_at"
|
|
84
|
+
? a.updatedAt - b.updatedAt
|
|
85
|
+
: a.path.localeCompare(b.path)) * direction,
|
|
86
|
+
)
|
|
87
|
+
.map((note) => ({
|
|
88
|
+
path: `${root}${note.path}`,
|
|
89
|
+
updated_at: minuteTimestamp(note.updatedAt),
|
|
90
|
+
...(by === "created_at"
|
|
91
|
+
? { created_at: minuteTimestamp(note.createdAt) }
|
|
92
|
+
: {}),
|
|
93
|
+
}));
|
|
94
|
+
const limit = integer(params["max_results"], 20, 100);
|
|
95
|
+
return {
|
|
96
|
+
files: files.slice(0, limit),
|
|
97
|
+
...(files.length > limit ? { truncated: true } : {}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (action !== "search_contents")
|
|
101
|
+
throw new Error("notes requires a supported action");
|
|
102
|
+
const query = params["query"];
|
|
103
|
+
if (typeof query !== "string" || !query)
|
|
104
|
+
throw new Error("notes search_contents requires query");
|
|
105
|
+
const files = [...notes.values()].filter((note) =>
|
|
106
|
+
note.path.startsWith(String(params["path_prefix"] ?? "")),
|
|
107
|
+
);
|
|
108
|
+
files.sort(
|
|
109
|
+
params["recent_file_first"] === true
|
|
110
|
+
? (a, b) => b.createdAt - a.createdAt
|
|
111
|
+
: (a, b) => a.path.localeCompare(b.path),
|
|
112
|
+
);
|
|
113
|
+
const found: Record<string, unknown>[] = [];
|
|
114
|
+
const fileLimit = integer(params["max_files"], 20, 100);
|
|
115
|
+
const matchLimit = integer(params["max_matches_per_file"], 20, 100);
|
|
116
|
+
for (const note of files) {
|
|
117
|
+
const matches = note.text
|
|
118
|
+
.split("\n")
|
|
119
|
+
.map((line, index) => ({ line_number: index + 1, line }))
|
|
120
|
+
.filter(({ line }) => line.includes(query));
|
|
121
|
+
if (!matches.length) continue;
|
|
122
|
+
if (found.length === fileLimit) return { files: found, truncated: true };
|
|
123
|
+
found.push({
|
|
124
|
+
path: `${root}${note.path}`,
|
|
125
|
+
matches: matches.slice(0, matchLimit),
|
|
126
|
+
...(matches.length > matchLimit ? { truncated: true } : {}),
|
|
127
|
+
...(note.mode === "append" ? { append_only: true } : {}),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return { files: found };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function lineIndex(
|
|
134
|
+
value: unknown,
|
|
135
|
+
lineCount: number,
|
|
136
|
+
fallback: number,
|
|
137
|
+
): number {
|
|
138
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value === 0)
|
|
139
|
+
return fallback;
|
|
140
|
+
const index = value > 0 ? value - 1 : lineCount + value;
|
|
141
|
+
return Math.max(0, Math.min(index, Math.max(0, lineCount - 1)));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function integer(value: unknown, fallback: number, max: number): number {
|
|
145
|
+
return typeof value === "number" && Number.isInteger(value)
|
|
146
|
+
? Math.max(1, Math.min(value, max))
|
|
147
|
+
: fallback;
|
|
148
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Check } from "typebox/value";
|
|
4
|
+
|
|
5
|
+
const OPTIONAL_STRING = Type.Optional(Type.String());
|
|
6
|
+
const OPTIONAL_BOOLEAN = Type.Optional(Type.Boolean());
|
|
7
|
+
const MATCH = Type.Object({ line_number: Type.Integer(), line: Type.String() });
|
|
8
|
+
|
|
9
|
+
// Pi codemode needs this declaration to return structuredContent rather than text.
|
|
10
|
+
export const NOTES_OUTPUT_SCHEMA = Type.Object(
|
|
11
|
+
{},
|
|
12
|
+
{ additionalProperties: true },
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
const NOTES_RESULT_SCHEMA = Type.Object(
|
|
16
|
+
{
|
|
17
|
+
file: Type.Optional(
|
|
18
|
+
Type.Union([
|
|
19
|
+
Type.Object({
|
|
20
|
+
path: Type.String(),
|
|
21
|
+
content: OPTIONAL_STRING,
|
|
22
|
+
append_only: OPTIONAL_BOOLEAN,
|
|
23
|
+
}),
|
|
24
|
+
Type.Null(),
|
|
25
|
+
]),
|
|
26
|
+
),
|
|
27
|
+
files: Type.Optional(
|
|
28
|
+
Type.Array(
|
|
29
|
+
Type.Object({
|
|
30
|
+
path: Type.String(),
|
|
31
|
+
updated_at: OPTIONAL_STRING,
|
|
32
|
+
created_at: OPTIONAL_STRING,
|
|
33
|
+
matches: Type.Optional(Type.Array(MATCH)),
|
|
34
|
+
truncated: OPTIONAL_BOOLEAN,
|
|
35
|
+
append_only: OPTIONAL_BOOLEAN,
|
|
36
|
+
}),
|
|
37
|
+
),
|
|
38
|
+
),
|
|
39
|
+
usage: OPTIONAL_STRING,
|
|
40
|
+
warnings: Type.Optional(Type.Array(Type.String())),
|
|
41
|
+
warning: OPTIONAL_STRING,
|
|
42
|
+
truncated: OPTIONAL_BOOLEAN,
|
|
43
|
+
read_only: OPTIONAL_BOOLEAN,
|
|
44
|
+
saved_at: OPTIONAL_STRING,
|
|
45
|
+
captured_at: OPTIONAL_STRING,
|
|
46
|
+
results: OPTIONAL_STRING,
|
|
47
|
+
actions: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
48
|
+
writes: OPTIONAL_STRING,
|
|
49
|
+
paths: OPTIONAL_STRING,
|
|
50
|
+
ranges: OPTIONAL_STRING,
|
|
51
|
+
defaults: OPTIONAL_STRING,
|
|
52
|
+
},
|
|
53
|
+
{ additionalProperties: false },
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
/** One canonical payload for native text and every programmatic caller. */
|
|
57
|
+
export function noteResult(payload: unknown): AgentToolResult<unknown> {
|
|
58
|
+
if (!Check(NOTES_RESULT_SCHEMA, payload))
|
|
59
|
+
throw new Error(
|
|
60
|
+
"Notes returned invalid data. Read the note before retrying a write.",
|
|
61
|
+
);
|
|
62
|
+
// Sharing annotations and storage bookkeeping are not note contents.
|
|
63
|
+
const {
|
|
64
|
+
read_only: _readOnly,
|
|
65
|
+
warning: _warning,
|
|
66
|
+
saved_at: _savedAt,
|
|
67
|
+
captured_at: _capturedAt,
|
|
68
|
+
...visible
|
|
69
|
+
} = payload;
|
|
70
|
+
if (visible.file)
|
|
71
|
+
visible.file = {
|
|
72
|
+
path: visible.file.path,
|
|
73
|
+
...(visible.file.content === undefined
|
|
74
|
+
? {}
|
|
75
|
+
: { content: visible.file.content }),
|
|
76
|
+
};
|
|
77
|
+
if (visible.files)
|
|
78
|
+
visible.files = visible.files.map(({ path, matches, truncated }) => ({
|
|
79
|
+
path,
|
|
80
|
+
...(matches === undefined ? {} : { matches }),
|
|
81
|
+
...(truncated === undefined ? {} : { truncated }),
|
|
82
|
+
}));
|
|
83
|
+
return {
|
|
84
|
+
content: [{ type: "text", text: JSON.stringify(visible) }],
|
|
85
|
+
structuredContent: visible,
|
|
86
|
+
details: {},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
6
|
+
import { hasFreshNotes } from "./fresh-notes.js";
|
|
7
|
+
|
|
8
|
+
const NOTE_SAVE_MARKER = "codex-note-save-marker";
|
|
9
|
+
|
|
10
|
+
/** Display and bookmarks share the same completed checkpoint evidence. */
|
|
11
|
+
export function registerNoteSaveMarkers(
|
|
12
|
+
pi: ExtensionAPI,
|
|
13
|
+
enabled: () => boolean,
|
|
14
|
+
currentWindowId: () => string | undefined,
|
|
15
|
+
) {
|
|
16
|
+
let manager: ExtensionContext["sessionManager"] | undefined;
|
|
17
|
+
let cached:
|
|
18
|
+
| {
|
|
19
|
+
leaf: string | null;
|
|
20
|
+
windowId: string | undefined;
|
|
21
|
+
id: string | undefined;
|
|
22
|
+
}
|
|
23
|
+
| undefined;
|
|
24
|
+
const restore = (_event: unknown, ctx: ExtensionContext) => {
|
|
25
|
+
manager = ctx.sessionManager;
|
|
26
|
+
cached = undefined;
|
|
27
|
+
};
|
|
28
|
+
pi.on("session_tree", restore);
|
|
29
|
+
pi.on("session_compact", restore);
|
|
30
|
+
pi.on("session_shutdown", () => {
|
|
31
|
+
manager = undefined;
|
|
32
|
+
cached = undefined;
|
|
33
|
+
});
|
|
34
|
+
pi.registerEntryRenderer(NOTE_SAVE_MARKER, (entry, _options, theme) => {
|
|
35
|
+
if (!enabled()) return undefined;
|
|
36
|
+
const content = theme.fg("success", "✓ Notes saved");
|
|
37
|
+
return new (class extends Text {
|
|
38
|
+
override render(width: number): string[] {
|
|
39
|
+
const leaf = manager?.getLeafId();
|
|
40
|
+
const windowId = currentWindowId();
|
|
41
|
+
if (
|
|
42
|
+
manager &&
|
|
43
|
+
(!cached || cached.leaf !== leaf || cached.windowId !== windowId)
|
|
44
|
+
) {
|
|
45
|
+
const branch = manager.getBranch();
|
|
46
|
+
cached = {
|
|
47
|
+
leaf: manager.getLeafId(),
|
|
48
|
+
windowId,
|
|
49
|
+
id: hasFreshNotes(branch, windowId)
|
|
50
|
+
? branch.findLast(
|
|
51
|
+
(item) =>
|
|
52
|
+
item.type === "custom" &&
|
|
53
|
+
item.customType === NOTE_SAVE_MARKER,
|
|
54
|
+
)?.id
|
|
55
|
+
: undefined,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const visible = manager && enabled() && cached?.id === entry.id;
|
|
59
|
+
this.setText(visible ? content : "");
|
|
60
|
+
return visible ? super.render(width) : [];
|
|
61
|
+
}
|
|
62
|
+
})("", 0, 0);
|
|
63
|
+
});
|
|
64
|
+
return {
|
|
65
|
+
start(ctx: ExtensionContext) {
|
|
66
|
+
restore(undefined, ctx);
|
|
67
|
+
},
|
|
68
|
+
record(
|
|
69
|
+
ctx: ExtensionContext,
|
|
70
|
+
windowId: string | undefined,
|
|
71
|
+
runId: string,
|
|
72
|
+
aborted: boolean,
|
|
73
|
+
) {
|
|
74
|
+
if (
|
|
75
|
+
!enabled() ||
|
|
76
|
+
aborted ||
|
|
77
|
+
!ctx.isIdle() ||
|
|
78
|
+
!hasFreshNotes(ctx.sessionManager.getBranch(), windowId, runId)
|
|
79
|
+
)
|
|
80
|
+
return;
|
|
81
|
+
const completed = ctx.sessionManager
|
|
82
|
+
.getBranch()
|
|
83
|
+
.findLast(
|
|
84
|
+
(entry) =>
|
|
85
|
+
entry.type === "message" && entry.message.role === "assistant",
|
|
86
|
+
);
|
|
87
|
+
if (
|
|
88
|
+
!completed ||
|
|
89
|
+
ctx.sessionManager
|
|
90
|
+
.getEntries()
|
|
91
|
+
.some(
|
|
92
|
+
(entry) =>
|
|
93
|
+
entry.type === "custom" &&
|
|
94
|
+
entry.customType === NOTE_SAVE_MARKER &&
|
|
95
|
+
entry.data &&
|
|
96
|
+
typeof entry.data === "object" &&
|
|
97
|
+
"completedEntryId" in entry.data &&
|
|
98
|
+
entry.data.completedEntryId === completed.id,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
return;
|
|
102
|
+
pi.appendEntry(NOTE_SAVE_MARKER, { completedEntryId: completed.id });
|
|
103
|
+
},
|
|
104
|
+
bookmark(ctx: ExtensionContext, windowId: string | undefined) {
|
|
105
|
+
if (!enabled()) return;
|
|
106
|
+
const branch = ctx.sessionManager.getBranch();
|
|
107
|
+
const marker = branch.findLastIndex(
|
|
108
|
+
(entry) =>
|
|
109
|
+
entry.type === "custom" && entry.customType === NOTE_SAVE_MARKER,
|
|
110
|
+
);
|
|
111
|
+
if (marker < 0) return;
|
|
112
|
+
const promptIndex = branch.findIndex(
|
|
113
|
+
(entry, index) =>
|
|
114
|
+
index > marker &&
|
|
115
|
+
entry.type === "message" &&
|
|
116
|
+
entry.message.role === "user",
|
|
117
|
+
);
|
|
118
|
+
const prompt = branch[promptIndex];
|
|
119
|
+
if (
|
|
120
|
+
!prompt ||
|
|
121
|
+
ctx.sessionManager.getLabel(prompt.id) ||
|
|
122
|
+
!hasFreshNotes(branch.slice(0, promptIndex), windowId)
|
|
123
|
+
)
|
|
124
|
+
return;
|
|
125
|
+
pi.setLabel(prompt.id, "Notes");
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AgentToolResult,
|
|
3
|
+
ExtensionAPI,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type {
|
|
7
|
+
CachedResponse,
|
|
8
|
+
LookupQuery,
|
|
9
|
+
SerializedCachedResponse,
|
|
10
|
+
} from "./bridge.js";
|
|
11
|
+
import { queryKey } from "./bridge.js";
|
|
12
|
+
import type { NotesLifecycle } from "./lifecycle.js";
|
|
13
|
+
import { noteResult } from "./note-result.js";
|
|
14
|
+
import { CACHE_RECEIPT, sessionRef, sourceSessionIds } from "./notes.js";
|
|
15
|
+
import type { NotesStore } from "./store.js";
|
|
16
|
+
|
|
17
|
+
export async function lookupNotes(
|
|
18
|
+
pi: ExtensionAPI,
|
|
19
|
+
store: NotesStore,
|
|
20
|
+
lifecycle: NotesLifecycle,
|
|
21
|
+
query: LookupQuery,
|
|
22
|
+
local: Record<string, unknown>,
|
|
23
|
+
callId: string,
|
|
24
|
+
ctx: ExtensionContext,
|
|
25
|
+
signal?: AbortSignal,
|
|
26
|
+
shared = false,
|
|
27
|
+
replacementsInScope = false,
|
|
28
|
+
): Promise<AgentToolResult<unknown>> {
|
|
29
|
+
let responses: readonly CachedResponse[] = store.cached(
|
|
30
|
+
sourceSessionIds(ctx),
|
|
31
|
+
query,
|
|
32
|
+
);
|
|
33
|
+
let state = responses.length ? "cache" : "unavailable";
|
|
34
|
+
let lookupFailed = false;
|
|
35
|
+
const bridge = lifecycle.bridge;
|
|
36
|
+
if (bridge?.lookup) {
|
|
37
|
+
let fetched: readonly CachedResponse[] | undefined;
|
|
38
|
+
try {
|
|
39
|
+
fetched = await bridge.lookup(query, ctx, signal);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (signal?.aborted) throw error;
|
|
42
|
+
lookupFailed = true;
|
|
43
|
+
}
|
|
44
|
+
if (signal?.aborted) throw new Error("Lookup cancelled");
|
|
45
|
+
if (fetched) {
|
|
46
|
+
try {
|
|
47
|
+
store.cache(sessionRef(ctx), fetched);
|
|
48
|
+
} catch {
|
|
49
|
+
throw new Error(
|
|
50
|
+
"Notes lookup could not finish. Retry when local storage is available.",
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
if (fetched.length)
|
|
54
|
+
pi.appendEntry(CACHE_RECEIPT, {
|
|
55
|
+
protocol: 1,
|
|
56
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
57
|
+
});
|
|
58
|
+
const exact = fetched.filter(
|
|
59
|
+
(response) => queryKey(response.query) === queryKey(query),
|
|
60
|
+
);
|
|
61
|
+
if (exact.length) {
|
|
62
|
+
responses = exact;
|
|
63
|
+
state = "live";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const canProject =
|
|
68
|
+
shared ||
|
|
69
|
+
(Boolean(bridge?.projectResult) && bridge?.canProject?.(ctx) !== false);
|
|
70
|
+
if (responses.length && !canProject) state = "incompatible";
|
|
71
|
+
const warnings: string[] = [];
|
|
72
|
+
if (state === "incompatible")
|
|
73
|
+
warnings.push(
|
|
74
|
+
"Some notes cannot be read with this model. Available notes are shown; ask the user to select a compatible Codex model to read the rest.",
|
|
75
|
+
);
|
|
76
|
+
else if (state === "cache")
|
|
77
|
+
warnings.push(
|
|
78
|
+
"These results could not be refreshed and may be outdated. Retry when access is restored.",
|
|
79
|
+
);
|
|
80
|
+
else if (lookupFailed)
|
|
81
|
+
warnings.push(
|
|
82
|
+
"Some notes could not be retrieved. Available notes are shown; retry the lookup to check for missing results.",
|
|
83
|
+
);
|
|
84
|
+
if (responses.length && canProject && replacementsInScope)
|
|
85
|
+
warnings.push(
|
|
86
|
+
"Older matches may refer to replaced notes. Read a note before relying on its excerpt; read returns the current saved version.",
|
|
87
|
+
);
|
|
88
|
+
const output = noteResult({
|
|
89
|
+
...local,
|
|
90
|
+
...(warnings.length ? { warnings } : {}),
|
|
91
|
+
});
|
|
92
|
+
if (shared)
|
|
93
|
+
return {
|
|
94
|
+
...output,
|
|
95
|
+
details: {
|
|
96
|
+
codexHistoryNotes: {},
|
|
97
|
+
externalNotesResponses: responses.map(
|
|
98
|
+
({ bytes, ...response }): SerializedCachedResponse => ({
|
|
99
|
+
...response,
|
|
100
|
+
bytesBase64: Buffer.from(bytes).toString("base64"),
|
|
101
|
+
}),
|
|
102
|
+
),
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
if (responses.length && canProject && bridge?.projectResult) {
|
|
106
|
+
try {
|
|
107
|
+
return await bridge.projectResult(output, responses, callId, ctx, signal);
|
|
108
|
+
} catch {
|
|
109
|
+
throw new Error(
|
|
110
|
+
"Notes could not be displayed. Retry the lookup with a compatible Codex model.",
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return output;
|
|
115
|
+
}
|