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

settings.ts

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