Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Duration from "effect/Duration";
3import * as Schema from "effect/Schema";
4import * as SchemaTransformation from "effect/SchemaTransformation";
5import { ForwardCompatibleNullable, TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
6import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
7import { EnvironmentMachineKind, ThreadEnvMode } from "./environment.ts";
8import {
9 DEFAULT_TEXT_GENERATION_MODEL,
10 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
11 ProviderOptionSelections,
12} from "./model.ts";
13import { ModelSelection } from "./orchestration.ts";
14import { BrowserProfile, BrowserProfileId, DEFAULT_BROWSER_PROFILE_ID } from "./browserProfile.ts";
15import {
16 DEFAULT_PREVIEW_APPEARANCE,
17 DEFAULT_PREVIEW_ZOOM_FACTOR,
18 FILL_PREVIEW_VIEWPORT,
19 PreviewAppearancePreference,
20 PreviewViewportSetting,
21 PreviewZoomFactor,
22} from "./preview.ts";
23import {
24 ProviderInstanceConfig,
25 ProviderInstanceId,
26 type ProviderDriverKind,
27} from "./providerInstance.ts";
28
29// ── Client Settings (local-only) ───────────────────────────────
30
31export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
32export type TimestampFormat = typeof TimestampFormat.Type;
33export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
34
35export const DiffLayout = Schema.Literals(["stacked", "split"]);
36export type DiffLayout = typeof DiffLayout.Type;
37export const DEFAULT_DIFF_LAYOUT: DiffLayout = "stacked";
38
39export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
40export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
41export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
42
43export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
44export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
45export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
46
47export const SidebarProjectGroupingMode = Schema.Literals([
48 "repository",
49 "repository_path",
50 "separate",
51]);
52export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
53export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
54export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;
55export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;
56export const SidebarThreadPreviewCount = Schema.Int.check(
57 Schema.isBetween({
58 minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
59 maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
60 }),
61);
62export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
63export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
64export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;
65export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;
66export const SidebarAutoSettleAfterDays = Schema.Number.check(
67 Schema.isBetween({
68 minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
69 maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
70 }),
71);
72export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
73export const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;
74export const MIN_GLASS_OPACITY = 40;
75export const MAX_GLASS_OPACITY = 100;
76export const GlassOpacity = Schema.Int.check(
77 Schema.isBetween({
78 minimum: MIN_GLASS_OPACITY,
79 maximum: MAX_GLASS_OPACITY,
80 }),
81);
82export type GlassOpacity = typeof GlassOpacity.Type;
83export const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;
84
85export const MIN_APPEARANCE_CONTRAST = 50;
86export const MAX_APPEARANCE_CONTRAST = 200;
87export const AppearanceContrast = Schema.Int.check(
88 Schema.isBetween({ minimum: MIN_APPEARANCE_CONTRAST, maximum: MAX_APPEARANCE_CONTRAST }),
89);
90export type AppearanceContrast = typeof AppearanceContrast.Type;
91export const DEFAULT_APPEARANCE_CONTRAST: AppearanceContrast = 100;
92export const MIN_PANEL_ANIMATION_DURATION_MS = 0;
93export const MAX_PANEL_ANIMATION_DURATION_MS = 400;
94export const PanelAnimationDurationMs = Schema.Int.check(
95 Schema.isBetween({
96 minimum: MIN_PANEL_ANIMATION_DURATION_MS,
97 maximum: MAX_PANEL_ANIMATION_DURATION_MS,
98 }),
99);
100export type PanelAnimationDurationMs = typeof PanelAnimationDurationMs.Type;
101export const DEFAULT_PANEL_ANIMATION_DURATION_MS: PanelAnimationDurationMs = 0;
102/**
103 * Font size preferences, in CSS pixels. The ranges are deliberately narrow:
104 * the interface size scales every rem-based dimension in the app, so the
105 * bounds keep layouts intact rather than offering unusable extremes.
106 */
107export const MIN_INTERFACE_FONT_SIZE = 12;
108export const MAX_INTERFACE_FONT_SIZE = 20;
109export const InterfaceFontSize = Schema.Int.check(
110 Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),
111);
112export type InterfaceFontSize = typeof InterfaceFontSize.Type;
113export const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;
114
115export const MIN_PROMPT_FONT_SIZE = 12;
116export const MAX_PROMPT_FONT_SIZE = 20;
117export const PromptFontSize = Schema.Int.check(
118 Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),
119);
120export type PromptFontSize = typeof PromptFontSize.Type;
121export const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;
122
123export const MIN_CODE_FONT_SIZE = 10;
124export const MAX_CODE_FONT_SIZE = 18;
125export const CodeFontSize = Schema.Int.check(
126 Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),
127);
128export type CodeFontSize = typeof CodeFontSize.Type;
129export const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;
130
131export const MIN_TERMINAL_FONT_SIZE = 8;
132export const MAX_TERMINAL_FONT_SIZE = 20;
133export const TerminalFontSize = Schema.Int.check(
134 Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),
135);
136export type TerminalFontSize = typeof TerminalFontSize.Type;
137export const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;
138
139export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill", "none"]);
140export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
141export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
142
143export const QuitConfirmationMode = Schema.Literals(["direct", "hold", "double-click"]);
144export type QuitConfirmationMode = typeof QuitConfirmationMode.Type;
145export const DEFAULT_QUIT_CONFIRMATION_MODE: QuitConfirmationMode = "hold";
146
147const LegacyConfirmQuit = Schema.Boolean.pipe(
148 Schema.decodeTo(
149 QuitConfirmationMode,
150 SchemaTransformation.transform({
151 decode: (confirmQuit): QuitConfirmationMode => (confirmQuit ? "hold" : "direct"),
152 encode: (mode) => mode === "hold",
153 }),
154 ),
155);
156
157const QuitConfirmationModeSetting = Schema.Union([QuitConfirmationMode, LegacyConfirmQuit]);
158
159/**
160 * A user-chosen font family (a single name or a comma-separated list). Empty
161 * means "use the app default"; clients compose their own fallback stacks.
162 */
163export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));
164export type FontFamilyPreference = typeof FontFamilyPreference.Type;
165
166/**
167 * The environment's theme, set with `t3 theme set <id>`. Each client applies
168 * it once per value — live when connected, on its next connect otherwise — so
169 * setting it switches every client, while a theme a user picks in Settings
170 * afterwards sticks until the next set. Empty means "no environment theme",
171 * which is also how it is cleared.
172 */
173export const DefaultThemePreference = Schema.String.check(Schema.isMaxLength(64));
174// Deliberately absent from ServerSettingsPatch: `t3 theme set` checks that an
175// id is syntactically valid and actually resolvable, and a generic RPC patch
176// would let a client write a theme no client can resolve, bypassing both.
177export type DefaultThemePreference = typeof DefaultThemePreference.Type;
178
179/**
180 * Defaults for the in-app preview browser, applied whenever a tab is opened
181 * without an explicit viewport/zoom/appearance — by the user opening a browser
182 * tab, or by an agent calling `preview_open` with no size. Recording quality is
183 * client-local for the same reason: the Chromium guest being captured belongs
184 * to the desktop app.
185 */
186export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;
187export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;
188export const BROWSER_RECORDING_FRAME_RATES = [30, 60] as const;
189export const BrowserRecordingFrameRate = Schema.Literals(BROWSER_RECORDING_FRAME_RATES);
190export type BrowserRecordingFrameRate = typeof BrowserRecordingFrameRate.Type;
191export const DEFAULT_BROWSER_RECORDING_FRAME_RATE: BrowserRecordingFrameRate = 30;
192/**
193 * Where a clicked link goes: the OS default browser, or a tab in the in-app
194 * browser beside the thread. "system" is the default because that is what
195 * every link did before the setting existed.
196 */
197export const BrowserLinkTarget = Schema.Literals(["system", "app"]);
198export type BrowserLinkTarget = typeof BrowserLinkTarget.Type;
199export const DEFAULT_BROWSER_LINK_TARGET: BrowserLinkTarget = "system";
200
201export const ClientSettingsSchema = Schema.Struct({
202 appearanceContrast: AppearanceContrast.pipe(
203 Schema.withDecodingDefault(Effect.succeed(DEFAULT_APPEARANCE_CONTRAST)),
204 ),
205 // Panel motion defaults to zero because width and height transitions cause
206 // layout work on every frame, which is noticeable on lower-power clients.
207 panelAnimationDurationMs: PanelAnimationDurationMs.pipe(
208 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PANEL_ANIMATION_DURATION_MS)),
209 ),
210 browserDefaultViewport: PreviewViewportSetting.pipe(
211 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_VIEWPORT)),
212 ),
213 browserDefaultZoomFactor: PreviewZoomFactor.pipe(
214 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_ZOOM_FACTOR)),
215 ),
216 browserDefaultAppearance: PreviewAppearancePreference.pipe(
217 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_APPEARANCE)),
218 ),
219 browserRecordingFrameRate: BrowserRecordingFrameRate.pipe(
220 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_RECORDING_FRAME_RATE)),
221 ),
222 /**
223 * Where links clicked in a thread (chat markdown, terminal output) open.
224 * Only the desktop app has an in-app browser, so other clients ignore "app".
225 */
226 browserLinkTarget: BrowserLinkTarget.pipe(
227 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_LINK_TARGET)),
228 ),
229 /**
230 * Whether an agent using a preview pops the floating mini player into
231 * view. Only applies when the agent didn't ask either way — an explicit
232 * `open`/`show` on `preview_open` still wins, since that is the agent
233 * deliberately showing or hiding its work.
234 */
235 browserAutoShowFloatingPreview: Schema.Boolean.pipe(
236 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW)),
237 ),
238 /**
239 * User-created browser profiles. The built-in Default and Incognito profiles
240 * are synthesized by `resolveBrowserProfiles`, not stored here, so they
241 * cannot be renamed away or deleted.
242 */
243 browserProfiles: Schema.Array(BrowserProfile).pipe(
244 Schema.withDecodingDefault(Effect.succeed([])),
245 ),
246 /** Profile new tabs open under. Falls back to Default if it no longer exists. */
247 browserDefaultProfileId: BrowserProfileId.pipe(
248 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_PROFILE_ID)),
249 ),
250 // Desktop-only. Boolean values from older settings files decode to their
251 // equivalent mode and encode back as the canonical string value.
252 confirmQuit: QuitConfirmationModeSetting.pipe(
253 Schema.withDecodingDefault(Effect.succeed(DEFAULT_QUIT_CONFIRMATION_MODE)),
254 ),
255 confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
256 confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
257 confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
258 continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
259 Schema.withDecodingDefault(Effect.succeed(false)),
260 ),
261 dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
262 Schema.withDecodingDefault(Effect.succeed([])),
263 ),
264 diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
265 diffLayout: DiffLayout.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_DIFF_LAYOUT))),
266 environmentIdentificationMode: EnvironmentIdentificationMode.pipe(
267 Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),
268 ),
269 glassOpacity: GlassOpacity.pipe(
270 Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
271 ),
272 fontSizeInterface: InterfaceFontSize.pipe(
273 Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),
274 ),
275 fontSizePrompt: PromptFontSize.pipe(
276 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),
277 ),
278 fontSizeCode: CodeFontSize.pipe(
279 Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),
280 ),
281 fontSizeTerminal: TerminalFontSize.pipe(
282 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),
283 ),
284 fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
285 fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
286 fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
287 fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
288 // Grayscale `-webkit-font-smoothing: antialiased` (thinner strokes);
289 // disabling restores the platform's heavier default. No effect off macOS.
290 fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
291 // Model favorites. Historically keyed by provider kind, now
292 // widened to `ProviderInstanceId` so users can favorite a specific model
293 // on a custom provider instance (e.g. "Codex Personal · gpt-5") without
294 // the UI collapsing it into the same bucket as the default Codex. The
295 // widening is backward-compatible by construction: prior provider-kind
296 // strings satisfy the `ProviderInstanceId` slug schema, so previously
297 // persisted favorites decode unchanged and continue to point at the
298 // default instance for their kind (because `defaultInstanceIdForDriver(kind)`
299 // uses the same slug). The field name is kept as `provider` for storage
300 // stability; new call sites should treat the value as an instance id.
301 favorites: Schema.Array(
302 Schema.Struct({
303 provider: ProviderInstanceId,
304 model: TrimmedNonEmptyString,
305 }),
306 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
307 providerModelPreferences: Schema.Record(
308 ProviderInstanceId,
309 Schema.Struct({
310 hiddenModels: Schema.Array(Schema.String).pipe(
311 Schema.withDecodingDefault(Effect.succeed([])),
312 ),
313 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
314 }),
315 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
316 // Legacy plan mode. The composer's Build/Plan toggle was removed from the
317 // default UI; this beta flag restores it (plus the /plan and /default slash
318 // commands) for users who still rely on the old workflow.
319 planModeEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
320 // Legacy context window meter. The composer hides it by default; users who
321 // still want the old usage indicator can restore it from Settings.
322 contextWindowMeterEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
323 // Desktop resting composer. Each trigger that settles an existing thread's
324 // composer into its single-line layout can be turned off on its own.
325 composerCollapseOnBlur: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
326 composerCollapseOnScroll: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
327 proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
328 showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
329 // Legacy sidebar (the original per-project tree). Deliberately a fresh key
330 // (was `sidebarV2Enabled` + `sidebarV2ConfiguredByUser`): decoding drops the
331 // old keys, so everyone, including prior beta opt-outs, resets to the new
332 // default sidebar.
333 legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
334 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
335 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
336 ),
337 sidebarProjectGroupingOverrides: Schema.Record(
338 TrimmedNonEmptyString,
339 SidebarProjectGroupingMode,
340 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
341 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
342 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
343 ),
344 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
345 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
346 ),
347 sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(
348 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),
349 ),
350 timestampFormat: TimestampFormat.pipe(
351 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
352 ),
353 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
354});
355export type ClientSettings = typeof ClientSettingsSchema.Type;
356
357export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
358
359// ── Server Settings (server-authoritative) ────────────────────
360
361const makeBinaryPathSetting = (fallback: string) =>
362 TrimmedString.pipe(
363 Schema.decodeTo(
364 Schema.String,
365 SchemaTransformation.transformOrFail({
366 decode: (value) => Effect.succeed(value || fallback),
367 encode: (value) => Effect.succeed(value),
368 }),
369 ),
370 Schema.withDecodingDefault(Effect.succeed(fallback)),
371 );
372
373export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch" | "select";
374
375export interface ProviderSettingsFormOption {
376 readonly value: string;
377 readonly label: string;
378}
379
380export interface ProviderSettingsFormAnnotation {
381 readonly control?: ProviderSettingsFormControl | undefined;
382 readonly placeholder?: string | undefined;
383 readonly hidden?: boolean | undefined;
384 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
385 /** Choices for a `select` control. The first entry is the default. */
386 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
387}
388
389export interface ProviderSettingsFormSchemaAnnotation {
390 readonly order?: readonly string[] | undefined;
391}
392
393declare module "effect/Schema" {
394 namespace Annotations {
395 interface Annotations {
396 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
397 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
398 }
399 }
400}
401
402export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
403 keyof Fields,
404 string
405>[];
406
407export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
408 fields: Fields,
409 options?: {
410 readonly order?: ProviderSettingsOrder<Fields> | undefined;
411 },
412): Schema.Struct<Fields> {
413 return Schema.Struct(fields).pipe(
414 Schema.annotate({
415 providerSettingsFormSchema:
416 options?.order === undefined ? undefined : { order: options.order },
417 }),
418 );
419}
420
421export const CodexSettings = makeProviderSettingsSchema(
422 {
423 enabled: Schema.Boolean.pipe(
424 Schema.withDecodingDefault(Effect.succeed(true)),
425 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
426 ),
427 binaryPath: makeBinaryPathSetting("codex").pipe(
428 Schema.annotateKey({
429 title: "Binary path",
430 description: "Path to the Codex binary used by this instance.",
431 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
432 }),
433 ),
434 homePath: TrimmedString.pipe(
435 Schema.withDecodingDefault(Effect.succeed("")),
436 Schema.annotateKey({
437 title: "CODEX_HOME path",
438 description: "Custom Codex home and config directory.",
439 providerSettingsForm: {
440 placeholder: "~/.codex",
441 clearWhenEmpty: "omit",
442 },
443 }),
444 ),
445 shadowHomePath: TrimmedString.pipe(
446 Schema.withDecodingDefault(Effect.succeed("")),
447 Schema.annotateKey({
448 title: "Shadow home path",
449 description:
450 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
451 providerSettingsForm: {
452 placeholder: "~/.codex-t3/personal",
453 clearWhenEmpty: "omit",
454 },
455 }),
456 ),
457 launchArgs: TrimmedString.pipe(
458 Schema.withDecodingDefault(Effect.succeed("")),
459 Schema.annotateKey({
460 title: "Launch arguments",
461 description: "Additional CLI arguments passed to codex app-server on session start.",
462 }),
463 ),
464 customModels: Schema.Array(Schema.String).pipe(
465 Schema.withDecodingDefault(Effect.succeed([])),
466 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
467 ),
468 },
469 {
470 order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
471 },
472);
473export type CodexSettings = typeof CodexSettings.Type;
474
475// Empty, or an integer from 100,000 to 1,000,000. Shared by the full
476// Claude settings schema and its patch so an out-of-range value fails at
477// the update that introduced it.
478const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
479
480export const ClaudeSettings = makeProviderSettingsSchema(
481 {
482 enabled: Schema.Boolean.pipe(
483 Schema.withDecodingDefault(Effect.succeed(true)),
484 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
485 ),
486 binaryPath: makeBinaryPathSetting("claude").pipe(
487 Schema.annotateKey({
488 title: "Binary path",
489 description: "Path to the Claude binary used by this instance.",
490 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
491 }),
492 ),
493 homePath: TrimmedString.pipe(
494 Schema.withDecodingDefault(Effect.succeed("")),
495 Schema.annotateKey({
496 title: "CLAUDE_CONFIG_DIR path",
497 description:
498 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
499 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
500 }),
501 ),
502 customModels: Schema.Array(Schema.String).pipe(
503 Schema.withDecodingDefault(Effect.succeed([])),
504 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
505 ),
506 launchArgs: Schema.String.pipe(
507 Schema.withDecodingDefault(Effect.succeed("")),
508 Schema.annotateKey({
509 title: "Launch arguments",
510 description: "Additional CLI arguments passed on session start.",
511 providerSettingsForm: {
512 placeholder: "e.g. --chrome",
513 clearWhenEmpty: "omit",
514 },
515 }),
516 ),
517 autoCompactWindow: TrimmedString.check(
518 Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN),
519 ).pipe(
520 Schema.withDecodingDefault(Effect.succeed("")),
521 Schema.annotateKey({
522 title: "Auto-compact after",
523 description:
524 "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
525 providerSettingsForm: {
526 placeholder: "e.g. 300000",
527 clearWhenEmpty: "omit",
528 },
529 }),
530 ),
531 },
532 {
533 order: ["binaryPath", "homePath", "autoCompactWindow", "launchArgs"],
534 },
535);
536export type ClaudeSettings = typeof ClaudeSettings.Type;
537
538export const CursorSettings = makeProviderSettingsSchema(
539 {
540 // Off by default like Grok and OpenCode. Users opt in from Settings.
541 enabled: Schema.Boolean.pipe(
542 Schema.withDecodingDefault(Effect.succeed(false)),
543 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
544 ),
545 binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
546 Schema.annotateKey({
547 title: "Binary path",
548 description: "Path to the Cursor agent binary.",
549 providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
550 }),
551 ),
552 apiEndpoint: TrimmedString.pipe(
553 Schema.withDecodingDefault(Effect.succeed("")),
554 Schema.annotateKey({
555 title: "API endpoint",
556 description: "Override the Cursor API endpoint for this instance.",
557 providerSettingsForm: {
558 placeholder: "https://...",
559 clearWhenEmpty: "omit",
560 },
561 }),
562 ),
563 customModels: Schema.Array(Schema.String).pipe(
564 Schema.withDecodingDefault(Effect.succeed([])),
565 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
566 ),
567 },
568 {
569 order: ["binaryPath", "apiEndpoint"],
570 },
571);
572export type CursorSettings = typeof CursorSettings.Type;
573
574export const GrokSettings = makeProviderSettingsSchema(
575 {
576 // Off by default (like Cursor and OpenCode): the binding is not yet
577 // stable enough to probe on every install. Users opt in from Settings.
578 enabled: Schema.Boolean.pipe(
579 Schema.withDecodingDefault(Effect.succeed(false)),
580 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
581 ),
582 binaryPath: makeBinaryPathSetting("grok").pipe(
583 Schema.annotateKey({
584 title: "Binary path",
585 description: "Path to the Grok CLI binary.",
586 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
587 }),
588 ),
589 customModels: Schema.Array(Schema.String).pipe(
590 Schema.withDecodingDefault(Effect.succeed([])),
591 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
592 ),
593 },
594 {
595 order: ["binaryPath"],
596 },
597);
598export type GrokSettings = typeof GrokSettings.Type;
599
600/**
601 * Antigravity ACP auth methods. Personal and Enterprise open a Google sign-in
602 * in the browser. The API key and Agent Platform methods take credentials from
603 * the instance config and never open a browser.
604 */
605export const ANTIGRAVITY_AUTH_METHODS = [
606 { value: "oauth-personal", label: "Google account" },
607 { value: "oauth-business", label: "Gemini Enterprise" },
608 { value: "gemini-api-key", label: "Gemini API key" },
609 { value: "agent-platform", label: "Agent Platform (Vertex AI)" },
610] as const satisfies ReadonlyArray<ProviderSettingsFormOption>;
611export const AntigravityAuthMethod = Schema.Literals(
612 ANTIGRAVITY_AUTH_METHODS.map((method) => method.value),
613);
614export type AntigravityAuthMethod = typeof AntigravityAuthMethod.Type;
615
616export const AntigravitySettings = makeProviderSettingsSchema(
617 {
618 enabled: Schema.Boolean.pipe(
619 Schema.withDecodingDefault(Effect.succeed(false)),
620 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
621 ),
622 authMethod: AntigravityAuthMethod.pipe(
623 Schema.withDecodingDefault(Effect.succeed("oauth-personal" as const)),
624 Schema.annotateKey({
625 title: "Sign-in method",
626 description:
627 "Google account uses your Antigravity subscription. Gemini Enterprise needs a GCP project and location. API key and Agent Platform bill the credential you enter.",
628 providerSettingsForm: {
629 control: "select",
630 options: ANTIGRAVITY_AUTH_METHODS,
631 clearWhenEmpty: "omit",
632 },
633 }),
634 ),
635 apiKey: TrimmedString.pipe(
636 Schema.withDecodingDefault(Effect.succeed("")),
637 Schema.annotateKey({
638 title: "API key",
639 description:
640 "Gemini API key, or a Vertex AI express key for Agent Platform. Stored in plain text on this environment.",
641 providerSettingsForm: {
642 control: "password",
643 placeholder: "Optional",
644 clearWhenEmpty: "omit",
645 },
646 }),
647 ),
648 gcpProject: TrimmedString.pipe(
649 Schema.withDecodingDefault(Effect.succeed("")),
650 Schema.annotateKey({
651 title: "GCP project",
652 description:
653 "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
654 providerSettingsForm: { placeholder: "my-project-id", clearWhenEmpty: "omit" },
655 }),
656 ),
657 gcpLocation: TrimmedString.pipe(
658 Schema.withDecodingDefault(Effect.succeed("")),
659 Schema.annotateKey({
660 title: "GCP location",
661 description: "Region for Gemini Enterprise or Agent Platform, such as us-central1.",
662 providerSettingsForm: { placeholder: "us-central1", clearWhenEmpty: "omit" },
663 }),
664 ),
665 binaryPath: TrimmedString.pipe(
666 Schema.withDecodingDefault(Effect.succeed("")),
667 Schema.annotateKey({
668 title: "Binary path",
669 description:
670 "Optional path to the official Antigravity ACP executable. Leave empty for automatic selection.",
671 providerSettingsForm: { placeholder: "Automatic", clearWhenEmpty: "persist" },
672 }),
673 ),
674 customModels: Schema.Array(Schema.String).pipe(
675 Schema.withDecodingDefault(Effect.succeed([])),
676 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
677 ),
678 },
679 { order: ["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"] },
680);
681export type AntigravitySettings = typeof AntigravitySettings.Type;
682
683export const OpenCodeSettings = makeProviderSettingsSchema(
684 {
685 // Off by default (like Cursor and Grok): the binding is not yet stable
686 // enough to probe on every install. Users opt in from Settings.
687 enabled: Schema.Boolean.pipe(
688 Schema.withDecodingDefault(Effect.succeed(false)),
689 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
690 ),
691 binaryPath: makeBinaryPathSetting("opencode").pipe(
692 Schema.annotateKey({
693 title: "Binary path",
694 description: "Path to the OpenCode binary.",
695 providerSettingsForm: {
696 placeholder: "opencode",
697 clearWhenEmpty: "omit",
698 },
699 }),
700 ),
701 serverUrl: TrimmedString.pipe(
702 Schema.withDecodingDefault(Effect.succeed("")),
703 Schema.annotateKey({
704 title: "Server URL",
705 description: "Leave blank to let T3 Code spawn the server when needed.",
706 providerSettingsForm: {
707 placeholder: "http://127.0.0.1:4096",
708 clearWhenEmpty: "omit",
709 },
710 }),
711 ),
712 serverPassword: TrimmedString.pipe(
713 Schema.withDecodingDefault(Effect.succeed("")),
714 Schema.annotateKey({
715 title: "Server password",
716 description: "Stored in plain text on disk.",
717 providerSettingsForm: {
718 control: "password",
719 placeholder: "Optional",
720 clearWhenEmpty: "omit",
721 },
722 }),
723 ),
724 customModels: Schema.Array(Schema.String).pipe(
725 Schema.withDecodingDefault(Effect.succeed([])),
726 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
727 ),
728 },
729 {
730 order: ["binaryPath", "serverUrl", "serverPassword"],
731 },
732);
733export type OpenCodeSettings = typeof OpenCodeSettings.Type;
734
735/**
736 * A read-only quota source outside this environment's provider CLIs. The
737 * only kind today is a CLIProxyAPI hub, whose management API reports the
738 * windows of every pooled account. The key travels in settings for now, like
739 * provider environment secrets; it is redacted before reaching a client.
740 */
741export const UsageLimitSourceConfig = Schema.Struct({
742 kind: Schema.Literal("cliproxy"),
743 label: Schema.optional(TrimmedNonEmptyString),
744 url: TrimmedNonEmptyString,
745 managementKey: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
746 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
747});
748export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;
749
750export const ObservabilitySettings = Schema.Struct({
751 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
752 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
753});
754export type ObservabilitySettings = typeof ObservabilitySettings.Type;
755
756export const SourceControlWritingStyleMode = Schema.Literals([
757 "repo_conventions",
758 "conventional_commits",
759 "custom",
760]);
761export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
762
763export const SourceControlWritingStyleSettings = Schema.Struct({
764 mode: SourceControlWritingStyleMode.pipe(
765 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
766 ),
767 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
768 followChangeRequestTemplates: Schema.Boolean.pipe(
769 Schema.withDecodingDefault(Effect.succeed(true)),
770 ),
771});
772export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
773
774export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
775export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
776
777export const BackgroundActivityProfile = Schema.Literals([
778 "balanced",
779 "performance",
780 "battery-saver",
781]);
782export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
783export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
784
785export const BackgroundActivityProfileSelection = Schema.Literals([
786 "balanced",
787 "performance",
788 "battery-saver",
789 "custom",
790]);
791export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
792
793export const BackgroundActivityOverrides = Schema.Struct({
794 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
795 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
796 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
797 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
798 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
799 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
800 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
801 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
802 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
803});
804export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
805
806export const BackgroundActivitySettings = Schema.Struct({
807 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
808 profile: BackgroundActivityProfileSelection.pipe(
809 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
810 ),
811 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
812 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
813}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
814export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
815
816export const ServerSettings = Schema.Struct({
817 // Legacy token-by-token assistant output. Deliberately a fresh key (was
818 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
819 // including prior opt-ins, resets to the buffered default.
820 enableLegacyTokenStreaming: Schema.Boolean.pipe(
821 Schema.withDecodingDefault(Effect.succeed(false)),
822 ),
823 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
824 /**
825 * Whether agents may drive the in-app preview browser. Turning this off
826 * withholds the MCP credential, so the `t3-code` server (and with it every
827 * `preview_*` tool) is never attached to a provider session, and the prompt
828 * text describing those tools is dropped along with them. The user's own
829 * browser panel is unaffected — this gates agent access only.
830 *
831 * Server-authoritative rather than client-local: tool injection and prompt
832 * construction both happen on the server, and the answer must not differ
833 * between a desktop window and a phone attached to the same server.
834 */
835 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
836 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
837 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
838 ),
839 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
840 backgroundActivity: BackgroundActivitySettings,
841 // Legacy flat fields retained for old settings files and old clients. New
842 // consumers should resolve `backgroundActivity` instead.
843 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
844 Schema.withDecodingDefault(
845 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
846 ),
847 ),
848 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
849 Schema.withDecodingDefault(
850 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
851 ),
852 ),
853 backgroundActivityProfile: BackgroundActivityProfile.pipe(
854 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
855 ),
856 defaultTheme: DefaultThemePreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
857 /**
858 * When the environment's theme was last set, so clients can tell a re-set
859 * of the same value from one they already applied: `t3 theme set` must act
860 * even when it names the theme it named before. Empty on environments
861 * provisioned by builds that predate it, where clients fall back to
862 * applying once per value.
863 */
864 defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
865 Schema.withDecodingDefault(Effect.succeed("")),
866 ),
867 /**
868 * The icon clients draw for this environment. Null means "use what the
869 * server detected" (`environment.platform.machine`), falling back to a
870 * generic server. Lives on the server, not the client, so every device
871 * sees the same machine. A kind picked on a newer server decodes as null
872 * here rather than failing the whole settings snapshot for an older client.
873 */
874 environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
875 Schema.withDecodingDefault(Effect.succeed(null)),
876 ),
877 defaultThreadEnvMode: ThreadEnvMode.pipe(
878 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
879 ),
880 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
881 Schema.withDecodingDefault(Effect.succeed(true)),
882 ),
883 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
884 textGenerationModelSelection: ModelSelection.pipe(
885 Schema.withDecodingDefault(
886 Effect.succeed({
887 instanceId: ProviderInstanceId.make("codex"),
888 model: DEFAULT_TEXT_GENERATION_MODEL,
889 options: [
890 {
891 id: "reasoningEffort",
892 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
893 },
894 ],
895 }),
896 ),
897 ),
898 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
899 Schema.withDecodingDefault(Effect.succeed({})),
900 ),
901 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
902 Schema.withDecodingDefault(Effect.succeed(null)),
903 ),
904
905 // Legacy single-instance-per-driver settings. Continues to be the source
906 // of truth until `providerInstances` (below) lands per-driver migration
907 // shims and the server starts hydrating instances from it. Driver-specific
908 // schemas live here for the duration of the migration; once each driver
909 // owns its config in its own package, this struct shrinks to nothing and
910 // is removed entirely.
911 providers: Schema.Struct({
912 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
913 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
914 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
915 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
916 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
917 antigravity: AntigravitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
918 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
919 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
920 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
921 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
922 // (forks, downgrades, in-flight PR branches) round-trip without loss.
923 // See providerInstance.ts for the forward/backward compatibility invariant.
924 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
925 Schema.withDecodingDefault(Effect.succeed({})),
926 ),
927 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
928 // Keyed by a user-chosen id so a source keeps its rows across edits. Entries
929 // this build cannot decode round-trip untouched, as provider instances do.
930 usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(
931 Schema.withDecodingDefault(Effect.succeed({})),
932 ),
933});
934export type ServerSettings = typeof ServerSettings.Type;
935
936export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
937
938/**
939 * Read the legacy `enabled` flag embedded in a provider instance config
940 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
941 * flag going forward; this reader exists for legacy `providers.<kind>`
942 * blobs and old settings files that still carry the flag in-config.
943 */
944export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
945 if (config === null || typeof config !== "object" || Array.isArray(config)) {
946 return undefined;
947 }
948 const enabled = (config as { readonly enabled?: unknown }).enabled;
949 return typeof enabled === "boolean" ? enabled : undefined;
950};
951
952/**
953 * Default enabled state for a built-in driver when neither the envelope nor
954 * the config blob carries a flag. Derived from the driver's settings schema
955 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
956 * the single source of truth. Unknown (fork) drivers default to enabled.
957 */
958export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
959 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
960 string,
961 { readonly enabled?: boolean } | undefined
962 >;
963 return legacyDefaults[driver]?.enabled ?? true;
964};
965
966/**
967 * Resolve whether a configured provider instance is enabled. An explicit
968 * false on either the envelope or the in-config flag wins (most
969 * restrictive), so a user's disable is never silently undone by the other
970 * flag. Otherwise: envelope, then config, then the driver's default.
971 */
972export const resolveProviderInstanceEnabled = (
973 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
974): boolean => {
975 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
976 if (instance.enabled === false || configEnabled === false) {
977 return false;
978 }
979 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
980};
981
982export const ServerSettingsOperation = Schema.Literals([
983 "normalize",
984 "check-exists",
985 "read-file",
986 "read-provider-history",
987 "read-secret",
988 "remove-secret",
989 "remove-stale-secret",
990 "write-secret",
991 "write-file",
992 "prepare-directory",
993]);
994export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
995
996export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
997 "ServerSettingsError",
998 {
999 settingsPath: Schema.String,
1000 operation: ServerSettingsOperation,
1001 providerInstanceId: Schema.optional(Schema.String),
1002 environmentVariable: Schema.optional(Schema.String),
1003 cause: Schema.Defect(),
1004 },
1005) {
1006 override get message(): string {
1007 const provider =
1008 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
1009 const variable =
1010 this.environmentVariable === undefined
1011 ? ""
1012 : ` and environment variable ${this.environmentVariable}`;
1013 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
1014 }
1015}
1016
1017// ── Unified type ─────────────────────────────────────────────────────
1018
1019export type UnifiedSettings = ServerSettings & ClientSettings;
1020export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
1021 ...DEFAULT_SERVER_SETTINGS,
1022 ...DEFAULT_CLIENT_SETTINGS,
1023};
1024
1025// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
1026
1027const ModelSelectionPatch = Schema.Struct({
1028 instanceId: Schema.optionalKey(ProviderInstanceId),
1029 model: Schema.optionalKey(TrimmedNonEmptyString),
1030 options: Schema.optionalKey(ProviderOptionSelections),
1031});
1032
1033const CodexSettingsPatch = Schema.Struct({
1034 enabled: Schema.optionalKey(Schema.Boolean),
1035 binaryPath: Schema.optionalKey(TrimmedString),
1036 homePath: Schema.optionalKey(TrimmedString),
1037 shadowHomePath: Schema.optionalKey(TrimmedString),
1038 launchArgs: Schema.optionalKey(TrimmedString),
1039 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1040});
1041
1042const ClaudeSettingsPatch = Schema.Struct({
1043 enabled: Schema.optionalKey(Schema.Boolean),
1044 binaryPath: Schema.optionalKey(TrimmedString),
1045 homePath: Schema.optionalKey(TrimmedString),
1046 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1047 launchArgs: Schema.optionalKey(TrimmedString),
1048 // Validated at the patch boundary so a typo fails the one update with a
1049 // schema error instead of a generic whole-settings failure.
1050 autoCompactWindow: Schema.optionalKey(
1051 TrimmedString.check(Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN)),
1052 ),
1053});
1054
1055const CursorSettingsPatch = Schema.Struct({
1056 enabled: Schema.optionalKey(Schema.Boolean),
1057 binaryPath: Schema.optionalKey(TrimmedString),
1058 apiEndpoint: Schema.optionalKey(TrimmedString),
1059 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1060});
1061
1062const GrokSettingsPatch = Schema.Struct({
1063 enabled: Schema.optionalKey(Schema.Boolean),
1064 binaryPath: Schema.optionalKey(TrimmedString),
1065 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1066});
1067
1068const AntigravitySettingsPatch = Schema.Struct({
1069 enabled: Schema.optionalKey(Schema.Boolean),
1070 authMethod: Schema.optionalKey(AntigravityAuthMethod),
1071 apiKey: Schema.optionalKey(TrimmedString),
1072 gcpProject: Schema.optionalKey(TrimmedString),
1073 gcpLocation: Schema.optionalKey(TrimmedString),
1074 binaryPath: Schema.optionalKey(TrimmedString),
1075 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1076});
1077
1078const OpenCodeSettingsPatch = Schema.Struct({
1079 enabled: Schema.optionalKey(Schema.Boolean),
1080 binaryPath: Schema.optionalKey(TrimmedString),
1081 serverUrl: Schema.optionalKey(TrimmedString),
1082 serverPassword: Schema.optionalKey(TrimmedString),
1083 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1084});
1085
1086export const ServerSettingsPatch = Schema.Struct({
1087 // Server settings
1088 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
1089 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1090 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1091 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1092 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1093 backgroundActivity: Schema.optionalKey(
1094 Schema.Struct({
1095 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
1096 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
1097 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
1098 overrides: Schema.optionalKey(BackgroundActivityOverrides),
1099 }),
1100 ),
1101 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1102 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1103 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
1104 environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
1105 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
1106 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1107 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
1108 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
1109 sourceControlWritingStyle: Schema.optionalKey(
1110 Schema.Struct({
1111 mode: Schema.optionalKey(SourceControlWritingStyleMode),
1112 customInstructions: Schema.optionalKey(TrimmedString),
1113 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
1114 }),
1115 ),
1116 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1117 observability: Schema.optionalKey(
1118 Schema.Struct({
1119 otlpTracesUrl: Schema.optionalKey(TrimmedString),
1120 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
1121 }),
1122 ),
1123 providers: Schema.optionalKey(
1124 Schema.Struct({
1125 codex: Schema.optionalKey(CodexSettingsPatch),
1126 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
1127 cursor: Schema.optionalKey(CursorSettingsPatch),
1128 grok: Schema.optionalKey(GrokSettingsPatch),
1129 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
1130 antigravity: Schema.optionalKey(AntigravitySettingsPatch),
1131 }),
1132 ),
1133 // Whole-map replacement for the new instance config. Patching individual
1134 // entries is intentionally out of scope: the map is small, and partial
1135 // patches risk leaving driver-specific config in a half-merged state.
1136 // The web UI sends a fully-formed map every time it edits this field.
1137 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
1138 // Per-entry, unlike `providerInstances`: a client only ever adds or removes
1139 // one source, and sending the whole map races another edit that has not
1140 // echoed back yet. `null` removes; the server merges into its current map.
1141 usageLimitSources: Schema.optionalKey(
1142 Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),
1143 ),
1144});
1145export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
1146
1147export const ClientSettingsPatch = Schema.Struct({
1148 appearanceContrast: Schema.optionalKey(AppearanceContrast),
1149 panelAnimationDurationMs: Schema.optionalKey(PanelAnimationDurationMs),
1150 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
1151 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
1152 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
1153 browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
1154 browserLinkTarget: Schema.optionalKey(BrowserLinkTarget),
1155 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
1156 browserProfiles: Schema.optionalKey(Schema.Array(BrowserProfile)),
1157 browserDefaultProfileId: Schema.optionalKey(BrowserProfileId),
1158 confirmQuit: Schema.optionalKey(QuitConfirmationMode),
1159 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
1160 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
1161 confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
1162 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1163 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
1164 diffLayout: Schema.optionalKey(DiffLayout),
1165 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
1166 glassOpacity: Schema.optionalKey(GlassOpacity),
1167 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
1168 fontSizePrompt: Schema.optionalKey(PromptFontSize),
1169 fontSizeCode: Schema.optionalKey(CodeFontSize),
1170 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
1171 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
1172 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
1173 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
1174 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
1175 fontSmoothing: Schema.optionalKey(Schema.Boolean),
1176 favorites: Schema.optionalKey(
1177 Schema.Array(
1178 Schema.Struct({
1179 provider: ProviderInstanceId,
1180 model: TrimmedNonEmptyString,
1181 }),
1182 ),
1183 ),
1184 providerModelPreferences: Schema.optionalKey(
1185 Schema.Record(
1186 ProviderInstanceId,
1187 Schema.Struct({
1188 hiddenModels: Schema.Array(Schema.String).pipe(
1189 Schema.withDecodingDefault(Effect.succeed([])),
1190 ),
1191 modelOrder: Schema.Array(Schema.String).pipe(
1192 Schema.withDecodingDefault(Effect.succeed([])),
1193 ),
1194 }),
1195 ),
1196 ),
1197 planModeEnabled: Schema.optionalKey(Schema.Boolean),
1198 contextWindowMeterEnabled: Schema.optionalKey(Schema.Boolean),
1199 composerCollapseOnBlur: Schema.optionalKey(Schema.Boolean),
1200 composerCollapseOnScroll: Schema.optionalKey(Schema.Boolean),
1201 proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean),
1202 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
1203 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
1204 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
1205 sidebarProjectGroupingOverrides: Schema.optionalKey(
1206 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
1207 ),
1208 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
1209 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
1210 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
1211 timestampFormat: Schema.optionalKey(TimestampFormat),
1212 wordWrap: Schema.optionalKey(Schema.Boolean),
1213});
1214export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;