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
376export const ClaudeSettings = makeProviderSettingsSchema(
377 {
378 enabled: Schema.Boolean.pipe(
379 Schema.withDecodingDefault(Effect.succeed(true)),
380 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
381 ),
382 binaryPath: makeBinaryPathSetting("claude").pipe(
383 Schema.annotateKey({
384 title: "Binary path",
385 description: "Path to the Claude binary used by this instance.",
386 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
387 }),
388 ),
389 homePath: TrimmedString.pipe(
390 Schema.withDecodingDefault(Effect.succeed("")),
391 Schema.annotateKey({
392 title: "CLAUDE_CONFIG_DIR path",
393 description:
394 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
395 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
396 }),
397 ),
398 customModels: Schema.Array(Schema.String).pipe(
399 Schema.withDecodingDefault(Effect.succeed([])),
400 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
401 ),
402 launchArgs: Schema.String.pipe(
403 Schema.withDecodingDefault(Effect.succeed("")),
404 Schema.annotateKey({
405 title: "Launch arguments",
406 description: "Additional CLI arguments passed on session start.",
407 providerSettingsForm: {
408 placeholder: "e.g. --chrome",
409 clearWhenEmpty: "omit",
410 },
411 }),
412 ),
413 },
414 {
415 order: ["binaryPath", "homePath", "launchArgs"],
416 },
417);
418export type ClaudeSettings = typeof ClaudeSettings.Type;
419
420export const CursorSettings = makeProviderSettingsSchema(
421 {
422 // Enabled by default alongside Codex and Claude Agent.
423 enabled: Schema.Boolean.pipe(
424 Schema.withDecodingDefault(Effect.succeed(true)),
425 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
426 ),
427 binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
428 Schema.annotateKey({
429 title: "Binary path",
430 description: "Path to the Cursor agent binary.",
431 providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
432 }),
433 ),
434 apiEndpoint: TrimmedString.pipe(
435 Schema.withDecodingDefault(Effect.succeed("")),
436 Schema.annotateKey({
437 title: "API endpoint",
438 description: "Override the Cursor API endpoint for this instance.",
439 providerSettingsForm: {
440 placeholder: "https://...",
441 clearWhenEmpty: "omit",
442 },
443 }),
444 ),
445 customModels: Schema.Array(Schema.String).pipe(
446 Schema.withDecodingDefault(Effect.succeed([])),
447 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
448 ),
449 },
450 {
451 order: ["binaryPath", "apiEndpoint"],
452 },
453);
454export type CursorSettings = typeof CursorSettings.Type;
455
456export const GrokSettings = makeProviderSettingsSchema(
457 {
458 // Off by default (like Cursor and OpenCode): the binding is not yet
459 // stable enough to probe on every install. Users opt in from Settings.
460 enabled: Schema.Boolean.pipe(
461 Schema.withDecodingDefault(Effect.succeed(false)),
462 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
463 ),
464 binaryPath: makeBinaryPathSetting("grok").pipe(
465 Schema.annotateKey({
466 title: "Binary path",
467 description: "Path to the Grok CLI binary.",
468 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
469 }),
470 ),
471 customModels: Schema.Array(Schema.String).pipe(
472 Schema.withDecodingDefault(Effect.succeed([])),
473 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
474 ),
475 },
476 {
477 order: ["binaryPath"],
478 },
479);
480export type GrokSettings = typeof GrokSettings.Type;
481
482export const OpenCodeSettings = makeProviderSettingsSchema(
483 {
484 // Off by default (like Cursor and Grok): the binding is not yet stable
485 // enough to probe on every install. Users opt in from Settings.
486 enabled: Schema.Boolean.pipe(
487 Schema.withDecodingDefault(Effect.succeed(false)),
488 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
489 ),
490 binaryPath: makeBinaryPathSetting("opencode").pipe(
491 Schema.annotateKey({
492 title: "Binary path",
493 description: "Path to the OpenCode binary.",
494 providerSettingsForm: {
495 placeholder: "opencode",
496 clearWhenEmpty: "omit",
497 },
498 }),
499 ),
500 serverUrl: TrimmedString.pipe(
501 Schema.withDecodingDefault(Effect.succeed("")),
502 Schema.annotateKey({
503 title: "Server URL",
504 description: "Leave blank to let T3 Code spawn the server when needed.",
505 providerSettingsForm: {
506 placeholder: "http://127.0.0.1:4096",
507 clearWhenEmpty: "omit",
508 },
509 }),
510 ),
511 serverPassword: TrimmedString.pipe(
512 Schema.withDecodingDefault(Effect.succeed("")),
513 Schema.annotateKey({
514 title: "Server password",
515 description: "Stored in plain text on disk.",
516 providerSettingsForm: {
517 control: "password",
518 placeholder: "Optional",
519 clearWhenEmpty: "omit",
520 },
521 }),
522 ),
523 customModels: Schema.Array(Schema.String).pipe(
524 Schema.withDecodingDefault(Effect.succeed([])),
525 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
526 ),
527 },
528 {
529 order: ["binaryPath", "serverUrl", "serverPassword"],
530 },
531);
532export type OpenCodeSettings = typeof OpenCodeSettings.Type;
533
534export const ObservabilitySettings = Schema.Struct({
535 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
536 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
537});
538export type ObservabilitySettings = typeof ObservabilitySettings.Type;
539
540export const SourceControlWritingStyleMode = Schema.Literals([
541 "repo_conventions",
542 "conventional_commits",
543 "custom",
544]);
545export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
546
547export const SourceControlWritingStyleSettings = Schema.Struct({
548 mode: SourceControlWritingStyleMode.pipe(
549 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
550 ),
551 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
552 followChangeRequestTemplates: Schema.Boolean.pipe(
553 Schema.withDecodingDefault(Effect.succeed(true)),
554 ),
555});
556export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
557
558export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
559export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
560
561export const BackgroundActivityProfile = Schema.Literals([
562 "balanced",
563 "performance",
564 "battery-saver",
565]);
566export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
567export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
568
569export const BackgroundActivityProfileSelection = Schema.Literals([
570 "balanced",
571 "performance",
572 "battery-saver",
573 "custom",
574]);
575export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
576
577export const BackgroundActivityOverrides = Schema.Struct({
578 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
579 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
580 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
581 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
582 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
583 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
584 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
585 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
586 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
587});
588export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
589
590export const BackgroundActivitySettings = Schema.Struct({
591 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
592 profile: BackgroundActivityProfileSelection.pipe(
593 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
594 ),
595 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
596 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
597}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
598export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
599
600export const ServerSettings = Schema.Struct({
601 // Legacy token-by-token assistant output. Deliberately a fresh key (was
602 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
603 // including prior opt-ins, resets to the buffered default.
604 enableLegacyTokenStreaming: Schema.Boolean.pipe(
605 Schema.withDecodingDefault(Effect.succeed(false)),
606 ),
607 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
608 /**
609 * Whether agents may drive the in-app preview browser. Turning this off
610 * withholds the MCP credential, so the `t3-code` server (and with it every
611 * `preview_*` tool) is never attached to a provider session, and the prompt
612 * text describing those tools is dropped along with them. The user's own
613 * browser panel is unaffected — this gates agent access only.
614 *
615 * Server-authoritative rather than client-local: tool injection and prompt
616 * construction both happen on the server, and the answer must not differ
617 * between a desktop window and a phone attached to the same server.
618 */
619 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
620 backgroundActivity: BackgroundActivitySettings,
621 // Legacy flat fields retained for old settings files and old clients. New
622 // consumers should resolve `backgroundActivity` instead.
623 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
624 Schema.withDecodingDefault(
625 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
626 ),
627 ),
628 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
629 Schema.withDecodingDefault(
630 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
631 ),
632 ),
633 backgroundActivityProfile: BackgroundActivityProfile.pipe(
634 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
635 ),
636 defaultThreadEnvMode: ThreadEnvMode.pipe(
637 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
638 ),
639 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
640 Schema.withDecodingDefault(Effect.succeed(true)),
641 ),
642 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
643 textGenerationModelSelection: ModelSelection.pipe(
644 Schema.withDecodingDefault(
645 Effect.succeed({
646 instanceId: ProviderInstanceId.make("codex"),
647 model: DEFAULT_TEXT_GENERATION_MODEL,
648 options: [
649 {
650 id: "reasoningEffort",
651 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
652 },
653 ],
654 }),
655 ),
656 ),
657 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
658 Schema.withDecodingDefault(Effect.succeed({})),
659 ),
660 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
661 Schema.withDecodingDefault(Effect.succeed(null)),
662 ),
663
664 // Legacy single-instance-per-driver settings. Continues to be the source
665 // of truth until `providerInstances` (below) lands per-driver migration
666 // shims and the server starts hydrating instances from it. Driver-specific
667 // schemas live here for the duration of the migration; once each driver
668 // owns its config in its own package, this struct shrinks to nothing and
669 // is removed entirely.
670 providers: Schema.Struct({
671 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
672 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
673 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
674 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
675 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
676 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
677 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
678 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
679 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
680 // (forks, downgrades, in-flight PR branches) round-trip without loss.
681 // See providerInstance.ts for the forward/backward compatibility invariant.
682 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
683 Schema.withDecodingDefault(Effect.succeed({})),
684 ),
685 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
686});
687export type ServerSettings = typeof ServerSettings.Type;
688
689export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
690
691/**
692 * Read the legacy `enabled` flag embedded in a provider instance config
693 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
694 * flag going forward; this reader exists for legacy `providers.<kind>`
695 * blobs and old settings files that still carry the flag in-config.
696 */
697export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
698 if (config === null || typeof config !== "object" || Array.isArray(config)) {
699 return undefined;
700 }
701 const enabled = (config as { readonly enabled?: unknown }).enabled;
702 return typeof enabled === "boolean" ? enabled : undefined;
703};
704
705/**
706 * Default enabled state for a built-in driver when neither the envelope nor
707 * the config blob carries a flag. Derived from the driver's settings schema
708 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
709 * the single source of truth. Unknown (fork) drivers default to enabled.
710 */
711export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
712 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
713 string,
714 { readonly enabled?: boolean } | undefined
715 >;
716 return legacyDefaults[driver]?.enabled ?? true;
717};
718
719/**
720 * Resolve whether a configured provider instance is enabled. An explicit
721 * false on either the envelope or the in-config flag wins (most
722 * restrictive), so a user's disable is never silently undone by the other
723 * flag. Otherwise: envelope, then config, then the driver's default.
724 */
725export const resolveProviderInstanceEnabled = (
726 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
727): boolean => {
728 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
729 if (instance.enabled === false || configEnabled === false) {
730 return false;
731 }
732 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
733};
734
735export const ServerSettingsOperation = Schema.Literals([
736 "normalize",
737 "check-exists",
738 "read-file",
739 "read-secret",
740 "remove-secret",
741 "remove-stale-secret",
742 "write-secret",
743 "write-file",
744 "prepare-directory",
745]);
746export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
747
748export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
749 "ServerSettingsError",
750 {
751 settingsPath: Schema.String,
752 operation: ServerSettingsOperation,
753 providerInstanceId: Schema.optional(Schema.String),
754 environmentVariable: Schema.optional(Schema.String),
755 cause: Schema.Defect(),
756 },
757) {
758 override get message(): string {
759 const provider =
760 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
761 const variable =
762 this.environmentVariable === undefined
763 ? ""
764 : ` and environment variable ${this.environmentVariable}`;
765 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
766 }
767}
768
769// ── Unified type ─────────────────────────────────────────────────────
770
771export type UnifiedSettings = ServerSettings & ClientSettings;
772export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
773 ...DEFAULT_SERVER_SETTINGS,
774 ...DEFAULT_CLIENT_SETTINGS,
775};
776
777// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
778
779const ModelSelectionPatch = Schema.Struct({
780 instanceId: Schema.optionalKey(ProviderInstanceId),
781 model: Schema.optionalKey(TrimmedNonEmptyString),
782 options: Schema.optionalKey(ProviderOptionSelections),
783});
784
785const CodexSettingsPatch = Schema.Struct({
786 enabled: Schema.optionalKey(Schema.Boolean),
787 binaryPath: Schema.optionalKey(TrimmedString),
788 homePath: Schema.optionalKey(TrimmedString),
789 shadowHomePath: Schema.optionalKey(TrimmedString),
790 launchArgs: Schema.optionalKey(TrimmedString),
791 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
792});
793
794const ClaudeSettingsPatch = Schema.Struct({
795 enabled: Schema.optionalKey(Schema.Boolean),
796 binaryPath: Schema.optionalKey(TrimmedString),
797 homePath: Schema.optionalKey(TrimmedString),
798 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
799 launchArgs: Schema.optionalKey(TrimmedString),
800});
801
802const CursorSettingsPatch = Schema.Struct({
803 enabled: Schema.optionalKey(Schema.Boolean),
804 binaryPath: Schema.optionalKey(TrimmedString),
805 apiEndpoint: Schema.optionalKey(TrimmedString),
806 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
807});
808
809const GrokSettingsPatch = Schema.Struct({
810 enabled: Schema.optionalKey(Schema.Boolean),
811 binaryPath: Schema.optionalKey(TrimmedString),
812 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
813});
814
815const OpenCodeSettingsPatch = Schema.Struct({
816 enabled: Schema.optionalKey(Schema.Boolean),
817 binaryPath: Schema.optionalKey(TrimmedString),
818 serverUrl: Schema.optionalKey(TrimmedString),
819 serverPassword: Schema.optionalKey(TrimmedString),
820 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
821});
822
823export const ServerSettingsPatch = Schema.Struct({
824 // Server settings
825 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
826 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
827 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
828 backgroundActivity: Schema.optionalKey(
829 Schema.Struct({
830 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
831 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
832 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
833 overrides: Schema.optionalKey(BackgroundActivityOverrides),
834 }),
835 ),
836 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
837 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
838 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
839 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
840 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
841 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
842 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
843 sourceControlWritingStyle: Schema.optionalKey(
844 Schema.Struct({
845 mode: Schema.optionalKey(SourceControlWritingStyleMode),
846 customInstructions: Schema.optionalKey(TrimmedString),
847 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
848 }),
849 ),
850 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
851 observability: Schema.optionalKey(
852 Schema.Struct({
853 otlpTracesUrl: Schema.optionalKey(TrimmedString),
854 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
855 }),
856 ),
857 providers: Schema.optionalKey(
858 Schema.Struct({
859 codex: Schema.optionalKey(CodexSettingsPatch),
860 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
861 cursor: Schema.optionalKey(CursorSettingsPatch),
862 grok: Schema.optionalKey(GrokSettingsPatch),
863 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
864 }),
865 ),
866 // Whole-map replacement for the new instance config. Patching individual
867 // entries is intentionally out of scope: the map is small, and partial
868 // patches risk leaving driver-specific config in a half-merged state.
869 // The web UI sends a fully-formed map every time it edits this field.
870 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
871});
872export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
873
874export const ClientSettingsPatch = Schema.Struct({
875 appearanceContrast: Schema.optionalKey(AppearanceContrast),
876 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
877 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
878 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
879 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
880 confirmQuit: Schema.optionalKey(Schema.Boolean),
881 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
882 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
883 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
884 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
885 glassOpacity: Schema.optionalKey(GlassOpacity),
886 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
887 fontSizePrompt: Schema.optionalKey(PromptFontSize),
888 fontSizeCode: Schema.optionalKey(CodeFontSize),
889 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
890 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
891 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
892 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
893 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
894 fontSmoothing: Schema.optionalKey(Schema.Boolean),
895 favorites: Schema.optionalKey(
896 Schema.Array(
897 Schema.Struct({
898 provider: ProviderInstanceId,
899 model: TrimmedNonEmptyString,
900 }),
901 ),
902 ),
903 providerModelPreferences: Schema.optionalKey(
904 Schema.Record(
905 ProviderInstanceId,
906 Schema.Struct({
907 hiddenModels: Schema.Array(Schema.String).pipe(
908 Schema.withDecodingDefault(Effect.succeed([])),
909 ),
910 modelOrder: Schema.Array(Schema.String).pipe(
911 Schema.withDecodingDefault(Effect.succeed([])),
912 ),
913 }),
914 ),
915 ),
916 planModeEnabled: Schema.optionalKey(Schema.Boolean),
917 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
918 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
919 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
920 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
921 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
922 sidebarProjectGroupingOverrides: Schema.optionalKey(
923 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
924 ),
925 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
926 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
927 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
928 timestampFormat: Schema.optionalKey(TimestampFormat),
929 wordWrap: Schema.optionalKey(Schema.Boolean),
930});
931export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;