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