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