pi-openai-toolkit 0.24.0 → 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 (37) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/config.schema.json +264 -264
  4. package/docs/configuration.md +304 -304
  5. package/package.json +123 -123
  6. package/src/compact-client.ts +412 -412
  7. package/src/compaction-projection.ts +35 -35
  8. package/src/config/legacy.ts +469 -469
  9. package/src/config/migration.ts +115 -115
  10. package/src/config/notifications.ts +46 -42
  11. package/src/config/policy.ts +115 -115
  12. package/src/config/v2.ts +1128 -1128
  13. package/src/config.ts +320 -320
  14. package/src/debug.ts +238 -238
  15. package/src/deferred-tool-carryover.ts +282 -282
  16. package/src/details-store.ts +151 -151
  17. package/src/extension-runtime.ts +1095 -1095
  18. package/src/image-generation/extension.ts +189 -189
  19. package/src/image-generation/protocol.ts +579 -579
  20. package/src/image-generation/types.ts +300 -300
  21. package/src/native-fallback.ts +140 -140
  22. package/src/payload-rewrite.ts +515 -515
  23. package/src/pi-context-hook.ts +117 -117
  24. package/src/remote-v2-client.ts +811 -811
  25. package/src/request-context-cache.ts +155 -155
  26. package/src/responses-headers.ts +180 -180
  27. package/src/retired-remote-windows.ts +35 -35
  28. package/src/runtime.ts +875 -875
  29. package/src/serializer.ts +882 -882
  30. package/src/supported-environment.ts +27 -27
  31. package/src/types.ts +541 -541
  32. package/src/web-search/alpha-client.ts +876 -876
  33. package/src/web-search/extension.ts +530 -530
  34. package/src/web-search/payload.ts +299 -299
  35. package/src/web-search/prompt.ts +60 -60
  36. package/src/web-search/types.ts +166 -166
  37. package/tsconfig.check.json +50 -50
@@ -1,469 +1,469 @@
1
- import * as os from "node:os";
2
- import * as path from "node:path";
3
- import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
- import {
5
- DEFAULT_COMPACTION_CONFIG,
6
- DEFAULT_TOOLKIT_CONFIG,
7
- DEFAULT_IMAGE_GENERATION_CONFIG,
8
- DEFAULT_IMAGE_GENERATION_MODEL,
9
- DEFAULT_NATIVE_FALLBACK_CONFIG,
10
- DEFAULT_WEB_SEARCH_CONFIG,
11
- RESPONSES_COMPACT_CAPABLE_APIS,
12
- THINKING_LEVELS,
13
- TOOLKIT_ID,
14
- type CompactionConfig,
15
- type ImageGenerationConfig,
16
- type RemoteV2ContextSource,
17
- type LoadedToolkitConfig,
18
- type NativeFallbackConfig,
19
- type ToolkitConfig,
20
- type WebSearchConfig,
21
- type WebSearchRoute,
22
- } from "../types";
23
- import { RETIRED_AUTO_MODE_MESSAGE, RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE, RETIRED_REMOTE_WINDOWS_MODE_MESSAGE } from "./policy";
24
- import { MAX_IMAGE_MODEL_ID_CHARS } from "../image-generation/types";
25
-
26
- export const CONFIG_DIR = path.join(os.homedir(), ".pi", "agent", "extensions", TOOLKIT_ID);
27
- export const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
28
-
29
- const TOP_LEVEL_FIELDS = new Set(["compaction", "webSearch", "imageGeneration", "autoMode"]);
30
- const COMPACTION_FIELDS = new Set([
31
- "enabled",
32
- "leaveManagedMode",
33
- "contextManagement",
34
- "allowCompactionContinuityBreak",
35
- "remoteCompactModel",
36
- "remoteV2ContextSource",
37
- "nativeFallback",
38
- "responsesApis",
39
- "gatewayContextModels",
40
- "contextReminderThresholdPercent",
41
- "notifyOnLoad",
42
- "debug",
43
- "logProviderPayloads",
44
- "logCompactResponses",
45
- "redactSensitiveData",
46
- "artifactRoot",
47
- ]);
48
- const NATIVE_FALLBACK_FIELDS = new Set(["enabled", "model", "thinkingLevel"]);
49
- const WEB_SEARCH_FIELDS = new Set(["enabled", "models", "defaultRoute", "routes"]);
50
- const IMAGE_GENERATION_FIELDS = new Set(["enabled", "models"]);
51
-
52
- function isRecord(value: unknown): value is Record<string, unknown> {
53
- return !!value && typeof value === "object" && !Array.isArray(value);
54
- }
55
-
56
- function resolveConfiguredPath(rawPath: string, baseDir: string): string {
57
- if (rawPath.startsWith("~/")) {
58
- return path.join(os.homedir(), rawPath.slice(2));
59
- }
60
- if (path.isAbsolute(rawPath)) {
61
- return path.resolve(rawPath);
62
- }
63
- return path.resolve(baseDir, rawPath);
64
- }
65
-
66
- function warnUnknownFields(
67
- value: Record<string, unknown>,
68
- knownFields: ReadonlySet<string>,
69
- fieldPath: string,
70
- warnings: string[],
71
- ): void {
72
- for (const key of Object.keys(value)) {
73
- if (!knownFields.has(key)) {
74
- warnings.push(`Ignoring ${fieldPath ? `${fieldPath}.` : ""}${key}: unknown field.`);
75
- }
76
- }
77
- }
78
-
79
- function toBoolean(value: unknown, fieldPath: string, warnings: string[]): boolean | undefined {
80
- if (value === undefined) return undefined;
81
- if (typeof value === "boolean") return value;
82
- warnings.push(`Ignoring ${fieldPath}: expected a boolean.`);
83
- return undefined;
84
- }
85
-
86
- function toRemoteV2ContextSource(
87
- value: unknown,
88
- fieldPath: string,
89
- warnings: string[],
90
- ): RemoteV2ContextSource | undefined {
91
- if (value === undefined) return undefined;
92
- if (typeof value === "string") {
93
- const normalized = value.trim();
94
- if (normalized === "pi-context-hook" || normalized === "legacy") return normalized;
95
- }
96
- warnings.push(`Ignoring ${fieldPath}: expected one of pi-context-hook, legacy.`);
97
- return undefined;
98
- }
99
-
100
- function toModelSpec(value: unknown, fieldPath: string, warnings: string[]): string | null | undefined {
101
- if (value === undefined) return undefined;
102
- if (value === null) return null;
103
- if (typeof value === "string" && value.trim().length > 0) {
104
- return value.trim();
105
- }
106
- warnings.push(`Ignoring ${fieldPath}: expected "provider/model-id" or null.`);
107
- return undefined;
108
- }
109
-
110
- function toThinkingLevel(value: unknown, fieldPath: string, warnings: string[]): ThinkingLevel | undefined {
111
- if (value === undefined) return undefined;
112
- if (typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value)) {
113
- return value as ThinkingLevel;
114
- }
115
- warnings.push(`Ignoring ${fieldPath}: expected one of ${THINKING_LEVELS.join(", ")}.`);
116
- return undefined;
117
- }
118
-
119
- function toSupportedApis(
120
- value: unknown,
121
- fieldPath: string,
122
- capableApis: readonly string[],
123
- warnings: string[],
124
- ): string[] | undefined {
125
- if (value === undefined) return undefined;
126
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
127
- warnings.push(`Ignoring ${fieldPath}: expected a string array.`);
128
- return undefined;
129
- }
130
-
131
- const capable = new Set(capableApis);
132
- const accepted: string[] = [];
133
- for (const item of new Set(value.map((entry) => entry.trim()).filter(Boolean))) {
134
- if (capable.has(item)) {
135
- accepted.push(item);
136
- } else {
137
- warnings.push(
138
- `Ignoring ${fieldPath} entry "${item}": only ${capableApis.join(", ")} are supported.`,
139
- );
140
- }
141
- }
142
-
143
- return accepted;
144
- }
145
-
146
- function toStringList(value: unknown, fieldPath: string, warnings: string[]): string[] | undefined {
147
- if (value === undefined) return undefined;
148
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
149
- warnings.push(`Ignoring ${fieldPath}: expected a string array.`);
150
- return undefined;
151
- }
152
-
153
- return [...new Set(value.map((entry) => entry.trim()).filter(Boolean))];
154
- }
155
-
156
- function toImageGenerationModels(value: unknown, fieldPath: string, warnings: string[]): string[] | undefined {
157
- const models = toStringList(value, fieldPath, warnings);
158
- if (models === undefined) return undefined;
159
- if (models.some((model) => model.length > MAX_IMAGE_MODEL_ID_CHARS)) {
160
- warnings.push(
161
- `Ignoring ${fieldPath}: each model id must be at most ${MAX_IMAGE_MODEL_ID_CHARS} characters.`,
162
- );
163
- return undefined;
164
- }
165
- return models;
166
- }
167
-
168
- function toWebSearchRoute(
169
- value: unknown,
170
- fieldPath: string,
171
- warnings: string[],
172
- ): WebSearchRoute | undefined {
173
- if (value === undefined) return undefined;
174
- if (value === "local" || value === "hosted" || value === "standalone-alpha") {
175
- return value;
176
- }
177
- warnings.push(`Ignoring ${fieldPath}: expected one of local, hosted, standalone-alpha.`);
178
- return undefined;
179
- }
180
-
181
- function isExactWebSearchModelKey(value: string): boolean {
182
- const trimmed = value.trim();
183
- const separatorIndex = trimmed.indexOf("/");
184
- if (separatorIndex <= 0 || separatorIndex >= trimmed.length - 1) return false;
185
- if (/[\s*?\[\]{}]/.test(trimmed)) return false;
186
- const provider = trimmed.slice(0, separatorIndex);
187
- const modelId = trimmed.slice(separatorIndex + 1);
188
- return provider.length > 0 && modelId.length > 0;
189
- }
190
-
191
- function toWebSearchRoutes(
192
- value: unknown,
193
- fieldPath: string,
194
- warnings: string[],
195
- ): Record<string, WebSearchRoute> | undefined {
196
- if (value === undefined) return undefined;
197
- if (!isRecord(value)) {
198
- warnings.push(`Ignoring ${fieldPath}: expected a JSON object.`);
199
- return undefined;
200
- }
201
-
202
- const routes: Record<string, WebSearchRoute> = {};
203
- for (const [rawKey, rawRoute] of Object.entries(value)) {
204
- const key = rawKey.trim();
205
- if (!isExactWebSearchModelKey(key)) {
206
- warnings.push(`Ignoring ${fieldPath}.${rawKey}: expected an exact "provider/model-id" key.`);
207
- continue;
208
- }
209
- const route = toWebSearchRoute(rawRoute, `${fieldPath}.${rawKey}`, warnings);
210
- if (route !== undefined) routes[key] = route;
211
- }
212
- return routes;
213
- }
214
-
215
- function cloneDefaults(): ToolkitConfig {
216
- return {
217
- compaction: {
218
- ...DEFAULT_COMPACTION_CONFIG,
219
- nativeFallback: { ...DEFAULT_NATIVE_FALLBACK_CONFIG },
220
- responsesApis: [...DEFAULT_COMPACTION_CONFIG.responsesApis],
221
- gatewayContextModels: [...DEFAULT_COMPACTION_CONFIG.gatewayContextModels],
222
- },
223
- webSearch: {
224
- ...DEFAULT_WEB_SEARCH_CONFIG,
225
- models: [...DEFAULT_WEB_SEARCH_CONFIG.models],
226
- ...(DEFAULT_WEB_SEARCH_CONFIG.defaultRoute
227
- ? { defaultRoute: DEFAULT_WEB_SEARCH_CONFIG.defaultRoute }
228
- : {}),
229
- ...(DEFAULT_WEB_SEARCH_CONFIG.routes
230
- ? { routes: { ...DEFAULT_WEB_SEARCH_CONFIG.routes } }
231
- : {}),
232
- },
233
- imageGeneration: {
234
- ...DEFAULT_IMAGE_GENERATION_CONFIG,
235
- models: [...DEFAULT_IMAGE_GENERATION_CONFIG.models],
236
- },
237
- };
238
- }
239
-
240
- function applyNativeFallbackConfig(
241
- raw: Record<string, unknown>,
242
- resolved: NativeFallbackConfig,
243
- warnings: string[],
244
- ): void {
245
- warnUnknownFields(raw, NATIVE_FALLBACK_FIELDS, "compaction.nativeFallback", warnings);
246
- resolved.enabled =
247
- toBoolean(raw.enabled, "compaction.nativeFallback.enabled", warnings) ?? resolved.enabled;
248
-
249
- const modelSpec = toModelSpec(raw.model, "compaction.nativeFallback.model", warnings);
250
- if (modelSpec !== undefined) {
251
- resolved.model = modelSpec === null ? undefined : modelSpec;
252
- }
253
-
254
- resolved.thinkingLevel =
255
- toThinkingLevel(raw.thinkingLevel, "compaction.nativeFallback.thinkingLevel", warnings) ??
256
- resolved.thinkingLevel;
257
- }
258
-
259
- function applyCompactionConfig(
260
- raw: Record<string, unknown>,
261
- resolved: CompactionConfig,
262
- warnings: string[],
263
- ): void {
264
- warnUnknownFields(raw, COMPACTION_FIELDS, "compaction", warnings);
265
-
266
- resolved.enabled = toBoolean(raw.enabled, "compaction.enabled", warnings) ?? resolved.enabled;
267
- for (const key of ["leaveManagedMode", "contextReminderThresholdPercent"]) {
268
- if (Object.hasOwn(raw, key)) warnings.push(`Ignoring compaction.${key}: ${RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE}`);
269
- }
270
- if (Object.hasOwn(raw, "contextManagement")) {
271
- const mode = typeof raw.contextManagement === "string" ? raw.contextManagement.trim() : undefined;
272
- warnings.push(mode === "remote"
273
- ? `Ignoring compaction.contextManagement: ${RETIRED_REMOTE_WINDOWS_MODE_MESSAGE}`
274
- : mode === "off"
275
- ? `Ignoring compaction.contextManagement: ${RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE}`
276
- : "Ignoring compaction.contextManagement: expected off; remote has been removed.");
277
- }
278
- resolved.allowCompactionContinuityBreak =
279
- toBoolean(
280
- raw.allowCompactionContinuityBreak,
281
- "compaction.allowCompactionContinuityBreak",
282
- warnings,
283
- ) ?? resolved.allowCompactionContinuityBreak;
284
- resolved.notifyOnLoad =
285
- toBoolean(raw.notifyOnLoad, "compaction.notifyOnLoad", warnings) ?? resolved.notifyOnLoad;
286
- resolved.debug = toBoolean(raw.debug, "compaction.debug", warnings) ?? resolved.debug;
287
- resolved.logProviderPayloads =
288
- toBoolean(raw.logProviderPayloads, "compaction.logProviderPayloads", warnings) ??
289
- resolved.logProviderPayloads;
290
- resolved.logCompactResponses =
291
- toBoolean(raw.logCompactResponses, "compaction.logCompactResponses", warnings) ??
292
- resolved.logCompactResponses;
293
- resolved.redactSensitiveData =
294
- toBoolean(raw.redactSensitiveData, "compaction.redactSensitiveData", warnings) ??
295
- resolved.redactSensitiveData;
296
-
297
- const remoteCompactModelSpec = toModelSpec(
298
- raw.remoteCompactModel,
299
- "compaction.remoteCompactModel",
300
- warnings,
301
- );
302
- if (remoteCompactModelSpec !== undefined) {
303
- resolved.remoteCompactModel = remoteCompactModelSpec === null ? undefined : remoteCompactModelSpec;
304
- }
305
-
306
- resolved.remoteV2ContextSource =
307
- toRemoteV2ContextSource(raw.remoteV2ContextSource, "compaction.remoteV2ContextSource", warnings) ??
308
- resolved.remoteV2ContextSource;
309
-
310
- if (raw.nativeFallback !== undefined) {
311
- if (isRecord(raw.nativeFallback)) {
312
- applyNativeFallbackConfig(raw.nativeFallback, resolved.nativeFallback, warnings);
313
- } else {
314
- warnings.push("Ignoring compaction.nativeFallback: expected a JSON object.");
315
- }
316
- }
317
-
318
- const apis = toSupportedApis(
319
- raw.responsesApis,
320
- "compaction.responsesApis",
321
- RESPONSES_COMPACT_CAPABLE_APIS,
322
- warnings,
323
- );
324
- if (apis !== undefined) {
325
- resolved.responsesApis = apis;
326
- }
327
-
328
- const gatewayContextModels = toStringList(
329
- raw.gatewayContextModels,
330
- "compaction.gatewayContextModels",
331
- warnings,
332
- );
333
- if (gatewayContextModels !== undefined) {
334
- resolved.gatewayContextModels = gatewayContextModels;
335
- }
336
-
337
- if (typeof raw.artifactRoot === "string" && raw.artifactRoot.trim().length > 0) {
338
- resolved.artifactRoot = raw.artifactRoot.trim();
339
- } else if (raw.artifactRoot !== undefined) {
340
- warnings.push("Ignoring compaction.artifactRoot: expected a non-empty string.");
341
- }
342
- }
343
-
344
- function applyWebSearchConfig(
345
- raw: Record<string, unknown>,
346
- resolved: WebSearchConfig,
347
- warnings: string[],
348
- ): void {
349
- warnUnknownFields(raw, WEB_SEARCH_FIELDS, "webSearch", warnings);
350
- resolved.enabled = toBoolean(raw.enabled, "webSearch.enabled", warnings) ?? resolved.enabled;
351
-
352
- const models = toStringList(raw.models, "webSearch.models", warnings);
353
- if (models !== undefined) {
354
- resolved.models = models;
355
- }
356
-
357
- const defaultRoute = toWebSearchRoute(raw.defaultRoute, "webSearch.defaultRoute", warnings);
358
- if (defaultRoute !== undefined) {
359
- resolved.defaultRoute = defaultRoute;
360
- }
361
-
362
- const routes = toWebSearchRoutes(raw.routes, "webSearch.routes", warnings);
363
- if (routes !== undefined) {
364
- resolved.routes = routes;
365
- }
366
-
367
- if (defaultRoute !== undefined && resolved.models.length > 0) {
368
- warnings.push(
369
- "webSearch.defaultRoute overrides legacy webSearch.models for models without an exact webSearch.routes entry.",
370
- );
371
- }
372
- if (routes !== undefined) {
373
- for (const key of Object.keys(routes)) {
374
- if (resolved.models.includes(key)) {
375
- warnings.push(
376
- `webSearch.routes.${key} overrides the legacy webSearch.models entry for the same exact model.`,
377
- );
378
- }
379
- }
380
- }
381
- }
382
-
383
- function applyImageGenerationConfig(
384
- raw: Record<string, unknown>,
385
- resolved: ImageGenerationConfig,
386
- warnings: string[],
387
- ): void {
388
- warnUnknownFields(raw, IMAGE_GENERATION_FIELDS, "imageGeneration", warnings);
389
- resolved.enabled =
390
- toBoolean(raw.enabled, "imageGeneration.enabled", warnings) ?? resolved.enabled;
391
-
392
- const models = toImageGenerationModels(raw.models, "imageGeneration.models", warnings);
393
- if (models !== undefined) {
394
- // An empty or blank-only list cannot express a default, so keep the shipped model.
395
- if (models.length === 0) {
396
- warnings.push(
397
- `Ignoring imageGeneration.models: expected at least one model id; using ${DEFAULT_IMAGE_GENERATION_MODEL}.`,
398
- );
399
- } else {
400
- resolved.models = models;
401
- }
402
- }
403
- }
404
-
405
- /**
406
- * A retired `autoMode` section is ignored in any shape: an object, `null`, a scalar or a malformed
407
- * nested value. Nothing inside it is parsed, so its old validation can never invalidate another
408
- * feature, and its contents are never echoed back to the user.
409
- */
410
- function warnRetiredAutoMode(warnings: string[]): void {
411
- warnings.push(`Ignoring autoMode: ${RETIRED_AUTO_MODE_MESSAGE}`);
412
- }
413
-
414
- /**
415
- * Normalize the supported unversioned document without I/O or mutation.
416
- * Versioned decoding and operation resolution are owned by ../config.ts.
417
- */
418
- export function normalizeLegacyConfig(
419
- raw: Record<string, unknown> | undefined,
420
- configPath: string = CONFIG_PATH,
421
- warnings: string[] = [],
422
- ): LoadedToolkitConfig {
423
- const resolved = cloneDefaults();
424
- let source: string | undefined;
425
-
426
- if (raw) {
427
- source = configPath;
428
- warnUnknownFields(raw, TOP_LEVEL_FIELDS, "", warnings);
429
-
430
- if (raw.compaction !== undefined) {
431
- if (isRecord(raw.compaction)) {
432
- applyCompactionConfig(raw.compaction, resolved.compaction, warnings);
433
- } else {
434
- warnings.push("Ignoring compaction: expected a JSON object.");
435
- }
436
- }
437
-
438
- if (raw.webSearch !== undefined) {
439
- if (isRecord(raw.webSearch)) {
440
- applyWebSearchConfig(raw.webSearch, resolved.webSearch, warnings);
441
- } else {
442
- warnings.push("Ignoring webSearch: expected a JSON object.");
443
- }
444
- }
445
-
446
- if (raw.imageGeneration !== undefined) {
447
- if (isRecord(raw.imageGeneration)) {
448
- applyImageGenerationConfig(raw.imageGeneration, resolved.imageGeneration, warnings);
449
- } else {
450
- warnings.push("Ignoring imageGeneration: expected a JSON object.");
451
- }
452
- }
453
-
454
- if (Object.hasOwn(raw, "autoMode")) warnRetiredAutoMode(warnings);
455
- }
456
-
457
- resolved.compaction.artifactRoot = resolveConfiguredPath(
458
- resolved.compaction.artifactRoot,
459
- path.dirname(configPath),
460
- );
461
-
462
- return {
463
- config: resolved,
464
- source,
465
- warnings,
466
- };
467
- }
468
-
469
- export { DEFAULT_TOOLKIT_CONFIG };
1
+ import * as os from "node:os";
2
+ import * as path from "node:path";
3
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
+ import {
5
+ DEFAULT_COMPACTION_CONFIG,
6
+ DEFAULT_TOOLKIT_CONFIG,
7
+ DEFAULT_IMAGE_GENERATION_CONFIG,
8
+ DEFAULT_IMAGE_GENERATION_MODEL,
9
+ DEFAULT_NATIVE_FALLBACK_CONFIG,
10
+ DEFAULT_WEB_SEARCH_CONFIG,
11
+ RESPONSES_COMPACT_CAPABLE_APIS,
12
+ THINKING_LEVELS,
13
+ TOOLKIT_ID,
14
+ type CompactionConfig,
15
+ type ImageGenerationConfig,
16
+ type RemoteV2ContextSource,
17
+ type LoadedToolkitConfig,
18
+ type NativeFallbackConfig,
19
+ type ToolkitConfig,
20
+ type WebSearchConfig,
21
+ type WebSearchRoute,
22
+ } from "../types";
23
+ import { RETIRED_AUTO_MODE_MESSAGE, RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE, RETIRED_REMOTE_WINDOWS_MODE_MESSAGE } from "./policy";
24
+ import { MAX_IMAGE_MODEL_ID_CHARS } from "../image-generation/types";
25
+
26
+ export const CONFIG_DIR = path.join(os.homedir(), ".pi", "agent", "extensions", TOOLKIT_ID);
27
+ export const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
28
+
29
+ const TOP_LEVEL_FIELDS = new Set(["compaction", "webSearch", "imageGeneration", "autoMode"]);
30
+ const COMPACTION_FIELDS = new Set([
31
+ "enabled",
32
+ "leaveManagedMode",
33
+ "contextManagement",
34
+ "allowCompactionContinuityBreak",
35
+ "remoteCompactModel",
36
+ "remoteV2ContextSource",
37
+ "nativeFallback",
38
+ "responsesApis",
39
+ "gatewayContextModels",
40
+ "contextReminderThresholdPercent",
41
+ "notifyOnLoad",
42
+ "debug",
43
+ "logProviderPayloads",
44
+ "logCompactResponses",
45
+ "redactSensitiveData",
46
+ "artifactRoot",
47
+ ]);
48
+ const NATIVE_FALLBACK_FIELDS = new Set(["enabled", "model", "thinkingLevel"]);
49
+ const WEB_SEARCH_FIELDS = new Set(["enabled", "models", "defaultRoute", "routes"]);
50
+ const IMAGE_GENERATION_FIELDS = new Set(["enabled", "models"]);
51
+
52
+ function isRecord(value: unknown): value is Record<string, unknown> {
53
+ return !!value && typeof value === "object" && !Array.isArray(value);
54
+ }
55
+
56
+ function resolveConfiguredPath(rawPath: string, baseDir: string): string {
57
+ if (rawPath.startsWith("~/")) {
58
+ return path.join(os.homedir(), rawPath.slice(2));
59
+ }
60
+ if (path.isAbsolute(rawPath)) {
61
+ return path.resolve(rawPath);
62
+ }
63
+ return path.resolve(baseDir, rawPath);
64
+ }
65
+
66
+ function warnUnknownFields(
67
+ value: Record<string, unknown>,
68
+ knownFields: ReadonlySet<string>,
69
+ fieldPath: string,
70
+ warnings: string[],
71
+ ): void {
72
+ for (const key of Object.keys(value)) {
73
+ if (!knownFields.has(key)) {
74
+ warnings.push(`Ignoring ${fieldPath ? `${fieldPath}.` : ""}${key}: unknown field.`);
75
+ }
76
+ }
77
+ }
78
+
79
+ function toBoolean(value: unknown, fieldPath: string, warnings: string[]): boolean | undefined {
80
+ if (value === undefined) return undefined;
81
+ if (typeof value === "boolean") return value;
82
+ warnings.push(`Ignoring ${fieldPath}: expected a boolean.`);
83
+ return undefined;
84
+ }
85
+
86
+ function toRemoteV2ContextSource(
87
+ value: unknown,
88
+ fieldPath: string,
89
+ warnings: string[],
90
+ ): RemoteV2ContextSource | undefined {
91
+ if (value === undefined) return undefined;
92
+ if (typeof value === "string") {
93
+ const normalized = value.trim();
94
+ if (normalized === "pi-context-hook" || normalized === "legacy") return normalized;
95
+ }
96
+ warnings.push(`Ignoring ${fieldPath}: expected one of pi-context-hook, legacy.`);
97
+ return undefined;
98
+ }
99
+
100
+ function toModelSpec(value: unknown, fieldPath: string, warnings: string[]): string | null | undefined {
101
+ if (value === undefined) return undefined;
102
+ if (value === null) return null;
103
+ if (typeof value === "string" && value.trim().length > 0) {
104
+ return value.trim();
105
+ }
106
+ warnings.push(`Ignoring ${fieldPath}: expected "provider/model-id" or null.`);
107
+ return undefined;
108
+ }
109
+
110
+ function toThinkingLevel(value: unknown, fieldPath: string, warnings: string[]): ThinkingLevel | undefined {
111
+ if (value === undefined) return undefined;
112
+ if (typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value)) {
113
+ return value as ThinkingLevel;
114
+ }
115
+ warnings.push(`Ignoring ${fieldPath}: expected one of ${THINKING_LEVELS.join(", ")}.`);
116
+ return undefined;
117
+ }
118
+
119
+ function toSupportedApis(
120
+ value: unknown,
121
+ fieldPath: string,
122
+ capableApis: readonly string[],
123
+ warnings: string[],
124
+ ): string[] | undefined {
125
+ if (value === undefined) return undefined;
126
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
127
+ warnings.push(`Ignoring ${fieldPath}: expected a string array.`);
128
+ return undefined;
129
+ }
130
+
131
+ const capable = new Set(capableApis);
132
+ const accepted: string[] = [];
133
+ for (const item of new Set(value.map((entry) => entry.trim()).filter(Boolean))) {
134
+ if (capable.has(item)) {
135
+ accepted.push(item);
136
+ } else {
137
+ warnings.push(
138
+ `Ignoring ${fieldPath} entry "${item}": only ${capableApis.join(", ")} are supported.`,
139
+ );
140
+ }
141
+ }
142
+
143
+ return accepted;
144
+ }
145
+
146
+ function toStringList(value: unknown, fieldPath: string, warnings: string[]): string[] | undefined {
147
+ if (value === undefined) return undefined;
148
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
149
+ warnings.push(`Ignoring ${fieldPath}: expected a string array.`);
150
+ return undefined;
151
+ }
152
+
153
+ return [...new Set(value.map((entry) => entry.trim()).filter(Boolean))];
154
+ }
155
+
156
+ function toImageGenerationModels(value: unknown, fieldPath: string, warnings: string[]): string[] | undefined {
157
+ const models = toStringList(value, fieldPath, warnings);
158
+ if (models === undefined) return undefined;
159
+ if (models.some((model) => model.length > MAX_IMAGE_MODEL_ID_CHARS)) {
160
+ warnings.push(
161
+ `Ignoring ${fieldPath}: each model id must be at most ${MAX_IMAGE_MODEL_ID_CHARS} characters.`,
162
+ );
163
+ return undefined;
164
+ }
165
+ return models;
166
+ }
167
+
168
+ function toWebSearchRoute(
169
+ value: unknown,
170
+ fieldPath: string,
171
+ warnings: string[],
172
+ ): WebSearchRoute | undefined {
173
+ if (value === undefined) return undefined;
174
+ if (value === "local" || value === "hosted" || value === "standalone-alpha") {
175
+ return value;
176
+ }
177
+ warnings.push(`Ignoring ${fieldPath}: expected one of local, hosted, standalone-alpha.`);
178
+ return undefined;
179
+ }
180
+
181
+ function isExactWebSearchModelKey(value: string): boolean {
182
+ const trimmed = value.trim();
183
+ const separatorIndex = trimmed.indexOf("/");
184
+ if (separatorIndex <= 0 || separatorIndex >= trimmed.length - 1) return false;
185
+ if (/[\s*?\[\]{}]/.test(trimmed)) return false;
186
+ const provider = trimmed.slice(0, separatorIndex);
187
+ const modelId = trimmed.slice(separatorIndex + 1);
188
+ return provider.length > 0 && modelId.length > 0;
189
+ }
190
+
191
+ function toWebSearchRoutes(
192
+ value: unknown,
193
+ fieldPath: string,
194
+ warnings: string[],
195
+ ): Record<string, WebSearchRoute> | undefined {
196
+ if (value === undefined) return undefined;
197
+ if (!isRecord(value)) {
198
+ warnings.push(`Ignoring ${fieldPath}: expected a JSON object.`);
199
+ return undefined;
200
+ }
201
+
202
+ const routes: Record<string, WebSearchRoute> = {};
203
+ for (const [rawKey, rawRoute] of Object.entries(value)) {
204
+ const key = rawKey.trim();
205
+ if (!isExactWebSearchModelKey(key)) {
206
+ warnings.push(`Ignoring ${fieldPath}.${rawKey}: expected an exact "provider/model-id" key.`);
207
+ continue;
208
+ }
209
+ const route = toWebSearchRoute(rawRoute, `${fieldPath}.${rawKey}`, warnings);
210
+ if (route !== undefined) routes[key] = route;
211
+ }
212
+ return routes;
213
+ }
214
+
215
+ function cloneDefaults(): ToolkitConfig {
216
+ return {
217
+ compaction: {
218
+ ...DEFAULT_COMPACTION_CONFIG,
219
+ nativeFallback: { ...DEFAULT_NATIVE_FALLBACK_CONFIG },
220
+ responsesApis: [...DEFAULT_COMPACTION_CONFIG.responsesApis],
221
+ gatewayContextModels: [...DEFAULT_COMPACTION_CONFIG.gatewayContextModels],
222
+ },
223
+ webSearch: {
224
+ ...DEFAULT_WEB_SEARCH_CONFIG,
225
+ models: [...DEFAULT_WEB_SEARCH_CONFIG.models],
226
+ ...(DEFAULT_WEB_SEARCH_CONFIG.defaultRoute
227
+ ? { defaultRoute: DEFAULT_WEB_SEARCH_CONFIG.defaultRoute }
228
+ : {}),
229
+ ...(DEFAULT_WEB_SEARCH_CONFIG.routes
230
+ ? { routes: { ...DEFAULT_WEB_SEARCH_CONFIG.routes } }
231
+ : {}),
232
+ },
233
+ imageGeneration: {
234
+ ...DEFAULT_IMAGE_GENERATION_CONFIG,
235
+ models: [...DEFAULT_IMAGE_GENERATION_CONFIG.models],
236
+ },
237
+ };
238
+ }
239
+
240
+ function applyNativeFallbackConfig(
241
+ raw: Record<string, unknown>,
242
+ resolved: NativeFallbackConfig,
243
+ warnings: string[],
244
+ ): void {
245
+ warnUnknownFields(raw, NATIVE_FALLBACK_FIELDS, "compaction.nativeFallback", warnings);
246
+ resolved.enabled =
247
+ toBoolean(raw.enabled, "compaction.nativeFallback.enabled", warnings) ?? resolved.enabled;
248
+
249
+ const modelSpec = toModelSpec(raw.model, "compaction.nativeFallback.model", warnings);
250
+ if (modelSpec !== undefined) {
251
+ resolved.model = modelSpec === null ? undefined : modelSpec;
252
+ }
253
+
254
+ resolved.thinkingLevel =
255
+ toThinkingLevel(raw.thinkingLevel, "compaction.nativeFallback.thinkingLevel", warnings) ??
256
+ resolved.thinkingLevel;
257
+ }
258
+
259
+ function applyCompactionConfig(
260
+ raw: Record<string, unknown>,
261
+ resolved: CompactionConfig,
262
+ warnings: string[],
263
+ ): void {
264
+ warnUnknownFields(raw, COMPACTION_FIELDS, "compaction", warnings);
265
+
266
+ resolved.enabled = toBoolean(raw.enabled, "compaction.enabled", warnings) ?? resolved.enabled;
267
+ for (const key of ["leaveManagedMode", "contextReminderThresholdPercent"]) {
268
+ if (Object.hasOwn(raw, key)) warnings.push(`Ignoring compaction.${key}: ${RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE}`);
269
+ }
270
+ if (Object.hasOwn(raw, "contextManagement")) {
271
+ const mode = typeof raw.contextManagement === "string" ? raw.contextManagement.trim() : undefined;
272
+ warnings.push(mode === "remote"
273
+ ? `Ignoring compaction.contextManagement: ${RETIRED_REMOTE_WINDOWS_MODE_MESSAGE}`
274
+ : mode === "off"
275
+ ? `Ignoring compaction.contextManagement: ${RETIRED_REMOTE_WINDOWS_CONFIG_MESSAGE}`
276
+ : "Ignoring compaction.contextManagement: expected off; remote has been removed.");
277
+ }
278
+ resolved.allowCompactionContinuityBreak =
279
+ toBoolean(
280
+ raw.allowCompactionContinuityBreak,
281
+ "compaction.allowCompactionContinuityBreak",
282
+ warnings,
283
+ ) ?? resolved.allowCompactionContinuityBreak;
284
+ resolved.notifyOnLoad =
285
+ toBoolean(raw.notifyOnLoad, "compaction.notifyOnLoad", warnings) ?? resolved.notifyOnLoad;
286
+ resolved.debug = toBoolean(raw.debug, "compaction.debug", warnings) ?? resolved.debug;
287
+ resolved.logProviderPayloads =
288
+ toBoolean(raw.logProviderPayloads, "compaction.logProviderPayloads", warnings) ??
289
+ resolved.logProviderPayloads;
290
+ resolved.logCompactResponses =
291
+ toBoolean(raw.logCompactResponses, "compaction.logCompactResponses", warnings) ??
292
+ resolved.logCompactResponses;
293
+ resolved.redactSensitiveData =
294
+ toBoolean(raw.redactSensitiveData, "compaction.redactSensitiveData", warnings) ??
295
+ resolved.redactSensitiveData;
296
+
297
+ const remoteCompactModelSpec = toModelSpec(
298
+ raw.remoteCompactModel,
299
+ "compaction.remoteCompactModel",
300
+ warnings,
301
+ );
302
+ if (remoteCompactModelSpec !== undefined) {
303
+ resolved.remoteCompactModel = remoteCompactModelSpec === null ? undefined : remoteCompactModelSpec;
304
+ }
305
+
306
+ resolved.remoteV2ContextSource =
307
+ toRemoteV2ContextSource(raw.remoteV2ContextSource, "compaction.remoteV2ContextSource", warnings) ??
308
+ resolved.remoteV2ContextSource;
309
+
310
+ if (raw.nativeFallback !== undefined) {
311
+ if (isRecord(raw.nativeFallback)) {
312
+ applyNativeFallbackConfig(raw.nativeFallback, resolved.nativeFallback, warnings);
313
+ } else {
314
+ warnings.push("Ignoring compaction.nativeFallback: expected a JSON object.");
315
+ }
316
+ }
317
+
318
+ const apis = toSupportedApis(
319
+ raw.responsesApis,
320
+ "compaction.responsesApis",
321
+ RESPONSES_COMPACT_CAPABLE_APIS,
322
+ warnings,
323
+ );
324
+ if (apis !== undefined) {
325
+ resolved.responsesApis = apis;
326
+ }
327
+
328
+ const gatewayContextModels = toStringList(
329
+ raw.gatewayContextModels,
330
+ "compaction.gatewayContextModels",
331
+ warnings,
332
+ );
333
+ if (gatewayContextModels !== undefined) {
334
+ resolved.gatewayContextModels = gatewayContextModels;
335
+ }
336
+
337
+ if (typeof raw.artifactRoot === "string" && raw.artifactRoot.trim().length > 0) {
338
+ resolved.artifactRoot = raw.artifactRoot.trim();
339
+ } else if (raw.artifactRoot !== undefined) {
340
+ warnings.push("Ignoring compaction.artifactRoot: expected a non-empty string.");
341
+ }
342
+ }
343
+
344
+ function applyWebSearchConfig(
345
+ raw: Record<string, unknown>,
346
+ resolved: WebSearchConfig,
347
+ warnings: string[],
348
+ ): void {
349
+ warnUnknownFields(raw, WEB_SEARCH_FIELDS, "webSearch", warnings);
350
+ resolved.enabled = toBoolean(raw.enabled, "webSearch.enabled", warnings) ?? resolved.enabled;
351
+
352
+ const models = toStringList(raw.models, "webSearch.models", warnings);
353
+ if (models !== undefined) {
354
+ resolved.models = models;
355
+ }
356
+
357
+ const defaultRoute = toWebSearchRoute(raw.defaultRoute, "webSearch.defaultRoute", warnings);
358
+ if (defaultRoute !== undefined) {
359
+ resolved.defaultRoute = defaultRoute;
360
+ }
361
+
362
+ const routes = toWebSearchRoutes(raw.routes, "webSearch.routes", warnings);
363
+ if (routes !== undefined) {
364
+ resolved.routes = routes;
365
+ }
366
+
367
+ if (defaultRoute !== undefined && resolved.models.length > 0) {
368
+ warnings.push(
369
+ "webSearch.defaultRoute overrides legacy webSearch.models for models without an exact webSearch.routes entry.",
370
+ );
371
+ }
372
+ if (routes !== undefined) {
373
+ for (const key of Object.keys(routes)) {
374
+ if (resolved.models.includes(key)) {
375
+ warnings.push(
376
+ `webSearch.routes.${key} overrides the legacy webSearch.models entry for the same exact model.`,
377
+ );
378
+ }
379
+ }
380
+ }
381
+ }
382
+
383
+ function applyImageGenerationConfig(
384
+ raw: Record<string, unknown>,
385
+ resolved: ImageGenerationConfig,
386
+ warnings: string[],
387
+ ): void {
388
+ warnUnknownFields(raw, IMAGE_GENERATION_FIELDS, "imageGeneration", warnings);
389
+ resolved.enabled =
390
+ toBoolean(raw.enabled, "imageGeneration.enabled", warnings) ?? resolved.enabled;
391
+
392
+ const models = toImageGenerationModels(raw.models, "imageGeneration.models", warnings);
393
+ if (models !== undefined) {
394
+ // An empty or blank-only list cannot express a default, so keep the shipped model.
395
+ if (models.length === 0) {
396
+ warnings.push(
397
+ `Ignoring imageGeneration.models: expected at least one model id; using ${DEFAULT_IMAGE_GENERATION_MODEL}.`,
398
+ );
399
+ } else {
400
+ resolved.models = models;
401
+ }
402
+ }
403
+ }
404
+
405
+ /**
406
+ * A retired `autoMode` section is ignored in any shape: an object, `null`, a scalar or a malformed
407
+ * nested value. Nothing inside it is parsed, so its old validation can never invalidate another
408
+ * feature, and its contents are never echoed back to the user.
409
+ */
410
+ function warnRetiredAutoMode(warnings: string[]): void {
411
+ warnings.push(`Ignoring autoMode: ${RETIRED_AUTO_MODE_MESSAGE}`);
412
+ }
413
+
414
+ /**
415
+ * Normalize the supported unversioned document without I/O or mutation.
416
+ * Versioned decoding and operation resolution are owned by ../config.ts.
417
+ */
418
+ export function normalizeLegacyConfig(
419
+ raw: Record<string, unknown> | undefined,
420
+ configPath: string = CONFIG_PATH,
421
+ warnings: string[] = [],
422
+ ): LoadedToolkitConfig {
423
+ const resolved = cloneDefaults();
424
+ let source: string | undefined;
425
+
426
+ if (raw) {
427
+ source = configPath;
428
+ warnUnknownFields(raw, TOP_LEVEL_FIELDS, "", warnings);
429
+
430
+ if (raw.compaction !== undefined) {
431
+ if (isRecord(raw.compaction)) {
432
+ applyCompactionConfig(raw.compaction, resolved.compaction, warnings);
433
+ } else {
434
+ warnings.push("Ignoring compaction: expected a JSON object.");
435
+ }
436
+ }
437
+
438
+ if (raw.webSearch !== undefined) {
439
+ if (isRecord(raw.webSearch)) {
440
+ applyWebSearchConfig(raw.webSearch, resolved.webSearch, warnings);
441
+ } else {
442
+ warnings.push("Ignoring webSearch: expected a JSON object.");
443
+ }
444
+ }
445
+
446
+ if (raw.imageGeneration !== undefined) {
447
+ if (isRecord(raw.imageGeneration)) {
448
+ applyImageGenerationConfig(raw.imageGeneration, resolved.imageGeneration, warnings);
449
+ } else {
450
+ warnings.push("Ignoring imageGeneration: expected a JSON object.");
451
+ }
452
+ }
453
+
454
+ if (Object.hasOwn(raw, "autoMode")) warnRetiredAutoMode(warnings);
455
+ }
456
+
457
+ resolved.compaction.artifactRoot = resolveConfiguredPath(
458
+ resolved.compaction.artifactRoot,
459
+ path.dirname(configPath),
460
+ );
461
+
462
+ return {
463
+ config: resolved,
464
+ source,
465
+ warnings,
466
+ };
467
+ }
468
+
469
+ export { DEFAULT_TOOLKIT_CONFIG };