返回源码地图

packages/coding-agent/src/core/settings-manager.ts

v1.3.0 · 71023aec1546 · 03/12/15:读时迁移、project trust、reload诊断;非全部getter审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2import type { Model } from "@earendil-works/pi-ai";
3import type { ScrollViewScrollbar, TerminalCapabilities, WheelScrollLines } from "@earendil-works/pi-tui";
4import { randomUUID } from "crypto";
5import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
6import { dirname, join } from "path";
7import lockfile from "proper-lockfile";
8import { CONFIG_DIR_NAME, getAgentDir } from "../config.ts";
9import { normalizePath, resolvePath } from "../utils/paths.ts";
10import { stripBom } from "../utils/text.ts";
11import { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from "./http-dispatcher.ts";
12import { SETTINGS_DEFAULTS } from "./settings-defaults.ts";
13import type {
14 CacheWarmingMode,
15 CompactionModelOverride,
16 DefaultProjectTrust,
17 FullscreenExitOutput,
18 MermaidRenderingMode,
19 PackageSource,
20 QuietStartup,
21 SessionShareDestination,
22 Settings,
23 ThinkingBudgetsSettings,
24 TransportSetting,
25 TuiMode,
26 WarningSettings,
27} from "./settings-schema.ts";
28
29export type {
30 BranchSummarySettings,
31 CacheWarmingMode,
32 CodemodeMode,
33 CodemodeSettings,
34 CompactionModelOverride,
35 CompactionSettings,
36 DefaultProjectTrust,
37 FullscreenExitOutput,
38 ImageSettings,
39 MarkdownSettings,
40 MermaidRenderingMode,
41 PackageSource,
42 ProviderRetrySettings,
43 QuietStartup,
44 RetrySettings,
45 SessionShareDestination,
46 Settings,
47 TerminalSettings,
48 ThinkingBudgetsSettings,
49 TransportSetting,
50 TuiMode,
51 WarningSettings,
52} from "./settings-schema.ts";
53/** Cache-warming profile. "idle" also warms between agent runs. */
54export const CACHE_WARMING_MODES = ["off", "streaming", "idle"] as const satisfies readonly CacheWarmingMode[];
55
56const DEFAULT_COMPACTION_TOKEN_SETTINGS: Required<CompactionModelOverride> = {
57 reserveTokens: SETTINGS_DEFAULTS.compaction.reserveTokens,
58 keepRecentTokens: SETTINGS_DEFAULTS.compaction.keepRecentTokens,
59};
60
61function isMergeableObject(value: unknown): value is Record<string, unknown> {
62 return typeof value === "object" && value !== null && !Array.isArray(value);
63}
64
65function deepMergeObjects(base: Record<string, unknown>, overrides: Record<string, unknown>): Record<string, unknown> {
66 const result = { ...base };
67
68 for (const key of Object.keys(overrides)) {
69 const overrideValue = overrides[key];
70 if (overrideValue === undefined) {
71 continue;
72 }
73
74 const baseValue = base[key];
75 result[key] =
76 isMergeableObject(baseValue) && isMergeableObject(overrideValue)
77 ? deepMergeObjects(baseValue, overrideValue)
78 : overrideValue;
79 }
80
81 return result;
82}
83
84/** Tools enabled at startup when `defaultTools` does not change them. */
85export const DEFAULT_TOOL_NAMES: readonly string[] = ["read", "bash", "edit", "write"];
86
87/** Whether a tool selection entry is a `+name` or `-name` modifier. */
88export function isToolModifier(entry: unknown): boolean {
89 return typeof entry === "string" && (entry.startsWith("+") || entry.startsWith("-"));
90}
91
92/**
93 * Validate a tool list from `--tools` or the SDK `tools` option. It is either an allowlist of plain
94 * names and patterns or a list of only `+name`/`-name` entries with exact names. Returns the
95 * problem, or undefined when the list is valid.
96 */
97export function getToolListError(entries: readonly string[]): string | undefined {
98 const modifiers = entries.filter(isToolModifier);
99 if (modifiers.length === 0) return undefined;
100 if (modifiers.length < entries.length) return "tool names cannot be mixed with +name or -name entries";
101 const pattern = modifiers.find((entry) => entry.includes("*"));
102 if (pattern) return `+name and -name entries take exact tool names, not patterns: ${pattern}`;
103 return undefined;
104}
105
106/**
107 * Apply the `+name` and `-name` entries of `entries` to `base` in order: `+name` adds a tool and
108 * `-name` removes one. Other entries are ignored.
109 */
110export function applyToolModifiers(base: readonly string[], entries: readonly string[]): string[] {
111 const tools = [...base];
112 for (const entry of entries) {
113 if (!isToolModifier(entry)) continue;
114 const name = entry.slice(1);
115 const index = tools.indexOf(name);
116 if (entry.startsWith("+") && index === -1 && name) tools.push(name);
117 else if (entry.startsWith("-") && index !== -1) tools.splice(index, 1);
118 }
119 return tools;
120}
121
122/**
123 * Merge `defaultTools` of two settings layers. A list with plain tool names replaces the inherited
124 * one; a list of only `+name`/`-name` entries is appended, so it modifies the inherited selection.
125 */
126function mergeDefaultTools(base: string[] | undefined, overrides: string[] | undefined): string[] | undefined {
127 if (overrides === undefined) return base;
128 // Settings files are not validated; a malformed value replaces instead of throwing here.
129 if (!Array.isArray(base) || !Array.isArray(overrides) || !overrides.every(isToolModifier)) return overrides;
130 return [...base, ...overrides];
131}
132
133/**
134 * Resolve a merged `defaultTools` list: plain names replace `DEFAULT_TOOL_NAMES`, then `+name` adds
135 * and `-name` removes a tool, in list order.
136 */
137function resolveDefaultTools(entries: string[]): string[] {
138 const plain = entries.filter((entry) => !isToolModifier(entry));
139 return applyToolModifiers(plain.length > 0 || entries.length === 0 ? plain : DEFAULT_TOOL_NAMES, entries);
140}
141
142/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */
143function deepMergeSettings(base: Settings, overrides: Settings): Settings {
144 const merged = deepMergeObjects(base as Record<string, unknown>, overrides as Record<string, unknown>) as Settings;
145 const defaultTools = mergeDefaultTools(base.defaultTools, overrides.defaultTools);
146 return defaultTools === undefined ? merged : { ...merged, defaultTools };
147}
148
149function parseTimeoutSetting(value: unknown, settingName: string): number | undefined {
150 const timeoutMs = parseHttpIdleTimeoutMs(value);
151 if (timeoutMs !== undefined) {
152 return timeoutMs;
153 }
154 if (value !== undefined) {
155 throw new Error(`Invalid ${settingName} setting: ${String(value)}`);
156 }
157 return undefined;
158}
159
160export type SettingsScope = "global" | "project";
161
162export interface SettingsManagerCreateOptions {
163 projectTrusted?: boolean;
164}
165
166export interface SettingsStorage {
167 withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;
168}
169
170export interface SettingsError {
171 scope: SettingsScope;
172 path?: string;
173 error: Error;
174}
175
176type SettingsPaths = Partial<Record<SettingsScope, string>>;
177
178function toSettingsError(scope: SettingsScope, error: unknown, path?: string): SettingsError {
179 return {
180 scope,
181 ...(path ? { path } : {}),
182 error: error instanceof Error ? error : new Error(String(error)),
183 };
184}
185
186export class FileSettingsStorage implements SettingsStorage {
187 private globalSettingsPath: string;
188 private projectSettingsPath: string;
189
190 constructor(cwd: string, agentDir: string) {
191 const resolvedCwd = resolvePath(cwd);
192 const resolvedAgentDir = resolvePath(agentDir);
193 this.globalSettingsPath = join(resolvedAgentDir, "settings.json");
194 this.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, "settings.json");
195 }
196
197 private acquireLockSyncWithRetry(path: string): () => void {
198 const maxAttempts = 10;
199 const delayMs = 20;
200 let lastError: unknown;
201
202 for (let attempt = 1; attempt <= maxAttempts; attempt++) {
203 try {
204 return lockfile.lockSync(path, { realpath: false });
205 } catch (error) {
206 const code =
207 typeof error === "object" && error !== null && "code" in error
208 ? String((error as { code?: unknown }).code)
209 : undefined;
210 if (code !== "ELOCKED" || attempt === maxAttempts) {
211 throw error;
212 }
213 lastError = error;
214 const start = Date.now();
215 while (Date.now() - start < delayMs) {
216 // Sleep synchronously to avoid changing callers to async.
217 }
218 }
219 }
220
221 throw (lastError as Error) ?? new Error("Failed to acquire settings lock");
222 }
223
224 withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {
225 const path = scope === "global" ? this.globalSettingsPath : this.projectSettingsPath;
226 const dir = dirname(path);
227
228 let release: (() => void) | undefined;
229 try {
230 // Only create directory and lock if file exists or we need to write
231 const fileExists = existsSync(path);
232 if (fileExists) {
233 release = this.acquireLockSyncWithRetry(path);
234 }
235 const current = fileExists ? readFileSync(path, "utf-8") : undefined;
236 const next = fn(current);
237 if (next !== undefined) {
238 // Only create directory when we actually need to write
239 if (!existsSync(dir)) {
240 mkdirSync(dir, { recursive: true });
241 }
242 if (!release) {
243 release = this.acquireLockSyncWithRetry(path);
244 }
245 writeFileSync(path, next, "utf-8");
246 }
247 } finally {
248 if (release) {
249 release();
250 }
251 }
252 }
253}
254
255export class InMemorySettingsStorage implements SettingsStorage {
256 private global: string | undefined;
257 private project: string | undefined;
258
259 withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {
260 const current = scope === "global" ? this.global : this.project;
261 const next = fn(current);
262 if (next !== undefined) {
263 if (scope === "global") {
264 this.global = next;
265 } else {
266 this.project = next;
267 }
268 }
269 }
270}
271
272export class SettingsManager {
273 private storage: SettingsStorage;
274 private globalSettings: Settings;
275 private projectSettings: Settings;
276 private settings: Settings;
277 private projectTrusted: boolean;
278 private modifiedFields = new Set<keyof Settings>(); // Track global fields modified during session
279 private modifiedNestedFields = new Map<keyof Settings, Set<string>>(); // Track global nested field modifications
280 private modifiedProjectFields = new Set<keyof Settings>(); // Track project fields modified during session
281 private modifiedProjectNestedFields = new Map<keyof Settings, Set<string>>(); // Track project nested field modifications
282 private globalSettingsLoadError: Error | null = null; // Track if global settings file had parse errors
283 private projectSettingsLoadError: Error | null = null; // Track if project settings file had parse errors
284 private writeQueue: Promise<void> = Promise.resolve();
285 private errors: SettingsError[];
286 private settingsPaths: SettingsPaths;
287
288 private constructor(
289 storage: SettingsStorage,
290 initialGlobal: Settings,
291 initialProject: Settings,
292 globalLoadError: Error | null = null,
293 projectLoadError: Error | null = null,
294 initialErrors: SettingsError[] = [],
295 projectTrusted = true,
296 settingsPaths: SettingsPaths = {},
297 ) {
298 this.storage = storage;
299 this.globalSettings = initialGlobal;
300 this.projectSettings = initialProject;
301 this.projectTrusted = projectTrusted;
302 this.globalSettingsLoadError = globalLoadError;
303 this.projectSettingsLoadError = projectLoadError;
304 this.errors = [...initialErrors];
305 this.settingsPaths = settingsPaths;
306 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
307 }
308
309 /** Create a SettingsManager that loads from files */
310 static create(
311 cwd: string,
312 agentDir: string = getAgentDir(),
313 options: SettingsManagerCreateOptions = {},
314 ): SettingsManager {
315 const resolvedCwd = resolvePath(cwd);
316 const resolvedAgentDir = resolvePath(agentDir);
317 const storage = new FileSettingsStorage(resolvedCwd, resolvedAgentDir);
318 return SettingsManager.fromStorageWithPaths(storage, options, {
319 global: join(resolvedAgentDir, "settings.json"),
320 project: join(resolvedCwd, CONFIG_DIR_NAME, "settings.json"),
321 });
322 }
323
324 /** Create a SettingsManager from an arbitrary storage backend */
325 static fromStorage(storage: SettingsStorage, options: SettingsManagerCreateOptions = {}): SettingsManager {
326 return SettingsManager.fromStorageWithPaths(storage, options);
327 }
328
329 /** Create a manager while retaining optional file paths for reported storage errors. */
330 private static fromStorageWithPaths(
331 storage: SettingsStorage,
332 options: SettingsManagerCreateOptions,
333 settingsPaths: SettingsPaths = {},
334 ): SettingsManager {
335 const projectTrusted = options.projectTrusted ?? true;
336 const globalLoad = SettingsManager.tryLoadFromStorage(storage, "global");
337 const projectLoad = SettingsManager.tryLoadFromStorage(storage, "project", projectTrusted);
338 const initialErrors: SettingsError[] = [];
339 if (globalLoad.error) {
340 initialErrors.push(toSettingsError("global", globalLoad.error, settingsPaths.global));
341 }
342 if (projectLoad.error) {
343 initialErrors.push(toSettingsError("project", projectLoad.error, settingsPaths.project));
344 }
345
346 return new SettingsManager(
347 storage,
348 globalLoad.settings,
349 projectLoad.settings,
350 globalLoad.error,
351 projectLoad.error,
352 initialErrors,
353 projectTrusted,
354 settingsPaths,
355 );
356 }
357
358 /** Create an in-memory SettingsManager (no file I/O) */
359 static inMemory(settings: Partial<Settings> = {}, options: SettingsManagerCreateOptions = {}): SettingsManager {
360 const storage = new InMemorySettingsStorage();
361 const initialSettings = SettingsManager.migrateSettings(structuredClone(settings) as Record<string, unknown>);
362 storage.withLock("global", () => JSON.stringify(initialSettings, null, 2));
363 return SettingsManager.fromStorage(storage, options);
364 }
365
366 private static loadFromStorage(storage: SettingsStorage, scope: SettingsScope, projectTrusted = true): Settings {
367 if (scope === "project" && !projectTrusted) {
368 return {};
369 }
370
371 let content: string | undefined;
372 storage.withLock(scope, (current) => {
373 content = current;
374 return undefined;
375 });
376
377 if (!content) {
378 return {};
379 }
380 const settings = JSON.parse(stripBom(content));
381 return SettingsManager.migrateSettings(settings);
382 }
383
384 private static tryLoadFromStorage(
385 storage: SettingsStorage,
386 scope: SettingsScope,
387 projectTrusted = true,
388 ): { settings: Settings; error: Error | null } {
389 try {
390 return { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null };
391 } catch (error) {
392 return { settings: {}, error: error as Error };
393 }
394 }
395
396 /** Migrate old settings format to new format */
397 private static migrateSettings(settings: Record<string, unknown>): Settings {
398 // Migrate queueMode -> steeringMode
399 if ("queueMode" in settings && !("steeringMode" in settings)) {
400 settings.steeringMode = settings.queueMode;
401 delete settings.queueMode;
402 }
403
404 // Migrate legacy websockets boolean -> transport enum
405 if (!("transport" in settings) && typeof settings.websockets === "boolean") {
406 settings.transport = settings.websockets ? "websocket" : "sse";
407 delete settings.websockets;
408 }
409
410 // Migrate old skills object format to new array format
411 if (
412 "skills" in settings &&
413 typeof settings.skills === "object" &&
414 settings.skills !== null &&
415 !Array.isArray(settings.skills)
416 ) {
417 const skillsSettings = settings.skills as {
418 enableSkillCommands?: boolean;
419 customDirectories?: unknown;
420 };
421 if (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {
422 settings.enableSkillCommands = skillsSettings.enableSkillCommands;
423 }
424 if (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {
425 settings.skills = skillsSettings.customDirectories;
426 } else {
427 delete settings.skills;
428 }
429 }
430
431 // Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs
432 if (
433 "retry" in settings &&
434 typeof settings.retry === "object" &&
435 settings.retry !== null &&
436 !Array.isArray(settings.retry)
437 ) {
438 const retrySettings = settings.retry as Record<string, unknown>;
439 const providerSettings =
440 typeof retrySettings.provider === "object" && retrySettings.provider !== null
441 ? (retrySettings.provider as Record<string, unknown>)
442 : undefined;
443 if (
444 typeof retrySettings.maxDelayMs === "number" &&
445 (providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)
446 ) {
447 retrySettings.provider = {
448 ...(providerSettings ?? {}),
449 maxRetryDelayMs: retrySettings.maxDelayMs,
450 };
451 }
452 delete retrySettings.maxDelayMs;
453 }
454
455 return settings as Settings;
456 }
457
458 /** A copy of the effective settings: global and project settings merged, with overrides. */
459 getSettings(): Settings {
460 return structuredClone(this.settings);
461 }
462
463 getGlobalSettings(): Settings {
464 return structuredClone(this.globalSettings);
465 }
466
467 getProjectSettings(): Settings {
468 return structuredClone(this.projectSettings);
469 }
470
471 isProjectTrusted(): boolean {
472 return this.projectTrusted;
473 }
474
475 setProjectTrusted(trusted: boolean): void {
476 if (this.projectTrusted === trusted) {
477 return;
478 }
479
480 this.projectTrusted = trusted;
481 this.modifiedProjectFields.clear();
482 this.modifiedProjectNestedFields.clear();
483
484 if (!trusted) {
485 this.projectSettings = {};
486 this.projectSettingsLoadError = null;
487 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
488 return;
489 }
490
491 const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", trusted);
492 this.projectSettings = projectLoad.settings;
493 this.projectSettingsLoadError = projectLoad.error;
494 if (projectLoad.error) {
495 this.recordError("project", projectLoad.error);
496 }
497 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
498 }
499
500 async reload(): Promise<void> {
501 await this.writeQueue;
502 const globalLoad = SettingsManager.tryLoadFromStorage(this.storage, "global");
503 if (!globalLoad.error) {
504 this.globalSettings = globalLoad.settings;
505 this.globalSettingsLoadError = null;
506 } else {
507 this.globalSettingsLoadError = globalLoad.error;
508 this.recordError("global", globalLoad.error);
509 }
510
511 this.modifiedFields.clear();
512 this.modifiedNestedFields.clear();
513 this.modifiedProjectFields.clear();
514 this.modifiedProjectNestedFields.clear();
515
516 const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", this.projectTrusted);
517 if (!projectLoad.error) {
518 this.projectSettings = projectLoad.settings;
519 this.projectSettingsLoadError = null;
520 } else {
521 this.projectSettingsLoadError = projectLoad.error;
522 this.recordError("project", projectLoad.error);
523 }
524
525 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
526 }
527
528 /** Apply additional overrides on top of current settings */
529 applyOverrides(overrides: Partial<Settings>): void {
530 this.settings = deepMergeSettings(this.settings, overrides);
531 }
532
533 /** Mark a global field as modified during this session */
534 private markModified(field: keyof Settings, nestedKey?: string): void {
535 this.modifiedFields.add(field);
536 if (nestedKey) {
537 if (!this.modifiedNestedFields.has(field)) {
538 this.modifiedNestedFields.set(field, new Set());
539 }
540 this.modifiedNestedFields.get(field)!.add(nestedKey);
541 }
542 }
543
544 /** Mark a project field as modified during this session */
545 private markProjectModified(field: keyof Settings, nestedKey?: string): void {
546 this.modifiedProjectFields.add(field);
547 if (nestedKey) {
548 if (!this.modifiedProjectNestedFields.has(field)) {
549 this.modifiedProjectNestedFields.set(field, new Set());
550 }
551 this.modifiedProjectNestedFields.get(field)!.add(nestedKey);
552 }
553 }
554
555 private assertProjectTrustedForWrite(): void {
556 if (!this.projectTrusted) {
557 throw new Error("Project is not trusted; refusing to write project settings");
558 }
559 }
560
561 private recordError(scope: SettingsScope, error: unknown): void {
562 this.errors.push(toSettingsError(scope, error, this.settingsPaths[scope]));
563 }
564
565 private clearModifiedScope(scope: SettingsScope): void {
566 if (scope === "global") {
567 this.modifiedFields.clear();
568 this.modifiedNestedFields.clear();
569 return;
570 }
571
572 this.modifiedProjectFields.clear();
573 this.modifiedProjectNestedFields.clear();
574 }
575
576 private enqueueWrite(scope: SettingsScope, task: () => void): void {
577 this.writeQueue = this.writeQueue
578 .then(() => {
579 if (scope === "project") {
580 this.assertProjectTrustedForWrite();
581 }
582 task();
583 this.clearModifiedScope(scope);
584 })
585 .catch((error) => {
586 this.recordError(scope, error);
587 });
588 }
589
590 private cloneModifiedNestedFields(source: Map<keyof Settings, Set<string>>): Map<keyof Settings, Set<string>> {
591 const snapshot = new Map<keyof Settings, Set<string>>();
592 for (const [key, value] of source.entries()) {
593 snapshot.set(key, new Set(value));
594 }
595 return snapshot;
596 }
597
598 private persistScopedSettings(
599 scope: SettingsScope,
600 snapshotSettings: Settings,
601 modifiedFields: Set<keyof Settings>,
602 modifiedNestedFields: Map<keyof Settings, Set<string>>,
603 ): void {
604 this.storage.withLock(scope, (current) => {
605 const currentFileSettings = current
606 ? SettingsManager.migrateSettings(JSON.parse(stripBom(current)) as Record<string, unknown>)
607 : {};
608 const mergedSettings: Settings = { ...currentFileSettings };
609 for (const field of modifiedFields) {
610 const value = snapshotSettings[field];
611 if (modifiedNestedFields.has(field) && typeof value === "object" && value !== null) {
612 const nestedModified = modifiedNestedFields.get(field)!;
613 const baseNested = (currentFileSettings[field] as Record<string, unknown>) ?? {};
614 const inMemoryNested = value as Record<string, unknown>;
615 const mergedNested = { ...baseNested };
616 for (const nestedKey of nestedModified) {
617 mergedNested[nestedKey] = inMemoryNested[nestedKey];
618 }
619 (mergedSettings as Record<string, unknown>)[field] = mergedNested;
620 } else {
621 (mergedSettings as Record<string, unknown>)[field] = value;
622 }
623 }
624
625 return JSON.stringify(mergedSettings, null, 2);
626 });
627 }
628
629 private save(): void {
630 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
631
632 if (this.globalSettingsLoadError) {
633 return;
634 }
635
636 const snapshotGlobalSettings = structuredClone(this.globalSettings);
637 const modifiedFields = new Set(this.modifiedFields);
638 const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);
639
640 this.enqueueWrite("global", () => {
641 this.persistScopedSettings("global", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);
642 });
643 }
644
645 private saveProjectSettings(settings: Settings): void {
646 this.assertProjectTrustedForWrite();
647 this.projectSettings = structuredClone(settings);
648 this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
649
650 if (this.projectSettingsLoadError) {
651 return;
652 }
653
654 const snapshotProjectSettings = structuredClone(this.projectSettings);
655 const modifiedFields = new Set(this.modifiedProjectFields);
656 const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);
657 this.enqueueWrite("project", () => {
658 this.persistScopedSettings("project", snapshotProjectSettings, modifiedFields, modifiedNestedFields);
659 });
660 }
661
662 private updateProjectSettings(field: keyof Settings, update: (settings: Settings) => void): void {
663 this.assertProjectTrustedForWrite();
664 const projectSettings = structuredClone(this.projectSettings);
665 update(projectSettings);
666 this.markProjectModified(field);
667 this.saveProjectSettings(projectSettings);
668 }
669
670 async flush(): Promise<void> {
671 await this.writeQueue;
672 }
673
674 drainErrors(): SettingsError[] {
675 const drained = [...this.errors];
676 this.errors = [];
677 return drained;
678 }
679
680 getLastChangelogVersion(): string | undefined {
681 return this.settings.lastChangelogVersion;
682 }
683
684 setLastChangelogVersion(version: string): void {
685 this.globalSettings.lastChangelogVersion = version;
686 this.markModified("lastChangelogVersion");
687 this.save();
688 }
689
690 getSessionDir(): string | undefined {
691 const sessionDir = this.settings.sessionDir;
692 return sessionDir ? normalizePath(sessionDir) : sessionDir;
693 }
694
695 getDefaultProvider(): string | undefined {
696 return this.settings.defaultProvider;
697 }
698
699 getDefaultModel(): string | undefined {
700 return this.settings.defaultModel;
701 }
702
703 setDefaultProvider(provider: string): void {
704 this.globalSettings.defaultProvider = provider;
705 this.markModified("defaultProvider");
706 this.save();
707 }
708
709 setDefaultModel(modelId: string): void {
710 this.globalSettings.defaultModel = modelId;
711 this.markModified("defaultModel");
712 this.save();
713 }
714
715 setDefaultModelAndProvider(provider: string, modelId: string): void {
716 this.globalSettings.defaultProvider = provider;
717 this.globalSettings.defaultModel = modelId;
718 this.markModified("defaultProvider");
719 this.markModified("defaultModel");
720 this.save();
721 }
722
723 getSteeringMode(): "all" | "one-at-a-time" {
724 return this.settings.steeringMode || SETTINGS_DEFAULTS.steeringMode;
725 }
726
727 setSteeringMode(mode: "all" | "one-at-a-time"): void {
728 this.globalSettings.steeringMode = mode;
729 this.markModified("steeringMode");
730 this.save();
731 }
732
733 getFollowUpMode(): "all" | "one-at-a-time" {
734 return this.settings.followUpMode || SETTINGS_DEFAULTS.followUpMode;
735 }
736
737 setFollowUpMode(mode: "all" | "one-at-a-time"): void {
738 this.globalSettings.followUpMode = mode;
739 this.markModified("followUpMode");
740 this.save();
741 }
742
743 getThemeSetting(): string | undefined {
744 const value = this.settings.theme;
745 if (typeof value === "string") return value;
746 return undefined;
747 }
748
749 getTheme(): string | undefined {
750 const theme = this.getThemeSetting();
751 return theme?.includes("/") ? undefined : theme;
752 }
753
754 setTheme(theme: string): void {
755 this.globalSettings.theme = theme;
756 this.markModified("theme");
757 this.save();
758 }
759
760 getDefaultThinkingLevel(): ThinkingLevel | undefined {
761 return this.settings.defaultThinkingLevel;
762 }
763
764 setDefaultThinkingLevel(level: ThinkingLevel): void {
765 this.globalSettings.defaultThinkingLevel = level;
766 this.markModified("defaultThinkingLevel");
767 this.save();
768 }
769
770 getModelThinkingLevel(provider: string, modelId: string): ThinkingLevel | undefined {
771 return this.settings.modelThinkingLevels?.[`${provider}/${modelId}`];
772 }
773
774 getAllModelThinkingLevels(): Record<string, ThinkingLevel> {
775 return { ...(this.settings.modelThinkingLevels ?? {}) };
776 }
777
778 setModelThinkingLevel(provider: string, modelId: string, level: ThinkingLevel): void {
779 if (!this.globalSettings.modelThinkingLevels) {
780 this.globalSettings.modelThinkingLevels = {};
781 }
782 this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`] = level;
783 this.markModified("modelThinkingLevels");
784 this.save();
785 }
786
787 removeModelThinkingLevel(provider: string, modelId: string): void {
788 if (!this.globalSettings.modelThinkingLevels) return;
789 delete this.globalSettings.modelThinkingLevels[`${provider}/${modelId}`];
790 if (Object.keys(this.globalSettings.modelThinkingLevels).length === 0) {
791 delete this.globalSettings.modelThinkingLevels;
792 }
793 this.markModified("modelThinkingLevels");
794 this.save();
795 }
796
797 getTransport(): TransportSetting {
798 return this.settings.transport ?? SETTINGS_DEFAULTS.transport;
799 }
800
801 setTransport(transport: TransportSetting): void {
802 this.globalSettings.transport = transport;
803 this.markModified("transport");
804 this.save();
805 }
806
807 getSessionShareDestination(): SessionShareDestination {
808 const destination = this.settings.sessionShareDestination;
809 return destination === "gist" || destination === "radius"
810 ? destination
811 : SETTINGS_DEFAULTS.sessionShareDestination;
812 }
813
814 setSessionShareDestination(destination: SessionShareDestination): void {
815 this.globalSettings.sessionShareDestination = destination;
816 this.markModified("sessionShareDestination");
817 this.save();
818 }
819
820 getCompactionEnabled(): boolean {
821 return this.settings.compaction?.enabled ?? SETTINGS_DEFAULTS.compaction.enabled;
822 }
823
824 setCompactionEnabled(enabled: boolean): void {
825 if (!this.globalSettings.compaction) {
826 this.globalSettings.compaction = {};
827 }
828 this.globalSettings.compaction.enabled = enabled;
829 this.markModified("compaction", "enabled");
830 this.save();
831 }
832
833 private getCompactionTokenSetting(
834 field: keyof CompactionModelOverride,
835 model?: Pick<Model<string>, "provider" | "id">,
836 ): number {
837 const compaction = this.settings.compaction;
838 const ordinary = compaction?.[field];
839 if (ordinary !== undefined && (typeof ordinary !== "number" || !Number.isSafeInteger(ordinary) || ordinary < 0)) {
840 throw new Error(
841 `Invalid compaction.${field} setting: ${String(ordinary)}. Expected a non-negative safe integer.`,
842 );
843 }
844
845 const modelKey = model ? `${model.provider}/${model.id}` : undefined;
846 const entry = modelKey !== undefined ? compaction?.modelOverrides?.[modelKey] : undefined;
847 if (entry !== undefined && !isMergeableObject(entry)) {
848 throw new Error(
849 `Invalid compaction.modelOverrides["${modelKey}"] setting: ${String(entry)}. Expected an object.`,
850 );
851 }
852 const override = entry?.[field];
853 if (override !== undefined && (typeof override !== "number" || !Number.isSafeInteger(override) || override < 0)) {
854 throw new Error(
855 `Invalid compaction.modelOverrides["${modelKey}"].${field} setting: ${String(override)}. Expected a non-negative safe integer.`,
856 );
857 }
858 return override ?? ordinary ?? DEFAULT_COMPACTION_TOKEN_SETTINGS[field];
859 }
860
861 getCompactionReserveTokens(model?: Pick<Model<string>, "provider" | "id">): number {
862 return this.getCompactionTokenSetting("reserveTokens", model);
863 }
864
865 getCompactionKeepRecentTokens(model?: Pick<Model<string>, "provider" | "id">): number {
866 return this.getCompactionTokenSetting("keepRecentTokens", model);
867 }
868
869 /** Resolve each token setting through model override, ordinary setting, then built-in default. */
870 getCompactionSettings(model?: Pick<Model<string>, "provider" | "id">): {
871 enabled: boolean;
872 reserveTokens: number;
873 keepRecentTokens: number;
874 } {
875 return {
876 enabled: this.getCompactionEnabled(),
877 reserveTokens: this.getCompactionReserveTokens(model),
878 keepRecentTokens: this.getCompactionKeepRecentTokens(model),
879 };
880 }
881
882 getBranchSummarySettings(): { reserveTokens: number; skipPrompt: boolean } {
883 return {
884 reserveTokens: this.settings.branchSummary?.reserveTokens ?? SETTINGS_DEFAULTS.branchSummary.reserveTokens,
885 skipPrompt: this.settings.branchSummary?.skipPrompt ?? SETTINGS_DEFAULTS.branchSummary.skipPrompt,
886 };
887 }
888
889 getBranchSummarySkipPrompt(): boolean {
890 return this.settings.branchSummary?.skipPrompt ?? SETTINGS_DEFAULTS.branchSummary.skipPrompt;
891 }
892
893 getRetryEnabled(): boolean {
894 return this.settings.retry?.enabled ?? SETTINGS_DEFAULTS.retry.enabled;
895 }
896
897 setRetryEnabled(enabled: boolean): void {
898 if (!this.globalSettings.retry) {
899 this.globalSettings.retry = {};
900 }
901 this.globalSettings.retry.enabled = enabled;
902 this.markModified("retry", "enabled");
903 this.save();
904 }
905
906 getRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number; maxAgentDelayMs: number } {
907 return {
908 enabled: this.getRetryEnabled(),
909 maxRetries: this.settings.retry?.maxRetries ?? SETTINGS_DEFAULTS.retry.maxRetries,
910 baseDelayMs: this.settings.retry?.baseDelayMs ?? SETTINGS_DEFAULTS.retry.baseDelayMs,
911 maxAgentDelayMs: this.settings.retry?.maxAgentDelayMs ?? SETTINGS_DEFAULTS.retry.maxAgentDelayMs,
912 };
913 }
914
915 getHttpIdleTimeoutMs(): number {
916 return parseTimeoutSetting(this.settings.httpIdleTimeoutMs, "httpIdleTimeoutMs") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;
917 }
918
919 setHttpIdleTimeoutMs(timeoutMs: number): void {
920 if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
921 throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);
922 }
923 this.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);
924 this.markModified("httpIdleTimeoutMs");
925 this.save();
926 }
927
928 /** Read from global settings only because warming costs money. */
929 getCacheWarmingMode(): CacheWarmingMode {
930 const mode = this.globalSettings.cacheWarming;
931 return mode !== undefined && CACHE_WARMING_MODES.includes(mode) ? mode : SETTINGS_DEFAULTS.cacheWarming;
932 }
933
934 setCacheWarmingMode(mode: CacheWarmingMode): void {
935 this.globalSettings.cacheWarming = mode;
936 this.markModified("cacheWarming");
937 this.save();
938 }
939
940 getProviderRetrySettings(): { timeoutMs?: number; maxRetries?: number; maxRetryDelayMs: number } {
941 return {
942 timeoutMs: this.settings.retry?.provider?.timeoutMs,
943 maxRetries: this.settings.retry?.provider?.maxRetries,
944 maxRetryDelayMs:
945 this.settings.retry?.provider?.maxRetryDelayMs ?? SETTINGS_DEFAULTS.retry.provider.maxRetryDelayMs,
946 };
947 }
948
949 getWebSocketConnectTimeoutMs(): number | undefined {
950 return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, "websocketConnectTimeoutMs");
951 }
952
953 getHideThinkingBlock(): boolean {
954 return this.settings.hideThinkingBlock ?? SETTINGS_DEFAULTS.hideThinkingBlock;
955 }
956
957 getShowCacheMissNotices(): boolean {
958 return this.settings.showCacheMissNotices ?? SETTINGS_DEFAULTS.showCacheMissNotices;
959 }
960
961 getExternalEditorCommand(): string {
962 const configuredEditor = this.settings.externalEditor;
963 if (typeof configuredEditor === "string" && configuredEditor.trim() !== "") {
964 return configuredEditor;
965 }
966 const environmentEditor = process.env.VISUAL || process.env.EDITOR;
967 if (environmentEditor) {
968 return environmentEditor;
969 }
970 return process.platform === "win32" ? "notepad" : "nano";
971 }
972
973 setHideThinkingBlock(hide: boolean): void {
974 this.globalSettings.hideThinkingBlock = hide;
975 this.markModified("hideThinkingBlock");
976 this.save();
977 }
978
979 setShowCacheMissNotices(show: boolean): void {
980 this.globalSettings.showCacheMissNotices = show;
981 this.markModified("showCacheMissNotices");
982 this.save();
983 }
984
985 getShellPath(): string | undefined {
986 const shellPath = this.settings.shellPath;
987 return shellPath ? normalizePath(shellPath) : shellPath;
988 }
989
990 setShellPath(path: string | undefined): void {
991 this.globalSettings.shellPath = path;
992 this.markModified("shellPath");
993 this.save();
994 }
995
996 getQuietStartup(): QuietStartup {
997 const value = this.settings.quietStartup;
998 return value === true || value === "header" ? value : SETTINGS_DEFAULTS.quietStartup;
999 }
1000
1001 setQuietStartup(quiet: QuietStartup): void {
1002 this.globalSettings.quietStartup = quiet;
1003 this.markModified("quietStartup");
1004 this.save();
1005 }
1006
1007 getDefaultProjectTrust(): DefaultProjectTrust {
1008 const value = this.globalSettings.defaultProjectTrust;
1009 return value === "always" || value === "never" ? value : SETTINGS_DEFAULTS.defaultProjectTrust;
1010 }
1011
1012 setDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void {
1013 this.globalSettings.defaultProjectTrust = defaultProjectTrust;
1014 this.markModified("defaultProjectTrust");
1015 this.save();
1016 }
1017
1018 getShellCommandPrefix(): string | undefined {
1019 return this.settings.shellCommandPrefix;
1020 }
1021
1022 setShellCommandPrefix(prefix: string | undefined): void {
1023 this.globalSettings.shellCommandPrefix = prefix;
1024 this.markModified("shellCommandPrefix");
1025 this.save();
1026 }
1027
1028 getNpmCommand(): string[] | undefined {
1029 return this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;
1030 }
1031
1032 setNpmCommand(command: string[] | undefined): void {
1033 this.globalSettings.npmCommand = command ? [...command] : undefined;
1034 this.markModified("npmCommand");
1035 this.save();
1036 }
1037
1038 getCollapseChangelog(): boolean {
1039 return this.settings.collapseChangelog ?? SETTINGS_DEFAULTS.collapseChangelog;
1040 }
1041
1042 setCollapseChangelog(collapse: boolean): void {
1043 this.globalSettings.collapseChangelog = collapse;
1044 this.markModified("collapseChangelog");
1045 this.save();
1046 }
1047
1048 getEnableInstallTelemetry(): boolean {
1049 return this.settings.enableInstallTelemetry ?? SETTINGS_DEFAULTS.enableInstallTelemetry;
1050 }
1051
1052 setEnableInstallTelemetry(enabled: boolean): void {
1053 this.globalSettings.enableInstallTelemetry = enabled;
1054 this.markModified("enableInstallTelemetry");
1055 this.save();
1056 }
1057
1058 getEnableAnalytics(): boolean {
1059 return this.settings.enableAnalytics ?? SETTINGS_DEFAULTS.enableAnalytics;
1060 }
1061
1062 getTrackingId(): string | undefined {
1063 return this.settings.trackingId;
1064 }
1065
1066 /** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */
1067 setEnableAnalytics(enabled: boolean): void {
1068 this.globalSettings.enableAnalytics = enabled;
1069 this.markModified("enableAnalytics");
1070 if (enabled && !this.globalSettings.trackingId) {
1071 this.globalSettings.trackingId = randomUUID();
1072 this.markModified("trackingId");
1073 }
1074 this.save();
1075 }
1076
1077 /**
1078 * Stable ID of this installation, e.g. sent to OpenAI as its agent host ID.
1079 * Created on first use. Project settings are ignored so a committed project
1080 * settings file cannot give every clone the same ID.
1081 */
1082 getOrCreateDeviceId(): string {
1083 if (!this.globalSettings.deviceId) {
1084 this.globalSettings.deviceId = randomUUID();
1085 this.markModified("deviceId");
1086 this.save();
1087 }
1088 return this.globalSettings.deviceId;
1089 }
1090
1091 getPackages(): PackageSource[] {
1092 return [...(this.settings.packages ?? [])];
1093 }
1094
1095 setPackages(packages: PackageSource[]): void {
1096 this.globalSettings.packages = packages;
1097 this.markModified("packages");
1098 this.save();
1099 }
1100
1101 setProjectPackages(packages: PackageSource[]): void {
1102 this.updateProjectSettings("packages", (settings) => {
1103 settings.packages = packages;
1104 });
1105 }
1106
1107 getExtensionPaths(): string[] {
1108 return [...(this.settings.extensions ?? [])];
1109 }
1110
1111 setExtensionPaths(paths: string[]): void {
1112 this.globalSettings.extensions = paths;
1113 this.markModified("extensions");
1114 this.save();
1115 }
1116
1117 setProjectExtensionPaths(paths: string[]): void {
1118 this.updateProjectSettings("extensions", (settings) => {
1119 settings.extensions = paths;
1120 });
1121 }
1122
1123 getSkillPaths(): string[] {
1124 return [...(this.settings.skills ?? [])];
1125 }
1126
1127 setSkillPaths(paths: string[]): void {
1128 this.globalSettings.skills = paths;
1129 this.markModified("skills");
1130 this.save();
1131 }
1132
1133 setProjectSkillPaths(paths: string[]): void {
1134 this.updateProjectSettings("skills", (settings) => {
1135 settings.skills = paths;
1136 });
1137 }
1138
1139 getPromptTemplatePaths(): string[] {
1140 return [...(this.settings.prompts ?? [])];
1141 }
1142
1143 setPromptTemplatePaths(paths: string[]): void {
1144 this.globalSettings.prompts = paths;
1145 this.markModified("prompts");
1146 this.save();
1147 }
1148
1149 setProjectPromptTemplatePaths(paths: string[]): void {
1150 this.updateProjectSettings("prompts", (settings) => {
1151 settings.prompts = paths;
1152 });
1153 }
1154
1155 getThemePaths(): string[] {
1156 return [...(this.settings.themes ?? [])];
1157 }
1158
1159 setThemePaths(paths: string[]): void {
1160 this.globalSettings.themes = paths;
1161 this.markModified("themes");
1162 this.save();
1163 }
1164
1165 setProjectThemePaths(paths: string[]): void {
1166 this.updateProjectSettings("themes", (settings) => {
1167 settings.themes = paths;
1168 });
1169 }
1170
1171 getEnableSkillCommands(): boolean {
1172 return this.settings.enableSkillCommands ?? SETTINGS_DEFAULTS.enableSkillCommands;
1173 }
1174
1175 setEnableSkillCommands(enabled: boolean): void {
1176 this.globalSettings.enableSkillCommands = enabled;
1177 this.markModified("enableSkillCommands");
1178 this.save();
1179 }
1180
1181 getThinkingBudgets(): ThinkingBudgetsSettings | undefined {
1182 return this.settings.thinkingBudgets;
1183 }
1184
1185 getTerminalCapabilityOverrides(): Partial<TerminalCapabilities> {
1186 const terminal = this.settings.terminal;
1187 const images = terminal?.images;
1188 return {
1189 ...(images === "kitty" || images === "iterm2" ? { images } : images === false ? { images: null } : {}),
1190 ...(typeof terminal?.trueColor === "boolean" ? { trueColor: terminal.trueColor } : {}),
1191 ...(typeof terminal?.hyperlinks === "boolean" ? { hyperlinks: terminal.hyperlinks } : {}),
1192 };
1193 }
1194
1195 getShowImages(): boolean {
1196 return this.settings.terminal?.showImages ?? SETTINGS_DEFAULTS.terminal.showImages;
1197 }
1198
1199 setShowImages(show: boolean): void {
1200 if (!this.globalSettings.terminal) {
1201 this.globalSettings.terminal = {};
1202 }
1203 this.globalSettings.terminal.showImages = show;
1204 this.markModified("terminal", "showImages");
1205 this.save();
1206 }
1207
1208 getImageWidthCells(): number {
1209 const width = this.settings.terminal?.imageWidthCells;
1210 if (typeof width !== "number" || !Number.isFinite(width)) {
1211 return SETTINGS_DEFAULTS.terminal.imageWidthCells;
1212 }
1213 return Math.max(1, Math.floor(width));
1214 }
1215
1216 setImageWidthCells(width: number): void {
1217 if (!this.globalSettings.terminal) {
1218 this.globalSettings.terminal = {};
1219 }
1220 this.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));
1221 this.markModified("terminal", "imageWidthCells");
1222 this.save();
1223 }
1224
1225 getClearOnShrink(): boolean {
1226 // Settings takes precedence, then env var, then default false
1227 if (this.settings.terminal?.clearOnShrink !== undefined) {
1228 return this.settings.terminal.clearOnShrink;
1229 }
1230 if (process.env.PI_CLEAR_ON_SHRINK === "1") return true;
1231 return SETTINGS_DEFAULTS.terminal.clearOnShrink;
1232 }
1233
1234 setClearOnShrink(enabled: boolean): void {
1235 if (!this.globalSettings.terminal) {
1236 this.globalSettings.terminal = {};
1237 }
1238 this.globalSettings.terminal.clearOnShrink = enabled;
1239 this.markModified("terminal", "clearOnShrink");
1240 this.save();
1241 }
1242
1243 getShowTerminalProgress(): boolean {
1244 return this.settings.terminal?.showTerminalProgress ?? SETTINGS_DEFAULTS.terminal.showTerminalProgress;
1245 }
1246
1247 setShowTerminalProgress(enabled: boolean): void {
1248 if (!this.globalSettings.terminal) {
1249 this.globalSettings.terminal = {};
1250 }
1251 this.globalSettings.terminal.showTerminalProgress = enabled;
1252 this.markModified("terminal", "showTerminalProgress");
1253 this.save();
1254 }
1255
1256 getTuiMode(): TuiMode {
1257 return this.settings.tuiMode === "regular" ? "regular" : SETTINGS_DEFAULTS.tuiMode;
1258 }
1259
1260 setTuiMode(mode: TuiMode): void {
1261 this.globalSettings.tuiMode = mode;
1262 this.markModified("tuiMode");
1263 this.save();
1264 }
1265
1266 getFullscreenExitOutput(): FullscreenExitOutput {
1267 return this.settings.fullscreenExitOutput === "resume-hint"
1268 ? "resume-hint"
1269 : SETTINGS_DEFAULTS.fullscreenExitOutput;
1270 }
1271
1272 setFullscreenExitOutput(output: FullscreenExitOutput): void {
1273 this.globalSettings.fullscreenExitOutput = output;
1274 this.markModified("fullscreenExitOutput");
1275 this.save();
1276 }
1277
1278 getFullscreenScrollbar(): ScrollViewScrollbar {
1279 const mode = this.settings.fullscreenScrollbar;
1280 return mode === "always" || mode === "hidden" ? mode : SETTINGS_DEFAULTS.fullscreenScrollbar;
1281 }
1282
1283 setFullscreenScrollbar(mode: ScrollViewScrollbar): void {
1284 this.globalSettings.fullscreenScrollbar = mode;
1285 this.markModified("fullscreenScrollbar");
1286 this.save();
1287 }
1288
1289 getFullscreenCopyOnSelect(): boolean {
1290 return this.settings.fullscreenCopyOnSelect ?? SETTINGS_DEFAULTS.fullscreenCopyOnSelect;
1291 }
1292
1293 setFullscreenCopyOnSelect(enabled: boolean): void {
1294 this.globalSettings.fullscreenCopyOnSelect = enabled;
1295 this.markModified("fullscreenCopyOnSelect");
1296 this.save();
1297 }
1298
1299 getFullscreenWheelScrollLines(): WheelScrollLines {
1300 const lines = this.settings.fullscreenWheelScrollLines;
1301 return typeof lines === "number" && Number.isFinite(lines)
1302 ? Math.max(1, Math.min(100, Math.floor(lines)))
1303 : SETTINGS_DEFAULTS.fullscreenWheelScrollLines;
1304 }
1305
1306 setFullscreenWheelScrollLines(lines: WheelScrollLines): void {
1307 this.globalSettings.fullscreenWheelScrollLines =
1308 lines === "auto" ? lines : Math.max(1, Math.min(100, Math.floor(lines)));
1309 this.markModified("fullscreenWheelScrollLines");
1310 this.save();
1311 }
1312
1313 getImageAutoResize(): boolean {
1314 return this.settings.images?.autoResize ?? SETTINGS_DEFAULTS.images.autoResize;
1315 }
1316
1317 setImageAutoResize(enabled: boolean): void {
1318 if (!this.globalSettings.images) {
1319 this.globalSettings.images = {};
1320 }
1321 this.globalSettings.images.autoResize = enabled;
1322 this.markModified("images", "autoResize");
1323 this.save();
1324 }
1325
1326 getBlockImages(): boolean {
1327 return this.settings.images?.blockImages ?? SETTINGS_DEFAULTS.images.blockImages;
1328 }
1329
1330 setBlockImages(blocked: boolean): void {
1331 if (!this.globalSettings.images) {
1332 this.globalSettings.images = {};
1333 }
1334 this.globalSettings.images.blockImages = blocked;
1335 this.markModified("images", "blockImages");
1336 this.save();
1337 }
1338
1339 getEnabledModels(): string[] | undefined {
1340 return this.settings.enabledModels;
1341 }
1342
1343 /** The resolved `defaultTools` selection, or undefined when no settings layer sets it. */
1344 getDefaultTools(): string[] | undefined {
1345 const tools = this.settings.defaultTools;
1346 if (tools === undefined) return undefined;
1347 return resolveDefaultTools(Array.isArray(tools) ? tools.filter((tool) => typeof tool === "string") : []);
1348 }
1349
1350 setEnabledModels(patterns: string[] | undefined): void {
1351 this.globalSettings.enabledModels = patterns;
1352 this.markModified("enabledModels");
1353 this.save();
1354 }
1355
1356 getDoubleEscapeAction(): "fork" | "tree" | "none" {
1357 return this.settings.doubleEscapeAction ?? SETTINGS_DEFAULTS.doubleEscapeAction;
1358 }
1359
1360 setDoubleEscapeAction(action: "fork" | "tree" | "none"): void {
1361 this.globalSettings.doubleEscapeAction = action;
1362 this.markModified("doubleEscapeAction");
1363 this.save();
1364 }
1365
1366 getTreeFilterMode(): "default" | "no-tools" | "user-only" | "labeled-only" | "all" {
1367 const mode = this.settings.treeFilterMode;
1368 const valid = ["default", "no-tools", "user-only", "labeled-only", "all"];
1369 return mode && valid.includes(mode) ? mode : SETTINGS_DEFAULTS.treeFilterMode;
1370 }
1371
1372 setTreeFilterMode(mode: "default" | "no-tools" | "user-only" | "labeled-only" | "all"): void {
1373 this.globalSettings.treeFilterMode = mode;
1374 this.markModified("treeFilterMode");
1375 this.save();
1376 }
1377
1378 getShowHardwareCursor(): boolean {
1379 return this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === "1";
1380 }
1381
1382 setShowHardwareCursor(enabled: boolean): void {
1383 this.globalSettings.showHardwareCursor = enabled;
1384 this.markModified("showHardwareCursor");
1385 this.save();
1386 }
1387
1388 getEditorPaddingX(): number {
1389 return this.settings.editorPaddingX ?? SETTINGS_DEFAULTS.editorPaddingX;
1390 }
1391
1392 setEditorPaddingX(padding: number): void {
1393 this.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));
1394 this.markModified("editorPaddingX");
1395 this.save();
1396 }
1397
1398 getOutputPad(): 0 | 1 {
1399 return this.settings.outputPad === 0 ? 0 : SETTINGS_DEFAULTS.outputPad;
1400 }
1401
1402 setOutputPad(padding: 0 | 1): void {
1403 this.globalSettings.outputPad = padding;
1404 this.markModified("outputPad");
1405 this.save();
1406 }
1407
1408 getAutocompleteMaxVisible(): number {
1409 return this.settings.autocompleteMaxVisible ?? SETTINGS_DEFAULTS.autocompleteMaxVisible;
1410 }
1411
1412 setAutocompleteMaxVisible(maxVisible: number): void {
1413 this.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));
1414 this.markModified("autocompleteMaxVisible");
1415 this.save();
1416 }
1417
1418 getCodeBlockIndent(): string {
1419 return this.settings.markdown?.codeBlockIndent ?? SETTINGS_DEFAULTS.markdown.codeBlockIndent;
1420 }
1421
1422 getMermaidRenderingMode(): MermaidRenderingMode {
1423 const mode = this.settings.markdown?.mermaid;
1424 return mode === "off" || mode === "final" ? mode : SETTINGS_DEFAULTS.markdown.mermaid;
1425 }
1426
1427 setMermaidRenderingMode(mode: MermaidRenderingMode): void {
1428 this.globalSettings.markdown ??= {};
1429 this.globalSettings.markdown.mermaid = mode;
1430 this.markModified("markdown", "mermaid");
1431 this.save();
1432 }
1433
1434 getWarnings(): WarningSettings {
1435 return { ...(this.settings.warnings ?? {}) };
1436 }
1437
1438 setWarnings(warnings: WarningSettings): void {
1439 this.globalSettings.warnings = { ...warnings };
1440 this.markModified("warnings");
1441 this.save();
1442 }
1443}