@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,376 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AgentToolResult,
|
|
3
|
+
ExtensionAPI,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import {
|
|
7
|
+
bindProtectedOutputScope,
|
|
8
|
+
canDeliverProtectedOutput,
|
|
9
|
+
protectedAccountScope,
|
|
10
|
+
resolveActiveCodexProvider,
|
|
11
|
+
resolveProtectedOutputScope,
|
|
12
|
+
} from "@howaboua/pi-codex-conversion/code-mode";
|
|
13
|
+
import {
|
|
14
|
+
type ContextAgentIdentity,
|
|
15
|
+
canonicalContextIdentity,
|
|
16
|
+
contextAgentIdentity,
|
|
17
|
+
contextStorageAgentName,
|
|
18
|
+
contextTargetAgent,
|
|
19
|
+
isContextAgentName,
|
|
20
|
+
} from "./agent-identity.js";
|
|
21
|
+
import type { CachedResponse, LookupQuery } from "./bridge.js";
|
|
22
|
+
import type {
|
|
23
|
+
RemoteNoteReference,
|
|
24
|
+
SharedContextRequest,
|
|
25
|
+
SharedContextResult,
|
|
26
|
+
} from "./context-sharing.js";
|
|
27
|
+
import { noteResult } from "./note-result.js";
|
|
28
|
+
|
|
29
|
+
const ENDPOINTS = {
|
|
30
|
+
list_files_by_prefix: [
|
|
31
|
+
"file_order",
|
|
32
|
+
"file_order_by",
|
|
33
|
+
"max_results",
|
|
34
|
+
"prefix",
|
|
35
|
+
],
|
|
36
|
+
read_file: ["path", "start_line", "stop_line"],
|
|
37
|
+
search_contents: [
|
|
38
|
+
"max_files",
|
|
39
|
+
"max_matches_per_file",
|
|
40
|
+
"path_prefix",
|
|
41
|
+
"query",
|
|
42
|
+
"recent_file_first",
|
|
43
|
+
],
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
function readQuery(query: LookupQuery): {
|
|
47
|
+
action: string;
|
|
48
|
+
args: Record<string, unknown>;
|
|
49
|
+
} {
|
|
50
|
+
if (query.namespace !== "notes")
|
|
51
|
+
throw new Error(
|
|
52
|
+
"History is available only from saved Pi JSONL sessions. Restore access to the session on this machine, then retry.",
|
|
53
|
+
);
|
|
54
|
+
const action = query.params["action"];
|
|
55
|
+
const actions: Record<string, readonly string[]> = ENDPOINTS;
|
|
56
|
+
if (typeof action !== "string" || !Object.hasOwn(actions, action))
|
|
57
|
+
throw new Error("Remote lookup requires a supported read action");
|
|
58
|
+
const fields = actions[action]!;
|
|
59
|
+
for (const [field, value] of Object.entries(query.params)) {
|
|
60
|
+
if (field === "action") continue;
|
|
61
|
+
if (!fields.includes(field))
|
|
62
|
+
throw new Error(`${query.namespace} ${action} does not accept ${field}`);
|
|
63
|
+
if (value === undefined || value === null) continue;
|
|
64
|
+
if (
|
|
65
|
+
[
|
|
66
|
+
"max_results",
|
|
67
|
+
"max_files",
|
|
68
|
+
"max_matches_per_file",
|
|
69
|
+
"start_line",
|
|
70
|
+
"stop_line",
|
|
71
|
+
].includes(field)
|
|
72
|
+
) {
|
|
73
|
+
if (
|
|
74
|
+
typeof value !== "number" ||
|
|
75
|
+
!Number.isSafeInteger(value) ||
|
|
76
|
+
(!["start_line", "stop_line"].includes(field) && value < 1)
|
|
77
|
+
)
|
|
78
|
+
throw new Error(`Invalid ${field}`);
|
|
79
|
+
} else if (field === "recent_file_first") {
|
|
80
|
+
if (typeof value !== "boolean") throw new Error(`Invalid ${field}`);
|
|
81
|
+
} else if (typeof value !== "string") throw new Error(`Invalid ${field}`);
|
|
82
|
+
}
|
|
83
|
+
const required =
|
|
84
|
+
action === "read_file"
|
|
85
|
+
? ["path"]
|
|
86
|
+
: action === "search_contents"
|
|
87
|
+
? ["query"]
|
|
88
|
+
: [];
|
|
89
|
+
for (const field of required)
|
|
90
|
+
if (typeof query.params[field] !== "string" || !query.params[field])
|
|
91
|
+
throw new Error(`${query.namespace} ${action} requires ${field}`);
|
|
92
|
+
const { action: _action, ...args } = query.params;
|
|
93
|
+
return { action, args };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function scope(
|
|
97
|
+
identity: ContextAgentIdentity,
|
|
98
|
+
accountId: string,
|
|
99
|
+
baseUrl: string,
|
|
100
|
+
): string {
|
|
101
|
+
return JSON.stringify({
|
|
102
|
+
threadId: identity.threadId,
|
|
103
|
+
sessionId: identity.sessionId,
|
|
104
|
+
agentName: contextStorageAgentName(identity),
|
|
105
|
+
accountScope: protectedAccountScope(accountId),
|
|
106
|
+
baseUrl,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function authenticated(ctx: ExtensionContext) {
|
|
111
|
+
const identity = contextAgentIdentity(ctx);
|
|
112
|
+
const before = JSON.stringify([identity, ctx.model]);
|
|
113
|
+
const provider = await resolveActiveCodexProvider(ctx);
|
|
114
|
+
const unchanged = () =>
|
|
115
|
+
before === JSON.stringify([contextAgentIdentity(ctx), ctx.model]);
|
|
116
|
+
if (!unchanged())
|
|
117
|
+
throw new Error(
|
|
118
|
+
"Context changed during authentication; retry in the original session",
|
|
119
|
+
);
|
|
120
|
+
if (
|
|
121
|
+
identity.accountScope &&
|
|
122
|
+
identity.accountScope !== protectedAccountScope(provider.accountId)
|
|
123
|
+
)
|
|
124
|
+
throw new Error("Remote contents belong to a different account");
|
|
125
|
+
if (identity.backendUrl && identity.backendUrl !== provider.baseUrl)
|
|
126
|
+
throw new Error("Remote contents belong to a different backend");
|
|
127
|
+
return {
|
|
128
|
+
identity,
|
|
129
|
+
provider,
|
|
130
|
+
unchanged,
|
|
131
|
+
source: scope(identity, provider.accountId, provider.baseUrl),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Automatic hybrid reads only. Writes and encrypted argument dispatch are deliberately absent. */
|
|
136
|
+
export function createNotesRemoteService(pi: ExtensionAPI) {
|
|
137
|
+
return {
|
|
138
|
+
canProject: (ctx: ExtensionContext) =>
|
|
139
|
+
ctx.model?.api === "openai-codex-responses" &&
|
|
140
|
+
canDeliverProtectedOutput(pi, ctx),
|
|
141
|
+
lookup: lookupRemoteNotes,
|
|
142
|
+
projectResult: projectNotesResponses,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function lookupRemoteNotes(
|
|
147
|
+
query: LookupQuery,
|
|
148
|
+
ctx: ExtensionContext,
|
|
149
|
+
signal?: AbortSignal,
|
|
150
|
+
): Promise<readonly CachedResponse[]> {
|
|
151
|
+
return lookup(query, ctx, signal);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function lookup(
|
|
155
|
+
query: LookupQuery,
|
|
156
|
+
ctx: ExtensionContext,
|
|
157
|
+
signal?: AbortSignal,
|
|
158
|
+
target?: RemoteNoteReference,
|
|
159
|
+
): Promise<readonly CachedResponse[]> {
|
|
160
|
+
const { action, args } = readQuery(query);
|
|
161
|
+
if (target) {
|
|
162
|
+
const identity = canonicalContextIdentity(target.identity);
|
|
163
|
+
for (const field of ["path", "prefix", "path_prefix"]) {
|
|
164
|
+
const value = args[field];
|
|
165
|
+
if (
|
|
166
|
+
typeof value === "string" &&
|
|
167
|
+
(value === `${identity.agentName}/notes` ||
|
|
168
|
+
value.startsWith(`${identity.agentName}/notes/`))
|
|
169
|
+
)
|
|
170
|
+
args[field] =
|
|
171
|
+
`${contextStorageAgentName(identity)}${value.slice(identity.agentName.length)}`;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const auth = await authenticated(ctx);
|
|
175
|
+
if (target) checkReference(target, auth.provider);
|
|
176
|
+
const headers = auth.provider.headers;
|
|
177
|
+
headers.set(
|
|
178
|
+
"x-openai-tool-output-truncation-policy",
|
|
179
|
+
JSON.stringify({ mode: "tokens", limit: 10_000 }),
|
|
180
|
+
);
|
|
181
|
+
const response = await fetch(
|
|
182
|
+
`${auth.provider.baseUrl.replace(/\/+$/, "")}/alpha/notes/v2/${action}`,
|
|
183
|
+
{
|
|
184
|
+
method: "POST",
|
|
185
|
+
headers,
|
|
186
|
+
signal: signal
|
|
187
|
+
? AbortSignal.any([signal, AbortSignal.timeout(35_000)])
|
|
188
|
+
: AbortSignal.timeout(35_000),
|
|
189
|
+
body: JSON.stringify({
|
|
190
|
+
...args,
|
|
191
|
+
context: {
|
|
192
|
+
session_id: target?.identity.sessionId ?? auth.identity.sessionId,
|
|
193
|
+
current_agent_name: contextStorageAgentName(
|
|
194
|
+
target?.identity ?? auth.identity,
|
|
195
|
+
),
|
|
196
|
+
},
|
|
197
|
+
}),
|
|
198
|
+
},
|
|
199
|
+
);
|
|
200
|
+
if (!response.ok)
|
|
201
|
+
throw new Error(`Remote lookup failed (${response.status})`);
|
|
202
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
203
|
+
const envelope: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
|
204
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope))
|
|
205
|
+
throw new Error("Remote lookup returned invalid data");
|
|
206
|
+
if (!auth.unchanged())
|
|
207
|
+
throw new Error(
|
|
208
|
+
"Context changed during lookup; retry in the original session",
|
|
209
|
+
);
|
|
210
|
+
return [
|
|
211
|
+
{
|
|
212
|
+
query,
|
|
213
|
+
bytes,
|
|
214
|
+
encoding: response.headers.get("content-type") ?? "application/json",
|
|
215
|
+
source: target
|
|
216
|
+
? scope(target.identity, auth.provider.accountId, auth.provider.baseUrl)
|
|
217
|
+
: auth.source,
|
|
218
|
+
fetchedAt: Date.now(),
|
|
219
|
+
coverage: "unknown",
|
|
220
|
+
},
|
|
221
|
+
];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function checkReference(
|
|
225
|
+
reference: RemoteNoteReference,
|
|
226
|
+
provider: { accountId: string; baseUrl: string },
|
|
227
|
+
): void {
|
|
228
|
+
if (
|
|
229
|
+
reference.identity.accountScope !==
|
|
230
|
+
protectedAccountScope(provider.accountId)
|
|
231
|
+
)
|
|
232
|
+
throw new Error("Saved remote contents belong to a different account");
|
|
233
|
+
if (
|
|
234
|
+
reference.baseUrl !== provider.baseUrl ||
|
|
235
|
+
reference.identity.backendUrl !== provider.baseUrl
|
|
236
|
+
)
|
|
237
|
+
throw new Error("Saved remote contents belong to a different backend");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function verifyRemoteReference(
|
|
241
|
+
ctx: ExtensionContext,
|
|
242
|
+
reference: RemoteNoteReference,
|
|
243
|
+
): Promise<void> {
|
|
244
|
+
checkReference(reference, (await authenticated(ctx)).provider);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Saved references authorise reads against their original owner, never writes. */
|
|
248
|
+
export async function executeRemoteAttachment(
|
|
249
|
+
ctx: ExtensionContext,
|
|
250
|
+
reference: RemoteNoteReference,
|
|
251
|
+
request: SharedContextRequest,
|
|
252
|
+
signal?: AbortSignal,
|
|
253
|
+
): Promise<SharedContextResult> {
|
|
254
|
+
if (request.namespace === "history")
|
|
255
|
+
throw new Error(
|
|
256
|
+
"History is unavailable from a saved remote notes attachment. Open its saved Pi JSONL session on this machine, then retry.",
|
|
257
|
+
);
|
|
258
|
+
const identity = canonicalContextIdentity(reference.identity);
|
|
259
|
+
if (
|
|
260
|
+
request.sessionId !== reference.identity.sessionId ||
|
|
261
|
+
(request.agentName !== identity.agentName &&
|
|
262
|
+
request.agentName !== contextStorageAgentName(identity)) ||
|
|
263
|
+
contextTargetAgent(
|
|
264
|
+
request.namespace,
|
|
265
|
+
request.params,
|
|
266
|
+
reference.identity.agentName,
|
|
267
|
+
) !== request.agentName
|
|
268
|
+
)
|
|
269
|
+
throw new Error(
|
|
270
|
+
"Saved remote request does not belong to its checkpoint owner",
|
|
271
|
+
);
|
|
272
|
+
if (request.encryptedArguments)
|
|
273
|
+
throw new Error("Saved remote reads require ordinary query arguments");
|
|
274
|
+
const responses = await lookup(
|
|
275
|
+
{ namespace: request.namespace, params: request.params },
|
|
276
|
+
ctx,
|
|
277
|
+
signal,
|
|
278
|
+
reference,
|
|
279
|
+
);
|
|
280
|
+
return {
|
|
281
|
+
...noteResult({}),
|
|
282
|
+
details: {
|
|
283
|
+
codexHistoryNotes: {},
|
|
284
|
+
externalNotesResponses: responses.map(({ bytes, ...response }) => ({
|
|
285
|
+
...response,
|
|
286
|
+
bytesBase64: Buffer.from(bytes).toString("base64"),
|
|
287
|
+
})),
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function projectNotesResponses(
|
|
293
|
+
result: AgentToolResult<unknown>,
|
|
294
|
+
responses: readonly CachedResponse[],
|
|
295
|
+
callId: string,
|
|
296
|
+
ctx: ExtensionContext,
|
|
297
|
+
signal?: AbortSignal,
|
|
298
|
+
relay = false,
|
|
299
|
+
): Promise<AgentToolResult<unknown>> {
|
|
300
|
+
signal?.throwIfAborted();
|
|
301
|
+
if (!callId)
|
|
302
|
+
throw new Error("Protected delivery requires a current tool call");
|
|
303
|
+
if (!responses.length)
|
|
304
|
+
return { ...result, content: result.content.map((part) => ({ ...part })) };
|
|
305
|
+
const auth = await authenticated(ctx);
|
|
306
|
+
const source = responses[0]!.source;
|
|
307
|
+
if (relay) {
|
|
308
|
+
const provenance: unknown = JSON.parse(source);
|
|
309
|
+
if (
|
|
310
|
+
!provenance ||
|
|
311
|
+
typeof provenance !== "object" ||
|
|
312
|
+
!("accountScope" in provenance) ||
|
|
313
|
+
provenance.accountScope !==
|
|
314
|
+
protectedAccountScope(auth.provider.accountId) ||
|
|
315
|
+
!("baseUrl" in provenance) ||
|
|
316
|
+
provenance.baseUrl !== auth.provider.baseUrl ||
|
|
317
|
+
!("threadId" in provenance) ||
|
|
318
|
+
typeof provenance.threadId !== "string" ||
|
|
319
|
+
!provenance.threadId ||
|
|
320
|
+
!("sessionId" in provenance) ||
|
|
321
|
+
typeof provenance.sessionId !== "string" ||
|
|
322
|
+
!provenance.sessionId ||
|
|
323
|
+
!("agentName" in provenance) ||
|
|
324
|
+
typeof provenance.agentName !== "string" ||
|
|
325
|
+
!isContextAgentName(provenance.agentName)
|
|
326
|
+
)
|
|
327
|
+
throw new Error(
|
|
328
|
+
"Shared protected contents belong to a different account or backend",
|
|
329
|
+
);
|
|
330
|
+
} else if (source !== auth.source)
|
|
331
|
+
throw new Error("Cached response belongs to a different context");
|
|
332
|
+
const protectedOutputs = responses.map((response, index) => {
|
|
333
|
+
if (response.source !== source)
|
|
334
|
+
throw new Error("Protected responses have different owners");
|
|
335
|
+
readQuery(response.query);
|
|
336
|
+
const envelope: unknown = JSON.parse(
|
|
337
|
+
new TextDecoder().decode(response.bytes),
|
|
338
|
+
);
|
|
339
|
+
if (
|
|
340
|
+
!envelope ||
|
|
341
|
+
typeof envelope !== "object" ||
|
|
342
|
+
!("encrypted_output" in envelope) ||
|
|
343
|
+
typeof envelope.encrypted_output !== "string" ||
|
|
344
|
+
!envelope.encrypted_output.trim()
|
|
345
|
+
)
|
|
346
|
+
throw new Error("Cached response contains no protected output");
|
|
347
|
+
const hint =
|
|
348
|
+
"attachment_hint" in envelope &&
|
|
349
|
+
typeof envelope.attachment_hint === "string"
|
|
350
|
+
? envelope.attachment_hint
|
|
351
|
+
: undefined;
|
|
352
|
+
return {
|
|
353
|
+
resultId: `${callId}:${index}`,
|
|
354
|
+
name: response.query.namespace + (hint ? `; ${hint}` : ""),
|
|
355
|
+
encryptedOutput: envelope.encrypted_output,
|
|
356
|
+
};
|
|
357
|
+
});
|
|
358
|
+
const deliveryScope = await resolveProtectedOutputScope(ctx);
|
|
359
|
+
if (!auth.unchanged())
|
|
360
|
+
throw new Error(
|
|
361
|
+
"Context changed during protected delivery; retry in the original session",
|
|
362
|
+
);
|
|
363
|
+
signal?.throwIfAborted();
|
|
364
|
+
const details = {
|
|
365
|
+
...(result.details && typeof result.details === "object"
|
|
366
|
+
? result.details
|
|
367
|
+
: {}),
|
|
368
|
+
protectedOutputs,
|
|
369
|
+
};
|
|
370
|
+
bindProtectedOutputScope(details, deliveryScope);
|
|
371
|
+
return {
|
|
372
|
+
...result,
|
|
373
|
+
content: result.content.map((part) => ({ ...part })),
|
|
374
|
+
details,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CustomMessageEntryDraft,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
SessionBeforeCompactEvent,
|
|
5
|
+
SessionCompactFailedEvent,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { prepareCompactionProjection } from "./compaction-projection.js";
|
|
8
|
+
import type { NotesLifecycle } from "./lifecycle.js";
|
|
9
|
+
import type { ModelRoleHandoff } from "./model-roles.js";
|
|
10
|
+
|
|
11
|
+
type Rollover = {
|
|
12
|
+
sessionId: string;
|
|
13
|
+
windowId: string | undefined;
|
|
14
|
+
triggerTurn: boolean;
|
|
15
|
+
handoff?: ModelRoleHandoff;
|
|
16
|
+
} & (
|
|
17
|
+
| { phase: "scheduled" | "compacting" }
|
|
18
|
+
| { phase: "checking"; accepted?: AbortSignal }
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
// Owns scheduled rollover, compaction callback identity and manual cancellation receipts.
|
|
22
|
+
export class RolloverRequests {
|
|
23
|
+
private rollover: Rollover | undefined;
|
|
24
|
+
private cancelledCompact:
|
|
25
|
+
| {
|
|
26
|
+
sessionId: string;
|
|
27
|
+
signal: AbortSignal;
|
|
28
|
+
instructions: string | undefined;
|
|
29
|
+
}
|
|
30
|
+
| undefined;
|
|
31
|
+
private readonly host: Pick<
|
|
32
|
+
NotesLifecycle,
|
|
33
|
+
"active" | "windows" | "normalCompaction" | "newWindowRequests" | "fresh"
|
|
34
|
+
>;
|
|
35
|
+
private readonly openWindow: (
|
|
36
|
+
ctx: ExtensionContext,
|
|
37
|
+
triggerTurn: boolean,
|
|
38
|
+
trim: boolean,
|
|
39
|
+
handoff?: ModelRoleHandoff,
|
|
40
|
+
) => Promise<void>;
|
|
41
|
+
private readonly sendMessage: (
|
|
42
|
+
message: Omit<CustomMessageEntryDraft, "type">,
|
|
43
|
+
options: { triggerTurn: boolean },
|
|
44
|
+
) => void;
|
|
45
|
+
private readonly startCheckpoint: (
|
|
46
|
+
ctx: ExtensionContext,
|
|
47
|
+
instructions?: string,
|
|
48
|
+
) => void;
|
|
49
|
+
constructor(
|
|
50
|
+
host: RolloverRequests["host"],
|
|
51
|
+
openWindow: RolloverRequests["openWindow"],
|
|
52
|
+
sendMessage: RolloverRequests["sendMessage"],
|
|
53
|
+
startCheckpoint: RolloverRequests["startCheckpoint"],
|
|
54
|
+
) {
|
|
55
|
+
this.host = host;
|
|
56
|
+
this.openWindow = openWindow;
|
|
57
|
+
this.sendMessage = sendMessage;
|
|
58
|
+
this.startCheckpoint = startCheckpoint;
|
|
59
|
+
}
|
|
60
|
+
get pending(): boolean {
|
|
61
|
+
return Boolean(this.rollover);
|
|
62
|
+
}
|
|
63
|
+
reset(): void {
|
|
64
|
+
this.rollover = undefined;
|
|
65
|
+
this.cancelledCompact = undefined;
|
|
66
|
+
}
|
|
67
|
+
clear(): void {
|
|
68
|
+
this.rollover = undefined;
|
|
69
|
+
}
|
|
70
|
+
schedule(ctx: ExtensionContext, handoff?: ModelRoleHandoff): void {
|
|
71
|
+
this.rollover = {
|
|
72
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
73
|
+
windowId: this.host.windows.current?.currentWindowId,
|
|
74
|
+
phase: "scheduled",
|
|
75
|
+
triggerTurn: true,
|
|
76
|
+
...(handoff ? { handoff } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
settled(ctx: ExtensionContext): Promise<void> | undefined {
|
|
80
|
+
const rollover = this.rollover;
|
|
81
|
+
if (
|
|
82
|
+
rollover?.phase === "scheduled" &&
|
|
83
|
+
rollover.sessionId === ctx.sessionManager.getSessionId() &&
|
|
84
|
+
rollover.windowId === this.host.windows.current?.currentWindowId
|
|
85
|
+
) {
|
|
86
|
+
this.rollover = undefined;
|
|
87
|
+
return this.roll(ctx, rollover.triggerTurn, rollover.handoff);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async roll(
|
|
92
|
+
ctx: ExtensionContext,
|
|
93
|
+
triggerTurn: boolean,
|
|
94
|
+
handoff?: ModelRoleHandoff,
|
|
95
|
+
): Promise<void> {
|
|
96
|
+
const policy = triggerTurn ? this.host.newWindowRequests : undefined;
|
|
97
|
+
const checkOnly = !this.host.normalCompaction && policy === "pi-limits";
|
|
98
|
+
if (!this.host.normalCompaction && !checkOnly) {
|
|
99
|
+
await this.openWindow(ctx, triggerTurn, true, handoff);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const pending: Rollover = {
|
|
103
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
104
|
+
windowId: this.host.windows.current?.currentWindowId,
|
|
105
|
+
phase: checkOnly ? "checking" : "compacting",
|
|
106
|
+
triggerTurn,
|
|
107
|
+
...(handoff ? { handoff } : {}),
|
|
108
|
+
};
|
|
109
|
+
this.rollover = pending;
|
|
110
|
+
await new Promise<void>((resolve, reject) => {
|
|
111
|
+
const current = () =>
|
|
112
|
+
this.host.active &&
|
|
113
|
+
this.rollover === pending &&
|
|
114
|
+
pending.sessionId === ctx.sessionManager.getSessionId() &&
|
|
115
|
+
pending.windowId === this.host.windows.current?.currentWindowId;
|
|
116
|
+
const finish = (trim: boolean) => {
|
|
117
|
+
this.rollover = undefined;
|
|
118
|
+
void this.openWindow(ctx, triggerTurn, trim, handoff).then(
|
|
119
|
+
resolve,
|
|
120
|
+
reject,
|
|
121
|
+
);
|
|
122
|
+
};
|
|
123
|
+
ctx.compact({
|
|
124
|
+
onComplete: () => {
|
|
125
|
+
if (!current()) {
|
|
126
|
+
reject(new Error("Session changed during compaction"));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
finish(false);
|
|
130
|
+
},
|
|
131
|
+
onError: (error) => {
|
|
132
|
+
if (current()) {
|
|
133
|
+
// Only our own accepted gate cancels a summary in favour of notes-only rollover.
|
|
134
|
+
if (
|
|
135
|
+
pending.phase === "checking" &&
|
|
136
|
+
pending.accepted &&
|
|
137
|
+
!pending.accepted.aborted &&
|
|
138
|
+
error.message === "Compaction cancelled"
|
|
139
|
+
) {
|
|
140
|
+
finish(true);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (
|
|
144
|
+
error.message === "Nothing to compact (session too small)" ||
|
|
145
|
+
error.message === "Already compacted"
|
|
146
|
+
) {
|
|
147
|
+
if (policy === "unrestricted") {
|
|
148
|
+
// A new identity need not retire history when Pi has no summary work.
|
|
149
|
+
finish(false);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
this.rollover = undefined;
|
|
153
|
+
try {
|
|
154
|
+
if (triggerTurn)
|
|
155
|
+
this.sendMessage(
|
|
156
|
+
{
|
|
157
|
+
customType: "notes-compaction:continuation",
|
|
158
|
+
content:
|
|
159
|
+
"Not enough history to compact. Continue here; wait for more conversation before calling new_context again.",
|
|
160
|
+
display: true,
|
|
161
|
+
},
|
|
162
|
+
{ triggerTurn: true },
|
|
163
|
+
);
|
|
164
|
+
resolve();
|
|
165
|
+
} catch (error) {
|
|
166
|
+
reject(error);
|
|
167
|
+
}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (this.rollover === pending) this.rollover = undefined;
|
|
172
|
+
reject(error);
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
beforeCompact(
|
|
178
|
+
event: SessionBeforeCompactEvent,
|
|
179
|
+
ctx: ExtensionContext,
|
|
180
|
+
): { cancel: true } | undefined {
|
|
181
|
+
if (this.rollover?.phase === "checking" && event.reason === "manual") {
|
|
182
|
+
this.rollover.accepted = event.signal;
|
|
183
|
+
return { cancel: true };
|
|
184
|
+
}
|
|
185
|
+
if (this.allowsCompaction(event.reason)) {
|
|
186
|
+
return prepareCompactionProjection(event, ctx, this.host.windows);
|
|
187
|
+
}
|
|
188
|
+
if (event.reason === "manual")
|
|
189
|
+
this.cancelledCompact = {
|
|
190
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
191
|
+
signal: event.signal,
|
|
192
|
+
instructions: event.customInstructions,
|
|
193
|
+
};
|
|
194
|
+
return { cancel: true };
|
|
195
|
+
}
|
|
196
|
+
allowsCompaction(reason: SessionBeforeCompactEvent["reason"]): boolean {
|
|
197
|
+
if (this.rollover?.phase === "checking" && reason === "manual")
|
|
198
|
+
return false;
|
|
199
|
+
return (
|
|
200
|
+
!this.host.active ||
|
|
201
|
+
this.host.normalCompaction ||
|
|
202
|
+
this.rollover?.phase === "compacting" ||
|
|
203
|
+
reason === "overflow"
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
async compactFailed(
|
|
207
|
+
event: SessionCompactFailedEvent,
|
|
208
|
+
ctx: ExtensionContext,
|
|
209
|
+
): Promise<void> {
|
|
210
|
+
const pending = this.cancelledCompact;
|
|
211
|
+
this.cancelledCompact = undefined;
|
|
212
|
+
if (
|
|
213
|
+
!pending ||
|
|
214
|
+
event.reason !== "manual" ||
|
|
215
|
+
!event.aborted ||
|
|
216
|
+
pending.signal.aborted ||
|
|
217
|
+
pending.sessionId !== ctx.sessionManager.getSessionId()
|
|
218
|
+
)
|
|
219
|
+
return;
|
|
220
|
+
if (!pending.instructions?.trim() && this.host.fresh(ctx))
|
|
221
|
+
await this.roll(ctx, false);
|
|
222
|
+
else this.startCheckpoint(ctx, pending.instructions);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { Check } from "typebox/value";
|
|
3
|
+
import type {
|
|
4
|
+
SavedSessionLoader,
|
|
5
|
+
SavedSessionLocator,
|
|
6
|
+
} from "./context-sharing.js";
|
|
7
|
+
import {
|
|
8
|
+
readSavedNotesSession,
|
|
9
|
+
type SavedNotesSession,
|
|
10
|
+
validateSavedNotesSession,
|
|
11
|
+
} from "./saved-session.js";
|
|
12
|
+
import { savedFamilyIdentity } from "./saved-sharing-records.js";
|
|
13
|
+
import type { NotesStore } from "./store.js";
|
|
14
|
+
|
|
15
|
+
const Locations = Type.Array(
|
|
16
|
+
Type.Object({
|
|
17
|
+
machine: Type.String({ minLength: 1 }),
|
|
18
|
+
sessionFile: Type.String({ minLength: 1 }),
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
/** Local is relative to the session carrying the edge, not the machine running this reader. */
|
|
23
|
+
export function createSavedSessionAccess(
|
|
24
|
+
store: Pick<NotesStore, "sessionFile">,
|
|
25
|
+
namespace: "notes" | "history",
|
|
26
|
+
loader: SavedSessionLoader | undefined,
|
|
27
|
+
signal: AbortSignal | undefined,
|
|
28
|
+
) {
|
|
29
|
+
const locations = new WeakMap<SavedNotesSession, SavedSessionLocator>();
|
|
30
|
+
const containingMachine = (session: SavedNotesSession) =>
|
|
31
|
+
locations.get(session)?.machine ?? "local";
|
|
32
|
+
function locator(
|
|
33
|
+
session: SavedNotesSession,
|
|
34
|
+
machine: string,
|
|
35
|
+
sessionFile: string,
|
|
36
|
+
): SavedSessionLocator {
|
|
37
|
+
return {
|
|
38
|
+
machine: machine === "local" ? containingMachine(session) : machine,
|
|
39
|
+
sessionFile,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function load(
|
|
43
|
+
location: SavedSessionLocator,
|
|
44
|
+
): Promise<SavedNotesSession> {
|
|
45
|
+
signal?.throwIfAborted();
|
|
46
|
+
const session =
|
|
47
|
+
location.machine === "local"
|
|
48
|
+
? await readSavedNotesSession(
|
|
49
|
+
location.sessionFile,
|
|
50
|
+
signal,
|
|
51
|
+
namespace === "history",
|
|
52
|
+
)
|
|
53
|
+
: loader
|
|
54
|
+
? validateSavedNotesSession(
|
|
55
|
+
await loader(location, namespace === "history", signal),
|
|
56
|
+
)
|
|
57
|
+
: (() => {
|
|
58
|
+
throw Object.assign(
|
|
59
|
+
new Error(
|
|
60
|
+
"Saved context on that machine is unavailable. Request a handoff from its owner, or ask the user to reconnect the machine before retrying.",
|
|
61
|
+
),
|
|
62
|
+
{ code: "SAVED_SESSION_UNAVAILABLE" },
|
|
63
|
+
);
|
|
64
|
+
})();
|
|
65
|
+
locations.set(session, location);
|
|
66
|
+
return session;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function indexed(
|
|
70
|
+
current: SavedNotesSession,
|
|
71
|
+
target: string,
|
|
72
|
+
): Promise<SavedNotesSession | undefined> {
|
|
73
|
+
// An exact local hint avoids dead relay parents. Index rows never establish membership.
|
|
74
|
+
const family = savedFamilyIdentity(current);
|
|
75
|
+
const threadId = target.slice(1);
|
|
76
|
+
if (family && !threadId.includes("/") && target !== "/root") {
|
|
77
|
+
const file = store.sessionFile(threadId);
|
|
78
|
+
if (file) {
|
|
79
|
+
const saved = await load({ machine: "local", sessionFile: file });
|
|
80
|
+
const member = savedFamilyIdentity(saved);
|
|
81
|
+
if (
|
|
82
|
+
saved.threadId !== threadId ||
|
|
83
|
+
!member ||
|
|
84
|
+
member.storage !== "session" ||
|
|
85
|
+
member.sessionId !== family.sessionId ||
|
|
86
|
+
member.agentName !== target
|
|
87
|
+
)
|
|
88
|
+
throw new Error(
|
|
89
|
+
"This session cannot access the requested saved context. Request an accessible handoff or note path from its owner.",
|
|
90
|
+
);
|
|
91
|
+
return saved;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
async function find(target: string): Promise<SavedSessionLocator[]> {
|
|
97
|
+
const threadId = target.slice(1);
|
|
98
|
+
if (!loader?.find || target === "/root" || threadId.includes("/"))
|
|
99
|
+
return [];
|
|
100
|
+
signal?.throwIfAborted();
|
|
101
|
+
const value = await loader.find(threadId, signal);
|
|
102
|
+
signal?.throwIfAborted();
|
|
103
|
+
if (!Check(Locations, value))
|
|
104
|
+
throw new Error(
|
|
105
|
+
"Saved session discovery response is invalid. Update Notes on the other machine and retry.",
|
|
106
|
+
);
|
|
107
|
+
return [
|
|
108
|
+
...new Map(
|
|
109
|
+
value.map((location) => [
|
|
110
|
+
`${location.machine}\0${location.sessionFile}`,
|
|
111
|
+
location,
|
|
112
|
+
]),
|
|
113
|
+
).values(),
|
|
114
|
+
];
|
|
115
|
+
}
|
|
116
|
+
return { containingMachine, locator, load, indexed, find };
|
|
117
|
+
}
|