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