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