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