The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,154 lines 93.5 KB
Raw
1 import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts";
2 import {
3 AuthOrchestrationOperateScope,
4 AuthAccessWriteScope,
5 AuthSettingsWriteScope,
6 AuthProvidersManageScope,
7 type AuthEnvironmentScope,
8 } from "./auth.ts";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Duration from "effect/Duration";
12 import * as Schema from "effect/Schema";
13 import * as Struct from "effect/Struct";
14 import * as SchemaTransformation from "effect/SchemaTransformation";
15 import {
16 EnvironmentId,
17 ForwardCompatibleNullable,
18 ForwardCompatibleOptional,
19 OmittedWhenNull,
20 ProjectId,
21 ThreadId,
22 TrimmedNonEmptyString,
23 TrimmedString,
24 } from "./baseSchemas.ts";
25 import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
26 import { UsageModelFilter } from "./usage.ts";
27 import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts";
28 import { containsSecretReference, SettingsSecretValue } from "./settingsSecretValue.ts";
29 import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts";
30 import { KeybindingShortcut } from "./keybindings.ts";
31 import {
32 CustomModelSetting,
33 DEFAULT_TEXT_GENERATION_MODEL,
34 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
35 ProviderOptionSelections,
36 } from "./model.ts";
37 import { ModelSelection } from "./modelSelection.ts";
38 import { ProjectScript, type ProjectMutation } from "./project.ts";
39 import { DEFAULT_RUNTIME_MODE, RuntimeMode } from "./providerPolicy.ts";
40 import { BrowserProfile, BrowserProfileId, DEFAULT_BROWSER_PROFILE_ID } from "./browserProfile.ts";
41 import {
42 BrowserRecordingFrameRate,
43 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
44 DEFAULT_PREVIEW_APPEARANCE,
45 DEFAULT_PREVIEW_ZOOM_FACTOR,
46 FILL_PREVIEW_VIEWPORT,
47 PreviewAppearancePreference,
48 PreviewViewportSetting,
49 PreviewZoomFactor,
50 } from "./preview.ts";
51 import {
52 ProviderInstanceConfig,
53 ProviderInstanceId,
54 ProviderDriverKind,
55 } from "./providerInstance.ts";
56 import { PullRequestMergeMethod } from "./pullRequest.ts";
57 import {
58 CloudSpeechModelId,
59 SpeechAcceleration,
60 SpeechCorrectionCue,
61 SpeechCustomWords,
62 SpeechLanguage,
63 SpeechModelUnloadTimeout,
64 SpeechPostProcessingPromptSettings,
65 } from "./speech.ts";
66
67 export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
68 export type TimestampFormat = typeof TimestampFormat.Type;
69 const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
70
71 export const DiffLayout = Schema.Literals(["stacked", "split"]);
72 export type DiffLayout = typeof DiffLayout.Type;
73 const DEFAULT_DIFF_LAYOUT: DiffLayout = "stacked";
74
75 export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
76 export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
77 export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
78
79 export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
80 export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
81 const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
82
83 export const SidebarProjectGroupingMode = Schema.Literals([
84 "repository",
85 "repository_path",
86 "separate",
87 ]);
88 export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
89 const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
90 export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;
91 export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;
92 export const SidebarAutoSettleAfterDays = Schema.Number.check(
93 Schema.isBetween({
94 minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
95 maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
96 }),
97 );
98 export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
99 const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 7;
100
101 export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60;
102 export const MAX_SNOOZE_PRESETS = 8;
103 export const SnoozePresetDay = Schema.Literals([
104 "today",
105 "tomorrow",
106 "monday",
107 "tuesday",
108 "wednesday",
109 "thursday",
110 "friday",
111 "saturday",
112 "sunday",
113 ]);
114 export type SnoozePresetDay = typeof SnoozePresetDay.Type;
115 /** `after` wakes a fixed time from now. `at` wakes at a local time; a weekday is its next occurrence after today. */
116 export const SnoozePresetSetting = Schema.Union([
117 Schema.Struct({
118 kind: Schema.Literal("after"),
119 minutes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: MAX_SNOOZE_PRESET_MINUTES })),
120 }),
121 Schema.Struct({
122 kind: Schema.Literal("at"),
123 day: SnoozePresetDay,
124 time: Schema.String.check(Schema.isPattern(/^([01]\d|2[0-3]):[0-5]\d$/)),
125 }),
126 ]);
127 export type SnoozePresetSetting = typeof SnoozePresetSetting.Type;
128 export const SnoozePresetSettings = Schema.Array(SnoozePresetSetting).check(
129 Schema.isMaxLength(MAX_SNOOZE_PRESETS),
130 );
131 export const DEFAULT_SNOOZE_PRESETS: ReadonlyArray<SnoozePresetSetting> = [
132 { kind: "after", minutes: 60 },
133 { kind: "after", minutes: 180 },
134 { kind: "at", day: "today", time: "18:00" },
135 { kind: "at", day: "tomorrow", time: "09:00" },
136 { kind: "at", day: "monday", time: "09:00" },
137 ];
138
139 export const MIN_GLASS_OPACITY = 40;
140 export const MAX_GLASS_OPACITY = 100;
141 export const GlassOpacity = Schema.Int.check(
142 Schema.isBetween({
143 minimum: MIN_GLASS_OPACITY,
144 maximum: MAX_GLASS_OPACITY,
145 }),
146 );
147 export type GlassOpacity = typeof GlassOpacity.Type;
148 const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;
149
150 export const MIN_APPEARANCE_CONTRAST = 50;
151 export const MAX_APPEARANCE_CONTRAST = 200;
152 export const AppearanceContrast = Schema.Int.check(
153 Schema.isBetween({ minimum: MIN_APPEARANCE_CONTRAST, maximum: MAX_APPEARANCE_CONTRAST }),
154 );
155 export type AppearanceContrast = typeof AppearanceContrast.Type;
156 const DEFAULT_APPEARANCE_CONTRAST: AppearanceContrast = 100;
157 export const MIN_PANEL_ANIMATION_DURATION_MS = 0;
158 export const MAX_PANEL_ANIMATION_DURATION_MS = 400;
159 export const PanelAnimationDurationMs = Schema.Int.check(
160 Schema.isBetween({
161 minimum: MIN_PANEL_ANIMATION_DURATION_MS,
162 maximum: MAX_PANEL_ANIMATION_DURATION_MS,
163 }),
164 );
165 export type PanelAnimationDurationMs = typeof PanelAnimationDurationMs.Type;
166 const DEFAULT_PANEL_ANIMATION_DURATION_MS: PanelAnimationDurationMs = 0;
167
168 export const MIN_INTERFACE_FONT_SIZE = 12;
169 export const MAX_INTERFACE_FONT_SIZE = 20;
170 export const InterfaceFontSize = Schema.Int.check(
171 Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),
172 );
173 export type InterfaceFontSize = typeof InterfaceFontSize.Type;
174 export const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;
175
176 export const MIN_PROMPT_FONT_SIZE = 12;
177 export const MAX_PROMPT_FONT_SIZE = 20;
178 export const PromptFontSize = Schema.Int.check(
179 Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),
180 );
181 export type PromptFontSize = typeof PromptFontSize.Type;
182 export const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;
183
184 export const MIN_CODE_FONT_SIZE = 10;
185 export const MAX_CODE_FONT_SIZE = 18;
186 export const CodeFontSize = Schema.Int.check(
187 Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),
188 );
189 export type CodeFontSize = typeof CodeFontSize.Type;
190 export const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;
191
192 export const MIN_TERMINAL_FONT_SIZE = 8;
193 export const MAX_TERMINAL_FONT_SIZE = 20;
194 export const TerminalFontSize = Schema.Int.check(
195 Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),
196 );
197 export type TerminalFontSize = typeof TerminalFontSize.Type;
198 const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;
199
200 // "artwork" follows the running channel and shows nothing on Latest. The fixed artwork
201 // modes let any channel opt into a specific channel's art.
202 export const EnvironmentIdentificationMode = Schema.Literals([
203 "artwork",
204 "nightly-artwork",
205 "dev-artwork",
206 "pill",
207 "none",
208 ]);
209 export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
210 export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
211
212 export const SnapShotKeyChord = KeybindingShortcut.check(
213 Schema.makeFilter(
214 (shortcut) =>
215 shortcut.metaKey ||
216 shortcut.ctrlKey ||
217 shortcut.shiftKey ||
218 shortcut.altKey ||
219 shortcut.modKey ||
220 "Snapshot shortcut requires a modifier.",
221 ),
222 );
223 export type SnapShotKeyChord = typeof SnapShotKeyChord.Type;
224 export const SNAP_SHOT_MODIFIERS = ["shift", "meta", "control", "alt"] as const;
225 export const SnapShotModifier = Schema.Literals(SNAP_SHOT_MODIFIERS);
226 export type SnapShotModifier = typeof SnapShotModifier.Type;
227 export const SnapShotShortcut = Schema.Union([
228 Schema.Struct({ kind: Schema.Literal("both-shift-keys") }),
229 Schema.Struct({ kind: Schema.Literal("modifier-pair"), modifier: SnapShotModifier }),
230 SnapShotKeyChord,
231 ]);
232 export type SnapShotShortcut = typeof SnapShotShortcut.Type;
233 export const SnapShotSound = Schema.Literals(["soft-pop", "camera-shutter"]);
234 export type SnapShotSound = typeof SnapShotSound.Type;
235 const DEFAULT_SNAP_SHOT_SOUND: SnapShotSound = "soft-pop";
236
237 export type SnapShotModifierPairShortcut = Extract<SnapShotShortcut, { readonly kind: string }>;
238
239 export function isModifierPairShortcut(
240 shortcut: SnapShotShortcut,
241 ): shortcut is SnapShotModifierPairShortcut {
242 return "kind" in shortcut;
243 }
244
245 export function snapShotShortcutModifierPair(
246 shortcut: SnapShotModifierPairShortcut,
247 ): SnapShotModifier {
248 return shortcut.kind === "both-shift-keys" ? "shift" : shortcut.modifier;
249 }
250
251 const APPLE_MODIFIER_LABELS: Record<SnapShotModifier, string> = {
252 shift: "Shift",
253 meta: "Command",
254 control: "Control",
255 alt: "Option",
256 };
257 const OTHER_MODIFIER_LABELS: Record<SnapShotModifier, string> = {
258 shift: "Shift",
259 meta: "Super",
260 control: "Ctrl",
261 alt: "Alt",
262 };
263
264 export function snapShotModifierPairLabel(modifier: SnapShotModifier, apple: boolean): string {
265 const label = (apple ? APPLE_MODIFIER_LABELS : OTHER_MODIFIER_LABELS)[modifier];
266 return `${label} + ${label}`;
267 }
268 const DEFAULT_SNAP_SHOT_SHORTCUT: SnapShotShortcut = {
269 kind: "both-shift-keys",
270 };
271
272 export const NotificationMode = Schema.Literals([
273 "off",
274 "notifications",
275 "sound",
276 "notifications-and-sound",
277 ]);
278 export type NotificationMode = typeof NotificationMode.Type;
279
280 export const QuitConfirmationMode = Schema.Literals(["direct", "hold", "double-click"]);
281 export type QuitConfirmationMode = typeof QuitConfirmationMode.Type;
282 const DEFAULT_QUIT_CONFIRMATION_MODE: QuitConfirmationMode = "hold";
283
284 const LegacyConfirmQuit = Schema.Boolean.pipe(
285 Schema.decodeTo(
286 QuitConfirmationMode,
287 SchemaTransformation.transform({
288 decode: (confirmQuit): QuitConfirmationMode => (confirmQuit ? "hold" : "direct"),
289 encode: (mode) => mode === "hold",
290 }),
291 ),
292 );
293
294 const QuitConfirmationModeSetting = Schema.Union([QuitConfirmationMode, LegacyConfirmQuit]);
295
296 export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));
297 export type FontFamilyPreference = typeof FontFamilyPreference.Type;
298
299 /** Clients apply each environment theme set once; later local choices persist until the next set. Empty clears it. */
300 export const DefaultThemePreference = Schema.String.check(Schema.isMaxLength(64));
301 // Excluded from RPC patches so t3 theme set can validate syntax and resolvability.
302 export type DefaultThemePreference = typeof DefaultThemePreference.Type;
303
304 /** A mode clients apply once per set, like the default theme. Empty sets none. */
305 export const DefaultAppearancePreference = Schema.Literals(["", "light", "dark", "system"]);
306 export type DefaultAppearancePreference = typeof DefaultAppearancePreference.Type;
307
308 export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;
309 export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;
310 export {
311 BROWSER_RECORDING_FRAME_RATES,
312 BrowserRecordingFrameRate,
313 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
314 } from "./preview.ts";
315 export const BrowserLinkTarget = Schema.Literals(["system", "app"]);
316 export type BrowserLinkTarget = typeof BrowserLinkTarget.Type;
317 export const DEFAULT_BROWSER_LINK_TARGET: BrowserLinkTarget = "system";
318 /**
319 * Where a plain click opens a subagent, a side chat or a linked environment's thread: beside the
320 * thread you are in, or in its place. A modified click opens it in the other one.
321 */
322 export const SideThreadOpenTarget = Schema.Literals(["panel", "main"]);
323 export type SideThreadOpenTarget = typeof SideThreadOpenTarget.Type;
324 const DEFAULT_SIDE_THREAD_OPEN_TARGET: SideThreadOpenTarget = "panel";
325 /**
326 * What the address bar searches with when the input is not an address.
327 * "custom" uses `browserCustomSearchUrl`, a template with `%s` for the query.
328 */
329 export const BrowserSearchEngine = Schema.Literals([
330 "duckduckgo",
331 "google",
332 "bing",
333 "brave",
334 "kagi",
335 "ecosia",
336 "custom",
337 ]);
338 export type BrowserSearchEngine = typeof BrowserSearchEngine.Type;
339 export const DEFAULT_BROWSER_SEARCH_ENGINE: BrowserSearchEngine = "duckduckgo";
340 export const BROWSER_CUSTOM_SEARCH_URL_MAX_LENGTH = 2048;
341 export const BrowserCustomSearchUrl = Schema.String.check(
342 Schema.isMaxLength(BROWSER_CUSTOM_SEARCH_URL_MAX_LENGTH),
343 );
344
345 export const LoadBalancingWeights = Schema.Record(
346 TrimmedNonEmptyString,
347 Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 })),
348 );
349
350 export const DiffColorScheme = Schema.Literals(["red-green", "blue-orange"]);
351
352 export const ChatWidth = Schema.Literals(["comfortable", "wide", "full"]);
353 export type ChatWidth = typeof ChatWidth.Type;
354
355 /** How the composer shows reasoning effort: the level's name, or rising bars. */
356 export const EffortDisplay = Schema.Literals(["label", "bars"]);
357 export type EffortDisplay = typeof EffortDisplay.Type;
358
359 export const ToolCallVisibility = Schema.Literals(["showAll", "hideSuccessful", "hideAll", "zen"]);
360 export type ToolCallVisibility = typeof ToolCallVisibility.Type;
361
362 /** What the open thread reads to a screen reader: turn status, the agent's in-between messages too, or every step. */
363 export const ScreenReaderAnnouncements = Schema.Literals(["status", "messages", "everything"]);
364 export type ScreenReaderAnnouncements = typeof ScreenReaderAnnouncements.Type;
365
366 export const ModelFavorite = Schema.Struct({
367 provider: ProviderInstanceId,
368 model: TrimmedNonEmptyString,
369 });
370 export const ModelFavorites = Schema.Array(ModelFavorite);
371 export const ProviderModelPreferences = Schema.Record(
372 ProviderInstanceId,
373 Schema.Struct({
374 hiddenModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
375 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
376 }),
377 );
378 export type ModelPreferences = {
379 readonly favorites: typeof ModelFavorites.Type;
380 readonly providerModelPreferences: typeof ProviderModelPreferences.Type;
381 };
382
383 export const VoiceShortcutMode = Schema.Literals(["auto", "hold", "toggle"]);
384 export type VoiceShortcutMode = typeof VoiceShortcutMode.Type;
385
386 export const VoiceMicrophoneEntry = Schema.Union([
387 Schema.Struct({ kind: Schema.Literal("default") }),
388 Schema.Struct({ kind: Schema.Literal("device"), deviceId: Schema.String, label: Schema.String }),
389 ]);
390 export type VoiceMicrophoneEntry = typeof VoiceMicrophoneEntry.Type;
391
392 /**
393 * Where this device sends microphone audio. A cloud grant names the forwarding environment and
394 * the provider; an OpenRouter grant also names the exact model, since OpenRouter has no default.
395 */
396 export const VoiceTranscriptionDestination = Schema.Union([
397 Schema.Struct({ kind: Schema.Literal("environment"), environmentId: EnvironmentId }),
398 Schema.Struct({
399 kind: Schema.Literal("cloud"),
400 environmentId: EnvironmentId,
401 provider: Schema.Literals(["openai", "xai"]),
402 }),
403 Schema.Struct({
404 kind: Schema.Literal("cloud"),
405 environmentId: EnvironmentId,
406 provider: Schema.Literal("openrouter"),
407 model: CloudSpeechModelId,
408 }),
409 ]);
410 export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type;
411
412 export const ClientSettingsSchema = Schema.Struct({
413 notificationMode: NotificationMode.pipe(
414 Schema.withDecodingDefault(Effect.succeed("off" as const)),
415 ),
416 inAppNotificationsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
417 diffColorScheme: DiffColorScheme.pipe(
418 Schema.withDecodingDefault(Effect.succeed("red-green" as const)),
419 ),
420 chatWidth: ChatWidth.pipe(Schema.withDecodingDefault(Effect.succeed("comfortable" as const))),
421 effortDisplay: EffortDisplay.pipe(Schema.withDecodingDefault(Effect.succeed("label" as const))),
422 loadBalancingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
423 loadBalancingWeights: LoadBalancingWeights.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
424 appearanceContrast: AppearanceContrast.pipe(
425 Schema.withDecodingDefault(Effect.succeed(DEFAULT_APPEARANCE_CONTRAST)),
426 ),
427 // Zero avoids per-frame layout work from width/height transitions.
428 panelAnimationDurationMs: PanelAnimationDurationMs.pipe(
429 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PANEL_ANIMATION_DURATION_MS)),
430 ),
431 browserDefaultViewport: PreviewViewportSetting.pipe(
432 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_VIEWPORT)),
433 ),
434 browserDefaultZoomFactor: PreviewZoomFactor.pipe(
435 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_ZOOM_FACTOR)),
436 ),
437 browserDefaultAppearance: PreviewAppearancePreference.pipe(
438 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_APPEARANCE)),
439 ),
440 browserRecordingFrameRate: BrowserRecordingFrameRate.pipe(
441 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_RECORDING_FRAME_RATE)),
442 ),
443 browserRecordingShowKeyPresses: Schema.Boolean.pipe(
444 Schema.withDecodingDefault(Effect.succeed(false)),
445 ),
446 browserRecordingShowMousePresses: Schema.Boolean.pipe(
447 Schema.withDecodingDefault(Effect.succeed(false)),
448 ),
449
450 browserLinkTarget: BrowserLinkTarget.pipe(
451 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_LINK_TARGET)),
452 ),
453
454 browserSearchEngine: BrowserSearchEngine.pipe(
455 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_SEARCH_ENGINE)),
456 ),
457
458 // Kept when the engine is switched away from "custom" so switching back restores it.
459 browserCustomSearchUrl: BrowserCustomSearchUrl.pipe(
460 Schema.withDecodingDefault(Effect.succeed("")),
461 ),
462
463 browserAutoShowFloatingPreview: Schema.Boolean.pipe(
464 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW)),
465 ),
466
467 browserProfiles: Schema.Array(BrowserProfile).pipe(
468 Schema.withDecodingDefault(Effect.succeed([])),
469 ),
470
471 browserDefaultProfileId: BrowserProfileId.pipe(
472 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_PROFILE_ID)),
473 ),
474
475 confirmQuit: QuitConfirmationModeSetting.pipe(
476 Schema.withDecodingDefault(Effect.succeed(DEFAULT_QUIT_CONFIRMATION_MODE)),
477 ),
478 confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
479 confirmTerminalClose: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
480 confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
481 confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
482 diffFilesCollapsed: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
483 diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
484 diffLayout: DiffLayout.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_DIFF_LAYOUT))),
485 environmentIdentificationMode: EnvironmentIdentificationMode.pipe(
486 Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),
487 ),
488 glassOpacity: GlassOpacity.pipe(
489 Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
490 ),
491 fontSizeInterface: InterfaceFontSize.pipe(
492 Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),
493 ),
494 fontSizePrompt: PromptFontSize.pipe(
495 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),
496 ),
497 fontSizeCode: CodeFontSize.pipe(
498 Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),
499 ),
500 fontSizeTerminal: TerminalFontSize.pipe(
501 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),
502 ),
503 fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
504 fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
505 fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
506 fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
507
508 fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
509 // Older installs also decode to null; onboarding must additionally require an empty workspace.
510 onboardingCompletedAt: Schema.NullOr(Schema.String).pipe(
511 Schema.withDecodingDefault(Effect.succeed(null)),
512 ),
513 persistComposerContextStrip: Schema.Boolean.pipe(
514 Schema.withDecodingDefault(Effect.succeed(false)),
515 ),
516
517 favorites: ModelFavorites.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
518 providerModelPreferences: ProviderModelPreferences.pipe(
519 Schema.withDecodingDefault(Effect.succeed({})),
520 ),
521 pullRequestMergeMethodOverrides: Schema.Record(
522 TrimmedNonEmptyString,
523 PullRequestMergeMethod,
524 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
525
526 pullRequestLinksOpenInApp: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
527
528 composerRichTextEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
529 sendShortcut: Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"]).pipe(
530 Schema.withDecodingDefault(Effect.succeed("enter")),
531 ),
532 followUpBehavior: Schema.Literals(["queue", "steer"]).pipe(
533 Schema.withDecodingDefault(Effect.succeed("steer")),
534 ),
535 sideThreadOpenTarget: SideThreadOpenTarget.pipe(
536 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDE_THREAD_OPEN_TARGET)),
537 ),
538 proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
539 showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
540 boringSidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
541 boringSidebarMultilineRows: Schema.Boolean.pipe(
542 Schema.withDecodingDefault(Effect.succeed(false)),
543 ),
544 toolCallVisibility: ToolCallVisibility.pipe(
545 Schema.withDecodingDefault(Effect.succeed("showAll" as const)),
546 ),
547 screenReaderAnnouncements: ScreenReaderAnnouncements.pipe(
548 Schema.withDecodingDefault(Effect.succeed("status" as const)),
549 ),
550 screenReaderWindowTitle: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
551 // Retired Labs toggle. Still read as the default for the Usage item in threadDetailsItems.
552 threadDetailsUsageEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
553 // Sparse show/hide overrides for thread details card items. Missing ids use the client's
554 // default, so new items appear for everyone and unknown ids survive a downgrade.
555 threadDetailsItems: Schema.Record(Schema.String, Schema.Boolean).pipe(
556 Schema.withDecodingDefault(Effect.succeed({})),
557 ),
558 sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
559 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
560 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
561 ),
562 sidebarProjectGroupingOverrides: Schema.Record(
563 TrimmedNonEmptyString,
564 SidebarProjectGroupingMode,
565 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
566 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
567 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
568 ),
569 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
570 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
571 ),
572 timestampFormat: TimestampFormat.pipe(
573 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
574 ),
575 // Superseded by voiceMicrophones; read only to seed an empty order.
576 voiceMicrophone: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
577 // Device-local microphone order. Recording uses the first connected entry.
578 voiceMicrophones: Schema.Array(VoiceMicrophoneEntry).pipe(
579 Schema.withDecodingDefault(Effect.succeed([])),
580 ),
581 voiceShortcutMode: VoiceShortcutMode.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))),
582 speechLanguage: SpeechLanguage.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))),
583 speechTranslateToEnglish: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
584 speechCustomWords: SpeechCustomWords.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
585 speechSilenceFiltering: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
586 speechStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
587 speechRemoveFillerWords: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
588 speechPostProcessingPrompt: SpeechPostProcessingPromptSettings.pipe(
589 Schema.withDecodingDefault(
590 Effect.succeed({ mode: "default" as const, customInstructions: "" }),
591 ),
592 ),
593 speechCorrectionWord: SpeechCorrectionCue.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
594 // A locale code or "system". Open string so new locales and downgrades need no migration.
595 language: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("en"))),
596 snapShotEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
597 snapShotIncludeAccessibility: Schema.Boolean.pipe(
598 Schema.withDecodingDefault(Effect.succeed(true)),
599 ),
600 snapShotShortcut: SnapShotShortcut.pipe(
601 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNAP_SHOT_SHORTCUT)),
602 ),
603 snapShotPlaySound: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
604 snapShotSound: SnapShotSound.pipe(
605 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNAP_SHOT_SOUND)),
606 ),
607 snapShotFlash: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
608 snapShotAnimations: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
609 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
610 // Opt-in TeX typesetting in rendered Markdown. Off keeps math parsing and
611 // KaTeX out of the render path entirely.
612 mathRenderingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
613 });
614 export type ClientSettings = typeof ClientSettingsSchema.Type;
615
616 export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
617
618 const UsageModelTokenPrice = Schema.Number.check(
619 Schema.isFinite(),
620 Schema.isGreaterThanOrEqualTo(0),
621 );
622
623 /** Omitted cache rates use the input rate. */
624 export const UsageModelPriceOverride = Schema.Struct({
625 inputCostPerMillionTokens: UsageModelTokenPrice,
626 outputCostPerMillionTokens: UsageModelTokenPrice,
627 cacheReadCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),
628 cacheWriteCostPerMillionTokens: Schema.optionalKey(UsageModelTokenPrice),
629 });
630 export type UsageModelPriceOverride = typeof UsageModelPriceOverride.Type;
631
632 export const makeBinaryPathSetting = (fallback: string) =>
633 TrimmedString.pipe(
634 Schema.decodeTo(
635 Schema.String,
636 SchemaTransformation.transformEffect({
637 decode: (value) => Effect.succeed(value || fallback),
638 encode: (value) => Effect.succeed(value),
639 }),
640 ),
641 Schema.withDecodingDefault(Effect.succeed(fallback)),
642 );
643
644 export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch" | "select";
645
646 export interface ProviderSettingsFormOption {
647 readonly value: string;
648 readonly label: string;
649 }
650
651 export interface ProviderSettingsFormAnnotation {
652 readonly control?: ProviderSettingsFormControl | undefined;
653 readonly placeholder?: string | undefined;
654 readonly hidden?: boolean | undefined;
655 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
656
657 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
658 }
659
660 export function secretSettingsFields(schema: {
661 readonly fields: Readonly<Record<string, Schema.Top>>;
662 }): ReadonlyArray<string> {
663 return Object.entries(schema.fields).flatMap(([field, fieldSchema]) => {
664 return isSecretSetting(fieldSchema) ? [field] : [];
665 });
666 }
667
668 export interface ProviderSettingsFormSchemaAnnotation {
669 readonly order?: readonly string[] | undefined;
670 }
671
672 declare module "effect/Schema" {
673 namespace Annotations {
674 interface Annotations {
675 /** Store this credential separately and expose only whether it is configured to clients. */
676 readonly settingsSecret?: boolean | undefined;
677 /** Set by `SettingsSecretValue`: the credential may name a secret provider reference. */
678 readonly settingsSecretReference?: boolean | undefined;
679 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
680 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
681 }
682 }
683 }
684
685 export function secretSetting<S extends Schema.Top>(schema: S): S["Rebuild"] {
686 return schema.annotateKey({ settingsSecret: true });
687 }
688
689 /** A masked form field is a credential too, so none is saved or sent to clients as plain text. */
690 export function isSecretSetting(schema: Schema.Top): boolean {
691 const annotations = Schema.resolveAnnotationsKey(schema) ?? Schema.resolveAnnotations(schema);
692 return (
693 annotations?.settingsSecret === true ||
694 annotations?.providerSettingsForm?.control === "password"
695 );
696 }
697
698 export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
699 keyof Fields,
700 string
701 >[];
702
703 export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
704 fields: Fields,
705 options?: {
706 readonly order?: ProviderSettingsOrder<Fields> | undefined;
707 },
708 ): Schema.Struct<Fields> {
709 return Schema.Struct(fields).pipe(
710 Schema.annotate({
711 providerSettingsFormSchema:
712 options?.order === undefined ? undefined : { order: options.order },
713 }),
714 );
715 }
716
717 export const CodexSettings = makeProviderSettingsSchema(
718 {
719 setupMode: Schema.optionalKey(Schema.Literals(["managed", "existing"])).pipe(
720 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
721 ),
722 enabled: Schema.Boolean.pipe(
723 Schema.withDecodingDefault(Effect.succeed(true)),
724 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
725 ),
726 binaryPath: makeBinaryPathSetting("codex").pipe(
727 Schema.annotateKey({
728 title: "Binary path",
729 description: "Path to the Codex binary used by this instance.",
730 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
731 }),
732 ),
733 homePath: TrimmedString.pipe(
734 Schema.withDecodingDefault(Effect.succeed("")),
735 Schema.annotateKey({
736 title: "CODEX_HOME path",
737 description: "Custom Codex home and config directory.",
738 providerSettingsForm: {
739 placeholder: "~/.codex",
740 clearWhenEmpty: "omit",
741 },
742 }),
743 ),
744 shadowHomePath: TrimmedString.pipe(
745 Schema.withDecodingDefault(Effect.succeed("")),
746 Schema.annotateKey({
747 title: "Shadow home path",
748 description:
749 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
750 providerSettingsForm: {
751 placeholder: "~/.codex-t3/personal",
752 clearWhenEmpty: "omit",
753 },
754 }),
755 ),
756 launchArgs: TrimmedString.pipe(
757 Schema.withDecodingDefault(Effect.succeed("")),
758 Schema.annotateKey({
759 title: "Launch arguments",
760 description: "Additional CLI arguments passed to codex app-server on session start.",
761 }),
762 ),
763 customModels: Schema.Array(CustomModelSetting).pipe(
764 Schema.withDecodingDefault(Effect.succeed([])),
765 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
766 ),
767 },
768 {
769 order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
770 },
771 );
772 export type CodexSettings = typeof CodexSettings.Type;
773
774 const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
775
776 export const IDLE_COMPACTION_MODES = [
777 { value: "onReturn", label: "When you return" },
778 { value: "beforeCacheExpires", label: "Before the cache expires (beta)" },
779 { value: "off", label: "Never" },
780 ] as const;
781 export const IdleCompactionMode = Schema.Literals(IDLE_COMPACTION_MODES.map((mode) => mode.value));
782 export type IdleCompactionMode = typeof IdleCompactionMode.Type;
783
784 // Shipped clients reject the whole server config unless `compactIdleThreads` is boolean.
785 // Keep the mode in `idleCompaction`, but accept strings from older servers.
786 const LegacyCompactIdleThreads = Schema.Union([Schema.Boolean, IdleCompactionMode]);
787
788 const INSTANCE_IDLE_COMPACTION_MODES = [
789 { value: "default", label: "Use default" },
790 ...IDLE_COMPACTION_MODES,
791 ] as const;
792 const InstanceIdleCompaction = Schema.Literals(
793 INSTANCE_IDLE_COMPACTION_MODES.map((mode) => mode.value),
794 );
795
796 export const ClaudeSettings = makeProviderSettingsSchema(
797 {
798 enabled: Schema.Boolean.pipe(
799 Schema.withDecodingDefault(Effect.succeed(true)),
800 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
801 ),
802 binaryPath: makeBinaryPathSetting("claude").pipe(
803 Schema.annotateKey({
804 title: "Binary path",
805 description: "Path to the Claude binary used by this instance.",
806 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
807 }),
808 ),
809 homePath: TrimmedString.pipe(
810 Schema.withDecodingDefault(Effect.succeed("")),
811 Schema.annotateKey({
812 title: "CLAUDE_CONFIG_DIR path",
813 description:
814 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
815 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
816 }),
817 ),
818 customModels: Schema.Array(CustomModelSetting).pipe(
819 Schema.withDecodingDefault(Effect.succeed([])),
820 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
821 ),
822 launchArgs: Schema.String.pipe(
823 Schema.withDecodingDefault(Effect.succeed("")),
824 Schema.annotateKey({
825 title: "Launch arguments",
826 description: "Additional CLI arguments passed on session start.",
827 providerSettingsForm: {
828 placeholder: "e.g. --chrome",
829 clearWhenEmpty: "omit",
830 },
831 }),
832 ),
833 autoCompactWindow: TrimmedString.check(
834 Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN),
835 ).pipe(
836 Schema.withDecodingDefault(Effect.succeed("")),
837 Schema.annotateKey({
838 title: "Auto-compact after",
839 description:
840 "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
841 providerSettingsForm: {
842 placeholder: "e.g. 300000",
843 clearWhenEmpty: "omit",
844 },
845 }),
846 ),
847 idleCompaction: InstanceIdleCompaction.pipe(
848 Schema.withDecodingDefault(Effect.succeed("default" as const)),
849 Schema.annotateKey({
850 title: "Compact idle threads",
851 description:
852 "When to compact an idle thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Overrides the default in Providers > Advanced.",
853 providerSettingsForm: {
854 control: "select",
855 options: INSTANCE_IDLE_COMPACTION_MODES,
856 clearWhenEmpty: "omit",
857 },
858 }),
859 ),
860 },
861 {
862 order: ["binaryPath", "homePath", "autoCompactWindow", "idleCompaction", "launchArgs"],
863 },
864 );
865 export type ClaudeSettings = typeof ClaudeSettings.Type;
866
867 export const ANTIGRAVITY_AUTH_METHODS = [
868 { value: "oauth-personal", label: "Google account" },
869 { value: "oauth-business", label: "Gemini Enterprise" },
870 { value: "gemini-api-key", label: "Gemini API key" },
871 { value: "agent-platform", label: "Agent Platform (Vertex AI)" },
872 ] as const satisfies ReadonlyArray<ProviderSettingsFormOption>;
873 export const AntigravityAuthMethod = Schema.Literals(
874 ANTIGRAVITY_AUTH_METHODS.map((method) => method.value),
875 );
876 export type AntigravityAuthMethod = typeof AntigravityAuthMethod.Type;
877
878 export const AntigravitySettings = makeProviderSettingsSchema(
879 {
880 enabled: Schema.Boolean.pipe(
881 Schema.withDecodingDefault(Effect.succeed(false)),
882 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
883 ),
884 authMethod: AntigravityAuthMethod.pipe(
885 Schema.withDecodingDefault(Effect.succeed("oauth-personal" as const)),
886 Schema.annotateKey({
887 title: "Sign-in method",
888 description:
889 "Google accounts use your subscription; API keys and Agent Platform bill usage.",
890 providerSettingsForm: {
891 control: "select",
892 options: ANTIGRAVITY_AUTH_METHODS,
893 clearWhenEmpty: "omit",
894 },
895 }),
896 ),
897 apiKey: SettingsSecretValue.pipe(
898 secretSetting,
899 Schema.withDecodingDefault(Effect.succeed("")),
900 Schema.annotateKey({
901 title: "API key",
902 description: "Gemini or Vertex AI express key. Stored separately on the host.",
903 providerSettingsForm: {
904 control: "password",
905 placeholder: "Optional",
906 clearWhenEmpty: "omit",
907 },
908 }),
909 ),
910 gcpProject: TrimmedString.pipe(
911 Schema.withDecodingDefault(Effect.succeed("")),
912 Schema.annotateKey({
913 title: "GCP project",
914 description:
915 "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
916 providerSettingsForm: { placeholder: "my-project-id", clearWhenEmpty: "omit" },
917 }),
918 ),
919 gcpLocation: TrimmedString.pipe(
920 Schema.withDecodingDefault(Effect.succeed("")),
921 Schema.annotateKey({
922 title: "GCP location",
923 description: "Region for Gemini Enterprise or Agent Platform.",
924 providerSettingsForm: { placeholder: "us-central1", clearWhenEmpty: "omit" },
925 }),
926 ),
927 binaryPath: TrimmedString.pipe(
928 Schema.withDecodingDefault(Effect.succeed("")),
929 Schema.annotateKey({
930 title: "Binary path",
931 description: "Custom ACP executable. Leave empty to select automatically.",
932 providerSettingsForm: { placeholder: "Automatic", clearWhenEmpty: "persist" },
933 }),
934 ),
935 customModels: Schema.Array(CustomModelSetting).pipe(
936 Schema.withDecodingDefault(Effect.succeed([])),
937 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
938 ),
939 },
940 { order: ["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"] },
941 );
942 export type AntigravitySettings = typeof AntigravitySettings.Type;
943
944 export const UsageLimitSourceConfig = Schema.Struct({
945 kind: Schema.Literal("cliproxy"),
946 label: Schema.optional(TrimmedNonEmptyString),
947 url: TrimmedNonEmptyString,
948 managementKey: SettingsSecretValue.pipe(
949 Schema.withDecodingDefault(Effect.succeed("")),
950 secretSetting,
951 ),
952 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
953 });
954 export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;
955
956 export const TextGeneratorKind = Schema.Literals(["openaiCompatible", "anthropic"]);
957 export type TextGeneratorKind = typeof TextGeneratorKind.Type;
958
959 const TextGeneratorBaseUrl = TrimmedNonEmptyString.check(
960 Schema.isMaxLength(2048),
961 Schema.makeFilter((value) => {
962 try {
963 const url = new URL(value);
964 return (
965 (url.protocol === "http:" || url.protocol === "https:") &&
966 !url.username &&
967 !url.password &&
968 !url.search &&
969 !url.hash
970 );
971 } catch {
972 return false;
973 }
974 }),
975 );
976
977 /** A model API that only generates text. Its key shares the id namespace with provider instances. */
978 export const TextGeneratorConfig = Schema.Struct({
979 kind: TextGeneratorKind,
980 label: Schema.optional(TrimmedNonEmptyString),
981 baseUrl: TextGeneratorBaseUrl,
982 apiKey: SettingsSecretValue.pipe(Schema.withDecodingDefault(Effect.succeed("")), secretSetting),
983 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
984 });
985 export type TextGeneratorConfig = typeof TextGeneratorConfig.Type;
986
987 export const TextGeneratorModel = Schema.Struct({
988 id: TrimmedNonEmptyString,
989 name: TrimmedNonEmptyString,
990 });
991 export type TextGeneratorModel = typeof TextGeneratorModel.Type;
992
993 export const ListTextGeneratorModelsInput = Schema.Struct({
994 id: ProviderInstanceId,
995 /**
996 * Unsaved settings to check before saving, such as from the add dialog. A redacted key keeps
997 * the one saved under `id`.
998 */
999 config: Schema.optional(TextGeneratorConfig),
1000 /** Skip the server's cached list and ask the API again. */
1001 refresh: Schema.optional(Schema.Boolean),
1002 /** Also have a model answer a tiny prompt, which proves the key, endpoint, and model. */
1003 test: Schema.optional(Schema.Boolean),
1004 /** With `test`, the model to try; a cheap listed one when omitted. */
1005 model: Schema.optional(TrimmedNonEmptyString),
1006 });
1007 export type ListTextGeneratorModelsInput = typeof ListTextGeneratorModelsInput.Type;
1008
1009 export const ListTextGeneratorModelsResult = Schema.Struct({
1010 models: Schema.Array(TextGeneratorModel),
1011 /** The model that answered, when `test` was set. */
1012 testedModel: Schema.optional(TrimmedNonEmptyString),
1013 });
1014 export type ListTextGeneratorModelsResult = typeof ListTextGeneratorModelsResult.Type;
1015
1016 export class TextGeneratorError extends Schema.TaggedError<TextGeneratorError>()(
1017 "TextGeneratorError",
1018 { detail: Schema.String },
1019 ) {
1020 override get message(): string {
1021 return this.detail;
1022 }
1023 }
1024
1025 export const SecretProviderKind = SecretProviderSlug.pipe(Schema.brand("SecretProviderKind"));
1026 export type SecretProviderKind = typeof SecretProviderKind.Type;
1027
1028 export const SecretProviderLabel = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
1029
1030 /** Kinds decode their own config; unknown-kind envelopes round-trip verbatim across versions. */
1031 export const SecretProviderConfig = Schema.Struct({
1032 kind: SecretProviderKind,
1033 label: TrimmedNonEmptyString,
1034 config: Schema.optionalKey(Schema.Unknown),
1035 });
1036 export type SecretProviderConfig = typeof SecretProviderConfig.Type;
1037
1038 // Limits that may change later are enforced on writes only, never on the stored envelope. The
1039 // server also checks the kind and its config against the secret providers it has loaded.
1040 const SecretProviderConfigWrite = Schema.Struct({
1041 ...SecretProviderConfig.fields,
1042 label: SecretProviderLabel,
1043 });
1044
1045 export const SourceControlHostSettings = Schema.Record(Schema.String, Schema.Unknown);
1046 export type SourceControlHostSettings = typeof SourceControlHostSettings.Type;
1047
1048 export const ObservabilitySettings = Schema.Struct({
1049 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1050 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1051 otlpLogsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1052 });
1053 export type ObservabilitySettings = typeof ObservabilitySettings.Type;
1054
1055 export const SourceControlWritingStyleMode = Schema.Literals([
1056 "repo_conventions",
1057 "conventional_commits",
1058 "custom",
1059 ]);
1060 export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
1061
1062 export const SourceControlWritingStyleSettings = Schema.Struct({
1063 mode: SourceControlWritingStyleMode.pipe(
1064 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
1065 ),
1066 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1067 followChangeRequestTemplates: Schema.Boolean.pipe(
1068 Schema.withDecodingDefault(Effect.succeed(true)),
1069 ),
1070 });
1071 export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
1072
1073 const LegacySourceControlWritingStyle = TrimmedString.pipe(
1074 Schema.decodeTo(
1075 Schema.toType(SourceControlWritingStyleSettings),
1076 SchemaTransformation.transform({
1077 decode: (value): SourceControlWritingStyleSettings => ({
1078 mode: value.length > 0 ? "custom" : "repo_conventions",
1079 customInstructions: value,
1080 followChangeRequestTemplates: true,
1081 }),
1082 encode: (value) => value.customInstructions,
1083 }),
1084 ),
1085 );
1086
1087 // The struct member comes first so encoding uses its defaulted fields: the server strips
1088 // default sub-fields before writing settings.json, and a toType target would reject them.
1089 const SourceControlWritingStyleSetting = Schema.Union([
1090 SourceControlWritingStyleSettings,
1091 LegacySourceControlWritingStyle,
1092 ]);
1093
1094 export const BranchNamingMode = Schema.Literals(["static", "semantic", "custom"]);
1095 export type BranchNamingMode = typeof BranchNamingMode.Type;
1096
1097 export interface BranchNamingOptions {
1098 mode: BranchNamingMode;
1099 prefix: string;
1100 instructions: string;
1101 }
1102
1103 export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
1104 export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
1105
1106 export const BackgroundActivityProfile = Schema.Literals([
1107 "balanced",
1108 "performance",
1109 "battery-saver",
1110 ]);
1111 export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
1112 export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
1113
1114 export const BackgroundActivityProfileSelection = Schema.Literals([
1115 "balanced",
1116 "performance",
1117 "battery-saver",
1118 "custom",
1119 ]);
1120 export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
1121
1122 export const BackgroundActivityOverrides = Schema.Struct({
1123 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1124 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1125 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
1126 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
1127 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
1128 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
1129 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
1130 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
1131 });
1132 export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
1133
1134 export const BackgroundActivitySettings = Schema.Struct({
1135 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
1136 profile: BackgroundActivityProfileSelection.pipe(
1137 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
1138 ),
1139 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
1140 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
1141 }).pipe(Schema.withDecodingDefault(Effect.succeed({})));
1142 export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
1143
1144 export const ResponseStreamingMode = Schema.Literals(["turn", "paragraph"]);
1145 export type ResponseStreamingMode = typeof ResponseStreamingMode.Type;
1146
1147 const StorageRetentionDays = Schema.NullOr(
1148 Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3650 })),
1149 );
1150 const SettledWorktreeRetentionDays = Schema.NullOr(
1151 Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 3650 })),
1152 );
1153
1154 export const WorktreeKeepWhen = Schema.Literals([
1155 "any-local-files",
1156 "uncommitted-changes",
1157 "tracked-changes",
1158 ]);
1159 export type WorktreeKeepWhen = typeof WorktreeKeepWhen.Type;
1160
1161 export const WorktreeCleanupRules = Schema.Struct({
1162 worktreeKeepWhen: WorktreeKeepWhen.pipe(
1163 Schema.withDecodingDefault(Effect.succeed("uncommitted-changes")),
1164 ),
1165 worktreeAfterDays: StorageRetentionDays,
1166 worktreeSettledAfterDays: SettledWorktreeRetentionDays.pipe(
1167 Schema.withDecodingDefault(Effect.succeed(null)),
1168 ),
1169 worktreeOnMerge: Schema.Boolean,
1170 worktreeOnDelete: Schema.Boolean,
1171 worktreeUnchanged: Schema.Boolean,
1172 });
1173 export type WorktreeCleanupRules = typeof WorktreeCleanupRules.Type;
1174
1175 export const WorktreeCleanup = Schema.NullOr(
1176 Schema.Union([
1177 Schema.Struct({ mode: Schema.Literal("off") }),
1178 Schema.Struct({ mode: Schema.Literal("custom"), rules: WorktreeCleanupRules }),
1179 ]),
1180 );
1181 export type WorktreeCleanup = typeof WorktreeCleanup.Type;
1182
1183 export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [
1184 "worktreeCleanup",
1185 "defaultModelSelection",
1186 "defaultRuntimeMode",
1187 "defaultThreadEnvMode",
1188 "newWorktreesStartFromOrigin",
1189 "worktreeSubmodules",
1190 "defaultAutoPull",
1191 "defaultProjectScripts",
1192 "enableAgentBrowserAccess",
1193 "enableAgentDeviceAccess",
1194 "textGenerationModelSelection",
1195 "threadTitleInstructions",
1196 "sourceControlWriterModelSelection",
1197 "reviewGuideModelSelection",
1198 "reviewGuideInstructions",
1199 "sourceControlWritingStyle",
1200 "removeAgentCreditsOnMerge",
1201 "branchNamingMode",
1202 "branchNamePrefix",
1203 "branchNameInstructions",
1204 "pullRequestMergeMethod",
1205 "sidebarAutoSettleOnMerge",
1206 "sidebarAutoSettleAfterDays",
1207 "sidebarAutoSettleKeepPullRequests",
1208 "continueThreadsAfterServerUpdate",
1209 "responseStreamingMode",
1210 "speechProjectCustomWords",
1211 ] as const;
1212 export type ProjectScopedServerSettingKey = (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number];
1213
1214 export const ProjectProviderInstanceOverride = Schema.Struct({
1215 enabled: Schema.optionalKey(Schema.Boolean),
1216 });
1217 export type ProjectProviderInstanceOverride = typeof ProjectProviderInstanceOverride.Type;
1218
1219 /** Absent keys inherit; null is a value for nullable settings.
1220 * providerInstances overrides fields per instance; other keys replace the whole setting. */
1221 export const ProjectSettingsOverrides = Schema.Struct({
1222 worktreeCleanup: Schema.optionalKey(WorktreeCleanup),
1223 defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1224 defaultRuntimeMode: Schema.optionalKey(RuntimeMode),
1225 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
1226 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1227 worktreeSubmodules: ForwardCompatibleOptional(WorktreeSubmodules),
1228 defaultAutoPull: Schema.optionalKey(Schema.Boolean),
1229 defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)),
1230 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1231 enableAgentDeviceAccess: Schema.optionalKey(Schema.Boolean),
1232 textGenerationModelSelection: Schema.optionalKey(ModelSelection),
1233 threadTitleInstructions: Schema.optionalKey(TrimmedString),
1234 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1235 reviewGuideModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1236 reviewGuideInstructions: Schema.optionalKey(TrimmedString),
1237 sourceControlWritingStyle: Schema.optionalKey(SourceControlWritingStyleSetting),
1238 removeAgentCreditsOnMerge: Schema.optionalKey(Schema.Boolean),
1239 branchNamingMode: Schema.optionalKey(BranchNamingMode),
1240 branchNamePrefix: Schema.optionalKey(TrimmedString),
1241 branchNameInstructions: Schema.optionalKey(TrimmedString),
1242 pullRequestMergeMethod: Schema.optionalKey(Schema.NullOr(PullRequestMergeMethod)),
1243 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1244 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1245 sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean),
1246 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1247 responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
1248 speechProjectCustomWords: Schema.optionalKey(SpeechCustomWords),
1249 providerInstances: Schema.optionalKey(
1250 Schema.Record(ProviderInstanceId, ProjectProviderInstanceOverride),
1251 ),
1252 } satisfies Record<ProjectScopedServerSettingKey | "providerInstances", unknown>);
1253 export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type;
1254
1255 // Whole-entry writers must round-trip unknown keys; keep the type closed to catch misspellings.
1256 export const keepUnknownOverrideKeys = <Entry extends Schema.Struct<Schema.Struct.Fields>>(
1257 entry: Entry,
1258 ): Schema.Codec<
1259 Entry["Type"],
1260 Entry["Encoded"],
1261 Entry["DecodingServices"],
1262 Entry["EncodingServices"]
1263 > => Schema.StructWithRest(entry, [Schema.Record(Schema.String, Schema.Unknown)]);
1264
1265 /** True if null stores an override; otherwise null removes it. */
1266 export function isNullableProjectSettingsOverride(key: ProjectScopedServerSettingKey): boolean {
1267 return NULLABLE_PROJECT_SETTINGS_OVERRIDES.has(key);
1268 }
1269 const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettingKey> = new Set<
1270 {
1271 [K in ProjectScopedServerSettingKey]: null extends ProjectSettingsOverrides[K] ? K : never;
1272 }[ProjectScopedServerSettingKey]
1273 >([
1274 "defaultModelSelection",
1275 "sourceControlWriterModelSelection",
1276 "reviewGuideModelSelection",
1277 "pullRequestMergeMethod",
1278 "sidebarAutoSettleAfterDays",
1279 ]);
1280
1281 /** Reclaimable bytes from which the offline `t3 doctor` repair is worth suggesting. */
1282 export const DATABASE_COMPACTION_RECOMMENDED_BYTES = 1024 ** 3;
1283
1284 export const DatabaseStorageStatus = Schema.Struct({
1285 databaseBytes: Schema.Number,
1286 /** Free pages inside the file that an offline VACUUM (or incremental auto_vacuum) returns to disk. */
1287 reclaimableBytes: Schema.Number,
1288 /** False on databases created before incremental auto_vacuum; `t3 doctor` converts them. */
1289 incrementalVacuumEnabled: Schema.Boolean,
1290 /** Run on the host while offline. */
1291 compactCommand: Schema.String,
1292 /** The server can run the repair itself: the desktop app or background service restarts it. */
1293 canReclaim: Schema.optionalKey(Schema.Boolean),
1294 /** Why the last repair started from Settings failed. */
1295 reclaimFailure: Schema.optionalKey(Schema.String),
1296 });
1297 export type DatabaseStorageStatus = typeof DatabaseStorageStatus.Type;
1298
1299 export class DatabaseReclaimError extends Schema.TaggedError<DatabaseReclaimError>()(
1300 "DatabaseReclaimError",
1301 { reason: Schema.String },
1302 ) {
1303 override get message() {
1304 return this.reason;
1305 }
1306 }
1307
1308 export function shouldRecommendDatabaseCompaction(status: DatabaseStorageStatus): boolean {
1309 return (
1310 !status.incrementalVacuumEnabled &&
1311 status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES
1312 );
1313 }
1314
1315 /** Offline minutes the repair takes, at 30 s per GiB of live data (a BB-1 NVMe disk took 21 s). */
1316 export function databaseReclaimMinutes(status: DatabaseStorageStatus): number {
1317 const liveGiB = (status.databaseBytes - status.reclaimableBytes) / 1024 ** 3;
1318 return Math.max(1, Math.ceil(liveGiB / 2));
1319 }
1320
1321 export const StorageCleanupReportEntry = Schema.Struct({
1322 kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),
1323 outcome: Schema.Literals(["removed", "kept", "failed"]),
1324 reason: Schema.String,
1325 path: Schema.NullOr(Schema.String),
1326 projectPath: Schema.NullOr(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1327 threadId: Schema.NullOr(ThreadId),
1328 threadTitle: Schema.NullOr(Schema.String),
1329 bytes: Schema.NullOr(Schema.Number).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1330 files: Schema.NullOr(Schema.Number).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1331 });
1332 export type StorageCleanupReportEntry = typeof StorageCleanupReportEntry.Type;
1333 export const StorageCleanupReport = Schema.Struct({
1334 trigger: Schema.Literals(["automatic", "manual"]),
1335 startedAt: Schema.String,
1336 finishedAt: Schema.String,
1337 entries: Schema.Array(StorageCleanupReportEntry),
1338 counts: Schema.Struct({ removed: Schema.Number, kept: Schema.Number, failed: Schema.Number }),
1339 omittedCount: Schema.Number,
1340 bytesFreed: Schema.Number.pipe(Schema.withDecodingDefault(Effect.succeed(0))),
1341 });
1342 export type StorageCleanupReport = typeof StorageCleanupReport.Type;
1343
1344 export const StorageCleanupSettings = Schema.Struct({
1345 worktreeKeepWhen: WorktreeKeepWhen.pipe(
1346 Schema.withDecodingDefault(Effect.succeed("uncommitted-changes")),
1347 ),
1348 worktreeAfterDays: StorageRetentionDays.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1349 worktreeSettledAfterDays: SettledWorktreeRetentionDays.pipe(
1350 Schema.withDecodingDefault(Effect.succeed(null)),
1351 ),
1352 worktreeOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1353 worktreeOnDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1354 worktreeUnchanged: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1355 browserArtifactsAfterDays: StorageRetentionDays.pipe(
1356 Schema.withDecodingDefault(Effect.succeed(null)),
1357 ),
1358 logsAfterDays: StorageRetentionDays.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1359 });
1360 export type StorageCleanupSettings = typeof StorageCleanupSettings.Type;
1361
1362 const UsageHistoryRetentionDays = Schema.Union([
1363 Schema.Int.check(Schema.isGreaterThan(0)),
1364 Schema.Literal("unlimited"),
1365 ]);
1366
1367 const CloudSpeechCredential = SettingsSecretValue.pipe(
1368 Schema.withDecodingDefault(Effect.succeed("")),
1369 );
1370 export const CloudSpeechCredentials = Schema.Struct({
1371 openai: CloudSpeechCredential,
1372 xai: CloudSpeechCredential,
1373 openrouter: CloudSpeechCredential,
1374 });
1375
1376 export const ServerSettings = Schema.Struct({
1377 // Null means unmigrated; empty is authoritative and must not resurrect cleared preferences.
1378 favorites: Schema.NullOr(ModelFavorites).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1379 providerModelPreferences: Schema.NullOr(ProviderModelPreferences).pipe(
1380 Schema.withDecodingDefault(Effect.succeed(null)),
1381 ),
1382 worktreeCleanup: WorktreeCleanup.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
1383 storageCleanup: StorageCleanupSettings.pipe(
1384 Schema.withDecodingDefault(Effect.succeed(Schema.decodeSync(StorageCleanupSettings)({}))),
1385 ),
1386
1387 worktreesDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1388 /** macOS only, Labs beta: clone new worktrees from a cached checkout instead of writing every file. */
1389 fastWorktreeCheckout: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1390 /** Server-maintained history keeps old worktrees eligible for cleanup and review diffs. */
1391 previousWorktreesDirectories: Schema.Array(TrimmedString).pipe(
1392 Schema.withDecodingDefault(Effect.succeed([])),
1393 ),
1394 responseStreamingMode: ResponseStreamingMode.pipe(
1395 Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
1396 ),
1397 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1398 continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
1399 Schema.withDecodingDefault(Effect.succeed(true)),
1400 ),
1401 /** Holds an OS sleep inhibitor while any run is active; closing a laptop lid still sleeps it. */
1402 keepAwakeWhileAgentsWork: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1403 /** New T3 Connect device keys wait for approval from someone already trusted here. */
1404 requireConnectDeviceApproval: Schema.Boolean.pipe(
1405 Schema.withDecodingDefault(Effect.succeed(false)),
1406 ),
1407
1408 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1409 /** Lets clients reach this machine's loopback ports over `/api/preview/tunnel`. */
1410 enablePreviewTunnel: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1411 cloudSpeechCredentials: CloudSpeechCredentials.pipe(
1412 Schema.withDecodingDefault(Effect.succeed({ openai: "", xai: "", openrouter: "" })),
1413 ),
1414 speechModelId: Schema.String.pipe(
1415 Schema.withDecodingDefault(Effect.succeed("handy-computer/parakeet-unified-en-0.6b-gguf")),
1416 ),
1417 speechAcceleration: SpeechAcceleration.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))),
1418 speechModelUnloadTimeout: SpeechModelUnloadTimeout.pipe(
1419 Schema.withDecodingDefault(Effect.succeed("min_15")),
1420 ),
1421 // Vocabulary shared by everyone who dictates in a project; it lives with the project's environment.
1422 speechProjectCustomWords: SpeechCustomWords.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1423 // Null follows textGenerationModelSelection; a selection pins transcript cleanup to its own model.
1424 speechPostProcessingModelSelection: Schema.NullOr(ModelSelection).pipe(
1425 Schema.withDecodingDefault(Effect.succeed(null)),
1426 ),
1427 projectAgentBrowserAccessOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
1428 Schema.withDecodingDefault(Effect.succeed({})),
1429 ),
1430 defaultAutoPull: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1431 defaultProjectScripts: Schema.Array(ProjectScript).pipe(
1432 Schema.withDecodingDefault(Effect.succeed([])),
1433 ),
1434 projectScriptOverrides: Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))).pipe(
1435 Schema.withDecodingDefault(Effect.succeed({})),
1436 ),
1437 projectAutoPullOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
1438 Schema.withDecodingDefault(Effect.succeed({})),
1439 ),
1440 defaultModelSelection: Schema.NullOr(ModelSelection).pipe(
1441 Schema.withDecodingDefault(Effect.succeed(null)),
1442 ),
1443 fallbackModelSelection: Schema.NullOr(ModelSelection).pipe(
1444 Schema.withDecodingDefault(Effect.succeed(null)),
1445 ),
1446 defaultRuntimeMode: RuntimeMode.pipe(
1447 Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE)),
1448 ),
1449
1450 projectSettingsOverrides: Schema.Record(
1451 ProjectId,
1452 keepUnknownOverrideKeys(ProjectSettingsOverrides),
1453 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
1454 /** Fold once so restarts cannot undo later UI resets. */
1455 projectSettingsFolded: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1456
1457 enableAgentDeviceAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1458 /** Enabling the Device panel must not grant providers device control. */
1459 enableDeviceSupport: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1460 deviceOnboardingCompleted: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1461 deviceHosts: SshDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1462 easDeviceHosts: EasDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1463 simlockDeviceHosts: SimlockDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1464 /** Alpha: Simlock device hosts. Off, the server ignores `simlockDeviceHosts`. */
1465 simlockDeviceHostsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1466 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
1467 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
1468 ),
1469 compactIdleThreads: LegacyCompactIdleThreads.pipe(
1470 Schema.withDecodingDefault(Effect.succeed(false)),
1471 ),
1472 idleCompaction: Schema.optionalKey(IdleCompactionMode),
1473 snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1474 autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1475 snoozePresets: SnoozePresetSettings.pipe(
1476 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)),
1477 ),
1478 /** Clients hide threads with these tags while `hideTaggedThreads` is on. Bad entries drop alone, so a hand edit cannot reset settings. */
1479 hiddenThreadTags: Schema.Array(Schema.Unknown).pipe(
1480 Schema.decodeTo(
1481 Schema.Array(Schema.String),
1482 SchemaTransformation.transform<ReadonlyArray<string>, ReadonlyArray<unknown>>({
1483 decode: (values) => values.filter((value) => typeof value === "string"),
1484 encode: (values) => values,
1485 }),
1486 ),
1487 Schema.withDecodingDefault(Effect.succeed([])),
1488 ),
1489 hideTaggedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1490 /** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */
1491 guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1492 /**
1493 * Beta: links to the user's other machines, both ways. Off refuses new links, calls over links
1494 * and tasks on another machine; tasks already running there finish.
1495 */
1496 linkedEnvironmentsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1497 /** Beta: Claude and Codex predict the next prompt after completed turns. Codex follows a change at once; open Claude threads after they restart. */
1498 promptSuggestionsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1499 sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
1500 Schema.withDecodingDefault(Effect.succeed(false)),
1501 ),
1502 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1503 backgroundActivity: BackgroundActivitySettings,
1504
1505 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
1506 Schema.withDecodingDefault(
1507 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
1508 ),
1509 ),
1510 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
1511 Schema.withDecodingDefault(
1512 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
1513 ),
1514 ),
1515 backgroundActivityProfile: BackgroundActivityProfile.pipe(
1516 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
1517 ),
1518 defaultTheme: DefaultThemePreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1519 /** Distinguishes repeated sets of the same theme so clients apply each one. */
1520 defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
1521 Schema.withDecodingDefault(Effect.succeed("")),
1522 ),
1523 defaultAppearance: DefaultAppearancePreference.pipe(
1524 Schema.withDecodingDefault(Effect.succeed("" as const)),
1525 ),
1526 defaultAppearanceSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
1527 Schema.withDecodingDefault(Effect.succeed("")),
1528 ),
1529 environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
1530 Schema.withDecodingDefault(Effect.succeed(null)),
1531 ),
1532 /** Null inherits t3.json, then local; omit it on the wire for older clients requiring a literal. */
1533 defaultThreadEnvMode: OmittedWhenNull(ThreadEnvMode),
1534 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
1535 Schema.withDecodingDefault(Effect.succeed(true)),
1536 ),
1537 /** Null inherits t3.json, then recursive; unknown values decode to null for older clients. */
1538 worktreeSubmodules: ForwardCompatibleNullable(WorktreeSubmodules).pipe(
1539 Schema.withDecodingDefault(Effect.succeed(null)),
1540 ),
1541 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1542 /** Clones default to `<addProjectBaseDirectory>/<host>/<owner>/<repo>`, like ghq. */
1543 ghqCloneLayout: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1544 textGenerationModelSelection: ModelSelection.pipe(
1545 Schema.withDecodingDefault(
1546 Effect.succeed({
1547 instanceId: ProviderInstanceId.make("codex"),
1548 model: DEFAULT_TEXT_GENERATION_MODEL,
1549 options: [
1550 {
1551 id: "reasoningEffort",
1552 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
1553 },
1554 ],
1555 }),
1556 ),
1557 ),
1558 threadTitleInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1559 branchNamingMode: BranchNamingMode.pipe(
1560 Schema.withDecodingDefault(Effect.succeed("static" as const)),
1561 ),
1562 branchNamePrefix: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed("t3"))),
1563 branchNameInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1564 removeAgentCreditsOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1565 sourceControlWritingStyle: SourceControlWritingStyleSetting.pipe(
1566 Schema.withDecodingDefault(Effect.succeed({})),
1567 ),
1568 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
1569 Schema.withDecodingDefault(Effect.succeed(null)),
1570 ),
1571 reviewGuidesEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1572 reviewGuideModelSelection: Schema.NullOr(ModelSelection).pipe(
1573 Schema.withDecodingDefault(Effect.succeed(null)),
1574 ),
1575 reviewGuideInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1576
1577 pullRequestMergeMethod: Schema.NullOr(PullRequestMergeMethod).pipe(
1578 Schema.withDecodingDefault(Effect.succeed(null)),
1579 ),
1580
1581 // Schema.Unknown preserves unknown-driver configs across versions; see providerInstance.ts.
1582 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
1583 Schema.withDecodingDefault(Effect.succeed({})),
1584 ),
1585 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
1586 sourceControlHosts: Schema.Record(Schema.String, SourceControlHostSettings).pipe(
1587 Schema.withDecodingDefault(Effect.succeed({})),
1588 ),
1589 /** Hosts the add and publish project pickers offer, by kind. An unset host is off, except the default one. */
1590 offeredSourceControlProviders: Schema.Record(Schema.String, Schema.Boolean).pipe(
1591 Schema.withDecodingDefault(Effect.succeed({})),
1592 ),
1593 // User-chosen ids preserve rows across edits; undecodable entries round-trip untouched.
1594 usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(
1595 Schema.withDecodingDefault(Effect.succeed({})),
1596 ),
1597 textGenerators: Schema.Record(ProviderInstanceId, TextGeneratorConfig).pipe(
1598 Schema.withDecodingDefault(Effect.succeed({})),
1599 ),
1600 secretProviders: Schema.Record(SecretProviderId, SecretProviderConfig).pipe(
1601 Schema.withDecodingDefault(Effect.succeed({})),
1602 ),
1603
1604 usageHistoryRetentionDays: UsageHistoryRetentionDays.pipe(
1605 Schema.withDecodingDefault(Effect.succeed(92)),
1606 ),
1607
1608 usagePriceOverrides: Schema.Record(TrimmedNonEmptyString, UsageModelPriceOverride).pipe(
1609 Schema.withDecodingDefault(Effect.succeed({})),
1610 ),
1611
1612 usageModelAliases: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString).pipe(
1613 Schema.withDecodingDefault(Effect.succeed({})),
1614 ),
1615
1616 /** Sent by the Usage tab with each summary request to this environment; edit in settings.json. Invalid values are ignored. */
1617 usageModelFilter: ForwardCompatibleOptional(UsageModelFilter),
1618 });
1619 export type ServerSettings = typeof ServerSettings.Type;
1620
1621 export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
1622
1623 export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
1624 if (config === null || typeof config !== "object" || Array.isArray(config)) {
1625 return undefined;
1626 }
1627 const enabled = (config as { readonly enabled?: unknown }).enabled;
1628 return typeof enabled === "boolean" ? enabled : undefined;
1629 };
1630
1631 // Must match each driver's enabled decoding default.
1632 const DEFAULT_DISABLED_PROVIDER_DRIVERS: ReadonlySet<ProviderDriverKind> = new Set(
1633 ["cursor", "grok", "fx", "kiro", "muse", "pi", "opencode", "antigravity"].map((driver) =>
1634 ProviderDriverKind.make(driver),
1635 ),
1636 );
1637
1638 const DEFAULT_ENABLED_DEFAULT_INSTANCES: ReadonlySet<ProviderInstanceId> = new Set(
1639 ["codex", "claudeAgent"].map((instanceId) => ProviderInstanceId.make(instanceId)),
1640 );
1641
1642 export const isUnconfiguredDefaultInstanceEnabled = (instanceId: ProviderInstanceId): boolean =>
1643 DEFAULT_ENABLED_DEFAULT_INSTANCES.has(instanceId);
1644
1645 const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean =>
1646 !DEFAULT_DISABLED_PROVIDER_DRIVERS.has(driver);
1647
1648 export const resolveProviderInstanceEnabled = (
1649 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
1650 ): boolean => {
1651 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
1652 if (instance.enabled === false || configEnabled === false) {
1653 return false;
1654 }
1655 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
1656 };
1657
1658 export const resolveProjectProviderInstanceEnabled = (
1659 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
1660 projectId: ProjectId | null,
1661 instanceId: ProviderInstanceId,
1662 ): boolean => {
1663 const override =
1664 projectId === null
1665 ? undefined
1666 : settings.projectSettingsOverrides[projectId]?.providerInstances?.[instanceId]?.enabled;
1667 if (override !== undefined) return override;
1668 const instanceConfig = Object.hasOwn(settings.providerInstances, instanceId)
1669 ? settings.providerInstances[instanceId]
1670 : undefined;
1671 return instanceConfig !== undefined
1672 ? resolveProviderInstanceEnabled(instanceConfig)
1673 : isUnconfiguredDefaultInstanceEnabled(instanceId);
1674 };
1675
1676 /** The text generator a selection names, if any; it takes precedence over a provider instance. */
1677 export const textGeneratorForSelection = (
1678 settings: Pick<ServerSettings, "textGenerators">,
1679 instanceId: ProviderInstanceId,
1680 ): TextGeneratorConfig | undefined =>
1681 Object.hasOwn(settings.textGenerators, instanceId)
1682 ? settings.textGenerators[instanceId]
1683 : undefined;
1684
1685 /** Whether a text generation selection can run: an enabled text generator or provider instance. */
1686 export const resolveTextGenerationSelectionEnabled = (
1687 settings: Pick<
1688 ServerSettings,
1689 "providerInstances" | "projectSettingsOverrides" | "textGenerators"
1690 >,
1691 projectId: ProjectId | null,
1692 instanceId: ProviderInstanceId,
1693 ): boolean =>
1694 textGeneratorForSelection(settings, instanceId)?.enabled ??
1695 resolveProjectProviderInstanceEnabled(settings, projectId, instanceId);
1696
1697 const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
1698
1699 type IdleCompactionSettings = Pick<ServerSettings, "compactIdleThreads" | "idleCompaction">;
1700
1701 /** The environment-wide idle compaction mode, from whichever field the settings carry. */
1702 export const globalIdleCompaction = (settings: IdleCompactionSettings): IdleCompactionMode =>
1703 settings.idleCompaction ??
1704 (typeof settings.compactIdleThreads === "string"
1705 ? settings.compactIdleThreads
1706 : settings.compactIdleThreads
1707 ? "beforeCacheExpires"
1708 : "onReturn");
1709
1710 /** Sets the mode, and the legacy switch shipped clients still read alongside it. */
1711 export const withIdleCompaction = <S extends IdleCompactionSettings>(
1712 settings: S,
1713 mode: IdleCompactionMode,
1714 ): S => ({ ...settings, idleCompaction: mode, compactIdleThreads: mode === "beforeCacheExpires" });
1715
1716 /** Whether a server reads modes, rather than only the boolean switch from before them. */
1717 export const readsIdleCompactionModes = (settings: IdleCompactionSettings) =>
1718 settings.idleCompaction !== undefined || typeof settings.compactIdleThreads === "string";
1719
1720 /**
1721 * The patch that sets `mode` in the form the server's settings show it reads:
1722 * the mode for a server that has `idleCompaction` or kept the mode in the legacy
1723 * field, the boolean switch for a server from before modes.
1724 */
1725 export const idleCompactionPatch = (settings: IdleCompactionSettings, mode: IdleCompactionMode) =>
1726 settings.idleCompaction !== undefined
1727 ? { idleCompaction: mode }
1728 : readsIdleCompactionModes(settings)
1729 ? { compactIdleThreads: mode }
1730 : { compactIdleThreads: mode === "beforeCacheExpires" };
1731
1732 export const resolveIdleCompaction = (
1733 settings: Pick<ServerSettings, "providerInstances" | "compactIdleThreads" | "idleCompaction">,
1734 instanceId: ProviderInstanceId,
1735 ): IdleCompactionMode => {
1736 const instance = Object.hasOwn(settings.providerInstances, instanceId)
1737 ? settings.providerInstances[instanceId]
1738 : undefined;
1739 const override = decodeClaudeSettings(instance?.config ?? {}).pipe(
1740 Option.map((config) => config.idleCompaction),
1741 Option.getOrElse(() => "default" as const),
1742 );
1743 return override === "default" ? globalIdleCompaction(settings) : override;
1744 };
1745
1746 export const ServerSettingsOperation = Schema.Literals([
1747 "normalize",
1748 "check-exists",
1749 "create-provider-instance",
1750 "read-file",
1751 "read-provider-history",
1752 "read-project-settings",
1753 "read-secret",
1754 "remove-secret",
1755 "remove-stale-secret",
1756 "write-secret",
1757 "write-secret-provider",
1758 "write-file",
1759 "prepare-directory",
1760 "write-managed-setting",
1761 "use-disallowed-provider",
1762 ]);
1763 export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
1764
1765 /** Why a provider the administrator's policy leaves out cannot be used. */
1766 export const disallowedProviderMessage = (organization: string | undefined, label: string) =>
1767 `${organization === undefined ? "Your organization" : `${organization}'s`} policy does not allow the ${label} provider.`;
1768
1769 export class ServerSettingsError extends Schema.TaggedError<ServerSettingsError>()(
1770 "ServerSettingsError",
1771 {
1772 settingsPath: Schema.String,
1773 operation: ServerSettingsOperation,
1774 providerInstanceId: Schema.optional(Schema.String),
1775 environmentVariable: Schema.optional(Schema.String),
1776 /** For `write-managed-setting`: the locked dot path and who manages it. */
1777 managedSetting: Schema.optional(Schema.String),
1778 managedBy: Schema.optional(Schema.String),
1779 /** For `use-disallowed-provider`: the provider's name as users know it. */
1780 providerLabel: Schema.optional(Schema.String),
1781 cause: Schema.optional(Schema.Defect()),
1782 },
1783 ) {
1784 override get message(): string {
1785 if (this.operation === "write-managed-setting") {
1786 return `${this.managedSetting ?? "This setting"} is managed by ${this.managedBy ?? "your organization"} and cannot be changed.`;
1787 }
1788 if (this.operation === "use-disallowed-provider") {
1789 return disallowedProviderMessage(
1790 this.managedBy,
1791 this.providerLabel ?? this.providerInstanceId ?? "this",
1792 );
1793 }
1794 const provider =
1795 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
1796 const variable =
1797 this.environmentVariable === undefined
1798 ? ""
1799 : ` and environment variable ${this.environmentVariable}`;
1800 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
1801 }
1802 }
1803
1804 export type UnifiedSettings = Omit<ServerSettings, keyof ModelPreferences> & ClientSettings;
1805 export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
1806 ...DEFAULT_SERVER_SETTINGS,
1807 ...DEFAULT_CLIENT_SETTINGS,
1808 };
1809
1810 const ModelSelectionPatch = Schema.Struct({
1811 instanceId: Schema.optionalKey(ProviderInstanceId),
1812 model: Schema.optionalKey(TrimmedNonEmptyString),
1813 options: Schema.optionalKey(ProviderOptionSelections),
1814 });
1815
1816 export const ServerSettingsPatch = Schema.Struct({
1817 setModelFavorites: Schema.optionalKey(
1818 Schema.Array(Schema.Struct({ ...ModelFavorite.fields, favorite: Schema.Boolean })),
1819 ),
1820 setModelsHidden: Schema.optionalKey(
1821 Schema.Array(Schema.Struct({ ...ModelFavorite.fields, hidden: Schema.Boolean })),
1822 ),
1823 setProviderModelOrder: Schema.optionalKey(
1824 Schema.Struct({ provider: ProviderInstanceId, modelOrder: Schema.Array(TrimmedString) }),
1825 ),
1826 favorites: Schema.optionalKey(ModelFavorites),
1827 providerModelPreferences: Schema.optionalKey(ProviderModelPreferences),
1828 // Applied under the settings service's write lock, only while still unset.
1829 migrateModelPreferences: Schema.optionalKey(
1830 Schema.Struct({
1831 favorites: Schema.optionalKey(ModelFavorites),
1832 providerModelPreferences: Schema.optionalKey(ProviderModelPreferences),
1833 }),
1834 ),
1835 worktreeCleanup: Schema.optionalKey(
1836 Schema.NullOr(
1837 Schema.Union([
1838 Schema.Struct({ mode: Schema.Literal("off") }),
1839 Schema.Struct({
1840 mode: Schema.Literal("custom"),
1841 rules: Schema.Struct({
1842 worktreeKeepWhen: Schema.optionalKey(WorktreeKeepWhen),
1843 worktreeAfterDays: Schema.optionalKey(StorageRetentionDays),
1844 worktreeSettledAfterDays: Schema.optionalKey(SettledWorktreeRetentionDays),
1845 worktreeOnMerge: Schema.optionalKey(Schema.Boolean),
1846 worktreeOnDelete: Schema.optionalKey(Schema.Boolean),
1847 worktreeUnchanged: Schema.optionalKey(Schema.Boolean),
1848 }),
1849 }),
1850 ]),
1851 ),
1852 ),
1853 storageCleanup: Schema.optionalKey(
1854 Schema.Struct({
1855 worktreeKeepWhen: Schema.optionalKey(WorktreeKeepWhen),
1856 worktreeAfterDays: Schema.optionalKey(StorageRetentionDays),
1857 worktreeSettledAfterDays: Schema.optionalKey(SettledWorktreeRetentionDays),
1858 worktreeOnMerge: Schema.optionalKey(Schema.Boolean),
1859 worktreeOnDelete: Schema.optionalKey(Schema.Boolean),
1860 worktreeUnchanged: Schema.optionalKey(Schema.Boolean),
1861 browserArtifactsAfterDays: Schema.optionalKey(StorageRetentionDays),
1862 logsAfterDays: Schema.optionalKey(StorageRetentionDays),
1863 }),
1864 ),
1865 worktreesDirectory: Schema.optionalKey(TrimmedString),
1866 fastWorktreeCheckout: Schema.optionalKey(Schema.Boolean),
1867 responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
1868 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1869 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1870 keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean),
1871 requireConnectDeviceApproval: Schema.optionalKey(Schema.Boolean),
1872 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1873 enablePreviewTunnel: Schema.optionalKey(Schema.Boolean),
1874 cloudSpeechCredentials: Schema.optionalKey(
1875 Schema.Struct({
1876 openai: Schema.optionalKey(SettingsSecretValue),
1877 xai: Schema.optionalKey(SettingsSecretValue),
1878 openrouter: Schema.optionalKey(SettingsSecretValue),
1879 }),
1880 ),
1881 speechModelId: Schema.optionalKey(Schema.String),
1882 speechAcceleration: Schema.optionalKey(SpeechAcceleration),
1883 speechModelUnloadTimeout: Schema.optionalKey(SpeechModelUnloadTimeout),
1884 speechProjectCustomWords: Schema.optionalKey(SpeechCustomWords),
1885 speechPostProcessingModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1886 projectAgentBrowserAccessOverrides: Schema.optionalKey(
1887 Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
1888 ),
1889 defaultAutoPull: Schema.optionalKey(Schema.Boolean),
1890 defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)),
1891 projectScriptOverrides: Schema.optionalKey(
1892 Schema.Record(ProjectId, Schema.NullOr(Schema.Array(ProjectScript))),
1893 ),
1894 projectAutoPullOverrides: Schema.optionalKey(
1895 Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
1896 ),
1897 defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1898 defaultRuntimeMode: Schema.optionalKey(RuntimeMode),
1899 fallbackModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1900 /** Replaces each project's override set; null removes it. Omitted providerInstances retains its stored value. */
1901 projectSettingsOverrides: Schema.optionalKey(
1902 Schema.Record(
1903 ProjectId,
1904 Schema.NullOr(
1905 keepUnknownOverrideKeys(
1906 Schema.Struct({
1907 ...ProjectSettingsOverrides.fields,
1908 sourceControlWritingStyle: Schema.optionalKey(SourceControlWritingStyleSettings),
1909 }),
1910 ),
1911 ),
1912 ),
1913 ),
1914 enableAgentDeviceAccess: Schema.optionalKey(Schema.Boolean),
1915 enableDeviceSupport: Schema.optionalKey(Schema.Boolean),
1916 deviceOnboardingCompleted: Schema.optionalKey(Schema.Boolean),
1917 deviceHosts: Schema.optionalKey(SshDeviceHostConfigs),
1918 easDeviceHosts: Schema.optionalKey(EasDeviceHostConfigs),
1919 simlockDeviceHosts: Schema.optionalKey(SimlockDeviceHostConfigs),
1920 simlockDeviceHostsEnabled: Schema.optionalKey(Schema.Boolean),
1921 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1922 compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads),
1923 idleCompaction: Schema.optionalKey(IdleCompactionMode),
1924 sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean),
1925 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
1926 autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1927 snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1928 snoozePresets: Schema.optionalKey(SnoozePresetSettings),
1929 hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)),
1930 hideTaggedThreads: Schema.optionalKey(Schema.Boolean),
1931 guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
1932 linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean),
1933 promptSuggestionsEnabled: Schema.optionalKey(Schema.Boolean),
1934 backgroundActivity: Schema.optionalKey(
1935 Schema.Struct({
1936 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
1937 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
1938 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
1939 overrides: Schema.optionalKey(BackgroundActivityOverrides),
1940 }),
1941 ),
1942 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1943 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1944 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
1945 defaultTheme: Schema.optionalKey(DefaultThemePreference),
1946 defaultThemeSetAt: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(64))),
1947 defaultAppearance: Schema.optionalKey(DefaultAppearancePreference),
1948 defaultAppearanceSetAt: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(64))),
1949 environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
1950 defaultThreadEnvMode: Schema.optionalKey(Schema.NullOr(ThreadEnvMode)),
1951 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1952 worktreeSubmodules: Schema.optionalKey(Schema.NullOr(WorktreeSubmodules)),
1953 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
1954 ghqCloneLayout: Schema.optionalKey(Schema.Boolean),
1955 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
1956 threadTitleInstructions: Schema.optionalKey(TrimmedString),
1957 branchNamingMode: Schema.optionalKey(BranchNamingMode),
1958 branchNamePrefix: Schema.optionalKey(TrimmedString),
1959 branchNameInstructions: Schema.optionalKey(TrimmedString),
1960 removeAgentCreditsOnMerge: Schema.optionalKey(Schema.Boolean),
1961 sourceControlWritingStyle: Schema.optionalKey(
1962 Schema.Struct({
1963 mode: Schema.optionalKey(SourceControlWritingStyleMode),
1964 customInstructions: Schema.optionalKey(TrimmedString),
1965 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
1966 }),
1967 ),
1968 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1969 reviewGuidesEnabled: Schema.optionalKey(Schema.Boolean),
1970 reviewGuideModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
1971 reviewGuideInstructions: Schema.optionalKey(TrimmedString),
1972 pullRequestMergeMethod: Schema.optionalKey(Schema.NullOr(PullRequestMergeMethod)),
1973 observability: Schema.optionalKey(
1974 Schema.Struct({
1975 otlpTracesUrl: Schema.optionalKey(TrimmedString),
1976 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
1977 otlpLogsUrl: Schema.optionalKey(TrimmedString),
1978 }),
1979 ),
1980 /** Merges per host, replacing patched fields whole; redaction markers retain secrets, empty secrets remove them. A non-empty token map keeps the saved tokens of hosts it omits; an empty map clears them all. */
1981 sourceControlHosts: Schema.optionalKey(Schema.Record(Schema.String, SourceControlHostSettings)),
1982 offeredSourceControlProviders: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
1983 // Replace whole maps to avoid half-merged driver configs.
1984 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
1985 // Merge per source to avoid racing other edits; null removes an entry.
1986 usageLimitSources: Schema.optionalKey(
1987 Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),
1988 ),
1989 // Merge per entry like usageLimitSources; null removes an entry.
1990 textGenerators: Schema.optionalKey(
1991 Schema.Record(ProviderInstanceId, Schema.NullOr(TextGeneratorConfig)),
1992 ),
1993 secretProviders: Schema.optionalKey(
1994 Schema.Record(SecretProviderId, Schema.NullOr(SecretProviderConfigWrite)),
1995 ),
1996
1997 usageHistoryRetentionDays: Schema.optionalKey(UsageHistoryRetentionDays),
1998
1999 usagePriceOverrides: Schema.optionalKey(
2000 Schema.Record(TrimmedNonEmptyString, Schema.NullOr(UsageModelPriceOverride)),
2001 ),
2002
2003 usageModelAliases: Schema.optionalKey(
2004 Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)),
2005 ),
2006 });
2007 export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
2008
2009 /** The theme service sets theme defaults after it validates them, so clients cannot. */
2010 export const ClientServerSettingsPatch = ServerSettingsPatch.mapFields(
2011 Struct.omit(["defaultTheme", "defaultThemeSetAt", "defaultAppearance", "defaultAppearanceSetAt"]),
2012 );
2013
2014 export function requiredScopesForServerSettingsPatch(
2015 patch: ServerSettingsPatch,
2016 ): ReadonlyArray<AuthEnvironmentScope> {
2017 let changesProviders = false;
2018 let changesSettings = false;
2019 let changesAccess = false;
2020 for (const [key, value] of Object.entries(patch)) {
2021 if (value === undefined) continue;
2022 if (key === "requireConnectDeviceApproval" || key === "enablePreviewTunnel") {
2023 changesAccess = true;
2024 } else if (
2025 key === "providers" ||
2026 key === "providerInstances" ||
2027 key === "usageLimitSources" ||
2028 key === "textGenerators" ||
2029 key === "secretProviders"
2030 ) {
2031 changesProviders = true;
2032 } else {
2033 changesSettings = true;
2034 }
2035 }
2036 // A reference can name any secret the store holds; choosing where one goes is provider authority.
2037 if (containsSecretReference(patch)) changesProviders = true;
2038 // Removing a secret provider also clears the settings fields that read from it.
2039 if (Object.values(patch.secretProviders ?? {}).some((entry) => entry === null)) {
2040 changesSettings = true;
2041 }
2042 return [
2043 ...(changesSettings || (!changesProviders && !changesAccess) ? [AuthSettingsWriteScope] : []),
2044 ...(changesProviders ? [AuthProvidersManageScope] : []),
2045 ...(changesAccess ? [AuthAccessWriteScope] : []),
2046 ];
2047 }
2048
2049 /** Host-executed project scripts require settings-write authority in addition to orchestration:operate. */
2050 export function requiredScopesForProjectMutation(
2051 mutation: ProjectMutation,
2052 ): ReadonlyArray<AuthEnvironmentScope> {
2053 if (mutation.type === "project.delete" || mutation.scripts === undefined) {
2054 return [AuthOrchestrationOperateScope];
2055 }
2056 return [
2057 AuthOrchestrationOperateScope,
2058 ...requiredScopesForServerSettingsPatch({ defaultProjectScripts: mutation.scripts }),
2059 ];
2060 }
2061
2062 export const ClientSettingsPatch = Schema.Struct({
2063 notificationMode: Schema.optionalKey(NotificationMode),
2064 inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean),
2065 diffColorScheme: Schema.optionalKey(DiffColorScheme),
2066 chatWidth: Schema.optionalKey(ChatWidth),
2067 effortDisplay: Schema.optionalKey(EffortDisplay),
2068 loadBalancingEnabled: Schema.optionalKey(Schema.Boolean),
2069 loadBalancingWeights: Schema.optionalKey(LoadBalancingWeights),
2070 appearanceContrast: Schema.optionalKey(AppearanceContrast),
2071 panelAnimationDurationMs: Schema.optionalKey(PanelAnimationDurationMs),
2072 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
2073 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
2074 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
2075 browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
2076 browserRecordingShowKeyPresses: Schema.optionalKey(Schema.Boolean),
2077 browserRecordingShowMousePresses: Schema.optionalKey(Schema.Boolean),
2078 browserLinkTarget: Schema.optionalKey(BrowserLinkTarget),
2079 browserSearchEngine: Schema.optionalKey(BrowserSearchEngine),
2080 browserCustomSearchUrl: Schema.optionalKey(BrowserCustomSearchUrl),
2081 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
2082 browserProfiles: Schema.optionalKey(Schema.Array(BrowserProfile)),
2083 browserDefaultProfileId: Schema.optionalKey(BrowserProfileId),
2084 confirmQuit: Schema.optionalKey(QuitConfirmationMode),
2085 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
2086 confirmTerminalClose: Schema.optionalKey(Schema.Boolean),
2087 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
2088 confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
2089 diffFilesCollapsed: Schema.optionalKey(Schema.Boolean),
2090 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
2091 diffLayout: Schema.optionalKey(DiffLayout),
2092 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
2093 glassOpacity: Schema.optionalKey(GlassOpacity),
2094 onboardingCompletedAt: Schema.optionalKey(Schema.NullOr(Schema.String)),
2095 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
2096 fontSizePrompt: Schema.optionalKey(PromptFontSize),
2097 fontSizeCode: Schema.optionalKey(CodeFontSize),
2098 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
2099 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
2100 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
2101 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
2102 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
2103 fontSmoothing: Schema.optionalKey(Schema.Boolean),
2104 persistComposerContextStrip: Schema.optionalKey(Schema.Boolean),
2105 favorites: Schema.optionalKey(ModelFavorites),
2106 providerModelPreferences: Schema.optionalKey(ProviderModelPreferences),
2107 pullRequestMergeMethodOverrides: Schema.optionalKey(
2108 Schema.Record(TrimmedNonEmptyString, PullRequestMergeMethod),
2109 ),
2110 pullRequestLinksOpenInApp: Schema.optionalKey(Schema.Boolean),
2111 composerRichTextEnabled: Schema.optionalKey(Schema.Boolean),
2112 sendShortcut: Schema.optionalKey(Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"])),
2113 followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])),
2114 sideThreadOpenTarget: Schema.optionalKey(SideThreadOpenTarget),
2115 proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean),
2116 showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean),
2117 boringSidebarEnabled: Schema.optionalKey(Schema.Boolean),
2118 boringSidebarMultilineRows: Schema.optionalKey(Schema.Boolean),
2119 toolCallVisibility: Schema.optionalKey(ToolCallVisibility),
2120 screenReaderAnnouncements: Schema.optionalKey(ScreenReaderAnnouncements),
2121 screenReaderWindowTitle: Schema.optionalKey(Schema.Boolean),
2122 threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean),
2123 threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
2124 sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean),
2125 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
2126 sidebarProjectGroupingOverrides: Schema.optionalKey(
2127 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
2128 ),
2129 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
2130 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
2131 timestampFormat: Schema.optionalKey(TimestampFormat),
2132 voiceMicrophone: Schema.optionalKey(Schema.String),
2133 voiceMicrophones: Schema.optionalKey(Schema.Array(VoiceMicrophoneEntry)),
2134 voiceShortcutMode: Schema.optionalKey(VoiceShortcutMode),
2135 speechLanguage: Schema.optionalKey(SpeechLanguage),
2136 speechTranslateToEnglish: Schema.optionalKey(Schema.Boolean),
2137 speechCustomWords: Schema.optionalKey(SpeechCustomWords),
2138 speechSilenceFiltering: Schema.optionalKey(Schema.Boolean),
2139 speechStreaming: Schema.optionalKey(Schema.Boolean),
2140 speechRemoveFillerWords: Schema.optionalKey(Schema.Boolean),
2141 speechPostProcessingPrompt: Schema.optionalKey(SpeechPostProcessingPromptSettings),
2142 speechCorrectionWord: Schema.optionalKey(SpeechCorrectionCue),
2143 language: Schema.optionalKey(Schema.String),
2144 snapShotEnabled: Schema.optionalKey(Schema.Boolean),
2145 snapShotIncludeAccessibility: Schema.optionalKey(Schema.Boolean),
2146 snapShotShortcut: Schema.optionalKey(SnapShotShortcut),
2147 snapShotPlaySound: Schema.optionalKey(Schema.Boolean),
2148 snapShotSound: Schema.optionalKey(SnapShotSound),
2149 snapShotFlash: Schema.optionalKey(Schema.Boolean),
2150 snapShotAnimations: Schema.optionalKey(Schema.Boolean),
2151 wordWrap: Schema.optionalKey(Schema.Boolean),
2152 mathRenderingEnabled: Schema.optionalKey(Schema.Boolean),
2153 });
2154 export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;