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

settings.ts

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