pi-openai-toolkit 0.23.2 → 0.24.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.
Files changed (54) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +4 -15
  4. package/README.zh.md +4 -15
  5. package/config.schema.json +264 -278
  6. package/docs/configuration.md +304 -306
  7. package/docs/internals.md +34 -120
  8. package/package.json +123 -136
  9. package/src/compact-client.ts +412 -412
  10. package/src/compaction-projection.ts +35 -35
  11. package/src/config/legacy.ts +469 -519
  12. package/src/config/migration.ts +115 -103
  13. package/src/config/notifications.ts +46 -36
  14. package/src/config/policy.ts +115 -116
  15. package/src/config/v2.ts +1128 -1167
  16. package/src/config.ts +320 -310
  17. package/src/debug.ts +238 -238
  18. package/src/deferred-tool-carryover.ts +282 -282
  19. package/src/details-store.ts +151 -151
  20. package/src/extension-runtime.ts +1095 -1919
  21. package/src/image-generation/extension.ts +189 -189
  22. package/src/image-generation/protocol.ts +579 -579
  23. package/src/image-generation/types.ts +300 -300
  24. package/src/native-fallback.ts +140 -152
  25. package/src/payload-rewrite.ts +515 -515
  26. package/src/pi-context-hook.ts +117 -117
  27. package/src/remote-v2-client.ts +811 -811
  28. package/src/request-context-cache.ts +155 -155
  29. package/src/responses-headers.ts +180 -180
  30. package/src/retired-remote-windows.ts +35 -0
  31. package/src/runtime.ts +875 -865
  32. package/src/serializer.ts +882 -882
  33. package/src/supported-environment.ts +27 -27
  34. package/src/types.ts +541 -565
  35. package/src/web-search/alpha-client.ts +876 -876
  36. package/src/web-search/extension.ts +530 -530
  37. package/src/web-search/payload.ts +299 -299
  38. package/src/web-search/prompt.ts +60 -60
  39. package/src/web-search/types.ts +166 -166
  40. package/tsconfig.check.json +50 -50
  41. package/src/context-management/codex-provider.ts +0 -270
  42. package/src/context-management/history-notes.ts +0 -357
  43. package/src/context-management/manual-compact.ts +0 -247
  44. package/src/context-management/messages.ts +0 -238
  45. package/src/context-management/namespace-tools.ts +0 -426
  46. package/src/context-management/responses-tools.ts +0 -238
  47. package/src/context-management/scoped-compaction.ts +0 -89
  48. package/src/context-management/tool-contract.ts +0 -62
  49. package/src/context-management/tools.ts +0 -371
  50. package/src/context-management/types.ts +0 -168
  51. package/src/context-management/window-budget.ts +0 -83
  52. package/src/context-management/window-bulk.ts +0 -155
  53. package/src/context-management/window-manager.ts +0 -912
  54. package/src/context-management/window-request.ts +0 -125
@@ -1,247 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
3
- import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
- import { parseModelSpec } from "../runtime";
5
- import { THINKING_LEVELS } from "../types";
6
- import { findLatestNotesCheckpointSinceBoundary, findLatestWindowBoundaryEntry } from "./window-manager";
7
- import { isNonEmptyString, isRecord } from "./types";
8
- import type { ContextRolloverHandoff } from "./tools";
9
-
10
- export const MANUAL_COMPACT_ENTRY_TYPE = "pi-openai-toolkit:manual-compact";
11
- const PHASES = ["requested", "switching", "checkpointing", "rollover-scheduled", "restoring", "restore-needed", "completed", "failed", "cancelled", "superseded"] as const;
12
- type Phase = typeof PHASES[number];
13
- const TERMINAL = new Set<Phase>(["completed", "failed", "cancelled", "superseded"]);
14
-
15
- /** Non-LLM recovery state. No auth, model object, transcript or note text belongs here. */
16
- export type ManualCompactRecord = {
17
- version: 1;
18
- operationId: string;
19
- sessionId: string;
20
- sourceWindowId: string;
21
- anchorId: string;
22
- originalModel: string;
23
- targetModel: string;
24
- originalThinking: ThinkingLevel;
25
- phase: Phase;
26
- targetWindowId?: string;
27
- };
28
-
29
- export function decodeManualCompactRecord(value: unknown): ManualCompactRecord | undefined {
30
- if (!isRecord(value) || value.version !== 1
31
- || ![value.operationId, value.sessionId, value.sourceWindowId, value.anchorId].every(isNonEmptyString)
32
- || typeof value.originalModel !== "string" || !parseModelSpec(value.originalModel)
33
- || typeof value.targetModel !== "string" || !parseModelSpec(value.targetModel)
34
- || typeof value.originalThinking !== "string" || !(THINKING_LEVELS as readonly string[]).includes(value.originalThinking)
35
- || !PHASES.includes(value.phase as Phase)
36
- || (value.targetWindowId !== undefined && !isNonEmptyString(value.targetWindowId))) return undefined;
37
- return value as ManualCompactRecord;
38
- }
39
-
40
- function modelKey(model: ExtensionContext["model"]): string | undefined {
41
- return model && `${model.provider}/${model.id}`;
42
- }
43
- function requestEntry(entries: readonly SessionEntry[], record: ManualCompactRecord): SessionEntry | undefined {
44
- return entries.find((entry) => entry.type === "custom" && entry.customType === MANUAL_COMPACT_ENTRY_TYPE
45
- && decodeManualCompactRecord(entry.data)?.operationId === record.operationId);
46
- }
47
- function freshCheckpoint(entries: readonly SessionEntry[], record: ManualCompactRecord) {
48
- const request = requestEntry(entries, record);
49
- if (!request) return undefined;
50
- let afterId = request.id;
51
- // Queued user input delivered after a checkpoint must also be checkpointed.
52
- for (const entry of entries.slice(entries.indexOf(request) + 1)) {
53
- if (entry.type === "message" && entry.message.role === "user") afterId = entry.id;
54
- }
55
- return findLatestNotesCheckpointSinceBoundary(entries, record.sessionId, afterId);
56
- }
57
-
58
- /** Restore already-persisted legacy selections only; never start duty or inference. */
59
- export class ManagedManualCompact implements ContextRolloverHandoff {
60
- private record: ManualCompactRecord | undefined;
61
- private generation = 0;
62
- private selecting: string | undefined;
63
- private selectionPromise: Promise<boolean> | undefined;
64
- private expectedThinking: ThinkingLevel | undefined;
65
- private newerSelection: { model: NonNullable<ExtensionContext["model"]>; thinking: ThinkingLevel } | undefined;
66
- private maintenance = 0;
67
-
68
- constructor(private readonly pi: ExtensionAPI) {}
69
-
70
- get busy(): boolean { return !!this.record && !TERMINAL.has(this.record.phase); }
71
- get isMaintenance(): boolean { return this.maintenance > 0; }
72
- beginMaintenance(): () => void {
73
- this.maintenance++;
74
- let done = false;
75
- return () => { if (!done) { done = true; this.maintenance--; } };
76
- }
77
-
78
- private notify(ctx: ExtensionContext, text: string, error = false): void {
79
- const content = `Managed /compact: ${text}`;
80
- if (ctx.hasUI) ctx.ui.notify(content, error ? "warning" : "info");
81
- else this.pi.sendMessage({ customType: `${MANUAL_COMPACT_ENTRY_TYPE}:status`, content, display: true }, { triggerTurn: false });
82
- }
83
- private write(phase: Phase): void {
84
- if (!this.record) return;
85
- this.record = { ...this.record, phase };
86
- this.pi.appendEntry(MANUAL_COMPACT_ENTRY_TYPE, this.record);
87
- }
88
- private belongs(ctx: ExtensionContext, record = this.record): boolean {
89
- if (!record || ctx.sessionManager.getSessionId() !== record.sessionId) return false;
90
- const branch = ctx.sessionManager.getBranch();
91
- return branch.some((entry) => entry.id === record.anchorId) && !!requestEntry(branch, record);
92
- }
93
- private current(ctx: ExtensionContext, generation: number): boolean {
94
- return generation === this.generation && this.busy && this.belongs(ctx);
95
- }
96
-
97
- /** Legacy recovery may block a rollover, but never initiate a handoff. */
98
- prepare(_ctx: ExtensionContext): undefined {
99
- if (this.busy) throw new Error("Legacy /compact selection recovery is pending; wait for restoration.");
100
- return undefined;
101
- }
102
-
103
- /** Abort without waiting: a queued/mixed continuation must not send the captured temporary model. */
104
- turnEnded(ctx: ExtensionContext): void {
105
- if (this.busy) ctx.abort();
106
- }
107
- guardRequest(ctx: ExtensionContext): void {
108
- if (ctx.signal?.aborted) return;
109
- if (this.selectionPromise && this.newerSelection) {
110
- ctx.abort();
111
- throw new Error("Managed /compact is preserving your newer model selection; this provider request was cancelled.");
112
- }
113
- if (!this.busy) return;
114
- ctx.abort();
115
- throw new Error("Managed /compact is restoring the original model; this provider request was cancelled.");
116
- }
117
- guardTool(_name: string): { block: true; terminate: true; reason: string } | undefined {
118
- if (!this.busy && !this.selectionPromise) return;
119
- return { block: true, terminate: true, reason: "Legacy /compact selection recovery is pending. Wait for restoration before ordinary work." };
120
- }
121
-
122
- modelSelected(model: NonNullable<ExtensionContext["model"]>, ctx: ExtensionContext): void {
123
- if ((!this.busy && !this.selectionPromise) || modelKey(model) === this.selecting) return;
124
- this.newerSelection = { model, thinking: this.pi.getThinkingLevel() };
125
- ++this.generation;
126
- if (this.belongs(ctx)) this.write("superseded");
127
- if (!ctx.isIdle()) ctx.abort();
128
- this.notify(ctx, "stopped; your newer model selection takes priority.");
129
- }
130
- thinkingSelected(level: ThinkingLevel, ctx: ExtensionContext): void {
131
- if (!this.busy || this.selecting || level === this.expectedThinking) return;
132
- if (ctx.model) this.modelSelected(ctx.model, ctx);
133
- }
134
- private async honorNewerSelection(ctx: ExtensionContext): Promise<void> {
135
- const choice = this.newerSelection;
136
- if (!choice || ctx.sessionManager.getSessionId() !== this.record?.sessionId) return;
137
- const key = modelKey(choice.model)!;
138
- try {
139
- const selected = await this.select(key, ctx);
140
- if (choice !== this.newerSelection) { await this.honorNewerSelection(ctx); return; }
141
- if (!selected || modelKey(ctx.model) !== key) throw new Error("selection refused");
142
- this.setThinking(choice.thinking);
143
- } catch {
144
- if (choice !== this.newerSelection) { await this.honorNewerSelection(ctx); return; }
145
- if (!this.belongs(ctx) || !this.record) return;
146
- this.record = { ...this.record, originalModel: key, originalThinking: choice.thinking, targetModel: modelKey(ctx.model) ?? this.record.targetModel };
147
- this.write("restore-needed");
148
- this.notify(ctx, `could not preserve your newer selection ${key}; restore its authentication and reload, or select a model explicitly.`, true);
149
- }
150
- }
151
- private setThinking(level: ThinkingLevel): void {
152
- this.expectedThinking = level;
153
- this.pi.setThinkingLevel(level);
154
- // Pi emits this event without awaiting earlier extension handlers. Keep
155
- // the owned value so a delayed echo is not mistaken for a user selection.
156
- this.expectedThinking = this.pi.getThinkingLevel();
157
- }
158
- private async select(key: string, ctx: ExtensionContext): Promise<boolean> {
159
- if (this.selectionPromise) await this.selectionPromise.catch(() => false);
160
- if (modelKey(ctx.model) === key) return true;
161
- const spec = parseModelSpec(key)!;
162
- const model = ctx.modelRegistry.find(spec.provider, spec.modelId);
163
- if (!model) return false;
164
- this.selecting = key;
165
- const pending = this.pi.setModel(model);
166
- this.selectionPromise = pending;
167
- try {
168
- const selected = await pending;
169
- this.expectedThinking = this.pi.getThinkingLevel();
170
- return selected;
171
- } finally {
172
- if (this.selectionPromise === pending) { this.selecting = undefined; this.selectionPromise = undefined; }
173
- }
174
- }
175
-
176
- async settled(ctx: ExtensionContext): Promise<boolean> {
177
- if (!this.busy) return false;
178
- if (this.record?.phase === "restore-needed" || this.record?.phase === "restoring") return true;
179
- await this.finish(ctx, true);
180
- return true;
181
- }
182
-
183
- private async finish(ctx: ExtensionContext, inspectMarker: boolean): Promise<void> {
184
- const record = this.record;
185
- if (!record || !ctx.isIdle()) return;
186
- const generation = this.generation;
187
- if (!this.belongs(ctx)) { this.record = undefined; ++this.generation; return; }
188
- const branch = ctx.sessionManager.getBranch();
189
- const marker = findLatestWindowBoundaryEntry(branch, record.sessionId);
190
- const switched = inspectMarker && !!record.targetWindowId && marker?.details.contextManagement.currentWindowId === record.targetWindowId
191
- && marker.details.contextManagement.previousWindowId === record.sourceWindowId;
192
- const receipt = switched ? freshCheckpoint(branch.slice(0, branch.indexOf(marker!)), record) : undefined;
193
- if (modelKey(ctx.model) !== record.targetModel && modelKey(ctx.model) !== record.originalModel) {
194
- this.write("superseded"); return;
195
- }
196
- this.write("restoring");
197
- try {
198
- if (!(await this.select(record.originalModel, ctx))) throw new Error("selection refused");
199
- if (!this.current(ctx, generation)) { await this.honorNewerSelection(ctx); return; }
200
- this.setThinking(record.originalThinking);
201
- if (modelKey(ctx.model) !== record.originalModel || this.pi.getThinkingLevel() !== record.originalThinking) throw new Error("restoration did not match");
202
- } catch {
203
- if (!this.current(ctx, generation)) return;
204
- this.write("restore-needed");
205
- this.notify(ctx, `could not restore ${record.originalModel}; no continuation was started. Restore model/auth, then reload or select a model explicitly.`, true);
206
- return;
207
- }
208
- this.write(switched && receipt ? "completed" : "failed");
209
- this.notify(ctx, switched && receipt ? `new window persisted; restored ${record.originalModel}.` : "legacy checkpoint duty stopped; original model restored.", !receipt);
210
- }
211
-
212
- /** Reload/navigation recovers selection only. It never retries inference or writes notes. */
213
- async recover(ctx: ExtensionContext): Promise<void> {
214
- const previous = this.busy ? this.record : undefined;
215
- ++this.generation;
216
- await this.selectionPromise?.catch(() => false);
217
- if (previous && ctx.isIdle() && previous.sessionId === ctx.sessionManager.getSessionId()
218
- && modelKey(ctx.model) === previous.targetModel && !this.belongs(ctx, previous)) {
219
- // Tree navigation can leave the owned temporary selection on a sibling
220
- // without its request anchor. Re-anchor recovery only; never resume work.
221
- const anchorId = ctx.sessionManager.getLeafId();
222
- if (anchorId) {
223
- this.record = { ...previous, operationId: randomUUID(), anchorId, targetWindowId: undefined };
224
- this.write("restoring");
225
- await this.finish(ctx, false);
226
- return;
227
- }
228
- }
229
- this.record = undefined;
230
- this.newerSelection = undefined;
231
- const branch = ctx.sessionManager.getBranch();
232
- const latest = [...branch].reverse().find((entry) => entry.type === "custom" && entry.customType === MANUAL_COMPACT_ENTRY_TYPE);
233
- if (!latest || latest.type !== "custom") return;
234
- const record = decodeManualCompactRecord(latest.data);
235
- if (!record || TERMINAL.has(record.phase) || record.sessionId !== ctx.sessionManager.getSessionId()) return;
236
- // A newer explicit model change on the branch wins over the saved operation.
237
- if (branch.slice(branch.indexOf(latest) + 1).some((entry) => entry.type === "model_change" && `${entry.provider}/${entry.modelId}` !== record.targetModel && `${entry.provider}/${entry.modelId}` !== record.originalModel)) return;
238
- this.record = record;
239
- await this.finish(ctx, true);
240
- }
241
- async shutdown(ctx: ExtensionContext): Promise<void> {
242
- ++this.generation;
243
- await this.selectionPromise?.catch(() => false);
244
- if (this.busy) await this.finish(ctx, true);
245
- this.record = undefined;
246
- }
247
- }
@@ -1,238 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
3
- import { getCurrentSystemMessage, getCurrentTools } from "@earendil-works/pi-ai";
4
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
- import {
6
- CODEX_CONTEXT_WINDOW_MESSAGE_TYPE,
7
- CONTEXT_MANAGEMENT_PROTOCOL,
8
- CONTEXT_WINDOW_COMPACTION_STRATEGY,
9
- CONTEXT_WINDOW_FALLBACK_BUFFER,
10
- CONTEXT_WINDOW_REMINDER_THRESHOLD,
11
- type CodexContextManagementMessageDetails,
12
- type ContextManagementMessageKind,
13
- type ContextWindowCompactionDetails,
14
- type ContextWindowIdentity,
15
- type NotesCheckpointReceipt,
16
- isCodexContextManagementMessageDetails,
17
- isContextWindowCompactionDetails,
18
- } from "./types";
19
-
20
- export {
21
- CODEX_CONTEXT_WINDOW_MESSAGE_TYPE,
22
- CONTEXT_WINDOW_COMPACTION_STRATEGY,
23
- CONTEXT_WINDOW_FALLBACK_BUFFER,
24
- CONTEXT_WINDOW_REMINDER_THRESHOLD,
25
- isCodexContextManagementMessageDetails,
26
- isContextWindowCompactionDetails,
27
- };
28
- export type {
29
- CodexContextManagementMessageDetails,
30
- ContextManagementMessageKind,
31
- ContextWindowCompactionDetails,
32
- ContextWindowIdentity,
33
- };
34
-
35
- export const CONTEXT_WINDOW_COMPACTION_SUMMARY =
36
- "[Pi Codex context-window boundary; no conversation summary was generated.]";
37
-
38
- const CONTEXT_WINDOW_GUIDANCE = `<context_window_guidance>
39
- Before calling new_context, checkpoint the active request, known history IDs, decisions, progress, learnings and next steps in notes, and wait for that result to be persisted; only a persisted successful result in the current window unlocks the rollover. If new_context reports that a rollover is already scheduled, do not call it again in the same window. When this message includes a completed context-switch handoff, follow that post-rollover section first instead of restarting the pre-rollover checkpoint steps. A thread hint is supplemental and must not replace the local checkpoint receipt. No conversation summary carries over, and history is only for missing details.
40
- </context_window_guidance>`;
41
-
42
- export function renderContextWindowMessage(
43
- identity: ContextWindowIdentity,
44
- threadHint?: string,
45
- checkpoint?: NotesCheckpointReceipt,
46
- ): string {
47
- const lines = [
48
- "<context_window>",
49
- "Agent name: /root",
50
- `First context window id: ${identity.firstWindowId}`,
51
- `Current context window id: ${identity.currentWindowId}`,
52
- ];
53
- if (identity.previousWindowId) lines.push(`Previous context window id: ${identity.previousWindowId}`);
54
- if (checkpoint) {
55
- lines.push("Context switch completed. This is the first turn in the new context window.");
56
- lines.push("Checkpoint successfully written:");
57
- lines.push(` Read this note before doing anything else with notes action "read_file": ${JSON.stringify(checkpoint.path)}`);
58
- lines.push("After reading the checkpoint receipt, resume the active user task.");
59
- lines.push("Do not immediately create another checkpoint or call new_context as part of this handoff. Only prepare a new checkpoint when a later context rollover is actually needed.");
60
- }
61
- if (threadHint) lines.push(threadHint);
62
- lines.push("</context_window>");
63
- return `${CONTEXT_WINDOW_GUIDANCE}\n\n${lines.join("\n")}`;
64
- }
65
-
66
- export function renderContextWindowReminder(remainingTokens: number): string {
67
- return `<context_window_reminder>
68
- Only ${Math.max(0, Math.floor(remainingTokens))} context tokens remain. Checkpoint the active request, state and known history IDs in notes, then call new_context; no conversation summary carries over.
69
- </context_window_reminder>`;
70
- }
71
-
72
- export const CONTEXT_WINDOW_FALLBACK_MESSAGE = `<context_window_reminder>
73
- Context exhausted. Do not continue or answer. Make exactly one notes write or append call that checkpoints the active request, state and known history IDs, then call new_context. Use no other tools before rollover.
74
- </context_window_reminder>`;
75
-
76
- export function isContextWindowBoundary(
77
- message: AgentMessage,
78
- ): message is Extract<AgentMessage, { role: "custom" }> & {
79
- details: CodexContextManagementMessageDetails;
80
- } {
81
- return (
82
- message.role === "custom" &&
83
- message.customType === CODEX_CONTEXT_WINDOW_MESSAGE_TYPE &&
84
- isCodexContextManagementMessageDetails(message.details) &&
85
- message.details.contextManagement.kind === "window"
86
- );
87
- }
88
-
89
- export function sendContextWindowMessage(
90
- pi: ExtensionAPI,
91
- content: string,
92
- kind: ContextManagementMessageKind,
93
- identity: ContextWindowIdentity,
94
- options: { triggerTurn: boolean; sessionId?: string },
95
- trimPreviousWindow = false,
96
- ): void {
97
- const details: CodexContextManagementMessageDetails = {
98
- protocol: CONTEXT_MANAGEMENT_PROTOCOL,
99
- id: randomUUID(),
100
- ...(options.sessionId ? { sessionId: options.sessionId } : {}),
101
- contextManagement: {
102
- protocol: CONTEXT_MANAGEMENT_PROTOCOL,
103
- kind,
104
- ...identity,
105
- ...(trimPreviousWindow ? { trimPreviousWindow: true as const } : {}),
106
- },
107
- };
108
- pi.sendMessage({
109
- customType: CODEX_CONTEXT_WINDOW_MESSAGE_TYPE,
110
- content,
111
- display: true,
112
- details,
113
- }, options.triggerTurn
114
- ? { deliverAs: "steer", triggerTurn: true }
115
- : { triggerTurn: false });
116
- }
117
-
118
- /** Whether a transcript message is a Pi system message (prompt sections and tool deltas). */
119
- export function isSystemTranscriptMessage(message: AgentMessage): boolean {
120
- return (message as unknown as { role?: string }).role === "system";
121
- }
122
-
123
- /** Tool names the provider would send for this message list, after replaying every delta. */
124
- export function declaredToolNames(messages: readonly AgentMessage[]): string[] {
125
- return getCurrentTools(messages).map((tool) => tool.name);
126
- }
127
-
128
- export type SystemHeadRepair<TMessage extends AgentMessage = AgentMessage> = {
129
- /** The window to send: trimmed, trimmed plus a rebuilt head, or untrimmed when the trim is unsafe. */
130
- readonly messages: readonly TMessage[];
131
- /** A head from before the boundary was re-anchored at the front of the window. */
132
- repaired: boolean;
133
- /** The trim was refused because the window would lose declared tools. */
134
- shrinkRejected: boolean;
135
- /** Tool names the trimmed window would have lost; empty on every safe path. */
136
- lostToolNames: string[];
137
- /** The system message this window anchors on, when one could be determined. */
138
- head: AgentMessage | undefined;
139
- };
140
-
141
- /**
142
- * Keep Pi 0.86's prompt and tool head alive across a context-window trim.
143
- *
144
- * Pi 0.86 no longer sends the system prompt and the tool loadout beside the
145
- * transcript: `Agent#createContextSnapshot()` hands over messages only, and the
146
- * Responses transport rebuilds `params.tools` from the `system` messages inside the
147
- * message list (`resolveTranscriptTools(getInitialSystemMessage(messages))`). Trimming
148
- * everything before a window boundary therefore deletes the one message that declares
149
- * every tool, and Pi does not re-declare it because the persisted transcript still looks
150
- * unchanged. The result is a window the model can only answer from memory.
151
- *
152
- * The merged state of the trimmed-away system messages is re-anchored as the leading
153
- * message of the window. When even that would lose declared tools, the trim is refused:
154
- * a window that still carries the previous turns beats a window with no tools at all.
155
- */
156
- export function preserveSystemHead<TMessage extends AgentMessage>(args: {
157
- readonly messages: readonly TMessage[];
158
- boundaryIndex: number;
159
- /**
160
- * Head observed in an earlier projection. A durable compaction can drop the original
161
- * declaration from the branch, leaving nothing to rebuild from, so the last known head
162
- * is re-anchored instead of sending a window with no tools.
163
- */
164
- fallbackHead?: AgentMessage;
165
- }): SystemHeadRepair<TMessage> {
166
- const { messages, boundaryIndex, fallbackHead } = args;
167
- const window = messages.slice(Math.max(boundaryIndex, 0));
168
- const prefix = messages.slice(0, Math.max(boundaryIndex, 0));
169
-
170
- const anchorFallback = (): SystemHeadRepair<TMessage> | undefined => {
171
- if (!fallbackHead || messages.some(isSystemTranscriptMessage)) return undefined;
172
- // A boundary compaction can retire the entry that declared the tools, leaving a
173
- // branch whose only system state is gone. Nothing in the list can be rebuilt, so
174
- // the head remembered from an earlier projection is re-anchored instead.
175
- const reused: readonly TMessage[] = [
176
- fallbackHead as unknown as TMessage,
177
- ...window.filter((message) => !isSystemTranscriptMessage(message)),
178
- ];
179
- return { messages: reused, repaired: true, shrinkRejected: false, lostToolNames: [], head: fallbackHead };
180
- };
181
-
182
- if (boundaryIndex <= 0 || prefix.length === 0) {
183
- return anchorFallback() ?? {
184
- messages: window,
185
- repaired: false,
186
- shrinkRejected: false,
187
- lostToolNames: [],
188
- head: getCurrentSystemMessage(messages) ?? fallbackHead,
189
- };
190
- }
191
-
192
- const declared = declaredToolNames(messages);
193
- const completeHead = getCurrentSystemMessage(messages);
194
- if (!completeHead) {
195
- const reused = anchorFallback();
196
- if (reused) return reused;
197
- if (!messages.some(isSystemTranscriptMessage) && declared.length === 0) {
198
- // Pre-0.86 transcripts carry no system messages: the trim stays exactly as before.
199
- return { messages: window, repaired: false, shrinkRejected: false, lostToolNames: [], head: undefined };
200
- }
201
- return { messages, repaired: false, shrinkRejected: true, lostToolNames: declared, head: undefined };
202
- }
203
-
204
- const windowFirst = window[0];
205
- if (windowFirst && isSystemTranscriptMessage(windowFirst)) {
206
- const kept = new Set(declaredToolNames(window));
207
- const lostFromWindow = declared.filter((name) => !kept.has(name));
208
- if (lostFromWindow.length === 0) {
209
- return {
210
- messages: window,
211
- repaired: false,
212
- shrinkRejected: false,
213
- lostToolNames: [],
214
- head: windowFirst as unknown as AgentMessage,
215
- };
216
- }
217
- return {
218
- messages,
219
- repaired: false,
220
- shrinkRejected: true,
221
- lostToolNames: lostFromWindow,
222
- head: windowFirst as unknown as AgentMessage,
223
- };
224
- }
225
-
226
- // Later system messages are folded into the rebuilt head, so a patch cannot be read
227
- // as a complete declaration by a transport that only anchors the first one.
228
- const rebuilt: readonly TMessage[] = [
229
- completeHead as unknown as TMessage,
230
- ...window.filter((message) => !isSystemTranscriptMessage(message)),
231
- ];
232
- const after = new Set(declaredToolNames(rebuilt));
233
- const lostToolNames = declared.filter((name) => !after.has(name));
234
- if (lostToolNames.length > 0) {
235
- return { messages, repaired: false, shrinkRejected: true, lostToolNames, head: completeHead };
236
- }
237
- return { messages: rebuilt, repaired: true, shrinkRejected: false, lostToolNames: [], head: completeHead };
238
- }