Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settings.ts

1,181 lines50.5 KB

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