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