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

settings.ts

1,367 lines58.7 KB

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