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,89 +0,0 @@
1
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
- import {
3
- estimateTokens,
4
- findCutPoint,
5
- type FileOperations,
6
- type SessionBeforeCompactEvent,
7
- type SessionEntry,
8
- } from "@earendil-works/pi-coding-agent";
9
- import { isRecord } from "./types";
10
- import type { RemoteWindowCompactionInput } from "./window-manager";
11
-
12
- function addFileOperation(name: string, args: unknown, files: FileOperations): void {
13
- if (!isRecord(args) || typeof args.path !== "string") return;
14
- if (name === "read") files.read.add(args.path);
15
- else if (name === "write") files.written.add(args.path);
16
- else if (name === "edit") files.edited.add(args.path);
17
- }
18
-
19
- /** Only canonical, current-window operations may contribute summary file metadata. */
20
- function collectFileOperations(messages: readonly AgentMessage[], scope: RemoteWindowCompactionInput): FileOperations {
21
- const files: FileOperations = { read: new Set(), written: new Set(), edited: new Set() };
22
- const previous = scope.owningCompaction;
23
- if (previous && isRecord(previous.details)) {
24
- for (const path of Array.isArray(previous.details.readFiles) ? previous.details.readFiles : []) {
25
- if (typeof path === "string") files.read.add(path);
26
- }
27
- for (const path of Array.isArray(previous.details.modifiedFiles) ? previous.details.modifiedFiles : []) {
28
- if (typeof path === "string") files.edited.add(path);
29
- }
30
- }
31
- for (const message of messages) {
32
- if (message.role === "assistant") {
33
- for (const block of message.content) if (block.type === "toolCall") addFileOperation(block.name, block.arguments, files);
34
- } else if (message.role === "toolResult") {
35
- for (const call of message.nestedCalls?.calls ?? []) addFileOperation(call.name, call.arguments, files);
36
- }
37
- }
38
- return files;
39
- }
40
-
41
- /**
42
- * Adapt canonical contributions to the public cut-point primitive. These are
43
- * detached in-memory views with REAL source IDs, never entries to persist.
44
- * Omitted entries contribute nothing; edited messages replace their raw values.
45
- */
46
- export function prepareScopedNativeCompaction(
47
- event: SessionBeforeCompactEvent,
48
- scope: RemoteWindowCompactionInput,
49
- ): SessionBeforeCompactEvent {
50
- const entries: SessionEntry[] = [];
51
- for (const projected of scope.entries) {
52
- if (projected.sourceEntry.type === "compaction") continue;
53
- const messages = projected.messages.filter((message) => message.role !== "system");
54
- if (!messages.length) continue;
55
- // A single retained ID cannot safely identify a split within one source.
56
- if (messages.length !== 1) throw new Error("compaction-source-projection-unavailable");
57
- entries.push({ type: "message", id: projected.sourceEntry.id, parentId: projected.sourceEntry.parentId,
58
- timestamp: projected.sourceEntry.timestamp, message: structuredClone(messages[0]!) });
59
- }
60
- if (!entries.length) throw new Error("unsafe-compaction-retained-start");
61
- const settings = event.preparation.settings;
62
- if (!settings || !Number.isFinite(settings.keepRecentTokens) || !Number.isFinite(settings.reserveTokens)) {
63
- throw new Error("compaction-settings-unavailable");
64
- }
65
- const owner = scope.owningCompaction;
66
- const ownerIndex = owner ? event.branchEntries.findIndex((entry) => entry.id === owner.id) : -1;
67
- if (owner && ownerIndex < scope.windowBoundaryIndex) throw new Error("compaction-owner-mismatch");
68
- const lowerIndex = Math.max(scope.windowBoundaryIndex, ownerIndex);
69
- const minimumKeptIndex = entries.findIndex((entry) => event.branchEntries.findIndex((raw) => raw.id === entry.id) >= lowerIndex);
70
- if (minimumKeptIndex < 0) throw new Error("compaction-current-window-too-small");
71
- const cut = findCutPoint(entries, minimumKeptIndex, entries.length, settings.keepRecentTokens);
72
- const kept = entries[cut.firstKeptEntryIndex];
73
- if (kept?.type !== "message" || kept.message.role === "toolResult") throw new Error("unsafe-compaction-retained-start");
74
- const firstKeptEntryId = kept.id;
75
- if (!firstKeptEntryId) throw new Error("unsafe-compaction-retained-start");
76
- const messages = (start: number, end: number) => entries.slice(start, end).flatMap((entry) => entry.type === "message" ? [entry.message] : []);
77
- const messagesToSummarize = messages(0, cut.isSplitTurn ? cut.turnStartIndex : cut.firstKeptEntryIndex);
78
- const turnPrefixMessages = cut.isSplitTurn ? messages(cut.turnStartIndex, cut.firstKeptEntryIndex) : [];
79
- return {
80
- ...event,
81
- preparation: {
82
- firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn: cut.isSplitTurn,
83
- tokensBefore: scope.messages.reduce((tokens, message) => tokens + estimateTokens(message), 0),
84
- previousSummary: scope.owningCompaction?.summary,
85
- fileOps: collectFileOperations([...messagesToSummarize, ...turnPrefixMessages], scope),
86
- settings: { ...settings },
87
- },
88
- };
89
- }
@@ -1,62 +0,0 @@
1
- export const HISTORY_ACTIONS = [
2
- "list_windows",
3
- "list_items",
4
- "read_item",
5
- "search_contents",
6
- ] as const;
7
-
8
- export const NOTES_ACTIONS = [
9
- "list_files_by_prefix",
10
- "read_file",
11
- "search_contents",
12
- "append_to_file",
13
- "write_file",
14
- ] as const;
15
-
16
- /** Stable names shared by Toolkit registration and an external Pi launcher. */
17
- export const CONTEXT_MANAGEMENT_TOOL_NAMES = [
18
- "new_context",
19
- "get_context_remaining",
20
- "history",
21
- "notes",
22
- ] as const;
23
-
24
- export type HistoryAction = (typeof HISTORY_ACTIONS)[number];
25
- export type NotesAction = (typeof NOTES_ACTIONS)[number];
26
- export type ContextManagementToolName = (typeof CONTEXT_MANAGEMENT_TOOL_NAMES)[number];
27
-
28
- export type ContextToolSelection = {
29
- /** Pi's explicit tool allowlist. Omitted means use Pi's default selection. */
30
- tools?: readonly string[];
31
- /** Pi's default suppression mode. Both values are explicit host policy. */
32
- noTools?: "all" | "builtin";
33
- /** Pi applies this denylist after the allowlist. */
34
- excludeTools?: readonly string[];
35
- };
36
-
37
- /**
38
- * Add Toolkit context tools to a host-provided allowlist without overriding an
39
- * explicit no-tools or exclude-tools decision. The launcher owns model eligibility;
40
- * this helper only owns the shared selection contract.
41
- */
42
- export function ensureContextManagementToolsInAllowlist(
43
- selection: ContextToolSelection,
44
- eligible: boolean,
45
- ): string[] | undefined {
46
- if (!eligible || selection.noTools !== undefined || selection.tools === undefined) {
47
- return selection.tools === undefined ? undefined : [...selection.tools];
48
- }
49
-
50
- const excluded = new Set(selection.excludeTools ?? []);
51
- const names = [...selection.tools];
52
- for (const name of CONTEXT_MANAGEMENT_TOOL_NAMES) {
53
- if (!excluded.has(name) && !names.includes(name)) names.push(name);
54
- }
55
- return names;
56
- }
57
-
58
- export const HISTORY_DESCRIPTION =
59
- "Prior-window detail. Pass IDs unchanged. Search, never browse.";
60
-
61
- export const NOTES_DESCRIPTION =
62
- "Cross-window checkpoints on virtual paths. Relative uses current agent; cross-agent uses <agent>/notes[/path].";
@@ -1,371 +0,0 @@
1
- import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
- import { StringEnum, Type } from "@earendil-works/pi-ai";
3
- import { executeHistoryNotesTool, type CodexHistoryNotesDetails } from "./history-notes";
4
- import { type CodexContextWindowManager } from "./window-manager";
5
- import {
6
- HISTORY_ACTION_FIELDS,
7
- HISTORY_ENDPOINTS,
8
- NOTES_ACTION_FIELDS,
9
- NOTES_ENDPOINTS,
10
- } from "./history-notes";
11
- import type { ContextWindowIdentity, HistoryAction, NotesAction } from "./types";
12
-
13
- const EMPTY_PARAMETERS = Type.Object({}, { additionalProperties: false });
14
-
15
- type PublishedTool = {
16
- name: string;
17
- description: string;
18
- parameters: unknown;
19
- promptGuidelines?: string[];
20
- };
21
-
22
- /**
23
- * Pi's ToolInfo wrapper is new, but its definition fields retain the objects
24
- * registered by the extension. Keep identity checks for those fields: an exact
25
- * foreign clone under the same name is still not ownership of our tool.
26
- */
27
- function isOurTool(
28
- actual: PublishedTool,
29
- expected: { description: string; parameters: unknown; promptGuidelines?: string[] },
30
- ): boolean {
31
- return actual.description === expected.description
32
- && actual.parameters === expected.parameters
33
- && actual.promptGuidelines === expected.promptGuidelines;
34
- }
35
- const HISTORY_ACTIONS = Object.keys(HISTORY_ENDPOINTS) as [HistoryAction, ...HistoryAction[]];
36
- const NOTES_ACTIONS = Object.keys(NOTES_ENDPOINTS) as [NotesAction, ...NotesAction[]];
37
-
38
- export const HISTORY_PARAMETERS = Type.Object({
39
- action: StringEnum(HISTORY_ACTIONS),
40
- agent_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
41
- item_id: Type.Optional(Type.String()),
42
- limit: Type.Optional(Type.Integer({ minimum: 1 })),
43
- limit_chars: Type.Optional(Type.Integer({ minimum: 1 })),
44
- max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1 })),
45
- offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
46
- query: Type.Optional(Type.String()),
47
- recent_first: Type.Optional(Type.Boolean()),
48
- role: Type.Optional(Type.Union([StringEnum(["user", "assistant", "tool", "system", "developer"] as const), Type.Null()])),
49
- tool_name: Type.Optional(Type.Union([Type.String(), Type.Null()])),
50
- tool_namespace: Type.Optional(Type.Union([Type.String(), Type.Null()])),
51
- window_id: Type.Optional(Type.Union([Type.String(), Type.Null()])),
52
- }, { additionalProperties: false });
53
-
54
- export const NOTES_PARAMETERS = Type.Object({
55
- action: StringEnum(NOTES_ACTIONS),
56
- file_order: Type.Optional(StringEnum(["ascending", "descending"] as const)),
57
- file_order_by: Type.Optional(StringEnum(["name", "created_at", "updated_at"] as const)),
58
- max_files: Type.Optional(Type.Integer({ minimum: 1 })),
59
- max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1 })),
60
- max_results: Type.Optional(Type.Integer({ minimum: 1 })),
61
- path: Type.Optional(Type.String()),
62
- path_prefix: Type.Optional(Type.Union([Type.String(), Type.Null()])),
63
- prefix: Type.Optional(Type.Union([Type.String(), Type.Null()])),
64
- query: Type.Optional(Type.String()),
65
- recent_file_first: Type.Optional(Type.Boolean()),
66
- start_line: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
67
- stop_line: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
68
- text: Type.Optional(Type.String()),
69
- }, { additionalProperties: false });
70
-
71
- export interface NewContextDetails { started: boolean; }
72
-
73
- export const NEW_CONTEXT_PARAMETERS = Type.Object({}, { additionalProperties: false });
74
-
75
- export const NEW_CONTEXT_CHECKPOINT_REQUIRED_MESSAGE =
76
- "new_context refused: no persisted successful notes checkpoint in the current context window. "
77
- + "Write the active request, decisions, progress and next steps with notes append_to_file or write_file, "
78
- + "wait until that notes result is persisted, then retry new_context in a later tool turn. "
79
- + "Do not pass force arguments and do not repeat new_context while a rollover is already scheduled.";
80
-
81
- export const NEW_CONTEXT_COOLDOWN_MESSAGE =
82
- "new_context refused: this window was entered by a context switch and has not run any substantive "
83
- + "tool yet. Read the checkpoint receipt with notes read_file, continue the active task with real "
84
- + "tools, and call new_context only once this window has produced tool activity.";
85
- export interface ContextRemainingDetails {
86
- remainingTokens?: number;
87
- windowId?: string;
88
- contextWindow: number;
89
- }
90
-
91
- export type ContextManagementTools = {
92
- newContext: ToolDefinition<typeof NEW_CONTEXT_PARAMETERS, NewContextDetails>;
93
- getContextRemaining: ToolDefinition<typeof EMPTY_PARAMETERS, ContextRemainingDetails>;
94
- history: ToolDefinition<typeof HISTORY_PARAMETERS, CodexHistoryNotesDetails>;
95
- notes: ToolDefinition<typeof NOTES_PARAMETERS, CodexHistoryNotesDetails>;
96
- };
97
-
98
- export type ContextOperationPolicy = { active: boolean; gatewayModels: readonly string[] };
99
- type ContextActivity = (ctx: ExtensionContext) => Promise<boolean | ContextOperationPolicy> | boolean | ContextOperationPolicy;
100
-
101
- export interface ContextRolloverHandoff {
102
- prepare(ctx: ExtensionContext): { triggerTurn: false; beforeSchedule: (identity: ContextWindowIdentity) => void } | undefined;
103
- }
104
-
105
- export function createContextManagementTools(
106
- pi: ExtensionAPI,
107
- manager: CodexContextWindowManager,
108
- isActive: ContextActivity,
109
- getGatewayModels: () => readonly string[] = () => [],
110
- handoff?: ContextRolloverHandoff,
111
- ): ContextManagementTools {
112
- const assertActive = async (ctx: ExtensionContext): Promise<readonly string[]> => {
113
- const policy = await isActive(ctx);
114
- if (!(typeof policy === "boolean" ? policy : policy.active)) throw new Error("remote-context-inactive");
115
- return typeof policy === "boolean" ? getGatewayModels() : policy.gatewayModels;
116
- };
117
- const newContext: ToolDefinition<typeof NEW_CONTEXT_PARAMETERS, NewContextDetails> = {
118
- name: "new_context",
119
- label: "new_context",
120
- description: "Start a new remote Codex context window without generating a conversation summary. Requires a persisted successful notes checkpoint in the current window.",
121
- parameters: NEW_CONTEXT_PARAMETERS,
122
- exposure: "direct",
123
- promptSnippet: "Start a new remote Codex context window without summarizing history.",
124
- promptGuidelines: [
125
- "Before this new_context call, checkpoint active work in notes; only a persisted successful notes append/write in the current window unlocks this rollover, and no conversation summary carries over.",
126
- "A successful new_context completes one context switch. In the next window, read the checkpoint receipt first when present, then resume the active user task; do not immediately create another checkpoint or call new_context as part of that handoff.",
127
- "Wait for the notes tool result before calling new_context; an in-flight or failed write is not a checkpoint. If new_context reports that a rollover is already scheduled, do not call it again in the same window.",
128
- ],
129
- executionMode: "sequential",
130
- async execute(_id, _params, signal, _update, ctx) {
131
- const gatewayModels = await assertActive(ctx);
132
- manager.synchronize(ctx);
133
- if (manager.hasPendingRollover(ctx)) {
134
- return {
135
- content: [{ type: "text", text: "A new context window is already scheduled." }],
136
- details: { started: false },
137
- };
138
- }
139
- if (!manager.canRolloverFromCurrentWindow(ctx)) {
140
- return {
141
- content: [{ type: "text", text: NEW_CONTEXT_COOLDOWN_MESSAGE }],
142
- details: { started: false },
143
- };
144
- }
145
- if (!manager.hasNotesCheckpointSinceBoundary(ctx)) {
146
- throw new Error(NEW_CONTEXT_CHECKPOINT_REQUIRED_MESSAGE);
147
- }
148
- const scheduling = handoff?.prepare(ctx);
149
- const started = await manager.startNewWindow(pi, ctx, {
150
- triggerTurn: true,
151
- signal,
152
- trimPreviousWindow: true,
153
- gatewayModels,
154
- ...scheduling,
155
- });
156
- return {
157
- content: [{
158
- type: "text",
159
- text: started
160
- ? "Context switch scheduled successfully. In the next context window, read the checkpoint receipt first when present, then resume the active user task; do not immediately create another checkpoint or call new_context."
161
- : "A new context window is already scheduled.",
162
- }],
163
- details: { started },
164
- ...(started && scheduling ? { terminate: true } : {}),
165
- };
166
- },
167
- };
168
- const getContextRemaining: ToolDefinition<typeof EMPTY_PARAMETERS, ContextRemainingDetails> = {
169
- name: "get_context_remaining",
170
- label: "get_context_remaining",
171
- description: "Get the remaining tokens in the current remote Codex context window.",
172
- parameters: EMPTY_PARAMETERS,
173
- exposure: "direct",
174
- async execute(_id, _params, _signal, _update, ctx) {
175
- await assertActive(ctx);
176
- const remaining = manager.remaining(ctx);
177
- return {
178
- content: [{ type: "text", text: remaining.remainingTokens === undefined ? "You have unknown tokens left in this context window." : `You have ${remaining.remainingTokens} tokens left in this context window.` }],
179
- details: remaining,
180
- };
181
- },
182
- };
183
- const history: ToolDefinition<typeof HISTORY_PARAMETERS, CodexHistoryNotesDetails> = {
184
- name: "history",
185
- label: "history",
186
- description: "Search or read prior remote Codex context-window history. Pass IDs unchanged.",
187
- parameters: HISTORY_PARAMETERS,
188
- exposure: "direct",
189
- promptSnippet: "Search or read prior remote Codex context-window history.",
190
- promptGuidelines: [
191
- "When the user asks about decisions, code, or details from earlier in the conversation that are no longer in the current context window, use history first instead of relying on fragments that survived compaction.",
192
- "Use read_item with the exact item_id returned by list_items or search_contents; never rewrite, truncate, or guess IDs.",
193
- "Before starting a new context window, use history to verify which earlier work the user still expects to be honored, then checkpoint anything not yet durable in notes.",
194
- "Prefer search_contents over list_items when you only need a known fact; list_items is for getting an overview of what windows and items exist.",
195
- "History is read-only; make no edits through it. Edits and durable checkpoints belong to notes.",
196
- ],
197
- execute: async (_id, params, _signal, _update, ctx) => {
198
- const gatewayModels = await assertActive(ctx);
199
- return executeHistoryNotesTool("history", params.action, params as Record<string, unknown>, ctx, _signal, gatewayModels);
200
- },
201
- };
202
- const notes: ToolDefinition<typeof NOTES_PARAMETERS, CodexHistoryNotesDetails> = {
203
- name: "notes",
204
- label: "notes",
205
- description: "Read and checkpoint remote Codex notes across context windows.",
206
- parameters: NOTES_PARAMETERS,
207
- exposure: "direct",
208
- promptSnippet: "Read and checkpoint remote Codex notes across context windows.",
209
- promptGuidelines: [
210
- "Before calling new_context, checkpoint the current turn's active work (unfinished tasks, decisions, open questions, references) into notes with append_to_file or write_file so it survives the window change; wait for that result to be persisted before calling new_context.",
211
- "After a successful new_context handoff, read the checkpoint receipt first when present and resume the active user task; do not immediately create another checkpoint or call new_context unless a later rollover is actually needed.",
212
- "When a large task spans multiple context windows, keep a running note per line of work and read it at the start of each new window; append new state instead of replacing it unless the note is stale.",
213
- "Prefer read_file or search_contents for looking things up; reserve write_file for explicit rewrite/clear and append_to_file for incremental state.",
214
- "Keep note text concise and self-contained: it may be read later without the rest of the conversation, so include identifiers and verbatim key decisions, not hearsay summaries.",
215
- "Do not store live credentials, API keys, or full request bodies in notes; record the fact and where it lives instead.",
216
- ],
217
- executionMode: "sequential",
218
- execute: async (_id, params, _signal, _update, ctx) => {
219
- const gatewayModels = await assertActive(ctx);
220
- return executeHistoryNotesTool("notes", params.action, params as Record<string, unknown>, ctx, _signal, gatewayModels);
221
- },
222
- };
223
- return { newContext, getContextRemaining, history, notes };
224
- }
225
-
226
- export type ContextToolRegistrationState = "verified" | "excluded" | "conflict" | "unverified";
227
-
228
- export type ContextToolSyncResult = {
229
- synced: boolean;
230
- registrationState: ContextToolRegistrationState;
231
- };
232
-
233
- export class ContextManagementToolController {
234
- private readonly registeredNames = new Set<string>();
235
- private readonly definitions = new Map<string, {
236
- description: string;
237
- parameters: unknown;
238
- promptGuidelines?: string[];
239
- }>();
240
- private registered = false;
241
- private verifiedOnce = false;
242
-
243
- constructor(private readonly pi: ExtensionAPI) {}
244
-
245
- register(tools: ContextManagementTools): boolean {
246
- const definitions = [tools.newContext, tools.getContextRemaining, tools.history, tools.notes];
247
- const api = this.pi as ExtensionAPI & { registerTool?: (tool: unknown) => void };
248
- if (typeof api.registerTool !== "function") return false;
249
-
250
- // registerTool() is a registration method and is valid while Pi is loading
251
- // the extension. Do not call action methods such as getAllTools() here;
252
- // those are bound only after extension loading completes.
253
- try {
254
- for (const definition of definitions) api.registerTool(definition);
255
- this.registered = true;
256
- } catch {
257
- // Pi rejects a registration whose name is already owned elsewhere.
258
- this.registered = false;
259
- return false;
260
- }
261
-
262
- this.registeredNames.clear();
263
- this.definitions.clear();
264
- this.verifiedOnce = false;
265
- for (const definition of definitions) {
266
- this.registeredNames.add(definition.name);
267
- this.definitions.set(definition.name, {
268
- description: definition.description,
269
- parameters: definition.parameters,
270
- promptGuidelines: definition.promptGuidelines,
271
- });
272
- }
273
- // A successful call only proves the hand-off; it does not prove the runtime
274
- // published the definitions. `checkRegistration()` reads that from Pi.
275
- return true;
276
- }
277
-
278
- /**
279
- * Read registration state until the runtime confirms publication.
280
- *
281
- * Pi 0.86 can reject action methods while a session replacement is still
282
- * binding, and can publish the registry after `session_start` ran. Negative
283
- * reads remain retryable; only a successful verification is cached for this
284
- * controller instance. A Pi reload creates a new controller.
285
- */
286
- checkRegistration(): ContextToolRegistrationState {
287
- if (!this.registered) return "conflict";
288
- // A confirmed publication is kept: the expensive part was never the read, it
289
- // was trusting a failed one. Only negative verdicts are recomputed each time.
290
- if (this.verifiedOnce) return "verified";
291
- let available: PublishedTool[];
292
- try {
293
- const api = this.pi as ExtensionAPI & { getAllTools?: () => PublishedTool[] };
294
- if (typeof api.getAllTools !== "function") return "conflict";
295
- available = api.getAllTools();
296
- } catch {
297
- // Stale or unbound runtime: retry on the next sync.
298
- return "unverified";
299
- }
300
- const byName = new Map(available.map((tool) => [tool.name, tool]));
301
- let missing = false;
302
- let conflict = false;
303
- let published = 0;
304
- for (const name of this.registeredNames) {
305
- const actual = byName.get(name);
306
- const expected = this.definitions.get(name);
307
- if (actual === undefined || expected === undefined) {
308
- missing = true;
309
- continue;
310
- }
311
- published += 1;
312
- if (!isOurTool(actual, expected)) conflict = true;
313
- }
314
- if (conflict) return "conflict";
315
- // A readable registry with no Toolkit-owned definitions is the positive
316
- // host-filtering signal used by --no-tools/restricted child sessions.
317
- if (published === 0) return "excluded";
318
- if (missing) return "unverified";
319
- this.verifiedOnce = true;
320
- return "verified";
321
- }
322
-
323
- sync(active: boolean): ContextToolSyncResult {
324
- const registrationState = this.checkRegistration();
325
- if (registrationState !== "verified") return { synced: false, registrationState };
326
- const api = this.pi as ExtensionAPI & { getActiveTools?: () => string[]; setActiveTools?: (names: string[]) => void };
327
- if (typeof api.getActiveTools !== "function" || typeof api.setActiveTools !== "function") {
328
- return { synced: false, registrationState };
329
- }
330
- try {
331
- const current = api.getActiveTools();
332
- // Pi may activate a newly registered tool before the first sync. Once
333
- // registration is verified, every registered name belongs to this
334
- // controller: active models get all four, inactive models get none.
335
- const next = active
336
- ? [...current, ...[...this.registeredNames].filter((name) => !current.includes(name))]
337
- : current.filter((name) => !this.registeredNames.has(name));
338
- if (next.length !== current.length) api.setActiveTools(next);
339
- return { synced: true, registrationState };
340
- } catch {
341
- return { synced: false, registrationState };
342
- }
343
- }
344
-
345
- reset(): void {
346
- this.sync(false);
347
- }
348
- get isRegistered(): boolean { return this.checkRegistration() === "verified"; }
349
- get registrationState(): ContextToolRegistrationState { return this.checkRegistration(); }
350
- }
351
-
352
- export function registerContextManagementTools(
353
- pi: ExtensionAPI,
354
- manager: CodexContextWindowManager,
355
- isActive: ContextActivity,
356
- getGatewayModels?: () => readonly string[],
357
- handoff?: ContextRolloverHandoff,
358
- ): ContextManagementToolController {
359
- const controller = new ContextManagementToolController(pi);
360
- controller.register(createContextManagementTools(pi, manager, isActive, getGatewayModels, handoff));
361
- return controller;
362
- }
363
-
364
- export const _contextToolsTest = {
365
- EMPTY_PARAMETERS,
366
- NEW_CONTEXT_PARAMETERS,
367
- HISTORY_PARAMETERS,
368
- NOTES_PARAMETERS,
369
- HISTORY_ACTION_FIELDS,
370
- NOTES_ACTION_FIELDS,
371
- };
@@ -1,168 +0,0 @@
1
- import type { ContextManagementMode } from "../types";
2
-
3
- export type { ContextManagementMode };
4
-
5
- export const CONTEXT_MANAGEMENT_PROTOCOL = 1 as const;
6
- export const CODEX_CONTEXT_WINDOW_MESSAGE_TYPE = "codex-context-window" as const;
7
- export const CONTEXT_WINDOW_COMPACTION_STRATEGY = "codex-context-window" as const;
8
- export const CONTEXT_WINDOW_REMINDER_THRESHOLD = 6_144;
9
- export const CONTEXT_WINDOW_FALLBACK_BUFFER = 16_384;
10
-
11
- export type ContextManagementMessageKind = "window" | "reminder" | "fallback";
12
-
13
- export type ContextWindowIdentity = {
14
- firstWindowId: string;
15
- currentWindowId: string;
16
- previousWindowId?: string;
17
- windowNumber: number;
18
- };
19
-
20
- /** Persisted-session evidence identifying the note that can restore a rollover. */
21
- export type NotesCheckpointReceipt = {
22
- path: string;
23
- toolCallId: string;
24
- };
25
-
26
- export type CodexContextManagementMessageDetails = {
27
- protocol: typeof CONTEXT_MANAGEMENT_PROTOCOL;
28
- id: string;
29
- sessionId?: string;
30
- contextManagement: ContextWindowIdentity & {
31
- protocol: typeof CONTEXT_MANAGEMENT_PROTOCOL;
32
- kind: ContextManagementMessageKind;
33
- trimPreviousWindow?: true;
34
- };
35
- };
36
-
37
- export type ContextWindowCompactionDetails = {
38
- protocol: typeof CONTEXT_MANAGEMENT_PROTOCOL;
39
- strategy: typeof CONTEXT_WINDOW_COMPACTION_STRATEGY;
40
- windowId?: string;
41
- };
42
-
43
- export type RemoteContextFailureReason =
44
- | "context-management-inactive"
45
- | "unsupported-model"
46
- | "unsupported-api"
47
- | "unsupported-backend"
48
- | "auth-resolution-failed"
49
- | "missing-token"
50
- | "missing-api-key"
51
- | "missing-account-id"
52
- | "missing-base-url"
53
- | "missing-session-id"
54
- | "invalid-account-token"
55
- | "backend-timeout"
56
- | "aborted"
57
- | "http-error"
58
- | "invalid-json"
59
- | "invalid-response"
60
- | "protocol-error";
61
-
62
- export type NativeCodexContextProvider = {
63
- kind: "native-codex";
64
- route: "openai-codex";
65
- provider: "openai-codex";
66
- api: "openai-codex-responses";
67
- model: string;
68
- baseUrl: string;
69
- token: string;
70
- accountId: string;
71
- headers: Record<string, string>;
72
- };
73
-
74
- export type GatewayCodexContextProvider = {
75
- kind: "codex-gateway";
76
- route: "codex-gateway";
77
- /** Operator-defined provider name; matched via compaction.gatewayContextModels. */
78
- provider: string;
79
- api: "openai-responses";
80
- model: string;
81
- baseUrl: string;
82
- apiKey: string;
83
- headers: Record<string, string>;
84
- };
85
-
86
- export type CodexContextProvider = NativeCodexContextProvider | GatewayCodexContextProvider;
87
-
88
- export type CodexContextProviderResolution =
89
- | { ok: true; provider: CodexContextProvider }
90
- | {
91
- ok: false;
92
- reason: RemoteContextFailureReason;
93
- provider?: string;
94
- api?: string;
95
- model?: string;
96
- baseUrl?: string;
97
- };
98
-
99
- export type HistoryAction =
100
- | "list_windows"
101
- | "list_items"
102
- | "read_item"
103
- | "search_contents";
104
-
105
- export type NotesAction =
106
- | "list_files_by_prefix"
107
- | "read_file"
108
- | "search_contents"
109
- | "append_to_file"
110
- | "write_file";
111
-
112
- export type HistoryNotesResponse = Record<string, unknown>;
113
-
114
- export type HistoryNotesResult =
115
- | { ok: true; value: HistoryNotesResponse }
116
- | {
117
- ok: false;
118
- reason: Exclude<RemoteContextFailureReason, "context-management-inactive" | "unsupported-model" | "unsupported-api">;
119
- status?: number;
120
- };
121
-
122
- export function isRecord(value: unknown): value is Record<string, unknown> {
123
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
124
- }
125
-
126
- export function isNonEmptyString(value: unknown): value is string {
127
- return typeof value === "string" && value.trim().length > 0;
128
- }
129
-
130
- export function isContextWindowIdentity(value: unknown): value is ContextWindowIdentity {
131
- if (!isRecord(value)) return false;
132
- return (
133
- isNonEmptyString(value.firstWindowId) &&
134
- isNonEmptyString(value.currentWindowId) &&
135
- (value.previousWindowId === undefined || isNonEmptyString(value.previousWindowId)) &&
136
- Number.isInteger(value.windowNumber) &&
137
- (value.windowNumber as number) >= 0
138
- );
139
- }
140
-
141
- export function isCodexContextManagementMessageDetails(
142
- value: unknown,
143
- ): value is CodexContextManagementMessageDetails {
144
- if (!isRecord(value) || value.protocol !== CONTEXT_MANAGEMENT_PROTOCOL || !isNonEmptyString(value.id)) {
145
- return false;
146
- }
147
- if (value.sessionId !== undefined && !isNonEmptyString(value.sessionId)) return false;
148
- if (!isRecord(value.contextManagement) || value.contextManagement.protocol !== CONTEXT_MANAGEMENT_PROTOCOL) {
149
- return false;
150
- }
151
- const context = value.contextManagement;
152
- if (!isRecord(context)) return false;
153
- const trimPreviousWindow = context.trimPreviousWindow;
154
- return (
155
- (context.kind === "window" || context.kind === "reminder" || context.kind === "fallback") &&
156
- isContextWindowIdentity(context) &&
157
- (trimPreviousWindow === undefined || trimPreviousWindow === true)
158
- );
159
- }
160
-
161
- export function isContextWindowCompactionDetails(value: unknown): value is ContextWindowCompactionDetails {
162
- return (
163
- isRecord(value) &&
164
- value.protocol === CONTEXT_MANAGEMENT_PROTOCOL &&
165
- value.strategy === CONTEXT_WINDOW_COMPACTION_STRATEGY &&
166
- (value.windowId === undefined || isNonEmptyString(value.windowId))
167
- );
168
- }