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