pi-agent-browser-native 0.2.40 → 0.2.41

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.
@@ -0,0 +1,679 @@
1
+ // @ts-check
2
+ /**
3
+ * Purpose: Canonical pi-agent-browser-native config policy shared by runtime and setup CLI.
4
+ * Responsibilities: Own config paths, provider descriptors, project-local credential safety, layer validation/merge, status projection, and redacted summaries.
5
+ * Scope: Pure configuration policy plus synchronous status loading; secret command execution and browser/web-search runtime calls live elsewhere.
6
+ */
7
+
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join, resolve } from "node:path";
11
+
12
+ /** @typedef {"explicit-only" | "authenticated-only" | "always"} BrowserDefaultProfilePolicy */
13
+ /** @typedef {"global" | "project" | "override" | "env-fallback"} AgentBrowserConfigScope */
14
+ /** @typedef {"global" | "project" | "override"} ConfigLayerScope */
15
+ /** @typedef {"literal" | "env" | "command"} CredentialSourceKind */
16
+ /** @typedef {"exa" | "brave"} WebSearchProvider */
17
+ /** @typedef {"exaApiKey" | "braveApiKey"} WebSearchProviderConfigKey */
18
+ /** @typedef {{ provider: WebSearchProvider; apiKeyEnv: string; configKey: WebSearchProviderConfigKey; label: string }} WebSearchProviderDescriptor */
19
+ /** @typedef {{ name: string; policy?: BrowserDefaultProfilePolicy }} BrowserDefaultProfileConfig */
20
+ /** @typedef {{ enabled?: boolean; preferredProvider?: WebSearchProvider; braveApiKey?: string; exaApiKey?: string }} WebSearchConfig */
21
+ /** @typedef {{ defaultProfile?: BrowserDefaultProfileConfig; executablePath?: string; defaultLaunchArgs?: string[] }} BrowserConfig */
22
+ /** @typedef {{ version?: 1; webSearch?: WebSearchConfig; browser?: BrowserConfig }} AgentBrowserConfig */
23
+ /** @typedef {{ config: AgentBrowserConfig; path: string; scope: ConfigLayerScope }} ConfigLayer */
24
+ /** @typedef {{ kind: CredentialSourceKind; provider?: WebSearchProvider; rawValue: string; scope: AgentBrowserConfigScope }} CredentialSource */
25
+ /** @typedef {{ global: string; project: string; override?: string }} AgentBrowserConfigPaths */
26
+ /** @typedef {{ browserDefaultProfile?: Required<BrowserDefaultProfileConfig>; browserDefaultProfileScope?: ConfigLayerScope; browserExecutablePath?: string; browserExecutablePathScope?: ConfigLayerScope; trustedBrowserDefaultProfile?: Required<BrowserDefaultProfileConfig>; trustedBrowserDefaultProfileScope?: Exclude<ConfigLayerScope, "project">; trustedBrowserExecutablePath?: string; trustedBrowserExecutablePathScope?: Exclude<ConfigLayerScope, "project">; config: AgentBrowserConfig; webSearchCredentialSources: Partial<Record<WebSearchProvider, CredentialSource>>; webSearchEnabled: boolean; webSearchPreferredProvider: WebSearchProvider; errors: string[]; layers: ConfigLayer[]; paths: AgentBrowserConfigPaths; warnings: string[] }} AgentBrowserConfigState */
27
+ /** @typedef {{ scope: string; path: string; exists: boolean }} ConfigFileSummary */
28
+
29
+ export const AGENT_BROWSER_CONFIG_ENV = "PI_AGENT_BROWSER_CONFIG";
30
+ export const BRAVE_API_KEY_ENV = "BRAVE_API_KEY";
31
+ export const EXA_API_KEY_ENV = "EXA_API_KEY";
32
+ export const CONFIG_RELATIVE_PATH = /** @type {const} */ ([".pi", "config", "pi-agent-browser-native", "config.json"]);
33
+ export const GLOBAL_CONFIG_RELATIVE_PATH = /** @type {const} */ ([".pi", "config", "pi-agent-browser-native", "config.json"]);
34
+ export const SECRET_COMMAND_TIMEOUT_MS = 15_000;
35
+
36
+ /** @type {Readonly<Record<WebSearchProvider, WebSearchProviderDescriptor>>} */
37
+ export const WEB_SEARCH_PROVIDER_DESCRIPTORS = Object.freeze({
38
+ exa: Object.freeze({
39
+ provider: "exa",
40
+ apiKeyEnv: EXA_API_KEY_ENV,
41
+ configKey: "exaApiKey",
42
+ label: "Exa",
43
+ }),
44
+ brave: Object.freeze({
45
+ provider: "brave",
46
+ apiKeyEnv: BRAVE_API_KEY_ENV,
47
+ configKey: "braveApiKey",
48
+ label: "Brave Search",
49
+ }),
50
+ });
51
+ /** @type {readonly WebSearchProvider[]} */
52
+ export const WEB_SEARCH_PROVIDERS = Object.freeze(["exa", "brave"]);
53
+ /** @type {WebSearchProvider} */
54
+ export const DEFAULT_WEB_SEARCH_PROVIDER = "exa";
55
+ /** @type {Readonly<Record<WebSearchProvider, WebSearchProviderConfigKey>>} */
56
+ export const WEB_SEARCH_PROVIDER_CONFIG_KEYS = Object.freeze({
57
+ exa: WEB_SEARCH_PROVIDER_DESCRIPTORS.exa.configKey,
58
+ brave: WEB_SEARCH_PROVIDER_DESCRIPTORS.brave.configKey,
59
+ });
60
+ /** @type {Readonly<Record<WebSearchProvider, string>>} */
61
+ export const WEB_SEARCH_PROVIDER_ENV_VARS = Object.freeze({
62
+ exa: WEB_SEARCH_PROVIDER_DESCRIPTORS.exa.apiKeyEnv,
63
+ brave: WEB_SEARCH_PROVIDER_DESCRIPTORS.brave.apiKeyEnv,
64
+ });
65
+
66
+ /**
67
+ * @param {unknown} value
68
+ * @returns {value is WebSearchProvider}
69
+ */
70
+ export function isWebSearchProvider(value) {
71
+ return typeof value === "string" && WEB_SEARCH_PROVIDERS.includes(/** @type {WebSearchProvider} */ (value));
72
+ }
73
+
74
+ /**
75
+ * @param {WebSearchProvider} provider
76
+ * @returns {WebSearchProviderDescriptor}
77
+ */
78
+ export function getWebSearchProviderDescriptor(provider) {
79
+ const descriptor = WEB_SEARCH_PROVIDER_DESCRIPTORS[provider];
80
+ if (!descriptor) throw new Error(`Unknown web-search provider: ${String(provider)}`);
81
+ return descriptor;
82
+ }
83
+
84
+ /** @param {WebSearchProvider} provider */
85
+ export function getWebSearchProviderLabel(provider) {
86
+ return getWebSearchProviderDescriptor(provider).label;
87
+ }
88
+
89
+ /** @param {WebSearchProvider} provider */
90
+ export function getWebSearchProviderEnvVar(provider) {
91
+ return getWebSearchProviderDescriptor(provider).apiKeyEnv;
92
+ }
93
+
94
+ /**
95
+ * @param {WebSearchProvider} provider
96
+ * @returns {WebSearchProviderConfigKey}
97
+ */
98
+ export function getWebSearchProviderConfigKey(provider) {
99
+ return getWebSearchProviderDescriptor(provider).configKey;
100
+ }
101
+
102
+ /** @param {NodeJS.ProcessEnv} [env] */
103
+ export function getGlobalAgentBrowserConfigPath(env = process.env) {
104
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
105
+ return join(home, ...GLOBAL_CONFIG_RELATIVE_PATH);
106
+ }
107
+
108
+ /** @param {string} [cwd] */
109
+ export function getProjectAgentBrowserConfigPath(cwd = process.cwd()) {
110
+ return resolve(cwd, ...CONFIG_RELATIVE_PATH);
111
+ }
112
+
113
+ /**
114
+ * @param {{ cwd?: string; env?: NodeJS.ProcessEnv }} [options]
115
+ * @returns {AgentBrowserConfigPaths}
116
+ */
117
+ export function getAgentBrowserConfigPaths(options = {}) {
118
+ const env = options.env ?? process.env;
119
+ const override = env[AGENT_BROWSER_CONFIG_ENV]?.trim();
120
+ return {
121
+ global: getGlobalAgentBrowserConfigPath(env),
122
+ project: getProjectAgentBrowserConfigPath(options.cwd),
123
+ ...(override ? { override: resolve(override) } : {}),
124
+ };
125
+ }
126
+
127
+ /**
128
+ * @param {AgentBrowserConfig} base
129
+ * @param {AgentBrowserConfig} override
130
+ * @returns {AgentBrowserConfig}
131
+ */
132
+ export function mergeAgentBrowserConfig(base, override) {
133
+ return {
134
+ ...base,
135
+ ...override,
136
+ browser: {
137
+ ...(base.browser ?? {}),
138
+ ...(override.browser ?? {}),
139
+ defaultProfile: override.browser?.defaultProfile ?? base.browser?.defaultProfile,
140
+ },
141
+ webSearch: {
142
+ ...(base.webSearch ?? {}),
143
+ ...(override.webSearch ?? {}),
144
+ },
145
+ };
146
+ }
147
+
148
+ /**
149
+ * @param {unknown} value
150
+ * @returns {value is Record<string, unknown>}
151
+ */
152
+ function isRecord(value) {
153
+ return typeof value === "object" && value !== null && !Array.isArray(value);
154
+ }
155
+
156
+ /**
157
+ * @param {unknown} value
158
+ * @param {string} path
159
+ * @param {string[]} errors
160
+ */
161
+ function validateString(value, path, errors) {
162
+ if (value === undefined) return undefined;
163
+ if (typeof value !== "string") {
164
+ errors.push(`${path} must be a string.`);
165
+ return undefined;
166
+ }
167
+ return value;
168
+ }
169
+
170
+ /**
171
+ * @param {unknown} value
172
+ * @param {string} path
173
+ * @param {string[]} errors
174
+ * @returns {string[] | undefined}
175
+ */
176
+ function validateStringArray(value, path, errors) {
177
+ if (value === undefined) return undefined;
178
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
179
+ errors.push(`${path} must be an array of strings.`);
180
+ return undefined;
181
+ }
182
+ return value;
183
+ }
184
+
185
+ /**
186
+ * @param {unknown} value
187
+ * @param {string} path
188
+ * @param {string[]} errors
189
+ */
190
+ function validateBoolean(value, path, errors) {
191
+ if (value === undefined) return undefined;
192
+ if (typeof value !== "boolean") {
193
+ errors.push(`${path} must be a boolean.`);
194
+ return undefined;
195
+ }
196
+ return value;
197
+ }
198
+
199
+ /**
200
+ * @param {unknown} value
201
+ * @param {string} path
202
+ * @param {string[]} errors
203
+ * @returns {WebSearchProvider | undefined}
204
+ */
205
+ export function validateWebSearchProvider(value, path, errors) {
206
+ if (value === undefined) return undefined;
207
+ const provider = validateString(value, path, errors)?.trim();
208
+ if (provider === undefined) return undefined;
209
+ if (!isWebSearchProvider(provider)) {
210
+ errors.push(`${path} must be one of ${WEB_SEARCH_PROVIDERS.join(", ")}.`);
211
+ return undefined;
212
+ }
213
+ return provider;
214
+ }
215
+
216
+ /**
217
+ * @param {unknown} value
218
+ * @param {string} path
219
+ * @param {string[]} errors
220
+ * @returns {BrowserDefaultProfileConfig | undefined}
221
+ */
222
+ function validateBrowserDefaultProfile(value, path, errors) {
223
+ if (value === undefined) return undefined;
224
+ if (!isRecord(value)) {
225
+ errors.push(`${path} must be an object.`);
226
+ return undefined;
227
+ }
228
+ const name = validateString(value.name, `${path}.name`, errors)?.trim();
229
+ if (!name) {
230
+ errors.push(`${path}.name must not be blank.`);
231
+ return undefined;
232
+ }
233
+ const rawPolicy = validateString(value.policy, `${path}.policy`, errors);
234
+ const policy = rawPolicy ?? "authenticated-only";
235
+ if (!["explicit-only", "authenticated-only", "always"].includes(policy)) {
236
+ errors.push(`${path}.policy must be one of explicit-only, authenticated-only, always.`);
237
+ return undefined;
238
+ }
239
+ return { name, policy: /** @type {BrowserDefaultProfilePolicy} */ (policy) };
240
+ }
241
+
242
+ /** @param {string} rawValue */
243
+ export function isPlaintextCredentialValue(rawValue) {
244
+ const trimmed = rawValue.trim();
245
+ return Boolean(trimmed) && !trimmed.startsWith("!") && !trimmed.startsWith("$");
246
+ }
247
+
248
+ /**
249
+ * @param {string} rawValue
250
+ * @param {WebSearchProvider} provider
251
+ */
252
+ export function isProjectSafeCredentialValueForProvider(rawValue, provider) {
253
+ const envName = getWebSearchProviderEnvVar(provider);
254
+ const trimmed = rawValue.trim();
255
+ return trimmed === `$${envName}` || trimmed === `\${${envName}}`;
256
+ }
257
+
258
+ /**
259
+ * @param {unknown} value
260
+ * @param {string} path
261
+ * @param {ConfigLayerScope} scope
262
+ * @param {string[]} errors
263
+ * @param {string[]} warnings
264
+ * @returns {AgentBrowserConfig | undefined}
265
+ */
266
+ export function validateAgentBrowserConfig(value, path, scope, errors, warnings) {
267
+ if (!isRecord(value)) {
268
+ errors.push(`${path} must contain a JSON object.`);
269
+ return undefined;
270
+ }
271
+ if (value.version !== undefined && value.version !== 1) {
272
+ errors.push(`${path}.version must be 1 when present.`);
273
+ }
274
+ /** @type {AgentBrowserConfig} */
275
+ const config = value.version === 1 ? { version: 1 } : {};
276
+
277
+ if (value.webSearch !== undefined) {
278
+ if (!isRecord(value.webSearch)) {
279
+ errors.push(`${path}.webSearch must be an object.`);
280
+ } else {
281
+ /** @type {NonNullable<AgentBrowserConfig["webSearch"]>} */
282
+ const webSearch = {};
283
+ const enabled = validateBoolean(value.webSearch.enabled, `${path}.webSearch.enabled`, errors);
284
+ if (enabled !== undefined) webSearch.enabled = enabled;
285
+ const preferredProvider = validateWebSearchProvider(value.webSearch.preferredProvider, `${path}.webSearch.preferredProvider`, errors);
286
+ if (preferredProvider) webSearch.preferredProvider = preferredProvider;
287
+ for (const provider of WEB_SEARCH_PROVIDERS) {
288
+ const descriptor = getWebSearchProviderDescriptor(provider);
289
+ const apiKey = validateString(value.webSearch[descriptor.configKey], `${path}.webSearch.${descriptor.configKey}`, errors);
290
+ if (apiKey !== undefined) {
291
+ webSearch[descriptor.configKey] = apiKey;
292
+ if (scope === "project" && !isProjectSafeCredentialValueForProvider(apiKey, provider)) {
293
+ errors.push(`${path}.webSearch.${descriptor.configKey} must be exactly $${descriptor.apiKeyEnv} or \${${descriptor.apiKeyEnv}} in project-local config; plaintext, custom env aliases, interpolation literals, malformed env references, and command-backed project secrets are not allowed.`);
294
+ }
295
+ }
296
+ }
297
+ if (Object.keys(webSearch).length > 0) config.webSearch = webSearch;
298
+ }
299
+ }
300
+
301
+ if (value.browser !== undefined) {
302
+ if (!isRecord(value.browser)) {
303
+ errors.push(`${path}.browser must be an object.`);
304
+ } else {
305
+ config.browser = {};
306
+ const defaultProfile = validateBrowserDefaultProfile(value.browser.defaultProfile, `${path}.browser.defaultProfile`, errors);
307
+ if (defaultProfile) {
308
+ config.browser.defaultProfile = defaultProfile;
309
+ if (scope === "project" && defaultProfile.policy !== "explicit-only") {
310
+ warnings.push(`${path}.browser.defaultProfile is project-local; authenticated/always profile prompt guidance is emitted only from global or override config.`);
311
+ }
312
+ }
313
+ const executablePath = validateString(value.browser.executablePath, `${path}.browser.executablePath`, errors)?.trim();
314
+ if (executablePath) {
315
+ config.browser.executablePath = executablePath;
316
+ if (scope === "project") {
317
+ warnings.push(`${path}.browser.executablePath is project-local; executable launch prompt guidance is emitted only from global or override config.`);
318
+ }
319
+ }
320
+ const defaultLaunchArgs = validateStringArray(value.browser.defaultLaunchArgs, `${path}.browser.defaultLaunchArgs`, errors);
321
+ if (defaultLaunchArgs) {
322
+ config.browser.defaultLaunchArgs = defaultLaunchArgs;
323
+ warnings.push(`${path}.browser.defaultLaunchArgs is recorded for future use; current releases do not auto-inject default launch args.`);
324
+ }
325
+ }
326
+ }
327
+
328
+ for (const key of Object.keys(value)) {
329
+ if (!["version", "webSearch", "browser"].includes(key)) {
330
+ warnings.push(`${path}.${key} is not a recognized pi-agent-browser-native config field and was ignored.`);
331
+ }
332
+ }
333
+ return config;
334
+ }
335
+
336
+ /**
337
+ * @param {string} raw
338
+ * @param {string} path
339
+ * @param {ConfigLayerScope} scope
340
+ * @param {string[]} errors
341
+ * @param {string[]} warnings
342
+ * @returns {ConfigLayer | undefined}
343
+ */
344
+ export function parseAgentBrowserConfigLayer(raw, path, scope, errors, warnings) {
345
+ let parsed;
346
+ try {
347
+ parsed = JSON.parse(raw);
348
+ } catch (error) {
349
+ errors.push(`Could not parse ${scope} config ${path}: ${error instanceof Error ? error.message : String(error)}`);
350
+ return undefined;
351
+ }
352
+ const config = validateAgentBrowserConfig(parsed, path, scope, errors, warnings);
353
+ return config ? { config, path, scope } : undefined;
354
+ }
355
+
356
+ /**
357
+ * @param {string} rawValue
358
+ * @param {AgentBrowserConfigScope} scope
359
+ * @param {WebSearchProvider} [provider]
360
+ * @returns {CredentialSource | undefined}
361
+ */
362
+ export function classifyCredentialSource(rawValue, scope, provider) {
363
+ const trimmed = rawValue.trim();
364
+ if (!trimmed) return undefined;
365
+ if (trimmed.startsWith("!")) return { kind: "command", provider, rawValue: trimmed, scope };
366
+ if (trimmed.includes("$")) return { kind: "env", provider, rawValue: trimmed, scope };
367
+ return { kind: "literal", provider, rawValue: trimmed, scope };
368
+ }
369
+
370
+ /**
371
+ * @param {AgentBrowserConfig} config
372
+ * @returns {Required<BrowserDefaultProfileConfig> | undefined}
373
+ */
374
+ function getBrowserDefaultProfile(config) {
375
+ const profile = config.browser?.defaultProfile;
376
+ if (!profile?.name.trim()) return undefined;
377
+ return { name: profile.name.trim(), policy: profile.policy ?? "authenticated-only" };
378
+ }
379
+
380
+ /** @param {AgentBrowserConfig} config */
381
+ function getBrowserExecutablePath(config) {
382
+ const executablePath = config.browser?.executablePath?.trim();
383
+ return executablePath || undefined;
384
+ }
385
+
386
+ /**
387
+ * @param {ConfigLayer[]} layers
388
+ * @returns {ConfigLayerScope | undefined}
389
+ */
390
+ function getBrowserDefaultProfileScope(layers) {
391
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
392
+ const layer = layers[index];
393
+ if (layer?.config.browser?.defaultProfile !== undefined) return layer.scope;
394
+ }
395
+ return undefined;
396
+ }
397
+
398
+ /**
399
+ * @param {ConfigLayer[]} layers
400
+ * @returns {ConfigLayerScope | undefined}
401
+ */
402
+ function getBrowserExecutablePathScope(layers) {
403
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
404
+ const layer = layers[index];
405
+ if (layer?.config.browser?.executablePath !== undefined) return layer.scope;
406
+ }
407
+ return undefined;
408
+ }
409
+
410
+ /**
411
+ * @param {ConfigLayer[]} layers
412
+ * @returns {{ profile: Required<BrowserDefaultProfileConfig>; scope: Exclude<ConfigLayerScope, "project"> } | undefined}
413
+ */
414
+ function getTrustedBrowserDefaultProfile(layers) {
415
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
416
+ const layer = layers[index];
417
+ if (!layer || layer.scope === "project") continue;
418
+ const profile = getBrowserDefaultProfile(layer.config);
419
+ if (profile) return { profile, scope: /** @type {Exclude<ConfigLayerScope, "project">} */ (layer.scope) };
420
+ }
421
+ return undefined;
422
+ }
423
+
424
+ /**
425
+ * @param {ConfigLayer[]} layers
426
+ * @returns {{ executablePath: string; scope: Exclude<ConfigLayerScope, "project"> } | undefined}
427
+ */
428
+ function getTrustedBrowserExecutablePath(layers) {
429
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
430
+ const layer = layers[index];
431
+ if (!layer || layer.scope === "project") continue;
432
+ const executablePath = getBrowserExecutablePath(layer.config);
433
+ if (executablePath) return { executablePath, scope: /** @type {Exclude<ConfigLayerScope, "project">} */ (layer.scope) };
434
+ }
435
+ return undefined;
436
+ }
437
+
438
+ /**
439
+ * @param {ConfigLayer[]} layers
440
+ * @param {WebSearchProviderConfigKey} key
441
+ * @returns {AgentBrowserConfigScope}
442
+ */
443
+ function getWebSearchCredentialScope(layers, key) {
444
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
445
+ const layer = layers[index];
446
+ if (layer?.config.webSearch?.[key] !== undefined) return layer.scope;
447
+ }
448
+ return "global";
449
+ }
450
+
451
+ /**
452
+ * @param {{ env: NodeJS.ProcessEnv; layers: ConfigLayer[]; mergedConfig: AgentBrowserConfig }} options
453
+ * @returns {Partial<Record<WebSearchProvider, CredentialSource>>}
454
+ */
455
+ export function buildWebSearchCredentialSources(options) {
456
+ /** @type {Partial<Record<WebSearchProvider, CredentialSource>>} */
457
+ const sources = {};
458
+ for (const provider of WEB_SEARCH_PROVIDERS) {
459
+ const descriptor = getWebSearchProviderDescriptor(provider);
460
+ const apiKey = options.mergedConfig.webSearch?.[descriptor.configKey];
461
+ if (apiKey !== undefined) {
462
+ sources[provider] = classifyCredentialSource(apiKey, getWebSearchCredentialScope(options.layers, descriptor.configKey), provider);
463
+ }
464
+ if (!sources[provider] && options.env[descriptor.apiKeyEnv]?.trim()) {
465
+ sources[provider] = { kind: "literal", provider, rawValue: options.env[descriptor.apiKeyEnv] ?? "", scope: "env-fallback" };
466
+ }
467
+ }
468
+ return sources;
469
+ }
470
+
471
+ /**
472
+ * @param {{ env: NodeJS.ProcessEnv; layers: ConfigLayer[]; mergedConfig: AgentBrowserConfig; paths: AgentBrowserConfigPaths; errors: string[]; warnings: string[] }} options
473
+ * @returns {AgentBrowserConfigState}
474
+ */
475
+ export function buildAgentBrowserConfigState(options) {
476
+ const webSearchCredentialSources = buildWebSearchCredentialSources(options);
477
+ const trustedBrowserDefaultProfile = getTrustedBrowserDefaultProfile(options.layers);
478
+ const trustedBrowserExecutablePath = getTrustedBrowserExecutablePath(options.layers);
479
+ return {
480
+ browserDefaultProfile: getBrowserDefaultProfile(options.mergedConfig),
481
+ browserDefaultProfileScope: getBrowserDefaultProfileScope(options.layers),
482
+ browserExecutablePath: getBrowserExecutablePath(options.mergedConfig),
483
+ browserExecutablePathScope: getBrowserExecutablePathScope(options.layers),
484
+ trustedBrowserDefaultProfile: trustedBrowserDefaultProfile?.profile,
485
+ trustedBrowserDefaultProfileScope: trustedBrowserDefaultProfile?.scope,
486
+ trustedBrowserExecutablePath: trustedBrowserExecutablePath?.executablePath,
487
+ trustedBrowserExecutablePathScope: trustedBrowserExecutablePath?.scope,
488
+ config: options.mergedConfig,
489
+ webSearchCredentialSources,
490
+ webSearchEnabled: options.mergedConfig.webSearch?.enabled !== false,
491
+ webSearchPreferredProvider: options.mergedConfig.webSearch?.preferredProvider ?? DEFAULT_WEB_SEARCH_PROVIDER,
492
+ errors: options.errors,
493
+ layers: options.layers,
494
+ paths: options.paths,
495
+ warnings: options.warnings,
496
+ };
497
+ }
498
+
499
+ /**
500
+ * @param {string} path
501
+ * @param {ConfigLayerScope} scope
502
+ * @param {string[]} errors
503
+ * @param {string[]} warnings
504
+ * @returns {ConfigLayer | undefined}
505
+ */
506
+ function readConfigLayerSync(path, scope, errors, warnings) {
507
+ let raw;
508
+ try {
509
+ raw = readFileSync(path, "utf8");
510
+ } catch (error) {
511
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return undefined;
512
+ errors.push(`Could not read ${scope} config ${path}: ${error instanceof Error ? error.message : String(error)}`);
513
+ return undefined;
514
+ }
515
+ return parseAgentBrowserConfigLayer(raw, path, scope, errors, warnings);
516
+ }
517
+
518
+ /**
519
+ * @param {{ cwd?: string; env?: NodeJS.ProcessEnv }} [options]
520
+ * @returns {AgentBrowserConfigState}
521
+ */
522
+ export function loadAgentBrowserConfigStateSync(options = {}) {
523
+ const env = options.env ?? process.env;
524
+ const paths = getAgentBrowserConfigPaths({ cwd: options.cwd, env });
525
+ /** @type {string[]} */
526
+ const errors = [];
527
+ /** @type {string[]} */
528
+ const warnings = [];
529
+ /** @type {Array<{ path: string; scope: ConfigLayerScope }>} */
530
+ const layerCandidates = [
531
+ { path: paths.global, scope: "global" },
532
+ { path: paths.project, scope: "project" },
533
+ ...(paths.override ? [{ path: paths.override, scope: /** @type {ConfigLayerScope} */ ("override") }] : []),
534
+ ];
535
+ /** @type {ConfigLayer[]} */
536
+ const layers = [];
537
+ /** @type {AgentBrowserConfig} */
538
+ let mergedConfig = {};
539
+ for (const candidate of layerCandidates) {
540
+ const layer = readConfigLayerSync(candidate.path, candidate.scope, errors, warnings);
541
+ if (!layer) continue;
542
+ layers.push(layer);
543
+ mergedConfig = mergeAgentBrowserConfig(mergedConfig, layer.config);
544
+ }
545
+ return buildAgentBrowserConfigState({ env, errors, layers, mergedConfig, paths, warnings });
546
+ }
547
+
548
+ /**
549
+ * @param {string} rawValue
550
+ * @param {NodeJS.ProcessEnv} env
551
+ */
552
+ export function resolveEnvInterpolations(rawValue, env) {
553
+ let output = "";
554
+ for (let index = 0; index < rawValue.length; index += 1) {
555
+ const char = rawValue[index];
556
+ if (char !== "$") {
557
+ output += char;
558
+ continue;
559
+ }
560
+ const next = rawValue[index + 1];
561
+ if (next === "$") {
562
+ output += "$";
563
+ index += 1;
564
+ continue;
565
+ }
566
+ if (next === "!") {
567
+ output += "!";
568
+ index += 1;
569
+ continue;
570
+ }
571
+ let name = "";
572
+ if (next === "{") {
573
+ const end = rawValue.indexOf("}", index + 2);
574
+ if (end === -1) return undefined;
575
+ name = rawValue.slice(index + 2, end);
576
+ index = end;
577
+ } else {
578
+ const match = rawValue.slice(index + 1).match(/^([A-Za-z_][A-Za-z0-9_]*)/);
579
+ if (!match) {
580
+ output += "$";
581
+ continue;
582
+ }
583
+ name = match[1] ?? "";
584
+ index += name.length;
585
+ }
586
+ if (!name) return undefined;
587
+ const value = env[name];
588
+ if (value === undefined) return undefined;
589
+ output += value;
590
+ }
591
+ return output;
592
+ }
593
+
594
+ /**
595
+ * @param {AgentBrowserConfigState} state
596
+ * @param {WebSearchProvider | "auto"} [requestedProvider]
597
+ * @returns {WebSearchProvider[]}
598
+ */
599
+ export function getWebSearchProviderOrder(state, requestedProvider) {
600
+ if (requestedProvider && requestedProvider !== "auto") return [requestedProvider];
601
+ const preferred = state.webSearchPreferredProvider;
602
+ return [preferred, ...WEB_SEARCH_PROVIDERS.filter((provider) => provider !== preferred)];
603
+ }
604
+
605
+ /**
606
+ * @param {AgentBrowserConfigState} state
607
+ * @param {WebSearchProvider} provider
608
+ */
609
+ export function getWebSearchCredentialSource(state, provider) {
610
+ return state.webSearchCredentialSources[provider];
611
+ }
612
+
613
+ /**
614
+ * @param {CredentialSource | undefined} source
615
+ * @param {NodeJS.ProcessEnv} env
616
+ */
617
+ export function hasPotentialCredentialSource(source, env) {
618
+ if (!source) return false;
619
+ if (source.kind === "command") return true;
620
+ if (source.kind === "env") return Boolean(resolveEnvInterpolations(source.rawValue, env)?.trim());
621
+ return Boolean(source.rawValue.trim());
622
+ }
623
+
624
+ /**
625
+ * @param {AgentBrowserConfigState} state
626
+ * @param {NodeJS.ProcessEnv} [env]
627
+ */
628
+ export function canRegisterWebSearchTool(state, env = process.env) {
629
+ if (!state.webSearchEnabled || state.errors.length > 0) return false;
630
+ return WEB_SEARCH_PROVIDERS.some((provider) => hasPotentialCredentialSource(state.webSearchCredentialSources[provider], env));
631
+ }
632
+
633
+ /**
634
+ * @param {CredentialSource | undefined} source
635
+ * @param {WebSearchProvider} [provider]
636
+ */
637
+ export function getCredentialSourceSummary(source, provider) {
638
+ if (!source) return "not configured";
639
+ if (source.kind === "command") return `configured via command (${source.scope})`;
640
+ if (source.kind === "env") return `configured via environment interpolation (${source.scope})`;
641
+ if (source.scope === "env-fallback") {
642
+ return `configured via ${getWebSearchProviderEnvVar(provider ?? source.provider ?? DEFAULT_WEB_SEARCH_PROVIDER)} environment fallback`;
643
+ }
644
+ return `configured as plaintext ${source.scope} value [redacted]`;
645
+ }
646
+
647
+ /** @param {AgentBrowserConfigState} state */
648
+ export function formatBrowserProfileStatus(state) {
649
+ const profile = state.browserDefaultProfile;
650
+ if (!profile) return "not configured";
651
+ const scope = state.browserDefaultProfileScope ?? "unknown";
652
+ const base = `${profile.name} (policy: ${profile.policy}; ${scope})`;
653
+ if (scope !== "project") return base;
654
+ const trustedText = state.trustedBrowserDefaultProfile ? `; trusted guidance: ${state.trustedBrowserDefaultProfile.name} (${state.trustedBrowserDefaultProfileScope})` : "";
655
+ return `${base}; ignored for prompt guidance${trustedText}`;
656
+ }
657
+
658
+ /** @param {AgentBrowserConfigState} state */
659
+ export function formatBrowserExecutableStatus(state) {
660
+ const executablePath = state.browserExecutablePath;
661
+ if (!executablePath) return "not configured";
662
+ const scope = state.browserExecutablePathScope ?? "unknown";
663
+ if (scope !== "project") return `${executablePath} (${scope})`;
664
+ const trustedText = state.trustedBrowserExecutablePath ? `; trusted guidance: ${state.trustedBrowserExecutablePath} (${state.trustedBrowserExecutablePathScope})` : "";
665
+ return `${executablePath} (${scope}; ignored for prompt guidance${trustedText})`;
666
+ }
667
+
668
+ /**
669
+ * @param {AgentBrowserConfigState} state
670
+ * @param {(path: string) => boolean} [exists]
671
+ * @returns {ConfigFileSummary[]}
672
+ */
673
+ export function summarizeConfigFiles(state, exists = existsSync) {
674
+ return [
675
+ ["global", state.paths.global],
676
+ ["project", state.paths.project],
677
+ ...(state.paths.override ? [["override", state.paths.override]] : []),
678
+ ].map(([scope, path]) => ({ scope, path, exists: exists(path) }));
679
+ }