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

settings.ts

1,319 lines56.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: 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 DevinSettings = makeProviderSettingsSchema(
605 {
606 // Devin is opt-in because it requires a separately installed and authenticated CLI.
607 enabled: Schema.Boolean.pipe(
608 Schema.withDecodingDefault(Effect.succeed(false)),
609 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
610 ),
611 binaryPath: makeBinaryPathSetting("devin").pipe(
612 Schema.annotateKey({
613 title: "Binary path",
614 description: "Path to the Devin CLI binary.",
615 providerSettingsForm: { placeholder: "devin", clearWhenEmpty: "omit" },
616 }),
617 ),
618 customModels: Schema.Array(Schema.String).pipe(
619 Schema.withDecodingDefault(Effect.succeed([])),
620 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
621 ),
622 },
623 {
624 order: ["binaryPath"],
625 },
626);
627export type DevinSettings = typeof DevinSettings.Type;
628​
629export const GrokSettings = makeProviderSettingsSchema(
630 {
631 // Off by default (like Cursor and OpenCode): the binding is not yet
632 // stable enough to probe on every install. Users opt in from Settings.
633 enabled: Schema.Boolean.pipe(
634 Schema.withDecodingDefault(Effect.succeed(false)),
635 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
636 ),
637 binaryPath: makeBinaryPathSetting("grok").pipe(
638 Schema.annotateKey({
639 title: "Binary path",
640 description: "Path to the Grok CLI binary.",
641 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
642 }),
643 ),
644 customModels: Schema.Array(CustomModelSetting).pipe(
645 Schema.withDecodingDefault(Effect.succeed([])),
646 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
647 ),
648 },
649 {
650 order: ["binaryPath"],
651 },
652);
653export type GrokSettings = typeof GrokSettings.Type;
654​
655/**
656 * Antigravity ACP auth methods. Personal and Enterprise open a Google sign-in
657 * in the browser. The API key and Agent Platform methods take credentials from
658 * the instance config and never open a browser.
659 */
660export const ANTIGRAVITY_AUTH_METHODS = [
661 { value: "oauth-personal", label: "Google account" },
662 { value: "oauth-business", label: "Gemini Enterprise" },
663 { value: "gemini-api-key", label: "Gemini API key" },
664 { value: "agent-platform", label: "Agent Platform (Vertex AI)" },
665] as const satisfies ReadonlyArray<ProviderSettingsFormOption>;
666export const AntigravityAuthMethod = Schema.Literals(
667 ANTIGRAVITY_AUTH_METHODS.map((method) => method.value),
668);
669export type AntigravityAuthMethod = typeof AntigravityAuthMethod.Type;
670​
671export const AntigravitySettings = makeProviderSettingsSchema(
672 {
673 enabled: Schema.Boolean.pipe(
674 Schema.withDecodingDefault(Effect.succeed(false)),
675 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
676 ),
677 authMethod: AntigravityAuthMethod.pipe(
678 Schema.withDecodingDefault(Effect.succeed("oauth-personal" as const)),
679 Schema.annotateKey({
680 title: "Sign-in method",
681 description:
682 "Google account uses your Antigravity subscription. Gemini Enterprise needs a GCP project and location. API key and Agent Platform bill the credential you enter.",
683 providerSettingsForm: {
684 control: "select",
685 options: ANTIGRAVITY_AUTH_METHODS,
686 clearWhenEmpty: "omit",
687 },
688 }),
689 ),
690 apiKey: TrimmedString.pipe(
691 Schema.withDecodingDefault(Effect.succeed("")),
692 Schema.annotateKey({
693 title: "API key",
694 description:
695 "Gemini API key, or a Vertex AI express key for Agent Platform. Stored in plain text on this environment.",
696 providerSettingsForm: {
697 control: "password",
698 placeholder: "Optional",
699 clearWhenEmpty: "omit",
700 },
701 }),
702 ),
703 gcpProject: TrimmedString.pipe(
704 Schema.withDecodingDefault(Effect.succeed("")),
705 Schema.annotateKey({
706 title: "GCP project",
707 description:
708 "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
709 providerSettingsForm: { placeholder: "my-project-id", clearWhenEmpty: "omit" },
710 }),
711 ),
712 gcpLocation: TrimmedString.pipe(
713 Schema.withDecodingDefault(Effect.succeed("")),
714 Schema.annotateKey({
715 title: "GCP location",
716 description: "Region for Gemini Enterprise or Agent Platform, such as us-central1.",
717 providerSettingsForm: { placeholder: "us-central1", clearWhenEmpty: "omit" },
718 }),
719 ),
720 binaryPath: TrimmedString.pipe(
721 Schema.withDecodingDefault(Effect.succeed("")),
722 Schema.annotateKey({
723 title: "Binary path",
724 description:
725 "Optional path to the official Antigravity ACP executable. Leave empty for automatic selection.",
726 providerSettingsForm: { placeholder: "Automatic", clearWhenEmpty: "persist" },
727 }),
728 ),
729 customModels: Schema.Array(CustomModelSetting).pipe(
730 Schema.withDecodingDefault(Effect.succeed([])),
731 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
732 ),
733 },
734 { order: ["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"] },
735);
736export type AntigravitySettings = typeof AntigravitySettings.Type;
737​
738export const OpenCodeSettings = makeProviderSettingsSchema(
739 {
740 // Off by default (like Cursor and Grok): the binding is not yet stable
741 // enough to probe on every install. Users opt in from Settings.
742 enabled: Schema.Boolean.pipe(
743 Schema.withDecodingDefault(Effect.succeed(false)),
744 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
745 ),
746 binaryPath: makeBinaryPathSetting("opencode").pipe(
747 Schema.annotateKey({
748 title: "Binary path",
749 description: "Path to the OpenCode binary.",
750 providerSettingsForm: {
751 placeholder: "opencode",
752 clearWhenEmpty: "omit",
753 },
754 }),
755 ),
756 serverUrl: TrimmedString.pipe(
757 Schema.withDecodingDefault(Effect.succeed("")),
758 Schema.annotateKey({
759 title: "Server URL",
760 description: "Leave blank to let T3 Code spawn the server when needed.",
761 providerSettingsForm: {
762 placeholder: "http://127.0.0.1:4096",
763 clearWhenEmpty: "omit",
764 },
765 }),
766 ),
767 serverPassword: TrimmedString.pipe(
768 Schema.withDecodingDefault(Effect.succeed("")),
769 Schema.annotateKey({
770 title: "Server password",
771 description: "Stored in plain text on disk.",
772 providerSettingsForm: {
773 control: "password",
774 placeholder: "Optional",
775 clearWhenEmpty: "omit",
776 },
777 }),
778 ),
779 customModels: Schema.Array(CustomModelSetting).pipe(
780 Schema.withDecodingDefault(Effect.succeed([])),
781 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
782 ),
783 },
784 {
785 order: ["binaryPath", "serverUrl", "serverPassword"],
786 },
787);
788export type OpenCodeSettings = typeof OpenCodeSettings.Type;
789​
790/**
791 * A read-only quota source outside this environment's provider CLIs. The
792 * only kind today is a CLIProxyAPI hub, whose management API reports the
793 * windows of every pooled account. The key travels in settings for now, like
794 * provider environment secrets; it is redacted before reaching a client.
795 */
796export const UsageLimitSourceConfig = Schema.Struct({
797 kind: Schema.Literal("cliproxy"),
798 label: Schema.optional(TrimmedNonEmptyString),
799 url: TrimmedNonEmptyString,
800 managementKey: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
801 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
802});
803export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;
804​
805export const ObservabilitySettings = Schema.Struct({
806 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
807 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
808});
809export type ObservabilitySettings = typeof ObservabilitySettings.Type;
810​
811export const SourceControlWritingStyleMode = Schema.Literals([
812 "repo_conventions",
813 "conventional_commits",
814 "custom",
815]);
816export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
817​
818export const SourceControlWritingStyleSettings = Schema.Struct({
819 mode: SourceControlWritingStyleMode.pipe(
820 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
821 ),
822 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
823 followChangeRequestTemplates: Schema.Boolean.pipe(
824 Schema.withDecodingDefault(Effect.succeed(true)),
825 ),
826});
827export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
828​
829export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
830export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
831​
832export const BackgroundActivityProfile = Schema.Literals([
833 "balanced",
834 "performance",
835 "battery-saver",
836]);
837export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
838export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
839​
840export const BackgroundActivityProfileSelection = Schema.Literals([
841 "balanced",
842 "performance",
843 "battery-saver",
844 "custom",
845]);
846export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
847​
848export const BackgroundActivityOverrides = Schema.Struct({
849 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
850 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
851 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
852 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
853 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
854 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
855 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
856 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
857 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
858});
859export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
860​
861export const BackgroundActivitySettings = Schema.Struct({
862 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
863 profile: BackgroundActivityProfileSelection.pipe(
864 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
865 ),
866 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
867 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
868}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
869export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
870​
871export const ServerSettings = Schema.Struct({
872 // Legacy token-by-token assistant output. Deliberately a fresh key (was
873 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
874 // including prior opt-ins, resets to the buffered default.
875 enableLegacyTokenStreaming: Schema.Boolean.pipe(
876 Schema.withDecodingDefault(Effect.succeed(false)),
877 ),
878 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
879 // Retain the update-era key; recovery now needs an environment-owned opt-in.
880 continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
881 Schema.withDecodingDefault(Effect.succeed(false)),
882 ),
883 /**
884 * Whether agents may drive the in-app preview browser. Turning this off
885 * withholds the MCP credential, so the `t3-code` server (and with it every
886 * `preview_*` tool) is never attached to a provider session, and the prompt
887 * text describing those tools is dropped along with them. The user's own
888 * browser panel is unaffected — this gates agent access only.
889 *
890 * Server-authoritative rather than client-local: tool injection and prompt
891 * construction both happen on the server, and the answer must not differ
892 * between a desktop window and a phone attached to the same server.
893 */
894 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
895 projectAgentBrowserAccessOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
896 Schema.withDecodingDefault(Effect.succeed({})),
897 ),
898 defaultAutoPull: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
899 defaultProjectScripts: Schema.Array(ProjectScript).pipe(
900 Schema.withDecodingDefault(Effect.succeed([])),
901 ),
902 projectScriptOverrides: Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))).pipe(
903 Schema.withDecodingDefault(Effect.succeed({})),
904 ),
905 projectAutoPullOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
906 Schema.withDecodingDefault(Effect.succeed({})),
907 ),
908 defaultModelSelection: Schema.NullOr(ModelSelection).pipe(
909 Schema.withDecodingDefault(Effect.succeed(null)),
910 ),
911 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
912 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
913 ),
914 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
915 backgroundActivity: BackgroundActivitySettings,
916 // Legacy flat fields retained for old settings files and old clients. New
917 // consumers should resolve `backgroundActivity` instead.
918 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
919 Schema.withDecodingDefault(
920 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
921 ),
922 ),
923 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
924 Schema.withDecodingDefault(
925 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
926 ),
927 ),
928 backgroundActivityProfile: BackgroundActivityProfile.pipe(
929 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
930 ),
931 defaultTheme: DefaultThemePreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
932 /**
933 * When the environment's theme was last set, so clients can tell a re-set
934 * of the same value from one they already applied: `t3 theme set` must act
935 * even when it names the theme it named before. Empty on environments
936 * provisioned by builds that predate it, where clients fall back to
937 * applying once per value.
938 */
939 defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
940 Schema.withDecodingDefault(Effect.succeed("")),
941 ),
942 /**
943 * The icon clients draw for this environment. Null means "use what the
944 * server detected" (`environment.platform.machine`), falling back to a
945 * generic server. Lives on the server, not the client, so every device
946 * sees the same machine. A kind picked on a newer server decodes as null
947 * here rather than failing the whole settings snapshot for an older client.
948 */
949 environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
950 Schema.withDecodingDefault(Effect.succeed(null)),
951 ),
952 defaultThreadEnvMode: ThreadEnvMode.pipe(
953 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
954 ),
955 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
956 Schema.withDecodingDefault(Effect.succeed(true)),
957 ),
958 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
959 textGenerationModelSelection: ModelSelection.pipe(
960 Schema.withDecodingDefault(
961 Effect.succeed({
962 instanceId: ProviderInstanceId.make("codex"),
963 model: DEFAULT_TEXT_GENERATION_MODEL,
964 options: [
965 {
966 id: "reasoningEffort",
967 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
968 },
969 ],
970 }),
971 ),
972 ),
973 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
974 Schema.withDecodingDefault(Effect.succeed({})),
975 ),
976 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
977 Schema.withDecodingDefault(Effect.succeed(null)),
978 ),
979​
980 // Legacy single-instance-per-driver settings. Continues to be the source
981 // of truth until `providerInstances` (below) lands per-driver migration
982 // shims and the server starts hydrating instances from it. Driver-specific
983 // schemas live here for the duration of the migration; once each driver
984 // owns its config in its own package, this struct shrinks to nothing and
985 // is removed entirely.
986 providers: Schema.Struct({
987 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
988 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
989 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
990 devin: DevinSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
991 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
992 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
993 antigravity: AntigravitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
994 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
995 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
996 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
997 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
998 // (forks, downgrades, in-flight PR branches) round-trip without loss.
999 // See providerInstance.ts for the forward/backward compatibility invariant.
1000 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
1001 Schema.withDecodingDefault(Effect.succeed({})),
1002 ),
1003 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
1004 // Keyed by a user-chosen id so a source keeps its rows across edits. Entries
1005 // this build cannot decode round-trip untouched, as provider instances do.
1006 usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(
1007 Schema.withDecodingDefault(Effect.succeed({})),
1008 ),
1009 /** Exact model IDs, applied to past and future usage on this environment. */
1010 usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(
1011 Schema.withDecodingDefault(Effect.succeed({})),
1012 ),
1013});
1014export type ServerSettings = typeof ServerSettings.Type;
1015​
1016export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
1017​
1018/**
1019 * Read the legacy `enabled` flag embedded in a provider instance config
1020 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
1021 * flag going forward; this reader exists for legacy `providers.<kind>`
1022 * blobs and old settings files that still carry the flag in-config.
1023 */
1024export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
1025 if (config === null || typeof config !== "object" || Array.isArray(config)) {
1026 return undefined;
1028 const enabled = (config as { readonly enabled?: unknown }).enabled;
1029 return typeof enabled === "boolean" ? enabled : undefined;
1031​
1032/**
1033 * Default enabled state for a built-in driver when neither the envelope nor
1034 * the config blob carries a flag. Derived from the driver's settings schema
1035 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
1036 * the single source of truth. Unknown (fork) drivers default to enabled.
1037 */
1038export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
1039 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
1040 string,
1041 { readonly enabled?: boolean } | undefined
1042 >;
1043 return legacyDefaults[driver]?.enabled ?? true;
1045​
1046/**
1047 * Resolve whether a configured provider instance is enabled. An explicit
1048 * false on either the envelope or the in-config flag wins (most
1049 * restrictive), so a user's disable is never silently undone by the other
1050 * flag. Otherwise: envelope, then config, then the driver's default.
1051 */
1052export const resolveProviderInstanceEnabled = (
1053 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
1054): boolean => {
1055 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
1056 if (instance.enabled === false || configEnabled === false) {
1057 return false;
1059 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
1061​
1062export const ServerSettingsOperation = Schema.Literals([
1063 "normalize",
1064 "check-exists",
1065 "read-file",
1066 "read-provider-history",
1067 "read-secret",
1068 "remove-secret",
1069 "remove-stale-secret",
1070 "write-secret",
1071 "write-file",
1072 "prepare-directory",
1073]);
1074export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
1075​
1076export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
1077 "ServerSettingsError",
1079 settingsPath: Schema.String,
1080 operation: ServerSettingsOperation,
1081 providerInstanceId: Schema.optional(Schema.String),
1082 environmentVariable: Schema.optional(Schema.String),
1083 cause: Schema.Defect(),
1084 },
1085) {
1086 override get message(): string {
1087 const provider =
1088 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
1089 const variable =
1090 this.environmentVariable === undefined
1091 ? ""
1092 : ` and environment variable ${this.environmentVariable}`;
1093 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
1096​
1097// ── Unified type ─────────────────────────────────────────────────────
1098​
1099export type UnifiedSettings = ServerSettings & ClientSettings;
1100export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
1101 ...DEFAULT_SERVER_SETTINGS,
1102 ...DEFAULT_CLIENT_SETTINGS,
1104​
1105// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
1106​
1107const ModelSelectionPatch = Schema.Struct({
1108 instanceId: Schema.optionalKey(ProviderInstanceId),
1109 model: Schema.optionalKey(TrimmedNonEmptyString),
1110 options: Schema.optionalKey(ProviderOptionSelections),
1111});
1112​
1113const CodexSettingsPatch = Schema.Struct({
1114 enabled: Schema.optionalKey(Schema.Boolean),
1115 binaryPath: Schema.optionalKey(TrimmedString),
1116 homePath: Schema.optionalKey(TrimmedString),
1117 shadowHomePath: Schema.optionalKey(TrimmedString),
1118 launchArgs: Schema.optionalKey(TrimmedString),
1119 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1120});
1121​
1122const ClaudeSettingsPatch = Schema.Struct({
1123 enabled: Schema.optionalKey(Schema.Boolean),
1124 binaryPath: Schema.optionalKey(TrimmedString),
1125 homePath: Schema.optionalKey(TrimmedString),
1126 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1127 launchArgs: Schema.optionalKey(TrimmedString),
1128 // Validated at the patch boundary so a typo fails the one update with a
1129 // schema error instead of a generic whole-settings failure.
1130 autoCompactWindow: Schema.optionalKey(
1131 TrimmedString.check(Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN)),
1132 ),
1133});
1134​
1135const CursorSettingsPatch = Schema.Struct({
1136 enabled: Schema.optionalKey(Schema.Boolean),
1137 binaryPath: Schema.optionalKey(TrimmedString),
1138 apiEndpoint: Schema.optionalKey(TrimmedString),
1139 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1140});
1141​
1142const DevinSettingsPatch = Schema.Struct({
1143 enabled: Schema.optionalKey(Schema.Boolean),
1144 binaryPath: Schema.optionalKey(TrimmedString),
1145 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
1146});
1147​
1148const GrokSettingsPatch = Schema.Struct({
1149 enabled: Schema.optionalKey(Schema.Boolean),
1150 binaryPath: Schema.optionalKey(TrimmedString),
1151 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1152});
1153​
1154const AntigravitySettingsPatch = Schema.Struct({
1155 enabled: Schema.optionalKey(Schema.Boolean),
1156 authMethod: Schema.optionalKey(AntigravityAuthMethod),
1157 apiKey: Schema.optionalKey(TrimmedString),
1158 gcpProject: Schema.optionalKey(TrimmedString),
1159 gcpLocation: Schema.optionalKey(TrimmedString),
1160 binaryPath: Schema.optionalKey(TrimmedString),
1161 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1162});
1163​
1164const OpenCodeSettingsPatch = Schema.Struct({
1165 enabled: Schema.optionalKey(Schema.Boolean),
1166 binaryPath: Schema.optionalKey(TrimmedString),
1167 serverUrl: Schema.optionalKey(TrimmedString),
1168 serverPassword: Schema.optionalKey(TrimmedString),
1169 customModels: Schema.optionalKey(Schema.Array(CustomModelSetting)),
1170});
1171​
1172export const ServerSettingsPatch = Schema.Struct({
1173 // Server settings
1174 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
1175 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1176 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1177 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1178 projectAgentBrowserAccessOverrides: Schema.optionalKey(
1179 Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
1180 ),
1181 defaultAutoPull: Schema.optionalKey(Schema.Boolean),
1182 defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)),
1183 projectScriptOverrides: Schema.optionalKey(
1184 Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))),
1185 ),
1186 projectAutoPullOverrides: Schema.optionalKey(
1187 Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
1188 ),
1189 defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1190 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1191 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1192 backgroundActivity: Schema.optionalKey(
1193 Schema.Struct({
1194 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
1195 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
1196 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
1197 overrides: Schema.optionalKey(BackgroundActivityOverrides),
1198 }),
1199 ),
1200 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1201 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1202 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
1203 environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
1204 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
1205 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1206 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
1207 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
1208 sourceControlWritingStyle: Schema.optionalKey(
1209 Schema.Struct({
1210 mode: Schema.optionalKey(SourceControlWritingStyleMode),
1211 customInstructions: Schema.optionalKey(TrimmedString),
1212 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
1213 }),
1214 ),
1215 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1216 observability: Schema.optionalKey(
1217 Schema.Struct({
1218 otlpTracesUrl: Schema.optionalKey(TrimmedString),
1219 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
1220 }),
1221 ),
1222 providers: Schema.optionalKey(
1223 Schema.Struct({
1224 codex: Schema.optionalKey(CodexSettingsPatch),
1225 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
1226 cursor: Schema.optionalKey(CursorSettingsPatch),
1227 devin: Schema.optionalKey(DevinSettingsPatch),
1228 grok: Schema.optionalKey(GrokSettingsPatch),
1229 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
1230 antigravity: Schema.optionalKey(AntigravitySettingsPatch),
1231 }),
1232 ),
1233 // Whole-map replacement for the new instance config. Patching individual
1234 // entries is intentionally out of scope: the map is small, and partial
1235 // patches risk leaving driver-specific config in a half-merged state.
1236 // The web UI sends a fully-formed map every time it edits this field.
1237 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
1238 // Per-entry, unlike `providerInstances`: a client only ever adds or removes
1239 // one source, and sending the whole map races another edit that has not
1240 // echoed back yet. `null` removes; the server merges into its current map.
1241 usageLimitSources: Schema.optionalKey(
1242 Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),
1243 ),
1244 /** Each entry replaces one model's rates; `null` restores automatic pricing. */
1245 usagePriceOverrides: Schema.optionalKey(
1246 Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),
1247 ),
1248});
1249export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
1250​
1251export const ClientSettingsPatch = Schema.Struct({
1252 loadBalancingEnabled: Schema.optionalKey(Schema.Boolean),
1253 loadBalancingWeights: Schema.optionalKey(LoadBalancingWeights),
1254 appearanceContrast: Schema.optionalKey(AppearanceContrast),
1255 panelAnimationDurationMs: Schema.optionalKey(PanelAnimationDurationMs),
1256 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
1257 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
1258 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
1259 browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
1260 browserLinkTarget: Schema.optionalKey(BrowserLinkTarget),
1261 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
1262 browserProfiles: Schema.optionalKey(Schema.Array(BrowserProfile)),
1263 browserDefaultProfileId: Schema.optionalKey(BrowserProfileId),
1264 confirmQuit: Schema.optionalKey(QuitConfirmationMode),
1265 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
1266 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
1267 confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
1268 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
1269 diffLayout: Schema.optionalKey(DiffLayout),
1270 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
1271 glassOpacity: Schema.optionalKey(GlassOpacity),
1272 onboardingCompletedAt: Schema.optionalKey(Schema.NullOr(Schema.String)),
1273 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
1274 fontSizePrompt: Schema.optionalKey(PromptFontSize),
1275 fontSizeCode: Schema.optionalKey(CodeFontSize),
1276 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
1277 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
1278 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
1279 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
1280 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
1281 fontSmoothing: Schema.optionalKey(Schema.Boolean),
1282 favorites: Schema.optionalKey(
1283 Schema.Array(
1284 Schema.Struct({
1285 provider: ProviderInstanceId,
1286 model: TrimmedNonEmptyString,
1287 }),
1288 ),
1289 ),
1290 providerModelPreferences: Schema.optionalKey(
1291 Schema.Record(
1292 ProviderInstanceId,
1293 Schema.Struct({
1294 hiddenModels: Schema.Array(Schema.String).pipe(
1295 Schema.withDecodingDefault(Effect.succeed([])),
1296 ),
1297 modelOrder: Schema.Array(Schema.String).pipe(
1298 Schema.withDecodingDefault(Effect.succeed([])),
1299 ),
1300 }),
1301 ),
1302 ),
1303 planModeEnabled: Schema.optionalKey(Schema.Boolean),
1304 contextWindowMeterEnabled: Schema.optionalKey(Schema.Boolean),
1305 composerCollapseOnScroll: Schema.optionalKey(Schema.Boolean),
1306 proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean),
1307 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
1308 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
1309 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
1310 sidebarProjectGroupingOverrides: Schema.optionalKey(
1311 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
1312 ),
1313 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
1314 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
1315 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
1316 timestampFormat: Schema.optionalKey(TimestampFormat),
1317 wordWrap: Schema.optionalKey(Schema.Boolean),
1318});
1319export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;