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 "./orchestration.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 // Model favorites. Historically keyed by provider kind, now
290 // widened to `ProviderInstanceId` so users can favorite a specific model
291 // on a custom provider instance (e.g. "Codex Personal · gpt-5") without
292 // the UI collapsing it into the same bucket as the default Codex. The
293 // widening is backward-compatible by construction: prior provider-kind
294 // strings satisfy the `ProviderInstanceId` slug schema, so previously
295 // persisted favorites decode unchanged and continue to point at the
296 // default instance for their kind (because `defaultInstanceIdForDriver(kind)`
297 // uses the same slug). The field name is kept as `provider` for storage
298 // stability; new call sites should treat the value as an instance id.
299 favorites: Schema.Array(
300 Schema.Struct({
301 provider: ProviderInstanceId,
302 model: TrimmedNonEmptyString,
303 }),
304 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
305 providerModelPreferences: Schema.Record(
306 ProviderInstanceId,
307 Schema.Struct({
308 hiddenModels: Schema.Array(Schema.String).pipe(
309 Schema.withDecodingDefault(Effect.succeed([])),
310 ),
311 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
312 }),
313 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
314 // Legacy plan mode. The composer's Build/Plan toggle was removed from the
315 // default UI; this beta flag restores it (plus the /plan and /default slash
316 // commands) for users who still rely on the old workflow.
317 planModeEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
318 // Legacy context window meter. The composer hides it by default; users who
319 // still want the old usage indicator can restore it from Settings.
320 contextWindowMeterEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
321 // Desktop resting composer. Each trigger that settles an existing thread's
322 // composer into its single-line layout can be turned off on its own.
323 composerCollapseOnBlur: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
324 composerCollapseOnScroll: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
325 proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
326 showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
327 // Legacy sidebar (the original per-project tree). Deliberately a fresh key
328 // (was `sidebarV2Enabled` + `sidebarV2ConfiguredByUser`): decoding drops the
329 // old keys, so everyone, including prior beta opt-outs, resets to the new
330 // default sidebar.
331 legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
332 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
333 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
334 ),
335 sidebarProjectGroupingOverrides: Schema.Record(
336 TrimmedNonEmptyString,
337 SidebarProjectGroupingMode,
338 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
339 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
340 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
341 ),
342 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
343 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
344 ),
345 sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(
346 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),
347 ),
348 timestampFormat: TimestampFormat.pipe(
349 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
350 ),
351 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
352});
353export type ClientSettings = typeof ClientSettingsSchema.Type;
354
355export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
356
357// ── Server Settings (server-authoritative) ────────────────────
358
359const UsageModelTokenPrice = Schema.Number.check(
360 Schema.isFinite(),
361 Schema.isGreaterThanOrEqualTo(0),
362);
363
364/** USD per million tokens. Omitted cache rates use the input rate. */
365export const UsageModelPriceOverride = Schema.Struct({
366 inputCostPerMillionTokens: UsageModelTokenPrice,
367 outputCostPerMillionTokens: UsageModelTokenPrice,
368 cacheReadCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),
369 cacheWriteCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),
370});
371export type UsageModelPriceOverride = typeof UsageModelPriceOverride.Type;
372
373const makeBinaryPathSetting = (fallback: string) =>
374 TrimmedString.pipe(
375 Schema.decodeTo(
376 Schema.String,
377 SchemaTransformation.transformOrFail({
378 decode: (value) => Effect.succeed(value || fallback),
379 encode: (value) => Effect.succeed(value),
380 }),
381 ),
382 Schema.withDecodingDefault(Effect.succeed(fallback)),
383 );
384
385export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch" | "select";
386
387export interface ProviderSettingsFormOption {
388 readonly value: string;
389 readonly label: string;
390}
391
392export interface ProviderSettingsFormAnnotation {
393 readonly control?: ProviderSettingsFormControl | undefined;
394 readonly placeholder?: string | undefined;
395 readonly hidden?: boolean | undefined;
396 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
397 /** Choices for a `select` control. The first entry is the default. */
398 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
399}
400
401export interface ProviderSettingsFormSchemaAnnotation {
402 readonly order?: readonly string[] | undefined;
403}
404
405declare module "effect/Schema" {
406 namespace Annotations {
407 interface Annotations {
408 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
409 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
410 }
411 }
412}
413
414export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
415 keyof Fields,
416 string
417>[];
418
419export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
420 fields: Fields,
421 options?: {
422 readonly order?: ProviderSettingsOrder<Fields> | undefined;
423 },
424): Schema.Struct<Fields> {
425 return Schema.Struct(fields).pipe(
426 Schema.annotate({
427 providerSettingsFormSchema:
428 options?.order === undefined ? undefined : { order: options.order },
429 }),
430 );
431}
432
433export const CodexSettings = makeProviderSettingsSchema(
434 {
435 enabled: Schema.Boolean.pipe(
436 Schema.withDecodingDefault(Effect.succeed(true)),
437 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
438 ),
439 binaryPath: makeBinaryPathSetting("codex").pipe(
440 Schema.annotateKey({
441 title: "Binary path",
442 description: "Path to the Codex binary used by this instance.",
443 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
444 }),
445 ),
446 homePath: TrimmedString.pipe(
447 Schema.withDecodingDefault(Effect.succeed("")),
448 Schema.annotateKey({
449 title: "CODEX_HOME path",
450 description: "Custom Codex home and config directory.",
451 providerSettingsForm: {
452 placeholder: "~/.codex",
453 clearWhenEmpty: "omit",
454 },
455 }),
456 ),
457 shadowHomePath: TrimmedString.pipe(
458 Schema.withDecodingDefault(Effect.succeed("")),
459 Schema.annotateKey({
460 title: "Shadow home path",
461 description:
462 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
463 providerSettingsForm: {
464 placeholder: "~/.codex-t3/personal",
465 clearWhenEmpty: "omit",
466 },
467 }),
468 ),
469 launchArgs: TrimmedString.pipe(
470 Schema.withDecodingDefault(Effect.succeed("")),
471 Schema.annotateKey({
472 title: "Launch arguments",
473 description: "Additional CLI arguments passed to codex app-server on session start.",
474 }),
475 ),
476 customModels: Schema.Array(CustomModelSetting).pipe(
477 Schema.withDecodingDefault(Effect.succeed([])),
478 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
479 ),
480 },
481 {
482 order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
483 },
484);
485export type CodexSettings = typeof CodexSettings.Type;
486
487// Empty, or an integer from 100,000 to 1,000,000. Shared by the full
488// Claude settings schema and its patch so an out-of-range value fails at
489// the update that introduced it.
490const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
491
492export const ClaudeSettings = makeProviderSettingsSchema(
493 {
494 enabled: Schema.Boolean.pipe(
495 Schema.withDecodingDefault(Effect.succeed(true)),
496 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
497 ),
498 binaryPath: makeBinaryPathSetting("claude").pipe(
499 Schema.annotateKey({
500 title: "Binary path",
501 description: "Path to the Claude binary used by this instance.",
502 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
503 }),
504 ),
505 homePath: TrimmedString.pipe(
506 Schema.withDecodingDefault(Effect.succeed("")),
507 Schema.annotateKey({
508 title: "CLAUDE_CONFIG_DIR path",
509 description:
510 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
511 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
512 }),
513 ),
514 customModels: Schema.Array(CustomModelSetting).pipe(
515 Schema.withDecodingDefault(Effect.succeed([])),
516 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
517 ),
518 launchArgs: Schema.String.pipe(
519 Schema.withDecodingDefault(Effect.succeed("")),
520 Schema.annotateKey({
521 title: "Launch arguments",
522 description: "Additional CLI arguments passed on session start.",
523 providerSettingsForm: {
524 placeholder: "e.g. --chrome",
525 clearWhenEmpty: "omit",
526 },
527 }),
528 ),
529 autoCompactWindow: TrimmedString.check(
530 Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN),
531 ).pipe(
532 Schema.withDecodingDefault(Effect.succeed("")),
533 Schema.annotateKey({
534 title: "Auto-compact after",
535 description:
536 "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
537 providerSettingsForm: {
538 placeholder: "e.g. 300000",
539 clearWhenEmpty: "omit",
540 },
541 }),
542 ),
543 },
544 {
545 order: ["binaryPath", "homePath", "autoCompactWindow", "launchArgs"],
546 },
547);
548export type ClaudeSettings = typeof ClaudeSettings.Type;
549
550export const CursorSettings = makeProviderSettingsSchema(
551 {
552 // Off by default like Grok and OpenCode. Users opt in from Settings.
553 enabled: Schema.Boolean.pipe(
554 Schema.withDecodingDefault(Effect.succeed(false)),
555 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
556 ),
557 binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
558 Schema.annotateKey({
559 title: "Binary path",
560 description: "Path to the Cursor agent binary.",
561 providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
562 }),
563 ),
564 apiEndpoint: TrimmedString.pipe(
565 Schema.withDecodingDefault(Effect.succeed("")),
566 Schema.annotateKey({
567 title: "API endpoint",
568 description: "Override the Cursor API endpoint for this instance.",
569 providerSettingsForm: {
570 placeholder: "https://...",
571 clearWhenEmpty: "omit",
572 },
573 }),
574 ),
575 customModels: Schema.Array(CustomModelSetting).pipe(
576 Schema.withDecodingDefault(Effect.succeed([])),
577 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
578 ),
579 },
580 {
581 order: ["binaryPath", "apiEndpoint"],
582 },
583);
584export type CursorSettings = typeof CursorSettings.Type;
585
586export const GrokSettings = makeProviderSettingsSchema(
587 {
588 // Off by default (like Cursor and OpenCode): the binding is not yet
589 // stable enough to probe on every install. Users opt in from Settings.
590 enabled: Schema.Boolean.pipe(
591 Schema.withDecodingDefault(Effect.succeed(false)),
592 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
593 ),
594 binaryPath: makeBinaryPathSetting("grok").pipe(
595 Schema.annotateKey({
596 title: "Binary path",
597 description: "Path to the Grok CLI binary.",
598 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
599 }),
600 ),
601 customModels: Schema.Array(CustomModelSetting).pipe(
602 Schema.withDecodingDefault(Effect.succeed([])),
603 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
604 ),
605 },
606 {
607 order: ["binaryPath"],
608 },
609);
610export type GrokSettings = typeof GrokSettings.Type;
611
612/**
613 * Antigravity ACP auth methods. Personal and Enterprise open a Google sign-in
614 * in the browser. The API key and Agent Platform methods take credentials from
615 * the instance config and never open a browser.
616 */
617export const ANTIGRAVITY_AUTH_METHODS = [
618 { value: "oauth-personal", label: "Google account" },
619 { value: "oauth-business", label: "Gemini Enterprise" },
620 { value: "gemini-api-key", label: "Gemini API key" },
621 { value: "agent-platform", label: "Agent Platform (Vertex AI)" },
622] as const satisfies ReadonlyArray<ProviderSettingsFormOption>;
623export const AntigravityAuthMethod = Schema.Literals(
624 ANTIGRAVITY_AUTH_METHODS.map((method) => method.value),
625);
626export type AntigravityAuthMethod = typeof AntigravityAuthMethod.Type;
627
628export const AntigravitySettings = makeProviderSettingsSchema(
629 {
630 enabled: Schema.Boolean.pipe(
631 Schema.withDecodingDefault(Effect.succeed(false)),
632 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
633 ),
634 authMethod: AntigravityAuthMethod.pipe(
635 Schema.withDecodingDefault(Effect.succeed("oauth-personal" as const)),
636 Schema.annotateKey({
637 title: "Sign-in method",
638 description:
639 "Google account uses your Antigravity subscription. Gemini Enterprise needs a GCP project and location. API key and Agent Platform bill the credential you enter.",
640 providerSettingsForm: {
641 control: "select",
642 options: ANTIGRAVITY_AUTH_METHODS,
643 clearWhenEmpty: "omit",
644 },
645 }),
646 ),
647 apiKey: TrimmedString.pipe(
648 Schema.withDecodingDefault(Effect.succeed("")),
649 Schema.annotateKey({
650 title: "API key",
651 description:
652 "Gemini API key, or a Vertex AI express key for Agent Platform. Stored in plain text on this environment.",
653 providerSettingsForm: {
654 control: "password",
655 placeholder: "Optional",
656 clearWhenEmpty: "omit",
657 },
658 }),
659 ),
660 gcpProject: TrimmedString.pipe(
661 Schema.withDecodingDefault(Effect.succeed("")),
662 Schema.annotateKey({
663 title: "GCP project",
664 description:
665 "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
666 providerSettingsForm: { placeholder: "my-project-id", clearWhenEmpty: "omit" },
667 }),
668 ),
669 gcpLocation: TrimmedString.pipe(
670 Schema.withDecodingDefault(Effect.succeed("")),
671 Schema.annotateKey({
672 title: "GCP location",
673 description: "Region for Gemini Enterprise or Agent Platform, such as us-central1.",
674 providerSettingsForm: { placeholder: "us-central1", clearWhenEmpty: "omit" },
675 }),
676 ),
677 binaryPath: TrimmedString.pipe(
678 Schema.withDecodingDefault(Effect.succeed("")),
679 Schema.annotateKey({
680 title: "Binary path",
681 description:
682 "Optional path to the official Antigravity ACP executable. Leave empty for automatic selection.",
683 providerSettingsForm: { placeholder: "Automatic", clearWhenEmpty: "persist" },
684 }),
685 ),
686 customModels: Schema.Array(CustomModelSetting).pipe(
687 Schema.withDecodingDefault(Effect.succeed([])),
688 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
689 ),
690 },
691 { order: ["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"] },
692);
693export type AntigravitySettings = typeof AntigravitySettings.Type;
694
695export const OpenCodeSettings = makeProviderSettingsSchema(
696 {
697 // Off by default (like Cursor and Grok): the binding is not yet stable
698 // enough to probe on every install. Users opt in from Settings.
699 enabled: Schema.Boolean.pipe(
700 Schema.withDecodingDefault(Effect.succeed(false)),
701 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
702 ),
703 binaryPath: makeBinaryPathSetting("opencode").pipe(
704 Schema.annotateKey({
705 title: "Binary path",
706 description: "Path to the OpenCode binary.",
707 providerSettingsForm: {
708 placeholder: "opencode",
709 clearWhenEmpty: "omit",
710 },
711 }),
712 ),
713 serverUrl: TrimmedString.pipe(
714 Schema.withDecodingDefault(Effect.succeed("")),
715 Schema.annotateKey({
716 title: "Server URL",
717 description: "Leave blank to let T3 Code spawn the server when needed.",
718 providerSettingsForm: {
719 placeholder: "http://127.0.0.1:4096",
720 clearWhenEmpty: "omit",
721 },
722 }),
723 ),
724 serverPassword: TrimmedString.pipe(
725 Schema.withDecodingDefault(Effect.succeed("")),
726 Schema.annotateKey({
727 title: "Server password",
728 description: "Stored in plain text on disk.",
729 providerSettingsForm: {
730 control: "password",
731 placeholder: "Optional",
732 clearWhenEmpty: "omit",
733 },
734 }),
735 ),
736 customModels: Schema.Array(CustomModelSetting).pipe(
737 Schema.withDecodingDefault(Effect.succeed([])),
738 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
739 ),
740 },
741 {
742 order: ["binaryPath", "serverUrl", "serverPassword"],
743 },
744);
745export type OpenCodeSettings = typeof OpenCodeSettings.Type;
746
747/**
748 * A read-only quota source outside this environment's provider CLIs. The
749 * only kind today is a CLIProxyAPI hub, whose management API reports the
750 * windows of every pooled account. The key travels in settings for now, like
751 * provider environment secrets; it is redacted before reaching a client.
752 */
753export const UsageLimitSourceConfig = Schema.Struct({
754 kind: Schema.Literal("cliproxy"),
755 label: Schema.optional(TrimmedNonEmptyString),
756 url: TrimmedNonEmptyString,
757 managementKey: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
758 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
759});
760export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;
761
762export const ObservabilitySettings = Schema.Struct({
763 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
764 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
765});
766export type ObservabilitySettings = typeof ObservabilitySettings.Type;
767
768export const SourceControlWritingStyleMode = Schema.Literals([
769 "repo_conventions",
770 "conventional_commits",
771 "custom",
772]);
773export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
774
775export const SourceControlWritingStyleSettings = Schema.Struct({
776 mode: SourceControlWritingStyleMode.pipe(
777 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
778 ),
779 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
780 followChangeRequestTemplates: Schema.Boolean.pipe(
781 Schema.withDecodingDefault(Effect.succeed(true)),
782 ),
783});
784export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
785
786export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
787export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
788
789export const BackgroundActivityProfile = Schema.Literals([
790 "balanced",
791 "performance",
792 "battery-saver",
793]);
794export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
795export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
796
797export const BackgroundActivityProfileSelection = Schema.Literals([
798 "balanced",
799 "performance",
800 "battery-saver",
801 "custom",
802]);
803export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
804
805export const BackgroundActivityOverrides = Schema.Struct({
806 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
807 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
808 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
809 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
810 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
811 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
812 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
813 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
814 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
815});
816export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
817
818export const BackgroundActivitySettings = Schema.Struct({
819 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
820 profile: BackgroundActivityProfileSelection.pipe(
821 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
822 ),
823 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
824 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
825}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
826export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
827
828export const ServerSettings = Schema.Struct({
829 // Legacy token-by-token assistant output. Deliberately a fresh key (was
830 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
831 // including prior opt-ins, resets to the buffered default.
832 enableLegacyTokenStreaming: Schema.Boolean.pipe(
833 Schema.withDecodingDefault(Effect.succeed(false)),
834 ),
835 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
836 // Retain the update-era key; recovery now needs an environment-owned opt-in.
837 continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
838 Schema.withDecodingDefault(Effect.succeed(false)),
839 ),
840 /**
841 * Whether agents may drive the in-app preview browser. Turning this off
842 * withholds the MCP credential, so the `t3-code` server (and with it every
843 * `preview_*` tool) is never attached to a provider session, and the prompt
844 * text describing those tools is dropped along with them. The user's own
845 * browser panel is unaffected — this gates agent access only.
846 *
847 * Server-authoritative rather than client-local: tool injection and prompt
848 * construction both happen on the server, and the answer must not differ
849 * between a desktop window and a phone attached to the same server.
850 */
851 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
852 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
853 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
854 ),
855 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
856 backgroundActivity: BackgroundActivitySettings,
857 // Legacy flat fields retained for old settings files and old clients. New
858 // consumers should resolve `backgroundActivity` instead.
859 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
860 Schema.withDecodingDefault(
861 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
862 ),
863 ),
864 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
865 Schema.withDecodingDefault(
866 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
867 ),
868 ),
869 backgroundActivityProfile: BackgroundActivityProfile.pipe(
870 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
871 ),
872 defaultTheme: DefaultThemePreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
873 /**
874 * When the environment's theme was last set, so clients can tell a re-set
875 * of the same value from one they already applied: `t3 theme set` must act
876 * even when it names the theme it named before. Empty on environments
877 * provisioned by builds that predate it, where clients fall back to
878 * applying once per value.
879 */
880 defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
881 Schema.withDecodingDefault(Effect.succeed("")),
882 ),
883 /**
884 * The icon clients draw for this environment. Null means "use what the
885 * server detected" (`environment.platform.machine`), falling back to a
886 * generic server. Lives on the server, not the client, so every device
887 * sees the same machine. A kind picked on a newer server decodes as null
888 * here rather than failing the whole settings snapshot for an older client.
889 */
890 environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
891 Schema.withDecodingDefault(Effect.succeed(null)),
892 ),
893 defaultThreadEnvMode: ThreadEnvMode.pipe(
894 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
895 ),
896 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
897 Schema.withDecodingDefault(Effect.succeed(true)),
898 ),
899 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
900 textGenerationModelSelection: ModelSelection.pipe(
901 Schema.withDecodingDefault(
902 Effect.succeed({
903 instanceId: ProviderInstanceId.make("codex"),
904 model: DEFAULT_TEXT_GENERATION_MODEL,
905 options: [
906 {
907 id: "reasoningEffort",
908 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
909 },
910 ],
911 }),
912 ),
913 ),
914 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
915 Schema.withDecodingDefault(Effect.succeed({})),
916 ),
917 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
918 Schema.withDecodingDefault(Effect.succeed(null)),
919 ),
920
921 // Legacy single-instance-per-driver settings. Continues to be the source
922 // of truth until `providerInstances` (below) lands per-driver migration
923 // shims and the server starts hydrating instances from it. Driver-specific
924 // schemas live here for the duration of the migration; once each driver
925 // owns its config in its own package, this struct shrinks to nothing and
926 // is removed entirely.
927 providers: Schema.Struct({
928 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
929 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
930 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
931 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
932 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
933 antigravity: AntigravitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
934 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
935 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
936 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
937 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
938 // (forks, downgrades, in-flight PR branches) round-trip without loss.
939 // See providerInstance.ts for the forward/backward compatibility invariant.
940 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
941 Schema.withDecodingDefault(Effect.succeed({})),
942 ),
943 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
944 // Keyed by a user-chosen id so a source keeps its rows across edits. Entries
945 // this build cannot decode round-trip untouched, as provider instances do.
946 usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(
947 Schema.withDecodingDefault(Effect.succeed({})),
948 ),
949 /** Exact model IDs, applied to past and future usage on this environment. */
950 usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(
951 Schema.withDecodingDefault(Effect.succeed({})),
952 ),
953});
954export type ServerSettings = typeof ServerSettings.Type;
955
956export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
957
958/**
959 * Read the legacy `enabled` flag embedded in a provider instance config
960 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
961 * flag going forward; this reader exists for legacy `providers.<kind>`
962 * blobs and old settings files that still carry the flag in-config.
963 */
964export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
965 if (config === null || typeof config !== "object" || Array.isArray(config)) {
966 return undefined;
967 }
968 const enabled = (config as { readonly enabled?: unknown }).enabled;
969 return typeof enabled === "boolean" ? enabled : undefined;
970};
971
972/**
973 * Default enabled state for a built-in driver when neither the envelope nor
974 * the config blob carries a flag. Derived from the driver's settings schema
975 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
976 * the single source of truth. Unknown (fork) drivers default to enabled.
977 */
978export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
979 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
980 string,
981 { readonly enabled?: boolean } | undefined
982 >;
983 return legacyDefaults[driver]?.enabled ?? true;
984};
985
986/**
987 * Resolve whether a configured provider instance is enabled. An explicit
988 * false on either the envelope or the in-config flag wins (most
989 * restrictive), so a user's disable is never silently undone by the other
990 * flag. Otherwise: envelope, then config, then the driver's default.
991 */
992export const resolveProviderInstanceEnabled = (
993 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
994): boolean => {
995 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
996 if (instance.enabled === false || configEnabled === false) {
997 return false;
998 }
999 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
1000};
1001
1002export const ServerSettingsOperation = Schema.Literals([
1003 "normalize",
1004 "check-exists",
1005 "read-file",
1006 "read-provider-history",
1007 "read-secret",
1008 "remove-secret",
1009 "remove-stale-secret",
1010 "write-secret",
1011 "write-file",
1012 "prepare-directory",
1013]);
1014export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
1015
1016export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
1017 "ServerSettingsError",
1018 {
1019 settingsPath: Schema.String,
1020 operation: ServerSettingsOperation,
1021 providerInstanceId: Schema.optional(Schema.String),
1022 environmentVariable: Schema.optional(Schema.String),
1023 cause: Schema.Defect(),
1024 },
1025) {
1026 override get message(): string {
1027 const provider =
1028 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
1029 const variable =
1030 this.environmentVariable === undefined
1031 ? ""
1032 : ` and environment variable ${this.environmentVariable}`;
1033 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
1034 }
1035}
1036
1037// ── Unified type ─────────────────────────────────────────────────────
1038
1039export type UnifiedSettings = ServerSettings & ClientSettings;
1040export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
1041 ...DEFAULT_SERVER_SETTINGS,
1042 ...DEFAULT_CLIENT_SETTINGS,
1043};
1044
1045// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
1046
1047const ModelSelectionPatch = Schema.Struct({
1048 instanceId: Schema.optionalKey(ProviderInstanceId),
1049 model: Schema.optionalKey(TrimmedNonEmptyString),
1050 options: Schema.optionalKey(ProviderOptionSelections),
1051});
1052
1053const CodexSettingsPatch = Schema.Struct({
1054 enabled: Schema.optionalKey(Schema.Boolean),
1055 binaryPath: Schema.optionalKey(TrimmedString),
1056 homePath: Schema.optionalKey(TrimmedString),
1057 shadowHomePath: Schema.optionalKey(TrimmedString),
1058 launchArgs: Schema.optionalKey(TrimmedString),
1059 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1060});
1061
1062const ClaudeSettingsPatch = Schema.Struct({
1063 enabled: Schema.optionalKey(Schema.Boolean),
1064 binaryPath: Schema.optionalKey(TrimmedString),
1065 homePath: Schema.optionalKey(TrimmedString),
1066 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1067 launchArgs: Schema.optionalKey(TrimmedString),
1068 // Validated at the patch boundary so a typo fails the one update with a
1069 // schema error instead of a generic whole-settings failure.
1070 autoCompactWindow: Schema.optionalKey(
1071 TrimmedString.check(Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN)),
1072 ),
1073});
1074
1075const CursorSettingsPatch = Schema.Struct({
1076 enabled: Schema.optionalKey(Schema.Boolean),
1077 binaryPath: Schema.optionalKey(TrimmedString),
1078 apiEndpoint: Schema.optionalKey(TrimmedString),
1079 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1080});
1081
1082const GrokSettingsPatch = Schema.Struct({
1083 enabled: Schema.optionalKey(Schema.Boolean),
1084 binaryPath: Schema.optionalKey(TrimmedString),
1085 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1086});
1087
1088const AntigravitySettingsPatch = Schema.Struct({
1089 enabled: Schema.optionalKey(Schema.Boolean),
1090 authMethod: Schema.optionalKey(AntigravityAuthMethod),
1091 apiKey: Schema.optionalKey(TrimmedString),
1092 gcpProject: Schema.optionalKey(TrimmedString),
1093 gcpLocation: Schema.optionalKey(TrimmedString),
1094 binaryPath: Schema.optionalKey(TrimmedString),
1095 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1096});
1097
1098const OpenCodeSettingsPatch = Schema.Struct({
1099 enabled: Schema.optionalKey(Schema.Boolean),
1100 binaryPath: Schema.optionalKey(TrimmedString),
1101 serverUrl: Schema.optionalKey(TrimmedString),
1102 serverPassword: Schema.optionalKey(TrimmedString),
1103 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1104});
1105
1106export const ServerSettingsPatch = Schema.Struct({
1107 // Server settings
1108 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
1109 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1110 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1111 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1112 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1113 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1114 backgroundActivity: Schema.optionalKey(
1115 Schema.Struct({
1116 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
1117 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
1118 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
1119 overrides: Schema.optionalKey(BackgroundActivityOverrides),
1120 }),
1121 ),
1122 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1123 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1124 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
1125 environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
1126 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
1127 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1128 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
1129 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
1130 sourceControlWritingStyle: Schema.optionalKey(
1131 Schema.Struct({
1132 mode: Schema.optionalKey(SourceControlWritingStyleMode),
1133 customInstructions: Schema.optionalKey(TrimmedString),
1134 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
1135 }),
1136 ),
1137 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1138 observability: Schema.optionalKey(
1139 Schema.Struct({
1140 otlpTracesUrl: Schema.optionalKey(TrimmedString),
1141 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
1142 }),
1143 ),
1144 providers: Schema.optionalKey(
1145 Schema.Struct({
1146 codex: Schema.optionalKey(CodexSettingsPatch),
1147 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
1148 cursor: Schema.optionalKey(CursorSettingsPatch),
1149 grok: Schema.optionalKey(GrokSettingsPatch),
1150 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
1151 antigravity: Schema.optionalKey(AntigravitySettingsPatch),
1152 }),
1153 ),
1154 // Whole-map replacement for the new instance config. Patching individual
1155 // entries is intentionally out of scope: the map is small, and partial
1156 // patches risk leaving driver-specific config in a half-merged state.
1157 // The web UI sends a fully-formed map every time it edits this field.
1158 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
1159 // Per-entry, unlike `providerInstances`: a client only ever adds or removes
1160 // one source, and sending the whole map races another edit that has not
1161 // echoed back yet. `null` removes; the server merges into its current map.
1162 usageLimitSources: Schema.optionalKey(
1163 Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),
1164 ),
1165 /** Each entry replaces one model's rates; `null` restores automatic pricing. */
1166 usagePriceOverrides: Schema.optionalKey(
1167 Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),
1168 ),
1169});
1170export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
1171
1172export const ClientSettingsPatch = Schema.Struct({
1173 appearanceContrast: Schema.optionalKey(AppearanceContrast),
1174 panelAnimationDurationMs: Schema.optionalKey(PanelAnimationDurationMs),
1175 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
1176 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
1177 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
1178 browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
1179 browserLinkTarget: Schema.optionalKey(BrowserLinkTarget),
1180 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
1181 browserProfiles: Schema.optionalKey(Schema.Array(BrowserProfile)),
1182 browserDefaultProfileId: Schema.optionalKey(BrowserProfileId),
1183 confirmQuit: Schema.optionalKey(QuitConfirmationMode),
1184 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
1185 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
1186 confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
1187 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
1188 diffLayout: Schema.optionalKey(DiffLayout),
1189 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
1190 glassOpacity: Schema.optionalKey(GlassOpacity),
1191 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
1192 fontSizePrompt: Schema.optionalKey(PromptFontSize),
1193 fontSizeCode: Schema.optionalKey(CodeFontSize),
1194 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
1195 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
1196 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
1197 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
1198 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
1199 fontSmoothing: Schema.optionalKey(Schema.Boolean),
1200 favorites: Schema.optionalKey(
1201 Schema.Array(
1202 Schema.Struct({
1203 provider: ProviderInstanceId,
1204 model: TrimmedNonEmptyString,
1205 }),
1206 ),
1207 ),
1208 providerModelPreferences: Schema.optionalKey(
1209 Schema.Record(
1210 ProviderInstanceId,
1211 Schema.Struct({
1212 hiddenModels: Schema.Array(Schema.String).pipe(
1213 Schema.withDecodingDefault(Effect.succeed([])),
1214 ),
1215 modelOrder: Schema.Array(Schema.String).pipe(
1216 Schema.withDecodingDefault(Effect.succeed([])),
1217 ),
1218 }),
1219 ),
1220 ),
1221 planModeEnabled: Schema.optionalKey(Schema.Boolean),
1222 contextWindowMeterEnabled: Schema.optionalKey(Schema.Boolean),
1223 composerCollapseOnBlur: Schema.optionalKey(Schema.Boolean),
1224 composerCollapseOnScroll: Schema.optionalKey(Schema.Boolean),
1225 proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean),
1226 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
1227 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
1228 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
1229 sidebarProjectGroupingOverrides: Schema.optionalKey(
1230 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
1231 ),
1232 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
1233 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
1234 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
1235 timestampFormat: Schema.optionalKey(TimestampFormat),
1236 wordWrap: Schema.optionalKey(Schema.Boolean),
1237});
1238export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;