pi-openai-toolkit 0.22.3 → 0.23.1
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/README.md +4 -2
- package/README.zh.md +4 -2
- package/docs/configuration.md +5 -5
- package/docs/internals.md +11 -11
- package/package.json +2 -1
- package/src/context-management/manual-compact.ts +599 -422
- package/src/context-management/responses-tools.ts +238 -0
- package/src/context-management/window-manager.ts +94 -0
- package/src/extension-runtime.ts +348 -23
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert Pi tool declarations into Responses-API wire tools.
|
|
3
|
+
*
|
|
4
|
+
* Pi 1.3 exports `convertResponsesTools` only from
|
|
5
|
+
* `@earendil-works/pi-ai/api/openai-responses-shared`, but Pi's extension module
|
|
6
|
+
* aliases map a fixed allowlist of specifiers and do not include that subpath.
|
|
7
|
+
* Importing it from an extension therefore fails at load time with
|
|
8
|
+
* "Cannot find module", which silently disables every hook the extension owns.
|
|
9
|
+
*
|
|
10
|
+
* This module reproduces that conversion without the subpath import. The strict
|
|
11
|
+
* JSON-schema rewrite is a faithful port of Pi's `makeStrictJsonSchema`: it must
|
|
12
|
+
* stay byte-identical, because a compaction request has to declare the same tool
|
|
13
|
+
* schema as the live request it continues.
|
|
14
|
+
*/
|
|
15
|
+
import type { Tool } from "@earendil-works/pi-ai";
|
|
16
|
+
|
|
17
|
+
export type ResponsesWireTool =
|
|
18
|
+
| { type: "function"; name: string; description: string; parameters: unknown; strict?: boolean | null }
|
|
19
|
+
| { type: "custom"; name: string; description: string; format: { type: string; syntax: string; definition: string } };
|
|
20
|
+
|
|
21
|
+
export type ConvertResponsesToolsOptions = {
|
|
22
|
+
/** Value applied when a tool does not opt in explicitly. `null` means no default. */
|
|
23
|
+
strict?: boolean | null;
|
|
24
|
+
supportsStrictMode?: boolean;
|
|
25
|
+
supportsOpenAIGrammarTools?: boolean;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type JsonSchema = Record<string, unknown>;
|
|
29
|
+
|
|
30
|
+
type ConstrainedSampling = {
|
|
31
|
+
type: "json_schema" | "grammar";
|
|
32
|
+
strict?: "require" | "prefer" | "ignore";
|
|
33
|
+
variants?: { openai_lark?: string; openai_regex?: string };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Keywords the strict subset cannot express. Kept in sync with Pi's implementation. */
|
|
37
|
+
const UNSUPPORTED_STRICT_SCHEMA_KEYS = [
|
|
38
|
+
"$ref",
|
|
39
|
+
"$defs",
|
|
40
|
+
"definitions",
|
|
41
|
+
"allOf",
|
|
42
|
+
"oneOf",
|
|
43
|
+
"patternProperties",
|
|
44
|
+
"dependentSchemas",
|
|
45
|
+
"dependencies",
|
|
46
|
+
"unevaluatedProperties",
|
|
47
|
+
"propertyNames",
|
|
48
|
+
"contains",
|
|
49
|
+
"prefixItems",
|
|
50
|
+
"not",
|
|
51
|
+
"if",
|
|
52
|
+
"then",
|
|
53
|
+
"else",
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
class UnsupportedStrictJsonSchemaError extends Error {}
|
|
57
|
+
|
|
58
|
+
function isJsonSchemaObject(value: unknown): value is JsonSchema {
|
|
59
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isStructuredSchema(schema: unknown): boolean {
|
|
63
|
+
if (!isJsonSchemaObject(schema)) return false;
|
|
64
|
+
const types = typeof schema["type"] === "string"
|
|
65
|
+
? [schema["type"]]
|
|
66
|
+
: Array.isArray(schema["type"]) ? schema["type"] : [];
|
|
67
|
+
return types.includes("object")
|
|
68
|
+
|| types.includes("array")
|
|
69
|
+
|| schema["properties"] !== undefined
|
|
70
|
+
|| schema["items"] !== undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function schemaAllowsNull(schema: unknown): boolean {
|
|
74
|
+
if (!isJsonSchemaObject(schema)) return false;
|
|
75
|
+
if (schema["type"] === "null" || (Array.isArray(schema["type"]) && schema["type"].includes("null"))) return true;
|
|
76
|
+
if (schema["const"] === null || (Array.isArray(schema["enum"]) && schema["enum"].includes(null))) return true;
|
|
77
|
+
return Array.isArray(schema["anyOf"]) && schema["anyOf"].some((variant) => schemaAllowsNull(variant));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function makeJsonSchemaNodeStrict(schema: unknown): void { if (!isJsonSchemaObject(schema)) throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");
|
|
81
|
+
for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) {
|
|
82
|
+
if (schema[key] !== undefined) throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);
|
|
83
|
+
}
|
|
84
|
+
if (schema["anyOf"] !== undefined) {
|
|
85
|
+
if (!Array.isArray(schema["anyOf"]) || schema["anyOf"].length === 0) {
|
|
86
|
+
throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");
|
|
87
|
+
}
|
|
88
|
+
for (const variant of schema["anyOf"]) {
|
|
89
|
+
if (isStructuredSchema(variant)) throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");
|
|
90
|
+
makeJsonSchemaNodeStrict(variant);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (schema["items"] !== undefined) {
|
|
94
|
+
if (Array.isArray(schema["items"])) throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");
|
|
95
|
+
makeJsonSchemaNodeStrict(schema["items"]);
|
|
96
|
+
}
|
|
97
|
+
const isObjectSchema = schema["type"] === "object";
|
|
98
|
+
if (schema["properties"] !== undefined && !isObjectSchema) {
|
|
99
|
+
throw new UnsupportedStrictJsonSchemaError("properties require type object");
|
|
100
|
+
}
|
|
101
|
+
if (!isObjectSchema) return;
|
|
102
|
+
if (schema["additionalProperties"] !== undefined && schema["additionalProperties"] !== false) {
|
|
103
|
+
throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");
|
|
104
|
+
}
|
|
105
|
+
if (schema["properties"] !== undefined && !isJsonSchemaObject(schema["properties"])) {
|
|
106
|
+
throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");
|
|
107
|
+
}
|
|
108
|
+
if (schema["required"] !== undefined
|
|
109
|
+
&& (!Array.isArray(schema["required"]) || schema["required"].some((key) => typeof key !== "string"))) {
|
|
110
|
+
throw new UnsupportedStrictJsonSchemaError("object required must be a string array");
|
|
111
|
+
}
|
|
112
|
+
const properties = isJsonSchemaObject(schema["properties"]) ? schema["properties"] : {};
|
|
113
|
+
const propertyNames = Object.keys(properties);
|
|
114
|
+
const required = new Set(Array.isArray(schema["required"]) ? schema["required"] as string[] : []);
|
|
115
|
+
if ([...required].some((key) => !propertyNames.includes(key))) {
|
|
116
|
+
throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");
|
|
117
|
+
}
|
|
118
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
119
|
+
makeJsonSchemaNodeStrict(property);
|
|
120
|
+
if (!required.has(key) && !schemaAllowsNull(property)) {
|
|
121
|
+
properties[key] = { anyOf: [property, { type: "null" }] };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
schema["required"] = propertyNames;
|
|
125
|
+
schema["additionalProperties"] = false;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Convert a tool schema to the strict subset expected by provider constrained sampling. */
|
|
129
|
+
function makeStrictJsonSchema(schema: unknown): unknown {
|
|
130
|
+
const cloned = structuredClone(schema);
|
|
131
|
+
if (!isJsonSchemaObject(cloned)) throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
132
|
+
makeJsonSchemaNodeStrict(cloned);
|
|
133
|
+
if (cloned["type"] !== "object") throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
134
|
+
return cloned;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function constrainedSamplingOf(tool: Tool): ConstrainedSampling | undefined { const value = (tool as { constrainedSampling?: unknown }).constrainedSampling;
|
|
138
|
+
if (!value || typeof value !== "object") return undefined;
|
|
139
|
+
const type = (value as { type?: unknown }).type;
|
|
140
|
+
if (type !== "json_schema" && type !== "grammar") return undefined;
|
|
141
|
+
return value as ConstrainedSampling;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Only `openai_lark` / `openai_regex` variants can be expressed on the Responses wire. */
|
|
145
|
+
function grammarOf(tool: Tool): { syntax: string; definition: string } | undefined {
|
|
146
|
+
const sampling = constrainedSamplingOf(tool);
|
|
147
|
+
if (sampling?.type !== "grammar") return undefined;
|
|
148
|
+
const lark = sampling.variants?.openai_lark;
|
|
149
|
+
const regex = sampling.variants?.openai_regex;
|
|
150
|
+
const hasLark = typeof lark === "string" && lark.trim().length > 0;
|
|
151
|
+
const hasRegex = typeof regex === "string" && regex.trim().length > 0;
|
|
152
|
+
if (!hasLark && !hasRegex) {
|
|
153
|
+
throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);
|
|
154
|
+
}
|
|
155
|
+
return hasLark ? { syntax: "lark", definition: lark! } : { syntax: "regex", definition: regex! };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Whether the schema can be expressed in the strict subset at all. */
|
|
159
|
+
function isStrictExpressible(parameters: unknown): boolean {
|
|
160
|
+
try {
|
|
161
|
+
makeStrictJsonSchema(parameters);
|
|
162
|
+
return true;
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error instanceof UnsupportedStrictJsonSchemaError) return false;
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The reason `makeStrictJsonSchema` refused, for fail-closed error text. */
|
|
170
|
+
function strictUnsupportedReason(parameters: unknown): string {
|
|
171
|
+
try {
|
|
172
|
+
makeStrictJsonSchema(parameters);
|
|
173
|
+
return "the schema is unsupported";
|
|
174
|
+
} catch (error) {
|
|
175
|
+
return error instanceof Error ? error.message : String(error);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Resolve the effective strict flag for one tool, mirroring Pi's
|
|
181
|
+
* `resolveJsonSchemaStrictSampling` + `defaultStrict` composition.
|
|
182
|
+
*
|
|
183
|
+
* For any `json_schema` constrained sampling, Pi ignores the declared
|
|
184
|
+
* `strict` mode when the schema is expressible: it simply returns `true`.
|
|
185
|
+
* The mode only matters on the failure path, where `require` throws and
|
|
186
|
+
* everything else falls back to the caller's default. Pi's `defaultStrict`
|
|
187
|
+
* is `options.strict === undefined ? false : options.strict`, so an explicit
|
|
188
|
+
* `null` is forwarded verbatim onto the wire.
|
|
189
|
+
*/
|
|
190
|
+
function strictFor(tool: Tool, options: ConvertResponsesToolsOptions): boolean | null {
|
|
191
|
+
const supportsStrictMode = options.supportsStrictMode ?? true;
|
|
192
|
+
const sampling = constrainedSamplingOf(tool);
|
|
193
|
+
const fallback = options.strict === undefined ? false : options.strict;
|
|
194
|
+
if (sampling?.type !== "json_schema") return fallback;
|
|
195
|
+
if (supportsStrictMode) {
|
|
196
|
+
if (isStrictExpressible(tool.parameters)) return true;
|
|
197
|
+
if (sampling.strict === "require") {
|
|
198
|
+
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${strictUnsupportedReason(tool.parameters)}.`);
|
|
199
|
+
}
|
|
200
|
+
return fallback;
|
|
201
|
+
}
|
|
202
|
+
if (sampling.strict === "require") {
|
|
203
|
+
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
|
|
204
|
+
}
|
|
205
|
+
return fallback;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Mirror Pi's wire shape so compaction requests match ordinary Responses requests. */
|
|
209
|
+
export function convertResponsesTools(
|
|
210
|
+
tools: readonly Tool[],
|
|
211
|
+
options: ConvertResponsesToolsOptions = {},
|
|
212
|
+
): ResponsesWireTool[] {
|
|
213
|
+
const supportsStrictMode = options.supportsStrictMode ?? true;
|
|
214
|
+
const supportsOpenAIGrammarTools = options.supportsOpenAIGrammarTools ?? false;
|
|
215
|
+
return tools.map((tool) => {
|
|
216
|
+
if (supportsOpenAIGrammarTools) {
|
|
217
|
+
const grammar = grammarOf(tool);
|
|
218
|
+
if (grammar) {
|
|
219
|
+
return {
|
|
220
|
+
type: "custom" as const,
|
|
221
|
+
name: tool.name,
|
|
222
|
+
description: tool.description,
|
|
223
|
+
format: { type: "grammar", ...grammar },
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const strict = strictFor(tool, options);
|
|
228
|
+
const wire: ResponsesWireTool = {
|
|
229
|
+
type: "function",
|
|
230
|
+
name: tool.name,
|
|
231
|
+
description: tool.description,
|
|
232
|
+
parameters: strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters,
|
|
233
|
+
};
|
|
234
|
+
// Pi writes `strict` whenever the transport supports it, including `false` and `null`.
|
|
235
|
+
if (supportsStrictMode) wire.strict = strict;
|
|
236
|
+
return wire;
|
|
237
|
+
});
|
|
238
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
4
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
3
5
|
import type { ProviderHeaders } from "@earendil-works/pi-ai";
|
|
4
6
|
import {
|
|
@@ -65,6 +67,17 @@ type WindowBoundaryEntry = Extract<SessionEntry, { type: "custom_message" }> & {
|
|
|
65
67
|
details: CodexContextManagementMessageDetails;
|
|
66
68
|
};
|
|
67
69
|
|
|
70
|
+
/** Canonical input and real source anchors for one read-only manual compression. */
|
|
71
|
+
export type RemoteWindowCompactionInput = {
|
|
72
|
+
messages: AgentMessage[];
|
|
73
|
+
firstKeptEntryId: string;
|
|
74
|
+
/** Only a newer compaction can own this window; pre-window checkpoints are retired. */
|
|
75
|
+
owningCompaction?: Extract<SessionEntry, { type: "compaction" }>;
|
|
76
|
+
/** Entries whose visible contributions Pi will retain alongside the new checkpoint. */
|
|
77
|
+
retainedMessages: AgentMessage[];
|
|
78
|
+
windowBoundaryIndex: number;
|
|
79
|
+
};
|
|
80
|
+
|
|
68
81
|
/**
|
|
69
82
|
* In-process duplicate guard for one scheduled rollover. It is anchored to the
|
|
70
83
|
* session that scheduled it and to the exact target window id, so it can never
|
|
@@ -88,6 +101,14 @@ export class CodexContextWindowManager {
|
|
|
88
101
|
private pendingRollover: PendingRollover | undefined;
|
|
89
102
|
private readonly projectionDiagnostics = new Set<string>();
|
|
90
103
|
private lastKnownSystemHead: AgentMessage | undefined;
|
|
104
|
+
private readonly compactionProjection = new AsyncLocalStorage<boolean>();
|
|
105
|
+
|
|
106
|
+
get isPreparingCompaction(): boolean { return this.compactionProjection.getStore() === true; }
|
|
107
|
+
|
|
108
|
+
/** Keep read-only preparation scoped across awaits without affecting other live requests. */
|
|
109
|
+
withCompactionProjection<T>(prepare: () => Promise<T>): Promise<T> {
|
|
110
|
+
return this.compactionProjection.run(true, prepare);
|
|
111
|
+
}
|
|
91
112
|
/**
|
|
92
113
|
* Pi's getContextUsage() measures the durable transcript. Remote windows are
|
|
93
114
|
* projected only by this extension, so remember the last provider-visible
|
|
@@ -225,6 +246,7 @@ export class CodexContextWindowManager {
|
|
|
225
246
|
/** Delay encoding until verified retained copies have been removed. */
|
|
226
247
|
encodeEncryptedOutputs = true,
|
|
227
248
|
): AgentMessage[] {
|
|
249
|
+
if (this.isPreparingCompaction) return this.projectCompactionContext(messages);
|
|
228
250
|
// Recompute the request-only preview on every projection. Observing a
|
|
229
251
|
// queued marker must not authorize maintenance or retire the duplicate guard.
|
|
230
252
|
if (this.pendingRollover) this.pendingRollover.projected = false;
|
|
@@ -278,6 +300,78 @@ export class CodexContextWindowManager {
|
|
|
278
300
|
return projected;
|
|
279
301
|
}
|
|
280
302
|
|
|
303
|
+
/**
|
|
304
|
+
* Strict, read-only projection. Unlike live Remote projection, an unsafe head
|
|
305
|
+
* never falls back to the full transcript, updates identity, or records budget.
|
|
306
|
+
*/
|
|
307
|
+
projectCompactionContext(messages: readonly AgentMessage[], encodeEncryptedOutputs = false): AgentMessage[] {
|
|
308
|
+
if (this.pendingRollover || (this.boundary.kind !== "effective" && this.boundary.kind !== "superseded")) {
|
|
309
|
+
throw new Error("unsafe-compaction-window-boundary");
|
|
310
|
+
}
|
|
311
|
+
let boundaryIndex = 0;
|
|
312
|
+
if (this.boundary.kind === "effective") {
|
|
313
|
+
const boundary = this.boundary.entry;
|
|
314
|
+
boundaryIndex = messages.findIndex((message) => isContextWindowBoundary(message)
|
|
315
|
+
&& isDeepStrictEqual(message.details, boundary.details)
|
|
316
|
+
&& isDeepStrictEqual(message.content, boundary.content));
|
|
317
|
+
if (boundaryIndex < 0) throw new Error("compaction-window-boundary-missing");
|
|
318
|
+
}
|
|
319
|
+
const repair = preserveSystemHead({ messages, boundaryIndex });
|
|
320
|
+
if (!repair.head || repair.shrinkRejected) throw new Error("compaction-system-tool-head-lost");
|
|
321
|
+
return encodeEncryptedOutputs ? projectEncryptedToolResults(repair.messages) : [...repair.messages];
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
prepareRemoteCompaction(event: SessionBeforeCompactEvent, ctx: ExtensionContext): RemoteWindowCompactionInput {
|
|
325
|
+
this.synchronize(ctx);
|
|
326
|
+
if (this.hasPendingRollover(ctx) || (this.boundary.kind !== "effective" && this.boundary.kind !== "superseded")) {
|
|
327
|
+
throw new Error("unsafe-compaction-window-boundary");
|
|
328
|
+
}
|
|
329
|
+
const branch = ctx.sessionManager.getBranch();
|
|
330
|
+
if (!isDeepStrictEqual(event.branchEntries, branch)) throw new Error("compaction-branch-changed");
|
|
331
|
+
const projection = ctx.sessionManager.buildSessionProjection();
|
|
332
|
+
// Never manufacture source IDs or substitute a raw-history reconstruction.
|
|
333
|
+
if (!projection || !Array.isArray(projection.entries) || !Array.isArray(projection.messages)
|
|
334
|
+
|| !isDeepStrictEqual(projection.messages, projection.entries.flatMap((entry) => entry.messages))
|
|
335
|
+
|| new Set(projection.entries.map((entry) => entry.sourceEntry.id)).size !== projection.entries.length
|
|
336
|
+
|| projection.entries.some((entry) => !branch.some((raw) => raw.id === entry.sourceEntry.id && isDeepStrictEqual(raw, entry.sourceEntry)))) {
|
|
337
|
+
throw new Error("compaction-source-projection-unavailable");
|
|
338
|
+
}
|
|
339
|
+
const windowBoundaryIndex = branch.findIndex((entry) => entry.id === this.boundaryEntryId());
|
|
340
|
+
if (windowBoundaryIndex < 0) throw new Error("compaction-window-boundary-missing");
|
|
341
|
+
const latest = [...branch].reverse().find((entry) => entry.type === "compaction");
|
|
342
|
+
if (this.boundary.kind === "effective" && this.boundary.cleaned) {
|
|
343
|
+
// Details alone do not turn an arbitrary summary into Toolkit cleanup.
|
|
344
|
+
if (!latest || latest.type !== "compaction" || latest.fromHook !== true
|
|
345
|
+
|| latest.summary !== CONTEXT_WINDOW_COMPACTION_SUMMARY
|
|
346
|
+
|| !isContextWindowCompactionDetails(latest.details)
|
|
347
|
+
|| latest.details.windowId !== this.boundary.entry.details.contextManagement.currentWindowId
|
|
348
|
+
|| latest.firstKeptEntryId !== this.boundary.entry.id) throw new Error("unverified-window-cleanup");
|
|
349
|
+
}
|
|
350
|
+
const owningCompaction = this.boundary.kind === "superseded" && latest?.type === "compaction" ? latest : undefined;
|
|
351
|
+
if (this.boundary.kind === "superseded" && !owningCompaction) throw new Error("compaction-owner-missing");
|
|
352
|
+
const lowerId = owningCompaction?.id ?? this.boundary.entry.id;
|
|
353
|
+
const lowerIndex = branch.findIndex((entry) => entry.id === lowerId);
|
|
354
|
+
const requestedIndex = branch.findIndex((entry) => entry.id === event.preparation.firstKeptEntryId);
|
|
355
|
+
if (requestedIndex < 0 || lowerIndex < windowBoundaryIndex) throw new Error("unsafe-compaction-retained-start");
|
|
356
|
+
const firstKeptEntryId = requestedIndex < lowerIndex ? lowerId : event.preparation.firstKeptEntryId;
|
|
357
|
+
const keptIndex = Math.max(requestedIndex, lowerIndex);
|
|
358
|
+
const safeSources = new Set(projection.entries.filter((entry) => entry.messages.length > 0).map((entry) => entry.sourceEntry.id));
|
|
359
|
+
if (!safeSources.has(firstKeptEntryId)) throw new Error("unsafe-compaction-retained-start");
|
|
360
|
+
const retainedIds = new Set(branch.slice(keptIndex).map((entry) => entry.id));
|
|
361
|
+
return {
|
|
362
|
+
messages: this.projectCompactionContext(structuredClone(projection.messages)),
|
|
363
|
+
firstKeptEntryId,
|
|
364
|
+
owningCompaction,
|
|
365
|
+
retainedMessages: structuredClone(projection.entries.filter((entry) => retainedIds.has(entry.sourceEntry.id)
|
|
366
|
+
&& entry.sourceEntry.type !== "compaction").flatMap((entry) => entry.messages)),
|
|
367
|
+
windowBoundaryIndex,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private boundaryEntryId(): string | undefined {
|
|
372
|
+
return this.boundary.kind === "effective" || this.boundary.kind === "superseded" ? this.boundary.entry.id : undefined;
|
|
373
|
+
}
|
|
374
|
+
|
|
281
375
|
/**
|
|
282
376
|
* Trim everything before the window boundary while keeping Pi's prompt/tool head.
|
|
283
377
|
*
|