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

settings.ts

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