pi-openai-toolkit 0.14.13 → 0.15.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.
@@ -1,347 +1,353 @@
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 { 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 function createContextManagementTools(
99
- pi: ExtensionAPI,
100
- manager: CodexContextWindowManager,
101
- isActive: (ctx: ExtensionContext) => Promise<boolean> | boolean,
102
- getGatewayModels: () => readonly string[] = () => [],
103
- ): ContextManagementTools {
104
- const assertActive = async (ctx: ExtensionContext): Promise<void> => {
105
- if (!(await isActive(ctx))) throw new Error("remote-context-inactive");
106
- };
107
- const newContext: ToolDefinition<typeof NEW_CONTEXT_PARAMETERS, NewContextDetails> = {
108
- name: "new_context",
109
- label: "new_context",
110
- description: "Start a new remote Codex context window without generating a conversation summary. Requires a persisted successful notes checkpoint in the current window.",
111
- parameters: NEW_CONTEXT_PARAMETERS,
112
- promptSnippet: "Start a new remote Codex context window without summarizing history.",
113
- promptGuidelines: [
114
- "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.",
115
- "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.",
116
- "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.",
117
- ],
118
- executionMode: "sequential",
119
- async execute(_id, _params, signal, _update, ctx) {
120
- await assertActive(ctx);
121
- manager.synchronize(ctx);
122
- if (manager.hasPendingRollover(ctx)) {
123
- return {
124
- content: [{ type: "text", text: "A new context window is already scheduled." }],
125
- details: { started: false },
126
- };
127
- }
128
- if (!manager.canRolloverFromCurrentWindow(ctx)) {
129
- return {
130
- content: [{ type: "text", text: NEW_CONTEXT_COOLDOWN_MESSAGE }],
131
- details: { started: false },
132
- };
133
- }
134
- if (!manager.hasNotesCheckpointSinceBoundary(ctx)) {
135
- throw new Error(NEW_CONTEXT_CHECKPOINT_REQUIRED_MESSAGE);
136
- }
137
- const started = await manager.startNewWindow(pi, ctx, {
138
- triggerTurn: true,
139
- signal,
140
- trimPreviousWindow: true,
141
- });
142
- return {
143
- content: [{
144
- type: "text",
145
- text: started
146
- ? "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."
147
- : "A new context window is already scheduled.",
148
- }],
149
- details: { started },
150
- };
151
- },
152
- };
153
- const getContextRemaining: ToolDefinition<typeof EMPTY_PARAMETERS, ContextRemainingDetails> = {
154
- name: "get_context_remaining",
155
- label: "get_context_remaining",
156
- description: "Get the remaining tokens in the current remote Codex context window.",
157
- parameters: EMPTY_PARAMETERS,
158
- async execute(_id, _params, _signal, _update, ctx) {
159
- await assertActive(ctx);
160
- const remaining = manager.remaining(ctx);
161
- return {
162
- 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.` }],
163
- details: remaining,
164
- };
165
- },
166
- };
167
- const history: ToolDefinition<typeof HISTORY_PARAMETERS, CodexHistoryNotesDetails> = {
168
- name: "history",
169
- label: "history",
170
- description: "Search or read prior remote Codex context-window history. Pass IDs unchanged.",
171
- parameters: HISTORY_PARAMETERS,
172
- promptSnippet: "Search or read prior remote Codex context-window history.",
173
- promptGuidelines: [
174
- "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.",
175
- "Use read_item with the exact item_id returned by list_items or search_contents; never rewrite, truncate, or guess IDs.",
176
- "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.",
177
- "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.",
178
- "History is read-only; make no edits through it. Edits and durable checkpoints belong to notes.",
179
- ],
180
- execute: async (_id, params, _signal, _update, ctx) => {
181
- await assertActive(ctx);
182
- return executeHistoryNotesTool("history", params.action, params as Record<string, unknown>, ctx, _signal, getGatewayModels());
183
- },
184
- };
185
- const notes: ToolDefinition<typeof NOTES_PARAMETERS, CodexHistoryNotesDetails> = {
186
- name: "notes",
187
- label: "notes",
188
- description: "Read and checkpoint remote Codex notes across context windows.",
189
- parameters: NOTES_PARAMETERS,
190
- promptSnippet: "Read and checkpoint remote Codex notes across context windows.",
191
- promptGuidelines: [
192
- "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.",
193
- "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.",
194
- "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.",
195
- "Prefer read_file or search_contents for looking things up; reserve write_file for explicit rewrite/clear and append_to_file for incremental state.",
196
- "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.",
197
- "Do not store live credentials, API keys, or full request bodies in notes; record the fact and where it lives instead.",
198
- ],
199
- executionMode: "sequential",
200
- execute: async (_id, params, _signal, _update, ctx) => {
201
- await assertActive(ctx);
202
- return executeHistoryNotesTool("notes", params.action, params as Record<string, unknown>, ctx, _signal, getGatewayModels());
203
- },
204
- };
205
- return { newContext, getContextRemaining, history, notes };
206
- }
207
-
208
- export type ContextToolRegistrationState = "verified" | "conflict" | "unverified";
209
-
210
- export type ContextToolSyncResult = {
211
- synced: boolean;
212
- registrationState: ContextToolRegistrationState;
213
- };
214
-
215
- export class ContextManagementToolController {
216
- private readonly registeredNames = new Set<string>();
217
- private readonly definitions = new Map<string, {
218
- description: string;
219
- parameters: unknown;
220
- promptGuidelines?: string[];
221
- }>();
222
- private registered = false;
223
- private verifiedOnce = false;
224
-
225
- constructor(private readonly pi: ExtensionAPI) {}
226
-
227
- register(tools: ContextManagementTools): boolean {
228
- const definitions = [tools.newContext, tools.getContextRemaining, tools.history, tools.notes];
229
- const api = this.pi as ExtensionAPI & { registerTool?: (tool: unknown) => void };
230
- if (typeof api.registerTool !== "function") return false;
231
-
232
- // registerTool() is a registration method and is valid while Pi is loading
233
- // the extension. Do not call action methods such as getAllTools() here;
234
- // those are bound only after extension loading completes.
235
- try {
236
- for (const definition of definitions) api.registerTool(definition);
237
- this.registered = true;
238
- } catch {
239
- // Pi rejects a registration whose name is already owned elsewhere.
240
- this.registered = false;
241
- return false;
242
- }
243
-
244
- this.registeredNames.clear();
245
- this.definitions.clear();
246
- this.verifiedOnce = false;
247
- for (const definition of definitions) {
248
- this.registeredNames.add(definition.name);
249
- this.definitions.set(definition.name, {
250
- description: definition.description,
251
- parameters: definition.parameters,
252
- promptGuidelines: definition.promptGuidelines,
253
- });
254
- }
255
- // A successful call only proves the hand-off; it does not prove the runtime
256
- // published the definitions. `checkRegistration()` reads that from Pi.
257
- return true;
258
- }
259
-
260
- /**
261
- * Read registration state until the runtime confirms publication.
262
- *
263
- * Pi 0.86 can reject action methods while a session replacement is still
264
- * binding, and can publish the registry after `session_start` ran. Negative
265
- * reads remain retryable; only a successful verification is cached for this
266
- * controller instance. A Pi reload creates a new controller.
267
- */
268
- checkRegistration(): ContextToolRegistrationState {
269
- if (!this.registered) return "conflict";
270
- // A confirmed publication is kept: the expensive part was never the read, it
271
- // was trusting a failed one. Only negative verdicts are recomputed each time.
272
- if (this.verifiedOnce) return "verified";
273
- let available: PublishedTool[];
274
- try {
275
- const api = this.pi as ExtensionAPI & { getAllTools?: () => PublishedTool[] };
276
- if (typeof api.getAllTools !== "function") return "conflict";
277
- available = api.getAllTools();
278
- } catch {
279
- // Stale or unbound runtime: retry on the next sync.
280
- return "unverified";
281
- }
282
- const byName = new Map(available.map((tool) => [tool.name, tool]));
283
- let missing = false;
284
- let conflict = false;
285
- for (const name of this.registeredNames) {
286
- const actual = byName.get(name);
287
- const expected = this.definitions.get(name);
288
- if (actual === undefined || expected === undefined) {
289
- missing = true;
290
- continue;
291
- }
292
- if (!isOurTool(actual, expected)) conflict = true;
293
- }
294
- if (conflict) return "conflict";
295
- if (missing) return "unverified";
296
- this.verifiedOnce = true;
297
- return "verified";
298
- }
299
-
300
- sync(active: boolean): ContextToolSyncResult {
301
- const registrationState = this.checkRegistration();
302
- if (registrationState !== "verified") return { synced: false, registrationState };
303
- const api = this.pi as ExtensionAPI & { getActiveTools?: () => string[]; setActiveTools?: (names: string[]) => void };
304
- if (typeof api.getActiveTools !== "function" || typeof api.setActiveTools !== "function") {
305
- return { synced: false, registrationState };
306
- }
307
- try {
308
- const current = api.getActiveTools();
309
- // Pi may activate a newly registered tool before the first sync. Once
310
- // registration is verified, every registered name belongs to this
311
- // controller: active models get all four, inactive models get none.
312
- const next = active
313
- ? [...current, ...[...this.registeredNames].filter((name) => !current.includes(name))]
314
- : current.filter((name) => !this.registeredNames.has(name));
315
- if (next.length !== current.length) api.setActiveTools(next);
316
- return { synced: true, registrationState };
317
- } catch {
318
- return { synced: false, registrationState };
319
- }
320
- }
321
-
322
- reset(): void {
323
- this.sync(false);
324
- }
325
- get isRegistered(): boolean { return this.checkRegistration() === "verified"; }
326
- get registrationState(): ContextToolRegistrationState { return this.checkRegistration(); }
327
- }
328
-
329
- export function registerContextManagementTools(
330
- pi: ExtensionAPI,
331
- manager: CodexContextWindowManager,
332
- isActive: (ctx: ExtensionContext) => Promise<boolean> | boolean,
333
- getGatewayModels?: () => readonly string[],
334
- ): ContextManagementToolController {
335
- const controller = new ContextManagementToolController(pi);
336
- controller.register(createContextManagementTools(pi, manager, isActive, getGatewayModels));
337
- return controller;
338
- }
339
-
340
- export const _contextToolsTest = {
341
- EMPTY_PARAMETERS,
342
- NEW_CONTEXT_PARAMETERS,
343
- HISTORY_PARAMETERS,
344
- NOTES_PARAMETERS,
345
- HISTORY_ACTION_FIELDS,
346
- NOTES_ACTION_FIELDS,
347
- };
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 { 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 function createContextManagementTools(
102
+ pi: ExtensionAPI,
103
+ manager: CodexContextWindowManager,
104
+ isActive: ContextActivity,
105
+ getGatewayModels: () => readonly string[] = () => [],
106
+ ): ContextManagementTools {
107
+ const assertActive = async (ctx: ExtensionContext): Promise<readonly string[]> => {
108
+ const policy = await isActive(ctx);
109
+ if (!(typeof policy === "boolean" ? policy : policy.active)) throw new Error("remote-context-inactive");
110
+ return typeof policy === "boolean" ? getGatewayModels() : policy.gatewayModels;
111
+ };
112
+ const newContext: ToolDefinition<typeof NEW_CONTEXT_PARAMETERS, NewContextDetails> = {
113
+ name: "new_context",
114
+ label: "new_context",
115
+ description: "Start a new remote Codex context window without generating a conversation summary. Requires a persisted successful notes checkpoint in the current window.",
116
+ parameters: NEW_CONTEXT_PARAMETERS,
117
+ promptSnippet: "Start a new remote Codex context window without summarizing history.",
118
+ promptGuidelines: [
119
+ "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.",
120
+ "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.",
121
+ "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.",
122
+ ],
123
+ executionMode: "sequential",
124
+ async execute(_id, _params, signal, _update, ctx) {
125
+ const gatewayModels = await assertActive(ctx);
126
+ manager.synchronize(ctx);
127
+ if (manager.hasPendingRollover(ctx)) {
128
+ return {
129
+ content: [{ type: "text", text: "A new context window is already scheduled." }],
130
+ details: { started: false },
131
+ };
132
+ }
133
+ if (!manager.canRolloverFromCurrentWindow(ctx)) {
134
+ return {
135
+ content: [{ type: "text", text: NEW_CONTEXT_COOLDOWN_MESSAGE }],
136
+ details: { started: false },
137
+ };
138
+ }
139
+ if (!manager.hasNotesCheckpointSinceBoundary(ctx)) {
140
+ throw new Error(NEW_CONTEXT_CHECKPOINT_REQUIRED_MESSAGE);
141
+ }
142
+ const started = await manager.startNewWindow(pi, ctx, {
143
+ triggerTurn: true,
144
+ signal,
145
+ trimPreviousWindow: true,
146
+ gatewayModels,
147
+ });
148
+ return {
149
+ content: [{
150
+ type: "text",
151
+ text: started
152
+ ? "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."
153
+ : "A new context window is already scheduled.",
154
+ }],
155
+ details: { started },
156
+ };
157
+ },
158
+ };
159
+ const getContextRemaining: ToolDefinition<typeof EMPTY_PARAMETERS, ContextRemainingDetails> = {
160
+ name: "get_context_remaining",
161
+ label: "get_context_remaining",
162
+ description: "Get the remaining tokens in the current remote Codex context window.",
163
+ parameters: EMPTY_PARAMETERS,
164
+ async execute(_id, _params, _signal, _update, ctx) {
165
+ await assertActive(ctx);
166
+ const remaining = manager.remaining(ctx);
167
+ return {
168
+ 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.` }],
169
+ details: remaining,
170
+ };
171
+ },
172
+ };
173
+ const history: ToolDefinition<typeof HISTORY_PARAMETERS, CodexHistoryNotesDetails> = {
174
+ name: "history",
175
+ label: "history",
176
+ description: "Search or read prior remote Codex context-window history. Pass IDs unchanged.",
177
+ parameters: HISTORY_PARAMETERS,
178
+ promptSnippet: "Search or read prior remote Codex context-window history.",
179
+ promptGuidelines: [
180
+ "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.",
181
+ "Use read_item with the exact item_id returned by list_items or search_contents; never rewrite, truncate, or guess IDs.",
182
+ "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.",
183
+ "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.",
184
+ "History is read-only; make no edits through it. Edits and durable checkpoints belong to notes.",
185
+ ],
186
+ execute: async (_id, params, _signal, _update, ctx) => {
187
+ const gatewayModels = await assertActive(ctx);
188
+ return executeHistoryNotesTool("history", params.action, params as Record<string, unknown>, ctx, _signal, gatewayModels);
189
+ },
190
+ };
191
+ const notes: ToolDefinition<typeof NOTES_PARAMETERS, CodexHistoryNotesDetails> = {
192
+ name: "notes",
193
+ label: "notes",
194
+ description: "Read and checkpoint remote Codex notes across context windows.",
195
+ parameters: NOTES_PARAMETERS,
196
+ promptSnippet: "Read and checkpoint remote Codex notes across context windows.",
197
+ promptGuidelines: [
198
+ "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.",
199
+ "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.",
200
+ "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.",
201
+ "Prefer read_file or search_contents for looking things up; reserve write_file for explicit rewrite/clear and append_to_file for incremental state.",
202
+ "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.",
203
+ "Do not store live credentials, API keys, or full request bodies in notes; record the fact and where it lives instead.",
204
+ ],
205
+ executionMode: "sequential",
206
+ execute: async (_id, params, _signal, _update, ctx) => {
207
+ const gatewayModels = await assertActive(ctx);
208
+ return executeHistoryNotesTool("notes", params.action, params as Record<string, unknown>, ctx, _signal, gatewayModels);
209
+ },
210
+ };
211
+ return { newContext, getContextRemaining, history, notes };
212
+ }
213
+
214
+ export type ContextToolRegistrationState = "verified" | "conflict" | "unverified";
215
+
216
+ export type ContextToolSyncResult = {
217
+ synced: boolean;
218
+ registrationState: ContextToolRegistrationState;
219
+ };
220
+
221
+ export class ContextManagementToolController {
222
+ private readonly registeredNames = new Set<string>();
223
+ private readonly definitions = new Map<string, {
224
+ description: string;
225
+ parameters: unknown;
226
+ promptGuidelines?: string[];
227
+ }>();
228
+ private registered = false;
229
+ private verifiedOnce = false;
230
+
231
+ constructor(private readonly pi: ExtensionAPI) {}
232
+
233
+ register(tools: ContextManagementTools): boolean {
234
+ const definitions = [tools.newContext, tools.getContextRemaining, tools.history, tools.notes];
235
+ const api = this.pi as ExtensionAPI & { registerTool?: (tool: unknown) => void };
236
+ if (typeof api.registerTool !== "function") return false;
237
+
238
+ // registerTool() is a registration method and is valid while Pi is loading
239
+ // the extension. Do not call action methods such as getAllTools() here;
240
+ // those are bound only after extension loading completes.
241
+ try {
242
+ for (const definition of definitions) api.registerTool(definition);
243
+ this.registered = true;
244
+ } catch {
245
+ // Pi rejects a registration whose name is already owned elsewhere.
246
+ this.registered = false;
247
+ return false;
248
+ }
249
+
250
+ this.registeredNames.clear();
251
+ this.definitions.clear();
252
+ this.verifiedOnce = false;
253
+ for (const definition of definitions) {
254
+ this.registeredNames.add(definition.name);
255
+ this.definitions.set(definition.name, {
256
+ description: definition.description,
257
+ parameters: definition.parameters,
258
+ promptGuidelines: definition.promptGuidelines,
259
+ });
260
+ }
261
+ // A successful call only proves the hand-off; it does not prove the runtime
262
+ // published the definitions. `checkRegistration()` reads that from Pi.
263
+ return true;
264
+ }
265
+
266
+ /**
267
+ * Read registration state until the runtime confirms publication.
268
+ *
269
+ * Pi 0.86 can reject action methods while a session replacement is still
270
+ * binding, and can publish the registry after `session_start` ran. Negative
271
+ * reads remain retryable; only a successful verification is cached for this
272
+ * controller instance. A Pi reload creates a new controller.
273
+ */
274
+ checkRegistration(): ContextToolRegistrationState {
275
+ if (!this.registered) return "conflict";
276
+ // A confirmed publication is kept: the expensive part was never the read, it
277
+ // was trusting a failed one. Only negative verdicts are recomputed each time.
278
+ if (this.verifiedOnce) return "verified";
279
+ let available: PublishedTool[];
280
+ try {
281
+ const api = this.pi as ExtensionAPI & { getAllTools?: () => PublishedTool[] };
282
+ if (typeof api.getAllTools !== "function") return "conflict";
283
+ available = api.getAllTools();
284
+ } catch {
285
+ // Stale or unbound runtime: retry on the next sync.
286
+ return "unverified";
287
+ }
288
+ const byName = new Map(available.map((tool) => [tool.name, tool]));
289
+ let missing = false;
290
+ let conflict = false;
291
+ for (const name of this.registeredNames) {
292
+ const actual = byName.get(name);
293
+ const expected = this.definitions.get(name);
294
+ if (actual === undefined || expected === undefined) {
295
+ missing = true;
296
+ continue;
297
+ }
298
+ if (!isOurTool(actual, expected)) conflict = true;
299
+ }
300
+ if (conflict) return "conflict";
301
+ if (missing) return "unverified";
302
+ this.verifiedOnce = true;
303
+ return "verified";
304
+ }
305
+
306
+ sync(active: boolean): ContextToolSyncResult {
307
+ const registrationState = this.checkRegistration();
308
+ if (registrationState !== "verified") return { synced: false, registrationState };
309
+ const api = this.pi as ExtensionAPI & { getActiveTools?: () => string[]; setActiveTools?: (names: string[]) => void };
310
+ if (typeof api.getActiveTools !== "function" || typeof api.setActiveTools !== "function") {
311
+ return { synced: false, registrationState };
312
+ }
313
+ try {
314
+ const current = api.getActiveTools();
315
+ // Pi may activate a newly registered tool before the first sync. Once
316
+ // registration is verified, every registered name belongs to this
317
+ // controller: active models get all four, inactive models get none.
318
+ const next = active
319
+ ? [...current, ...[...this.registeredNames].filter((name) => !current.includes(name))]
320
+ : current.filter((name) => !this.registeredNames.has(name));
321
+ if (next.length !== current.length) api.setActiveTools(next);
322
+ return { synced: true, registrationState };
323
+ } catch {
324
+ return { synced: false, registrationState };
325
+ }
326
+ }
327
+
328
+ reset(): void {
329
+ this.sync(false);
330
+ }
331
+ get isRegistered(): boolean { return this.checkRegistration() === "verified"; }
332
+ get registrationState(): ContextToolRegistrationState { return this.checkRegistration(); }
333
+ }
334
+
335
+ export function registerContextManagementTools(
336
+ pi: ExtensionAPI,
337
+ manager: CodexContextWindowManager,
338
+ isActive: ContextActivity,
339
+ getGatewayModels?: () => readonly string[],
340
+ ): ContextManagementToolController {
341
+ const controller = new ContextManagementToolController(pi);
342
+ controller.register(createContextManagementTools(pi, manager, isActive, getGatewayModels));
343
+ return controller;
344
+ }
345
+
346
+ export const _contextToolsTest = {
347
+ EMPTY_PARAMETERS,
348
+ NEW_CONTEXT_PARAMETERS,
349
+ HISTORY_PARAMETERS,
350
+ NOTES_PARAMETERS,
351
+ HISTORY_ACTION_FIELDS,
352
+ NOTES_ACTION_FIELDS,
353
+ };