pi-openai-toolkit 0.24.1 → 0.24.2

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 (41) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +1 -1
  4. package/README.zh.md +1 -1
  5. package/config.schema.json +264 -264
  6. package/docs/configuration.md +304 -304
  7. package/docs/internals.md +3 -1
  8. package/package.json +123 -123
  9. package/src/codex-fast/extension.ts +1 -1
  10. package/src/compact-client.ts +412 -412
  11. package/src/compaction-projection.ts +35 -35
  12. package/src/config/legacy.ts +469 -469
  13. package/src/config/migration.ts +115 -115
  14. package/src/config/notifications.ts +46 -46
  15. package/src/config/policy.ts +115 -115
  16. package/src/config/v2.ts +1128 -1128
  17. package/src/config.ts +320 -320
  18. package/src/debug.ts +238 -238
  19. package/src/deferred-tool-carryover.ts +282 -282
  20. package/src/details-store.ts +151 -151
  21. package/src/extension-runtime.ts +1095 -1095
  22. package/src/image-generation/extension.ts +189 -189
  23. package/src/image-generation/protocol.ts +579 -579
  24. package/src/image-generation/types.ts +300 -300
  25. package/src/native-fallback.ts +140 -140
  26. package/src/payload-rewrite.ts +515 -515
  27. package/src/pi-context-hook.ts +117 -117
  28. package/src/remote-v2-client.ts +811 -811
  29. package/src/request-context-cache.ts +155 -155
  30. package/src/responses-headers.ts +180 -180
  31. package/src/retired-remote-windows.ts +35 -35
  32. package/src/runtime.ts +875 -875
  33. package/src/serializer.ts +883 -882
  34. package/src/supported-environment.ts +27 -27
  35. package/src/types.ts +541 -541
  36. package/src/web-search/alpha-client.ts +876 -876
  37. package/src/web-search/extension.ts +530 -530
  38. package/src/web-search/payload.ts +299 -299
  39. package/src/web-search/prompt.ts +60 -60
  40. package/src/web-search/types.ts +166 -166
  41. package/tsconfig.check.json +50 -50
package/src/config.ts CHANGED
@@ -1,320 +1,320 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
- import { getExactModelKey, type ExactModelScopeModel } from "./model-scope";
5
- import { resolveWebSearchRoute, type WebSearchModel } from "./web-search/types";
6
- import { CONFIG_PATH, normalizeLegacyConfig } from "./config/legacy";
7
- import { resolveV2Config } from "./config/v2";
8
- import {
9
- CONFIG_FEATURES,
10
- RETIRED_AUTO_MODE_ISSUE,
11
- RETIRED_REMOTE_WINDOWS_ISSUE,
12
- RETIRED_REMOTE_WINDOWS_MODE_ISSUE,
13
- RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE,
14
- RETIRED_REMOTE_WINDOWS_MODE_MESSAGE,
15
- createPolicyDefaults,
16
- type ConfigDocumentSnapshot,
17
- type ConfigFeature,
18
- type ConfigIssue,
19
- type ConfigOrigin,
20
- type EffectiveToolkitPolicy,
21
- type ResolvedToolkitPolicy,
22
- } from "./config/policy";
23
- import type { LoadedToolkitConfig, ToolkitConfig } from "./types";
24
-
25
- export { CONFIG_DIR, CONFIG_PATH } from "./config/legacy";
26
- export { DEFAULT_TOOLKIT_CONFIG } from "./types";
27
- export type { ConfigFeature, ConfigIssue, ConfigOrigin, EffectiveToolkitPolicy } from "./config/policy";
28
-
29
- export type ResolvedToolkitConfig = ResolvedToolkitPolicy & {
30
- /** Narrow adapters for existing feature engines, never raw document sections. */
31
- config: ToolkitConfig;
32
- format: ConfigDocumentSnapshot["format"];
33
- source?: string;
34
- modelKey?: string;
35
- /** Cross-feature protocol policy, independent of context enablement. */
36
- gatewayModelKeys: string[];
37
- /** Same decoded document for resolving another identity within this operation. */
38
- snapshot: LoadedToolkitConfig;
39
- };
40
-
41
- function isRecord(value: unknown): value is Record<string, unknown> {
42
- return !!value && typeof value === "object" && !Array.isArray(value);
43
- }
44
- function has(value: Record<string, unknown>, key: string): boolean {
45
- return Object.prototype.hasOwnProperty.call(value, key);
46
- }
47
- function freeze<T>(value: T): T {
48
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
49
- Object.freeze(value);
50
- for (const item of Object.values(value)) freeze(item);
51
- }
52
- return value;
53
- }
54
- function documentError(code: string): ConfigIssue {
55
- return { severity: "error", code, path: "$", feature: "document" };
56
- }
57
-
58
- /** Read exactly one global file. No project discovery, cache, writes or auth/network work. */
59
- export function loadToolkitConfig(configPath: string = CONFIG_PATH): LoadedToolkitConfig {
60
- let raw: unknown;
61
- let format: ConfigDocumentSnapshot["format"] = "missing";
62
- const issues: ConfigIssue[] = [];
63
- const warnings: string[] = [];
64
- try {
65
- const text = fs.readFileSync(configPath, "utf8");
66
- try {
67
- raw = JSON.parse(text);
68
- if (!isRecord(raw)) {
69
- format = "invalid";
70
- issues.push(documentError("expected-object"));
71
- } else if (has(raw, "schemaVersion")) {
72
- format = raw.schemaVersion === 2 ? "v2" : "invalid";
73
- if (format === "invalid") issues.push(documentError("unsupported-schema-version"));
74
- } else if (has(raw, "defaults") || has(raw, "models") || has(raw, "diagnostics")) {
75
- format = "invalid";
76
- issues.push(documentError("missing-schema-version"));
77
- } else {
78
- format = "legacy";
79
- }
80
- } catch {
81
- format = "invalid";
82
- issues.push(documentError("invalid-json"));
83
- }
84
- } catch (error) {
85
- if (!isRecord(error) || error.code !== "ENOENT") {
86
- format = "invalid";
87
- issues.push(documentError("unreadable-config"));
88
- }
89
- }
90
- for (const issue of issues) warnings.push(`Ignoring ${configPath}: ${issue.code}.`);
91
- const legacy = normalizeLegacyConfig(format === "legacy" && isRecord(raw) ? raw : undefined, configPath, warnings);
92
- return {
93
- ...legacy,
94
- ...(format === "v2" ? { source: configPath } : {}),
95
- document: freeze({ format, configPath, raw, issues }),
96
- };
97
- }
98
-
99
- function configuredPath(value: string, configPath: string): string {
100
- if (value.startsWith("~/")) return path.join(os.homedir(), value.slice(2));
101
- return path.resolve(path.dirname(configPath), value);
102
- }
103
-
104
- function leafPaths(value: unknown, prefix = ""): string[] {
105
- if (!isRecord(value)) return [prefix];
106
- return Object.entries(value).flatMap(([key, child]) => leafPaths(child, prefix ? `${prefix}.${key}` : key));
107
- }
108
-
109
- const LEGACY_PATHS: Record<string, string> = {
110
- "context.mode": "compaction.enabled",
111
- "context.remoteCompaction.model": "compaction.remoteCompactModel",
112
- "context.remoteCompaction.inputSource": "compaction.remoteV2ContextSource",
113
- "context.remoteCompaction.allowContinuityBreak": "compaction.allowCompactionContinuityBreak",
114
- "context.remoteCompaction.apis": "compaction.responsesApis",
115
- "context.nativeFallback.enabled": "compaction.nativeFallback.enabled",
116
- "context.nativeFallback.model": "compaction.nativeFallback.model",
117
- "context.nativeFallback.thinkingLevel": "compaction.nativeFallback.thinkingLevel",
118
- "webSearch.route": "webSearch.models",
119
- "imageGeneration.enabled": "imageGeneration.enabled",
120
- "imageGeneration.defaultModel": "imageGeneration.models",
121
- "imageGeneration.allowedModels": "imageGeneration.models",
122
- "compatibility.transport": "compaction.gatewayContextModels",
123
- "diagnostics.level": "compaction.debug",
124
- "diagnostics.notifyOnLoad": "compaction.notifyOnLoad",
125
- "diagnostics.captureRequests": "compaction.logProviderPayloads",
126
- "diagnostics.captureResponses": "compaction.logCompactResponses",
127
- "diagnostics.redactSensitiveData": "compaction.redactSensitiveData",
128
- "diagnostics.artifactRoot": "compaction.artifactRoot",
129
- };
130
- function containsPath(value: unknown, fieldPath: string): boolean {
131
- for (const key of fieldPath.split(".")) {
132
- if (!isRecord(value) || !has(value, key)) return false;
133
- value = value[key];
134
- }
135
- return true;
136
- }
137
-
138
- function legacyRouteKey(raw: unknown, modelKey: string | undefined): string | undefined {
139
- if (!modelKey || !isRecord(raw) || !isRecord(raw.webSearch) || !isRecord(raw.webSearch.routes)) return undefined;
140
- return Object.keys(raw.webSearch.routes).find((key) => key.trim() === modelKey);
141
- }
142
-
143
- function legacyIssues(loaded: LoadedToolkitConfig, modelKey: string | undefined): ConfigIssue[] {
144
- const raw = loaded.document?.raw;
145
- const rawWeb = isRecord(raw) && isRecord(raw.webSearch) ? raw.webSearch : undefined;
146
- // Route keys may contain dots or colons. Never recover identity by splitting a warning.
147
- const routeIssues: ConfigIssue[] = [];
148
- if (isRecord(rawWeb?.routes)) {
149
- for (const [key, value] of Object.entries(rawWeb.routes)) {
150
- const normalized = key.trim();
151
- const separator = normalized.indexOf("/");
152
- const exact = separator > 0 && separator < normalized.length - 1 && !/[\s*?\[\]{}]/.test(normalized);
153
- if (exact && typeof value === "string" && ["local", "hosted", "standalone-alpha"].includes(value)) continue;
154
- routeIssues.push({ severity: "error", code: "invalid-legacy-value", feature: "webSearch",
155
- path: exact ? `webSearch.routes[${JSON.stringify(normalized).slice(0, 180)}]` : "webSearch.routes.[invalid-model-key]",
156
- modelKey: normalized });
157
- }
158
- }
159
- const issues = loaded.warnings.filter((warning) => !warning.startsWith("Ignoring webSearch.routes.")).map((warning): ConfigIssue => {
160
- // A removed feature is retired, not invalid: it never blocks another feature.
161
- if (warning.startsWith("Ignoring autoMode:")) {
162
- return { severity: "warning", code: RETIRED_AUTO_MODE_ISSUE, path: "autoMode", feature: "document" };
163
- }
164
- const retiredField = /^Ignoring (compaction\.(?:contextManagement|leaveManagedMode|contextReminderThresholdPercent)):/.exec(warning)?.[1];
165
- if (retiredField && (warning.endsWith(RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE) || warning.endsWith(RETIRED_REMOTE_WINDOWS_MODE_MESSAGE))) {
166
- const selectedMode = warning.endsWith(RETIRED_REMOTE_WINDOWS_MODE_MESSAGE);
167
- return { severity: selectedMode ? "error" : "warning",
168
- code: selectedMode ? RETIRED_REMOTE_WINDOWS_MODE_ISSUE : RETIRED_REMOTE_WINDOWS_ISSUE,
169
- path: retiredField, feature: "context" };
170
- }
171
- const match = /^Ignoring ([^:]+):/.exec(warning);
172
- const field = warning.startsWith("Ignoring compaction.responsesApis entry ") ? "compaction.responsesApis" : match?.[1] ?? "$";
173
- const root = field.split(".")[0];
174
- const diagnostic = Object.entries(LEGACY_PATHS).some(([leaf, input]) => leaf.startsWith("diagnostics.") && input === field);
175
- const feature: ConfigFeature | "document" = diagnostic ? "diagnostics"
176
- : field === "compaction.gatewayContextModels" ? "compatibility" : root === "compaction" ? "context"
177
- : root === "webSearch" || root === "imageGeneration" ? root : "document";
178
- const supersededDefault = field === "webSearch.defaultRoute" && legacyRouteKey(raw, modelKey) !== undefined;
179
- const warningOnly = warning.endsWith("unknown field.") || !match
180
- || warning.includes("expected at least one model id") || supersededDefault;
181
- return {
182
- severity: warningOnly ? "warning" : "error",
183
- code: warning.endsWith("unknown field.") ? "unknown-legacy-field" : warningOnly ? "legacy-normalization" : "invalid-legacy-value",
184
- path: warning.endsWith("unknown field.") ? `${feature}.[unknown-field]` : field.slice(0, 220),
185
- feature,
186
- };
187
- });
188
- return [...issues, ...routeIssues];
189
- }
190
-
191
- function selectedInvalidFeatures(issues: ConfigIssue[], modelKey?: string): ConfigFeature[] {
192
- const invalid = new Set<ConfigFeature>();
193
- for (const issue of issues) {
194
- if (issue.severity !== "error" || (issue.modelKey !== undefined && issue.modelKey !== modelKey)) continue;
195
- if (issue.feature === "document") for (const feature of CONFIG_FEATURES) invalid.add(feature);
196
- else invalid.add(issue.feature);
197
- }
198
- return [...invalid];
199
- }
200
-
201
- function fromLegacy(loaded: LoadedToolkitConfig, model: WebSearchModel | undefined): ResolvedToolkitPolicy {
202
- const config = loaded.config;
203
- const compaction = config.compaction;
204
- const modelKey = getExactModelKey(model);
205
- const route = resolveWebSearchRoute({ model, config: config.webSearch });
206
- const policy = createPolicyDefaults();
207
- const issues = [...(loaded.document?.issues ?? []), ...legacyIssues(loaded, modelKey)];
208
- const retiredMode = issues.some((issue) => issue.code === RETIRED_REMOTE_WINDOWS_MODE_ISSUE);
209
- policy.context = {
210
- mode: !compaction.enabled || retiredMode ? "pi" : "remote-compaction",
211
- remoteCompaction: {
212
- model: compaction.remoteCompactModel ?? null,
213
- inputSource: compaction.remoteV2ContextSource,
214
- allowContinuityBreak: compaction.allowCompactionContinuityBreak,
215
- apis: [...compaction.responsesApis],
216
- },
217
- nativeFallback: { ...compaction.nativeFallback, model: compaction.nativeFallback.model ?? null },
218
- };
219
- policy.webSearch.route = route.route === "none" ? "unmanaged" : route.route;
220
- policy.imageGeneration = {
221
- enabled: config.imageGeneration.enabled,
222
- defaultModel: config.imageGeneration.models[0],
223
- allowedModels: [...config.imageGeneration.models],
224
- };
225
- policy.responsesWebSocket = { enabled: false };
226
- policy.compatibility.transport = modelKey && compaction.gatewayContextModels.includes(modelKey) ? "codex-gateway" : "standard";
227
- policy.diagnostics = {
228
- level: compaction.debug ? "debug" : "info",
229
- notifyOnLoad: compaction.notifyOnLoad,
230
- captureRequests: compaction.logProviderPayloads,
231
- captureResponses: compaction.logCompactResponses,
232
- redactSensitiveData: compaction.redactSensitiveData,
233
- artifactRoot: compaction.artifactRoot,
234
- };
235
- const origins: Record<string, ConfigOrigin> = Object.create(null);
236
- const raw = loaded.document?.raw;
237
- for (const leaf of leafPaths(policy)) {
238
- if (leaf === "context.mode" && retiredMode) {
239
- // A blocked old selection owns no supported effective-mode origin.
240
- origins[leaf] = { kind: "builtin" };
241
- continue;
242
- }
243
- let input = LEGACY_PATHS[leaf] ?? leaf;
244
- if (leaf === "webSearch.route") {
245
- if (!config.webSearch.enabled) input = "webSearch.enabled";
246
- else if (route.source === "exact") {
247
- const rawKey = legacyRouteKey(raw, modelKey);
248
- if (rawKey !== undefined) {
249
- origins[leaf] = { kind: "legacy", path: `webSearch.routes[${JSON.stringify(rawKey)}]`, source: loaded.source };
250
- continue;
251
- }
252
- }
253
- else if (route.source === "default") input = "webSearch.defaultRoute";
254
- }
255
- const ignored = loaded.warnings.some((warning) => warning.startsWith(`Ignoring ${input}:`));
256
- origins[leaf] = !ignored && ((raw && containsPath(raw, input)) || (!loaded.document && loaded.source))
257
- ? { kind: "legacy", path: input, source: loaded.source } : { kind: "builtin" };
258
- }
259
- return { policy, origins, issues, invalidFeatures: selectedInvalidFeatures(issues, modelKey) };
260
- }
261
-
262
- /** Internal engine adapter. All interpretation of document names stays in this module. */
263
- function engineConfig(policy: EffectiveToolkitPolicy, gatewayKeys: string[]): ToolkitConfig {
264
- const { context, diagnostics, imageGeneration } = policy;
265
- return {
266
- compaction: {
267
- enabled: context.mode !== "pi",
268
- remoteCompactModel: context.remoteCompaction.model ?? undefined,
269
- remoteV2ContextSource: context.remoteCompaction.inputSource,
270
- allowCompactionContinuityBreak: context.remoteCompaction.allowContinuityBreak,
271
- responsesApis: [...context.remoteCompaction.apis],
272
- gatewayContextModels: [...gatewayKeys],
273
- nativeFallback: { ...context.nativeFallback, model: context.nativeFallback.model ?? undefined },
274
- debug: diagnostics.level === "debug",
275
- notifyOnLoad: diagnostics.notifyOnLoad,
276
- logProviderPayloads: diagnostics.captureRequests,
277
- logCompactResponses: diagnostics.captureResponses,
278
- redactSensitiveData: diagnostics.redactSensitiveData,
279
- artifactRoot: diagnostics.artifactRoot,
280
- },
281
- webSearch: policy.webSearch.route === "unmanaged" ? { enabled: false, models: [] }
282
- : { enabled: true, models: [], defaultRoute: policy.webSearch.route },
283
- imageGeneration: { enabled: imageGeneration.enabled, models: [...imageGeneration.allowedModels] },
284
- };
285
- }
286
-
287
- /** Resolve one immutable snapshot for one model. Never reads disk or a model registry. */
288
- export function resolveToolkitConfig(loaded: LoadedToolkitConfig, model?: ExactModelScopeModel & { api?: string }): ResolvedToolkitConfig {
289
- // Injected readers are also decoded at the module seam; they may omit optional feature sections.
290
- if (!loaded.document) {
291
- const configPath = loaded.source ?? CONFIG_PATH;
292
- const normalized = normalizeLegacyConfig(loaded.config, configPath);
293
- loaded = { ...normalized, source: loaded.source, warnings: [...loaded.warnings, ...normalized.warnings],
294
- document: { format: "legacy", configPath, raw: loaded.config, issues: [] } };
295
- }
296
- const modelKey = getExactModelKey(model);
297
- const format = loaded.document?.format ?? "legacy";
298
- const v2 = format === "v2" ? resolveV2Config(loaded.document?.raw, modelKey) : undefined;
299
- const resolution = v2 ?? fromLegacy(loaded, model);
300
- const source = loaded.source;
301
- if (format === "v2") {
302
- resolution.policy.diagnostics.artifactRoot = configuredPath(resolution.policy.diagnostics.artifactRoot, loaded.document?.configPath ?? CONFIG_PATH);
303
- for (const origin of Object.values(resolution.origins)) if (origin.kind !== "builtin") origin.source = source;
304
- }
305
- const gatewayModelKeys = v2 ? v2.gatewayModelKeys : [...loaded.config.compaction.gatewayContextModels];
306
- const config = format === "v2" ? engineConfig(resolution.policy, gatewayModelKeys) : structuredClone(loaded.config);
307
- return freeze({ ...resolution, config, format, source, modelKey, gatewayModelKeys, snapshot: structuredClone(loaded) });
308
- }
309
-
310
- export class ToolkitConfigurationError extends Error {
311
- constructor(readonly features: readonly ConfigFeature[]) {
312
- super(`Toolkit configuration is invalid for ${features.join(", ")}; use /toolkit-config validate. No fallback policy was selected.`);
313
- this.name = "ToolkitConfigurationError";
314
- }
315
- }
316
-
317
- export function assertConfigValid(resolved: ResolvedToolkitConfig, ...features: ConfigFeature[]): void {
318
- const invalid = features.filter((feature) => resolved.invalidFeatures.includes(feature));
319
- if (invalid.length > 0) throw new ToolkitConfigurationError(invalid);
320
- }
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { getExactModelKey, type ExactModelScopeModel } from "./model-scope";
5
+ import { resolveWebSearchRoute, type WebSearchModel } from "./web-search/types";
6
+ import { CONFIG_PATH, normalizeLegacyConfig } from "./config/legacy";
7
+ import { resolveV2Config } from "./config/v2";
8
+ import {
9
+ CONFIG_FEATURES,
10
+ RETIRED_AUTO_MODE_ISSUE,
11
+ RETIRED_REMOTE_WINDOWS_ISSUE,
12
+ RETIRED_REMOTE_WINDOWS_MODE_ISSUE,
13
+ RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE,
14
+ RETIRED_REMOTE_WINDOWS_MODE_MESSAGE,
15
+ createPolicyDefaults,
16
+ type ConfigDocumentSnapshot,
17
+ type ConfigFeature,
18
+ type ConfigIssue,
19
+ type ConfigOrigin,
20
+ type EffectiveToolkitPolicy,
21
+ type ResolvedToolkitPolicy,
22
+ } from "./config/policy";
23
+ import type { LoadedToolkitConfig, ToolkitConfig } from "./types";
24
+
25
+ export { CONFIG_DIR, CONFIG_PATH } from "./config/legacy";
26
+ export { DEFAULT_TOOLKIT_CONFIG } from "./types";
27
+ export type { ConfigFeature, ConfigIssue, ConfigOrigin, EffectiveToolkitPolicy } from "./config/policy";
28
+
29
+ export type ResolvedToolkitConfig = ResolvedToolkitPolicy & {
30
+ /** Narrow adapters for existing feature engines, never raw document sections. */
31
+ config: ToolkitConfig;
32
+ format: ConfigDocumentSnapshot["format"];
33
+ source?: string;
34
+ modelKey?: string;
35
+ /** Cross-feature protocol policy, independent of context enablement. */
36
+ gatewayModelKeys: string[];
37
+ /** Same decoded document for resolving another identity within this operation. */
38
+ snapshot: LoadedToolkitConfig;
39
+ };
40
+
41
+ function isRecord(value: unknown): value is Record<string, unknown> {
42
+ return !!value && typeof value === "object" && !Array.isArray(value);
43
+ }
44
+ function has(value: Record<string, unknown>, key: string): boolean {
45
+ return Object.prototype.hasOwnProperty.call(value, key);
46
+ }
47
+ function freeze<T>(value: T): T {
48
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
49
+ Object.freeze(value);
50
+ for (const item of Object.values(value)) freeze(item);
51
+ }
52
+ return value;
53
+ }
54
+ function documentError(code: string): ConfigIssue {
55
+ return { severity: "error", code, path: "$", feature: "document" };
56
+ }
57
+
58
+ /** Read exactly one global file. No project discovery, cache, writes or auth/network work. */
59
+ export function loadToolkitConfig(configPath: string = CONFIG_PATH): LoadedToolkitConfig {
60
+ let raw: unknown;
61
+ let format: ConfigDocumentSnapshot["format"] = "missing";
62
+ const issues: ConfigIssue[] = [];
63
+ const warnings: string[] = [];
64
+ try {
65
+ const text = fs.readFileSync(configPath, "utf8");
66
+ try {
67
+ raw = JSON.parse(text);
68
+ if (!isRecord(raw)) {
69
+ format = "invalid";
70
+ issues.push(documentError("expected-object"));
71
+ } else if (has(raw, "schemaVersion")) {
72
+ format = raw.schemaVersion === 2 ? "v2" : "invalid";
73
+ if (format === "invalid") issues.push(documentError("unsupported-schema-version"));
74
+ } else if (has(raw, "defaults") || has(raw, "models") || has(raw, "diagnostics")) {
75
+ format = "invalid";
76
+ issues.push(documentError("missing-schema-version"));
77
+ } else {
78
+ format = "legacy";
79
+ }
80
+ } catch {
81
+ format = "invalid";
82
+ issues.push(documentError("invalid-json"));
83
+ }
84
+ } catch (error) {
85
+ if (!isRecord(error) || error.code !== "ENOENT") {
86
+ format = "invalid";
87
+ issues.push(documentError("unreadable-config"));
88
+ }
89
+ }
90
+ for (const issue of issues) warnings.push(`Ignoring ${configPath}: ${issue.code}.`);
91
+ const legacy = normalizeLegacyConfig(format === "legacy" && isRecord(raw) ? raw : undefined, configPath, warnings);
92
+ return {
93
+ ...legacy,
94
+ ...(format === "v2" ? { source: configPath } : {}),
95
+ document: freeze({ format, configPath, raw, issues }),
96
+ };
97
+ }
98
+
99
+ function configuredPath(value: string, configPath: string): string {
100
+ if (value.startsWith("~/")) return path.join(os.homedir(), value.slice(2));
101
+ return path.resolve(path.dirname(configPath), value);
102
+ }
103
+
104
+ function leafPaths(value: unknown, prefix = ""): string[] {
105
+ if (!isRecord(value)) return [prefix];
106
+ return Object.entries(value).flatMap(([key, child]) => leafPaths(child, prefix ? `${prefix}.${key}` : key));
107
+ }
108
+
109
+ const LEGACY_PATHS: Record<string, string> = {
110
+ "context.mode": "compaction.enabled",
111
+ "context.remoteCompaction.model": "compaction.remoteCompactModel",
112
+ "context.remoteCompaction.inputSource": "compaction.remoteV2ContextSource",
113
+ "context.remoteCompaction.allowContinuityBreak": "compaction.allowCompactionContinuityBreak",
114
+ "context.remoteCompaction.apis": "compaction.responsesApis",
115
+ "context.nativeFallback.enabled": "compaction.nativeFallback.enabled",
116
+ "context.nativeFallback.model": "compaction.nativeFallback.model",
117
+ "context.nativeFallback.thinkingLevel": "compaction.nativeFallback.thinkingLevel",
118
+ "webSearch.route": "webSearch.models",
119
+ "imageGeneration.enabled": "imageGeneration.enabled",
120
+ "imageGeneration.defaultModel": "imageGeneration.models",
121
+ "imageGeneration.allowedModels": "imageGeneration.models",
122
+ "compatibility.transport": "compaction.gatewayContextModels",
123
+ "diagnostics.level": "compaction.debug",
124
+ "diagnostics.notifyOnLoad": "compaction.notifyOnLoad",
125
+ "diagnostics.captureRequests": "compaction.logProviderPayloads",
126
+ "diagnostics.captureResponses": "compaction.logCompactResponses",
127
+ "diagnostics.redactSensitiveData": "compaction.redactSensitiveData",
128
+ "diagnostics.artifactRoot": "compaction.artifactRoot",
129
+ };
130
+ function containsPath(value: unknown, fieldPath: string): boolean {
131
+ for (const key of fieldPath.split(".")) {
132
+ if (!isRecord(value) || !has(value, key)) return false;
133
+ value = value[key];
134
+ }
135
+ return true;
136
+ }
137
+
138
+ function legacyRouteKey(raw: unknown, modelKey: string | undefined): string | undefined {
139
+ if (!modelKey || !isRecord(raw) || !isRecord(raw.webSearch) || !isRecord(raw.webSearch.routes)) return undefined;
140
+ return Object.keys(raw.webSearch.routes).find((key) => key.trim() === modelKey);
141
+ }
142
+
143
+ function legacyIssues(loaded: LoadedToolkitConfig, modelKey: string | undefined): ConfigIssue[] {
144
+ const raw = loaded.document?.raw;
145
+ const rawWeb = isRecord(raw) && isRecord(raw.webSearch) ? raw.webSearch : undefined;
146
+ // Route keys may contain dots or colons. Never recover identity by splitting a warning.
147
+ const routeIssues: ConfigIssue[] = [];
148
+ if (isRecord(rawWeb?.routes)) {
149
+ for (const [key, value] of Object.entries(rawWeb.routes)) {
150
+ const normalized = key.trim();
151
+ const separator = normalized.indexOf("/");
152
+ const exact = separator > 0 && separator < normalized.length - 1 && !/[\s*?\[\]{}]/.test(normalized);
153
+ if (exact && typeof value === "string" && ["local", "hosted", "standalone-alpha"].includes(value)) continue;
154
+ routeIssues.push({ severity: "error", code: "invalid-legacy-value", feature: "webSearch",
155
+ path: exact ? `webSearch.routes[${JSON.stringify(normalized).slice(0, 180)}]` : "webSearch.routes.[invalid-model-key]",
156
+ modelKey: normalized });
157
+ }
158
+ }
159
+ const issues = loaded.warnings.filter((warning) => !warning.startsWith("Ignoring webSearch.routes.")).map((warning): ConfigIssue => {
160
+ // A removed feature is retired, not invalid: it never blocks another feature.
161
+ if (warning.startsWith("Ignoring autoMode:")) {
162
+ return { severity: "warning", code: RETIRED_AUTO_MODE_ISSUE, path: "autoMode", feature: "document" };
163
+ }
164
+ const retiredField = /^Ignoring (compaction\.(?:contextManagement|leaveManagedMode|contextReminderThresholdPercent)):/.exec(warning)?.[1];
165
+ if (retiredField && (warning.endsWith(RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE) || warning.endsWith(RETIRED_REMOTE_WINDOWS_MODE_MESSAGE))) {
166
+ const selectedMode = warning.endsWith(RETIRED_REMOTE_WINDOWS_MODE_MESSAGE);
167
+ return { severity: selectedMode ? "error" : "warning",
168
+ code: selectedMode ? RETIRED_REMOTE_WINDOWS_MODE_ISSUE : RETIRED_REMOTE_WINDOWS_ISSUE,
169
+ path: retiredField, feature: "context" };
170
+ }
171
+ const match = /^Ignoring ([^:]+):/.exec(warning);
172
+ const field = warning.startsWith("Ignoring compaction.responsesApis entry ") ? "compaction.responsesApis" : match?.[1] ?? "$";
173
+ const root = field.split(".")[0];
174
+ const diagnostic = Object.entries(LEGACY_PATHS).some(([leaf, input]) => leaf.startsWith("diagnostics.") && input === field);
175
+ const feature: ConfigFeature | "document" = diagnostic ? "diagnostics"
176
+ : field === "compaction.gatewayContextModels" ? "compatibility" : root === "compaction" ? "context"
177
+ : root === "webSearch" || root === "imageGeneration" ? root : "document";
178
+ const supersededDefault = field === "webSearch.defaultRoute" && legacyRouteKey(raw, modelKey) !== undefined;
179
+ const warningOnly = warning.endsWith("unknown field.") || !match
180
+ || warning.includes("expected at least one model id") || supersededDefault;
181
+ return {
182
+ severity: warningOnly ? "warning" : "error",
183
+ code: warning.endsWith("unknown field.") ? "unknown-legacy-field" : warningOnly ? "legacy-normalization" : "invalid-legacy-value",
184
+ path: warning.endsWith("unknown field.") ? `${feature}.[unknown-field]` : field.slice(0, 220),
185
+ feature,
186
+ };
187
+ });
188
+ return [...issues, ...routeIssues];
189
+ }
190
+
191
+ function selectedInvalidFeatures(issues: ConfigIssue[], modelKey?: string): ConfigFeature[] {
192
+ const invalid = new Set<ConfigFeature>();
193
+ for (const issue of issues) {
194
+ if (issue.severity !== "error" || (issue.modelKey !== undefined && issue.modelKey !== modelKey)) continue;
195
+ if (issue.feature === "document") for (const feature of CONFIG_FEATURES) invalid.add(feature);
196
+ else invalid.add(issue.feature);
197
+ }
198
+ return [...invalid];
199
+ }
200
+
201
+ function fromLegacy(loaded: LoadedToolkitConfig, model: WebSearchModel | undefined): ResolvedToolkitPolicy {
202
+ const config = loaded.config;
203
+ const compaction = config.compaction;
204
+ const modelKey = getExactModelKey(model);
205
+ const route = resolveWebSearchRoute({ model, config: config.webSearch });
206
+ const policy = createPolicyDefaults();
207
+ const issues = [...(loaded.document?.issues ?? []), ...legacyIssues(loaded, modelKey)];
208
+ const retiredMode = issues.some((issue) => issue.code === RETIRED_REMOTE_WINDOWS_MODE_ISSUE);
209
+ policy.context = {
210
+ mode: !compaction.enabled || retiredMode ? "pi" : "remote-compaction",
211
+ remoteCompaction: {
212
+ model: compaction.remoteCompactModel ?? null,
213
+ inputSource: compaction.remoteV2ContextSource,
214
+ allowContinuityBreak: compaction.allowCompactionContinuityBreak,
215
+ apis: [...compaction.responsesApis],
216
+ },
217
+ nativeFallback: { ...compaction.nativeFallback, model: compaction.nativeFallback.model ?? null },
218
+ };
219
+ policy.webSearch.route = route.route === "none" ? "unmanaged" : route.route;
220
+ policy.imageGeneration = {
221
+ enabled: config.imageGeneration.enabled,
222
+ defaultModel: config.imageGeneration.models[0],
223
+ allowedModels: [...config.imageGeneration.models],
224
+ };
225
+ policy.responsesWebSocket = { enabled: false };
226
+ policy.compatibility.transport = modelKey && compaction.gatewayContextModels.includes(modelKey) ? "codex-gateway" : "standard";
227
+ policy.diagnostics = {
228
+ level: compaction.debug ? "debug" : "info",
229
+ notifyOnLoad: compaction.notifyOnLoad,
230
+ captureRequests: compaction.logProviderPayloads,
231
+ captureResponses: compaction.logCompactResponses,
232
+ redactSensitiveData: compaction.redactSensitiveData,
233
+ artifactRoot: compaction.artifactRoot,
234
+ };
235
+ const origins: Record<string, ConfigOrigin> = Object.create(null);
236
+ const raw = loaded.document?.raw;
237
+ for (const leaf of leafPaths(policy)) {
238
+ if (leaf === "context.mode" && retiredMode) {
239
+ // A blocked old selection owns no supported effective-mode origin.
240
+ origins[leaf] = { kind: "builtin" };
241
+ continue;
242
+ }
243
+ let input = LEGACY_PATHS[leaf] ?? leaf;
244
+ if (leaf === "webSearch.route") {
245
+ if (!config.webSearch.enabled) input = "webSearch.enabled";
246
+ else if (route.source === "exact") {
247
+ const rawKey = legacyRouteKey(raw, modelKey);
248
+ if (rawKey !== undefined) {
249
+ origins[leaf] = { kind: "legacy", path: `webSearch.routes[${JSON.stringify(rawKey)}]`, source: loaded.source };
250
+ continue;
251
+ }
252
+ }
253
+ else if (route.source === "default") input = "webSearch.defaultRoute";
254
+ }
255
+ const ignored = loaded.warnings.some((warning) => warning.startsWith(`Ignoring ${input}:`));
256
+ origins[leaf] = !ignored && ((raw && containsPath(raw, input)) || (!loaded.document && loaded.source))
257
+ ? { kind: "legacy", path: input, source: loaded.source } : { kind: "builtin" };
258
+ }
259
+ return { policy, origins, issues, invalidFeatures: selectedInvalidFeatures(issues, modelKey) };
260
+ }
261
+
262
+ /** Internal engine adapter. All interpretation of document names stays in this module. */
263
+ function engineConfig(policy: EffectiveToolkitPolicy, gatewayKeys: string[]): ToolkitConfig {
264
+ const { context, diagnostics, imageGeneration } = policy;
265
+ return {
266
+ compaction: {
267
+ enabled: context.mode !== "pi",
268
+ remoteCompactModel: context.remoteCompaction.model ?? undefined,
269
+ remoteV2ContextSource: context.remoteCompaction.inputSource,
270
+ allowCompactionContinuityBreak: context.remoteCompaction.allowContinuityBreak,
271
+ responsesApis: [...context.remoteCompaction.apis],
272
+ gatewayContextModels: [...gatewayKeys],
273
+ nativeFallback: { ...context.nativeFallback, model: context.nativeFallback.model ?? undefined },
274
+ debug: diagnostics.level === "debug",
275
+ notifyOnLoad: diagnostics.notifyOnLoad,
276
+ logProviderPayloads: diagnostics.captureRequests,
277
+ logCompactResponses: diagnostics.captureResponses,
278
+ redactSensitiveData: diagnostics.redactSensitiveData,
279
+ artifactRoot: diagnostics.artifactRoot,
280
+ },
281
+ webSearch: policy.webSearch.route === "unmanaged" ? { enabled: false, models: [] }
282
+ : { enabled: true, models: [], defaultRoute: policy.webSearch.route },
283
+ imageGeneration: { enabled: imageGeneration.enabled, models: [...imageGeneration.allowedModels] },
284
+ };
285
+ }
286
+
287
+ /** Resolve one immutable snapshot for one model. Never reads disk or a model registry. */
288
+ export function resolveToolkitConfig(loaded: LoadedToolkitConfig, model?: ExactModelScopeModel & { api?: string }): ResolvedToolkitConfig {
289
+ // Injected readers are also decoded at the module seam; they may omit optional feature sections.
290
+ if (!loaded.document) {
291
+ const configPath = loaded.source ?? CONFIG_PATH;
292
+ const normalized = normalizeLegacyConfig(loaded.config, configPath);
293
+ loaded = { ...normalized, source: loaded.source, warnings: [...loaded.warnings, ...normalized.warnings],
294
+ document: { format: "legacy", configPath, raw: loaded.config, issues: [] } };
295
+ }
296
+ const modelKey = getExactModelKey(model);
297
+ const format = loaded.document?.format ?? "legacy";
298
+ const v2 = format === "v2" ? resolveV2Config(loaded.document?.raw, modelKey) : undefined;
299
+ const resolution = v2 ?? fromLegacy(loaded, model);
300
+ const source = loaded.source;
301
+ if (format === "v2") {
302
+ resolution.policy.diagnostics.artifactRoot = configuredPath(resolution.policy.diagnostics.artifactRoot, loaded.document?.configPath ?? CONFIG_PATH);
303
+ for (const origin of Object.values(resolution.origins)) if (origin.kind !== "builtin") origin.source = source;
304
+ }
305
+ const gatewayModelKeys = v2 ? v2.gatewayModelKeys : [...loaded.config.compaction.gatewayContextModels];
306
+ const config = format === "v2" ? engineConfig(resolution.policy, gatewayModelKeys) : structuredClone(loaded.config);
307
+ return freeze({ ...resolution, config, format, source, modelKey, gatewayModelKeys, snapshot: structuredClone(loaded) });
308
+ }
309
+
310
+ export class ToolkitConfigurationError extends Error {
311
+ constructor(readonly features: readonly ConfigFeature[]) {
312
+ super(`Toolkit configuration is invalid for ${features.join(", ")}; use /toolkit-config validate. No fallback policy was selected.`);
313
+ this.name = "ToolkitConfigurationError";
314
+ }
315
+ }
316
+
317
+ export function assertConfigValid(resolved: ResolvedToolkitConfig, ...features: ConfigFeature[]): void {
318
+ const invalid = features.filter((feature) => resolved.invalidFeatures.includes(feature));
319
+ if (invalid.length > 0) throw new ToolkitConfigurationError(invalid);
320
+ }