Open History to see the last commit
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 { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
6import { ThreadEnvMode } from "./environment.ts";
7import {
8 DEFAULT_TEXT_GENERATION_MODEL,
9 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
10 ProviderOptionSelections,
11} from "./model.ts";
12import { ModelSelection } from "./orchestration.ts";
13import {
14 DEFAULT_PREVIEW_APPEARANCE,
15 DEFAULT_PREVIEW_ZOOM_FACTOR,
16 FILL_PREVIEW_VIEWPORT,
17 PreviewAppearancePreference,
18 PreviewViewportSetting,
19 PreviewZoomFactor,
20} from "./preview.ts";
21import {
22 ProviderInstanceConfig,
23 ProviderInstanceId,
24 type ProviderDriverKind,
25} from "./providerInstance.ts";
26
27// ── Client Settings (local-only) ───────────────────────────────
28
29export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
30export type TimestampFormat = typeof TimestampFormat.Type;
31export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
32
33export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
34export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
35export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
36
37export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
38export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
39export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
40
41export const SidebarProjectGroupingMode = Schema.Literals([
42 "repository",
43 "repository_path",
44 "separate",
45]);
46export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
47export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
48export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;
49export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;
50export const SidebarThreadPreviewCount = Schema.Int.check(
51 Schema.isBetween({
52 minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
53 maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
54 }),
55);
56export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
57export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
58export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;
59export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;
60export const SidebarAutoSettleAfterDays = Schema.Number.check(
61 Schema.isBetween({
62 minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
63 maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
64 }),
65);
66export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
67export const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;
68export const MIN_GLASS_OPACITY = 40;
69export const MAX_GLASS_OPACITY = 100;
70export const GlassOpacity = Schema.Int.check(
71 Schema.isBetween({
72 minimum: MIN_GLASS_OPACITY,
73 maximum: MAX_GLASS_OPACITY,
74 }),
75);
76export type GlassOpacity = typeof GlassOpacity.Type;
77export const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;
78
79export const MIN_APPEARANCE_CONTRAST = 50;
80export const MAX_APPEARANCE_CONTRAST = 200;
81export const AppearanceContrast = Schema.Int.check(
82 Schema.isBetween({ minimum: MIN_APPEARANCE_CONTRAST, maximum: MAX_APPEARANCE_CONTRAST }),
83);
84export type AppearanceContrast = typeof AppearanceContrast.Type;
85export const DEFAULT_APPEARANCE_CONTRAST: AppearanceContrast = 100;
86/**
87 * Font size preferences, in CSS pixels. The ranges are deliberately narrow:
88 * the interface size scales every rem-based dimension in the app, so the
89 * bounds keep layouts intact rather than offering unusable extremes.
90 */
91export const MIN_INTERFACE_FONT_SIZE = 12;
92export const MAX_INTERFACE_FONT_SIZE = 20;
93export const InterfaceFontSize = Schema.Int.check(
94 Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),
95);
96export type InterfaceFontSize = typeof InterfaceFontSize.Type;
97export const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;
98
99export const MIN_PROMPT_FONT_SIZE = 12;
100export const MAX_PROMPT_FONT_SIZE = 20;
101export const PromptFontSize = Schema.Int.check(
102 Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),
103);
104export type PromptFontSize = typeof PromptFontSize.Type;
105export const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;
106
107export const MIN_CODE_FONT_SIZE = 10;
108export const MAX_CODE_FONT_SIZE = 18;
109export const CodeFontSize = Schema.Int.check(
110 Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),
111);
112export type CodeFontSize = typeof CodeFontSize.Type;
113export const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;
114
115export const MIN_TERMINAL_FONT_SIZE = 8;
116export const MAX_TERMINAL_FONT_SIZE = 20;
117export const TerminalFontSize = Schema.Int.check(
118 Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),
119);
120export type TerminalFontSize = typeof TerminalFontSize.Type;
121export const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;
122
123export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill", "none"]);
124export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
125export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
126
127/**
128 * A user-chosen font family (a single name or a comma-separated list). Empty
129 * means "use the app default"; clients compose their own fallback stacks.
130 */
131export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));
132export type FontFamilyPreference = typeof FontFamilyPreference.Type;
133
134/**
135 * Defaults for the in-app preview browser, applied whenever a tab is opened
136 * without an explicit viewport/zoom/appearance — by the user opening a browser
137 * tab, or by an agent calling `preview_open` with no size. Client-local
138 * because the Chromium guest they configure is desktop-local.
139 */
140export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;
141export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;
142
143export const ClientSettingsSchema = Schema.Struct({
144 appearanceContrast: AppearanceContrast.pipe(
145 Schema.withDecodingDefault(Effect.succeed(DEFAULT_APPEARANCE_CONTRAST)),
146 ),
147 browserDefaultViewport: PreviewViewportSetting.pipe(
148 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_VIEWPORT)),
149 ),
150 browserDefaultZoomFactor: PreviewZoomFactor.pipe(
151 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_ZOOM_FACTOR)),
152 ),
153 browserDefaultAppearance: PreviewAppearancePreference.pipe(
154 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_APPEARANCE)),
155 ),
156 /**
157 * Whether an agent opening a preview pops the floating mini player into
158 * view. Only applies when the agent didn't ask either way — an explicit
159 * `open`/`show` on `preview_open` still wins, since that is the agent
160 * deliberately showing or hiding its work.
161 */
162 browserAutoShowFloatingPreview: Schema.Boolean.pipe(
163 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW)),
164 ),
165 // Desktop-only: require holding the quit shortcut (Cmd/Ctrl+Q) before the
166 // app quits; a quick tap only shows a hint. Browser clients ignore it.
167 confirmQuit: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
168 confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
169 confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
170 confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
171 dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
172 Schema.withDecodingDefault(Effect.succeed([])),
173 ),
174 diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
175 environmentIdentificationMode: EnvironmentIdentificationMode.pipe(
176 Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),
177 ),
178 glassOpacity: GlassOpacity.pipe(
179 Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
180 ),
181 fontSizeInterface: InterfaceFontSize.pipe(
182 Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),
183 ),
184 fontSizePrompt: PromptFontSize.pipe(
185 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),
186 ),
187 fontSizeCode: CodeFontSize.pipe(
188 Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),
189 ),
190 fontSizeTerminal: TerminalFontSize.pipe(
191 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),
192 ),
193 fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
194 fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
195 fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
196 fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
197 // Grayscale `-webkit-font-smoothing: antialiased` (thinner strokes);
198 // disabling restores the platform's heavier default. No effect off macOS.
199 fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
200 // Model favorites. Historically keyed by provider kind, now
201 // widened to `ProviderInstanceId` so users can favorite a specific model
202 // on a custom provider instance (e.g. "Codex Personal · gpt-5") without
203 // the UI collapsing it into the same bucket as the default Codex. The
204 // widening is backward-compatible by construction: prior provider-kind
205 // strings satisfy the `ProviderInstanceId` slug schema, so previously
206 // persisted favorites decode unchanged and continue to point at the
207 // default instance for their kind (because `defaultInstanceIdForDriver(kind)`
208 // uses the same slug). The field name is kept as `provider` for storage
209 // stability; new call sites should treat the value as an instance id.
210 favorites: Schema.Array(
211 Schema.Struct({
212 provider: ProviderInstanceId,
213 model: TrimmedNonEmptyString,
214 }),
215 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
216 providerModelPreferences: Schema.Record(
217 ProviderInstanceId,
218 Schema.Struct({
219 hiddenModels: Schema.Array(Schema.String).pipe(
220 Schema.withDecodingDefault(Effect.succeed([])),
221 ),
222 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
223 }),
224 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
225 // Legacy plan mode. The composer's Build/Plan toggle was removed from the
226 // default UI; this beta flag restores it (plus the /plan and /default slash
227 // commands) for users who still rely on the old workflow.
228 planModeEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
229 showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
230 // Legacy sidebar (the original per-project tree). Deliberately a fresh key
231 // (was `sidebarV2Enabled` + `sidebarV2ConfiguredByUser`): decoding drops the
232 // old keys, so everyone, including prior beta opt-outs, resets to the new
233 // default sidebar.
234 legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
235 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
236 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
237 ),
238 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
239 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
240 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
241 ),
242 sidebarProjectGroupingOverrides: Schema.Record(
243 TrimmedNonEmptyString,
244 SidebarProjectGroupingMode,
245 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
246 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
247 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
248 ),
249 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
250 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
251 ),
252 sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(
253 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),
254 ),
255 timestampFormat: TimestampFormat.pipe(
256 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
257 ),
258 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
259});
260export type ClientSettings = typeof ClientSettingsSchema.Type;
261
262export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
263
264// ── Server Settings (server-authoritative) ────────────────────
265
266// Moved to environment.ts so orchestration contracts can use it without an
267// import cycle; re-exported here for compatibility with deep imports.
268export { ThreadEnvMode } from "./environment.ts";
269
270const makeBinaryPathSetting = (fallback: string) =>
271 TrimmedString.pipe(
272 Schema.decodeTo(
273 Schema.String,
274 SchemaTransformation.transformOrFail({
275 decode: (value) => Effect.succeed(value || fallback),
276 encode: (value) => Effect.succeed(value),
277 }),
278 ),
279 Schema.withDecodingDefault(Effect.succeed(fallback)),
280 );
281
282export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch";
283
284export interface ProviderSettingsFormAnnotation {
285 readonly control?: ProviderSettingsFormControl | undefined;
286 readonly placeholder?: string | undefined;
287 readonly hidden?: boolean | undefined;
288 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
289}
290
291export interface ProviderSettingsFormSchemaAnnotation {
292 readonly order?: readonly string[] | undefined;
293}
294
295declare module "effect/Schema" {
296 namespace Annotations {
297 interface Annotations {
298 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
299 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
300 }
301 }
302}
303
304export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
305 keyof Fields,
306 string
307>[];
308
309export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
310 fields: Fields,
311 options?: {
312 readonly order?: ProviderSettingsOrder<Fields> | undefined;
313 },
314): Schema.Struct<Fields> {
315 return Schema.Struct(fields).pipe(
316 Schema.annotate({
317 providerSettingsFormSchema:
318 options?.order === undefined ? undefined : { order: options.order },
319 }),
320 );
321}
322
323export const CodexSettings = makeProviderSettingsSchema(
324 {
325 enabled: Schema.Boolean.pipe(
326 Schema.withDecodingDefault(Effect.succeed(true)),
327 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
328 ),
329 binaryPath: makeBinaryPathSetting("codex").pipe(
330 Schema.annotateKey({
331 title: "Binary path",
332 description: "Path to the Codex binary used by this instance.",
333 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
334 }),
335 ),
336 homePath: TrimmedString.pipe(
337 Schema.withDecodingDefault(Effect.succeed("")),
338 Schema.annotateKey({
339 title: "CODEX_HOME path",
340 description: "Custom Codex home and config directory.",
341 providerSettingsForm: {
342 placeholder: "~/.codex",
343 clearWhenEmpty: "omit",
344 },
345 }),
346 ),
347 shadowHomePath: TrimmedString.pipe(
348 Schema.withDecodingDefault(Effect.succeed("")),
349 Schema.annotateKey({
350 title: "Shadow home path",
351 description:
352 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
353 providerSettingsForm: {
354 placeholder: "~/.codex-t3/personal",
355 clearWhenEmpty: "omit",
356 },
357 }),
358 ),
359 launchArgs: TrimmedString.pipe(
360 Schema.withDecodingDefault(Effect.succeed("")),
361 Schema.annotateKey({
362 title: "Launch arguments",
363 description: "Additional CLI arguments passed to codex app-server on session start.",
364 }),
365 ),
366 customModels: Schema.Array(Schema.String).pipe(
367 Schema.withDecodingDefault(Effect.succeed([])),
368 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
369 ),
370 },
371 {
372 order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
373 },
374);
375export type CodexSettings = typeof CodexSettings.Type;
376
377// Empty, or an integer from 100,000 to 1,000,000. Shared by the full
378// Claude settings schema and its patch so an out-of-range value fails at
379// the update that introduced it.
380const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
381
382export const ClaudeSettings = makeProviderSettingsSchema(
383 {
384 enabled: Schema.Boolean.pipe(
385 Schema.withDecodingDefault(Effect.succeed(true)),
386 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
387 ),
388 binaryPath: makeBinaryPathSetting("claude").pipe(
389 Schema.annotateKey({
390 title: "Binary path",
391 description: "Path to the Claude binary used by this instance.",
392 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
393 }),
394 ),
395 homePath: TrimmedString.pipe(
396 Schema.withDecodingDefault(Effect.succeed("")),
397 Schema.annotateKey({
398 title: "CLAUDE_CONFIG_DIR path",
399 description:
400 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
401 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
402 }),
403 ),
404 customModels: Schema.Array(Schema.String).pipe(
405 Schema.withDecodingDefault(Effect.succeed([])),
406 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
407 ),
408 launchArgs: Schema.String.pipe(
409 Schema.withDecodingDefault(Effect.succeed("")),
410 Schema.annotateKey({
411 title: "Launch arguments",
412 description: "Additional CLI arguments passed on session start.",
413 providerSettingsForm: {
414 placeholder: "e.g. --chrome",
415 clearWhenEmpty: "omit",
416 },
417 }),
418 ),
419 autoCompactWindow: TrimmedString.check(
420 Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN),
421 ).pipe(
422 Schema.withDecodingDefault(Effect.succeed("")),
423 Schema.annotateKey({
424 title: "Auto-compact after",
425 description:
426 "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
427 providerSettingsForm: {
428 placeholder: "e.g. 300000",
429 clearWhenEmpty: "omit",
430 },
431 }),
432 ),
433 },
434 {
435 order: ["binaryPath", "homePath", "autoCompactWindow", "launchArgs"],
436 },
437);
438export type ClaudeSettings = typeof ClaudeSettings.Type;
439
440export const CursorSettings = makeProviderSettingsSchema(
441 {
442 // Off by default like Grok and OpenCode. Users opt in from Settings.
443 enabled: Schema.Boolean.pipe(
444 Schema.withDecodingDefault(Effect.succeed(false)),
445 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
446 ),
447 binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
448 Schema.annotateKey({
449 title: "Binary path",
450 description: "Path to the Cursor agent binary.",
451 providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
452 }),
453 ),
454 apiEndpoint: TrimmedString.pipe(
455 Schema.withDecodingDefault(Effect.succeed("")),
456 Schema.annotateKey({
457 title: "API endpoint",
458 description: "Override the Cursor API endpoint for this instance.",
459 providerSettingsForm: {
460 placeholder: "https://...",
461 clearWhenEmpty: "omit",
462 },
463 }),
464 ),
465 customModels: Schema.Array(Schema.String).pipe(
466 Schema.withDecodingDefault(Effect.succeed([])),
467 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
468 ),
469 },
470 {
471 order: ["binaryPath", "apiEndpoint"],
472 },
473);
474export type CursorSettings = typeof CursorSettings.Type;
475
476export const GrokSettings = makeProviderSettingsSchema(
477 {
478 // Off by default (like Cursor and OpenCode): the binding is not yet
479 // stable enough to probe on every install. Users opt in from Settings.
480 enabled: Schema.Boolean.pipe(
481 Schema.withDecodingDefault(Effect.succeed(false)),
482 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
483 ),
484 binaryPath: makeBinaryPathSetting("grok").pipe(
485 Schema.annotateKey({
486 title: "Binary path",
487 description: "Path to the Grok CLI binary.",
488 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
489 }),
490 ),
491 customModels: Schema.Array(Schema.String).pipe(
492 Schema.withDecodingDefault(Effect.succeed([])),
493 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
494 ),
495 },
496 {
497 order: ["binaryPath"],
498 },
499);
500export type GrokSettings = typeof GrokSettings.Type;
501
502export const OpenCodeSettings = makeProviderSettingsSchema(
503 {
504 // Off by default (like Cursor and Grok): the binding is not yet stable
505 // enough to probe on every install. Users opt in from Settings.
506 enabled: Schema.Boolean.pipe(
507 Schema.withDecodingDefault(Effect.succeed(false)),
508 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
509 ),
510 binaryPath: makeBinaryPathSetting("opencode").pipe(
511 Schema.annotateKey({
512 title: "Binary path",
513 description: "Path to the OpenCode binary.",
514 providerSettingsForm: {
515 placeholder: "opencode",
516 clearWhenEmpty: "omit",
517 },
518 }),
519 ),
520 serverUrl: TrimmedString.pipe(
521 Schema.withDecodingDefault(Effect.succeed("")),
522 Schema.annotateKey({
523 title: "Server URL",
524 description: "Leave blank to let T3 Code spawn the server when needed.",
525 providerSettingsForm: {
526 placeholder: "http://127.0.0.1:4096",
527 clearWhenEmpty: "omit",
528 },
529 }),
530 ),
531 serverPassword: TrimmedString.pipe(
532 Schema.withDecodingDefault(Effect.succeed("")),
533 Schema.annotateKey({
534 title: "Server password",
535 description: "Stored in plain text on disk.",
536 providerSettingsForm: {
537 control: "password",
538 placeholder: "Optional",
539 clearWhenEmpty: "omit",
540 },
541 }),
542 ),
543 customModels: Schema.Array(Schema.String).pipe(
544 Schema.withDecodingDefault(Effect.succeed([])),
545 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
546 ),
547 },
548 {
549 order: ["binaryPath", "serverUrl", "serverPassword"],
550 },
551);
552export type OpenCodeSettings = typeof OpenCodeSettings.Type;
553
554export const ObservabilitySettings = Schema.Struct({
555 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
556 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
557});
558export type ObservabilitySettings = typeof ObservabilitySettings.Type;
559
560export const SourceControlWritingStyleMode = Schema.Literals([
561 "repo_conventions",
562 "conventional_commits",
563 "custom",
564]);
565export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
566
567export const SourceControlWritingStyleSettings = Schema.Struct({
568 mode: SourceControlWritingStyleMode.pipe(
569 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
570 ),
571 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
572 followChangeRequestTemplates: Schema.Boolean.pipe(
573 Schema.withDecodingDefault(Effect.succeed(true)),
574 ),
575});
576export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
577
578export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
579export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
580
581export const BackgroundActivityProfile = Schema.Literals([
582 "balanced",
583 "performance",
584 "battery-saver",
585]);
586export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
587export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
588
589export const BackgroundActivityProfileSelection = Schema.Literals([
590 "balanced",
591 "performance",
592 "battery-saver",
593 "custom",
594]);
595export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
596
597export const BackgroundActivityOverrides = Schema.Struct({
598 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
599 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
600 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
601 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
602 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
603 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
604 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
605 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
606 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
607});
608export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
609
610export const BackgroundActivitySettings = Schema.Struct({
611 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
612 profile: BackgroundActivityProfileSelection.pipe(
613 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
614 ),
615 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
616 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
617}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
618export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
619
620export const ServerSettings = Schema.Struct({
621 // Legacy token-by-token assistant output. Deliberately a fresh key (was
622 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
623 // including prior opt-ins, resets to the buffered default.
624 enableLegacyTokenStreaming: Schema.Boolean.pipe(
625 Schema.withDecodingDefault(Effect.succeed(false)),
626 ),
627 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
628 /**
629 * Whether agents may drive the in-app preview browser. Turning this off
630 * withholds the MCP credential, so the `t3-code` server (and with it every
631 * `preview_*` tool) is never attached to a provider session, and the prompt
632 * text describing those tools is dropped along with them. The user's own
633 * browser panel is unaffected — this gates agent access only.
634 *
635 * Server-authoritative rather than client-local: tool injection and prompt
636 * construction both happen on the server, and the answer must not differ
637 * between a desktop window and a phone attached to the same server.
638 */
639 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
640 backgroundActivity: BackgroundActivitySettings,
641 // Legacy flat fields retained for old settings files and old clients. New
642 // consumers should resolve `backgroundActivity` instead.
643 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
644 Schema.withDecodingDefault(
645 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
646 ),
647 ),
648 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
649 Schema.withDecodingDefault(
650 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
651 ),
652 ),
653 backgroundActivityProfile: BackgroundActivityProfile.pipe(
654 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
655 ),
656 defaultThreadEnvMode: ThreadEnvMode.pipe(
657 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
658 ),
659 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
660 Schema.withDecodingDefault(Effect.succeed(true)),
661 ),
662 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
663 textGenerationModelSelection: ModelSelection.pipe(
664 Schema.withDecodingDefault(
665 Effect.succeed({
666 instanceId: ProviderInstanceId.make("codex"),
667 model: DEFAULT_TEXT_GENERATION_MODEL,
668 options: [
669 {
670 id: "reasoningEffort",
671 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
672 },
673 ],
674 }),
675 ),
676 ),
677 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
678 Schema.withDecodingDefault(Effect.succeed({})),
679 ),
680 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
681 Schema.withDecodingDefault(Effect.succeed(null)),
682 ),
683
684 // Legacy single-instance-per-driver settings. Continues to be the source
685 // of truth until `providerInstances` (below) lands per-driver migration
686 // shims and the server starts hydrating instances from it. Driver-specific
687 // schemas live here for the duration of the migration; once each driver
688 // owns its config in its own package, this struct shrinks to nothing and
689 // is removed entirely.
690 providers: Schema.Struct({
691 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
692 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
693 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
694 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
695 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
696 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
697 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
698 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
699 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
700 // (forks, downgrades, in-flight PR branches) round-trip without loss.
701 // See providerInstance.ts for the forward/backward compatibility invariant.
702 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
703 Schema.withDecodingDefault(Effect.succeed({})),
704 ),
705 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
706});
707export type ServerSettings = typeof ServerSettings.Type;
708
709export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
710
711/**
712 * Read the legacy `enabled` flag embedded in a provider instance config
713 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
714 * flag going forward; this reader exists for legacy `providers.<kind>`
715 * blobs and old settings files that still carry the flag in-config.
716 */
717export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
718 if (config === null || typeof config !== "object" || Array.isArray(config)) {
719 return undefined;
720 }
721 const enabled = (config as { readonly enabled?: unknown }).enabled;
722 return typeof enabled === "boolean" ? enabled : undefined;
723};
724
725/**
726 * Default enabled state for a built-in driver when neither the envelope nor
727 * the config blob carries a flag. Derived from the driver's settings schema
728 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
729 * the single source of truth. Unknown (fork) drivers default to enabled.
730 */
731export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
732 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
733 string,
734 { readonly enabled?: boolean } | undefined
735 >;
736 return legacyDefaults[driver]?.enabled ?? true;
737};
738
739/**
740 * Resolve whether a configured provider instance is enabled. An explicit
741 * false on either the envelope or the in-config flag wins (most
742 * restrictive), so a user's disable is never silently undone by the other
743 * flag. Otherwise: envelope, then config, then the driver's default.
744 */
745export const resolveProviderInstanceEnabled = (
746 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
747): boolean => {
748 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
749 if (instance.enabled === false || configEnabled === false) {
750 return false;
751 }
752 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
753};
754
755export const ServerSettingsOperation = Schema.Literals([
756 "normalize",
757 "check-exists",
758 "read-file",
759 "read-provider-history",
760 "read-secret",
761 "remove-secret",
762 "remove-stale-secret",
763 "write-secret",
764 "write-file",
765 "prepare-directory",
766]);
767export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
768
769export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
770 "ServerSettingsError",
771 {
772 settingsPath: Schema.String,
773 operation: ServerSettingsOperation,
774 providerInstanceId: Schema.optional(Schema.String),
775 environmentVariable: Schema.optional(Schema.String),
776 cause: Schema.Defect(),
777 },
778) {
779 override get message(): string {
780 const provider =
781 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
782 const variable =
783 this.environmentVariable === undefined
784 ? ""
785 : ` and environment variable ${this.environmentVariable}`;
786 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
787 }
788}
789
790// ── Unified type ─────────────────────────────────────────────────────
791
792export type UnifiedSettings = ServerSettings & ClientSettings;
793export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
794 ...DEFAULT_SERVER_SETTINGS,
795 ...DEFAULT_CLIENT_SETTINGS,
796};
797
798// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
799
800const ModelSelectionPatch = Schema.Struct({
801 instanceId: Schema.optionalKey(ProviderInstanceId),
802 model: Schema.optionalKey(TrimmedNonEmptyString),
803 options: Schema.optionalKey(ProviderOptionSelections),
804});
805
806const CodexSettingsPatch = Schema.Struct({
807 enabled: Schema.optionalKey(Schema.Boolean),
808 binaryPath: Schema.optionalKey(TrimmedString),
809 homePath: Schema.optionalKey(TrimmedString),
810 shadowHomePath: Schema.optionalKey(TrimmedString),
811 launchArgs: Schema.optionalKey(TrimmedString),
812 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
813});
814
815const ClaudeSettingsPatch = Schema.Struct({
816 enabled: Schema.optionalKey(Schema.Boolean),
817 binaryPath: Schema.optionalKey(TrimmedString),
818 homePath: Schema.optionalKey(TrimmedString),
819 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
820 launchArgs: Schema.optionalKey(TrimmedString),
821 // Validated at the patch boundary so a typo fails the one update with a
822 // schema error instead of a generic whole-settings failure.
823 autoCompactWindow: Schema.optionalKey(
824 TrimmedString.check(Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN)),
825 ),
826});
827
828const CursorSettingsPatch = Schema.Struct({
829 enabled: Schema.optionalKey(Schema.Boolean),
830 binaryPath: Schema.optionalKey(TrimmedString),
831 apiEndpoint: Schema.optionalKey(TrimmedString),
832 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
833});
834
835const GrokSettingsPatch = Schema.Struct({
836 enabled: Schema.optionalKey(Schema.Boolean),
837 binaryPath: Schema.optionalKey(TrimmedString),
838 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
839});
840
841const OpenCodeSettingsPatch = Schema.Struct({
842 enabled: Schema.optionalKey(Schema.Boolean),
843 binaryPath: Schema.optionalKey(TrimmedString),
844 serverUrl: Schema.optionalKey(TrimmedString),
845 serverPassword: Schema.optionalKey(TrimmedString),
846 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
847});
848
849export const ServerSettingsPatch = Schema.Struct({
850 // Server settings
851 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
852 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
853 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
854 backgroundActivity: Schema.optionalKey(
855 Schema.Struct({
856 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
857 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
858 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
859 overrides: Schema.optionalKey(BackgroundActivityOverrides),
860 }),
861 ),
862 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
863 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
864 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
865 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
866 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
867 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
868 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
869 sourceControlWritingStyle: Schema.optionalKey(
870 Schema.Struct({
871 mode: Schema.optionalKey(SourceControlWritingStyleMode),
872 customInstructions: Schema.optionalKey(TrimmedString),
873 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
874 }),
875 ),
876 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
877 observability: Schema.optionalKey(
878 Schema.Struct({
879 otlpTracesUrl: Schema.optionalKey(TrimmedString),
880 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
881 }),
882 ),
883 providers: Schema.optionalKey(
884 Schema.Struct({
885 codex: Schema.optionalKey(CodexSettingsPatch),
886 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
887 cursor: Schema.optionalKey(CursorSettingsPatch),
888 grok: Schema.optionalKey(GrokSettingsPatch),
889 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
890 }),
891 ),
892 // Whole-map replacement for the new instance config. Patching individual
893 // entries is intentionally out of scope: the map is small, and partial
894 // patches risk leaving driver-specific config in a half-merged state.
895 // The web UI sends a fully-formed map every time it edits this field.
896 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
897});
898export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
899
900export const ClientSettingsPatch = Schema.Struct({
901 appearanceContrast: Schema.optionalKey(AppearanceContrast),
902 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
903 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
904 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
905 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
906 confirmQuit: Schema.optionalKey(Schema.Boolean),
907 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
908 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
909 confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
910 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
911 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
912 glassOpacity: Schema.optionalKey(GlassOpacity),
913 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
914 fontSizePrompt: Schema.optionalKey(PromptFontSize),
915 fontSizeCode: Schema.optionalKey(CodeFontSize),
916 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
917 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
918 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
919 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
920 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
921 fontSmoothing: Schema.optionalKey(Schema.Boolean),
922 favorites: Schema.optionalKey(
923 Schema.Array(
924 Schema.Struct({
925 provider: ProviderInstanceId,
926 model: TrimmedNonEmptyString,
927 }),
928 ),
929 ),
930 providerModelPreferences: Schema.optionalKey(
931 Schema.Record(
932 ProviderInstanceId,
933 Schema.Struct({
934 hiddenModels: Schema.Array(Schema.String).pipe(
935 Schema.withDecodingDefault(Effect.succeed([])),
936 ),
937 modelOrder: Schema.Array(Schema.String).pipe(
938 Schema.withDecodingDefault(Effect.succeed([])),
939 ),
940 }),
941 ),
942 ),
943 planModeEnabled: Schema.optionalKey(Schema.Boolean),
944 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
945 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
946 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
947 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
948 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
949 sidebarProjectGroupingOverrides: Schema.optionalKey(
950 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
951 ),
952 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
953 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
954 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
955 timestampFormat: Schema.optionalKey(TimestampFormat),
956 wordWrap: Schema.optionalKey(Schema.Boolean),
957});
958export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;