config.ts 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655
  1. import {
  2. resolveRunawayGuardConfig,
  3. type RunawayGuardSettings,
  4. } from "./runaway-guard-config.js";
  5. import fs from "node:fs";
  6. import { restrictConfigFileSync, writePrivateConfigFileSync } from "./private-config-file.js";
  7. import path from "node:path";
  8. import os from "node:os";
  9. import { spawnSync } from "node:child_process";
  10. import { fileURLToPath } from "node:url";
  11. import yaml from "js-yaml";
  12. import { parseTuiConfig, type TuiConfig } from "./tui-config.js";
  13. import {
  14. applyManagedMinimaxContextLimits,
  15. applyRequiredProviderOverrides,
  16. migrateLegacyByokProvidersOnDisk,
  17. restrictLegacyByokBackups,
  18. normalizeLegacyThinkingEfforts,
  19. parseCustomProvidersConfig,
  20. parseMinimaxApiConfig,
  21. parseModelContextLimits,
  22. type RequiredProviderOverrideDeps,
  23. } from "./byok-config.js";
  24. import {
  25. type CuBackend,
  26. DEFAULT_CU_BACKEND,
  27. parseCuBackend,
  28. } from "./cu-backend.js";
  29. import { parseReviewConfig } from "./review-config.js";
  30. import { parseOpenCodeAdapterConfig } from "./opencode-config.js";
  31. import type { AsrConfig } from "./asr.js";
  32. import { ASR_DEFAULTS, parseAsrConfig } from "./asr.js";
  33. import {
  34. parsePermissionConfig,
  35. type PermissionConfig,
  36. } from "./permission-config.js";
  37. import type { SkillEvolveConfig } from "./skill-evolve-config.js";
  38. import {
  39. DEFAULT_SKILLS_CONFIG,
  40. parseSkillsConfig,
  41. type SkillsConfig,
  42. } from "./skills-config.js";
  43. import {
  44. DEFAULT_AGENT_RUNTIME_FRAMEWORK,
  45. parseAgentRuntimeConfig,
  46. type AgentRuntimeConfig,
  47. } from "./agent-runtime-config.js";
  48. import { resolveDataDir } from "./data-dir.js";
  49. import type { ProviderAuthMode } from "./provider-auth-mode.js";
  50. import { parseAgentsConfig, type AgentsConfig } from "./agent-capabilities.js";
  51. import {
  52. ASK_USER_CONFIG_DEFAULTS,
  53. parseAskUserConfig,
  54. type AskUserConfig,
  55. } from "./ask-user-config.js";
  56. import {
  57. GOAL_CONFIG_DEFAULTS,
  58. parseGoalConfig,
  59. type GoalConfig,
  60. } from "./goal-config.js";
  61. import {
  62. TOOL_RESULT_COMPACTION_DEFAULTS,
  63. parseToolResultCompactionConfig,
  64. type ToolResultCompactionSettings,
  65. } from "./tool-result-compaction-config.js";
  66. import {
  67. BROWSER_CONFIG_DEFAULTS,
  68. parseBrowserConfig,
  69. type BrowserConfig,
  70. } from "./browser-config.js";
  71. import {
  72. parseSandboxConfig,
  73. SANDBOX_CONFIG_DEFAULTS,
  74. type SandboxConfig,
  75. } from "./sandbox-config.js";
  76. export type { TuiConfig, TuiCustomStatusLineConfig } from "./tui-config.js";
  77. /** Set to `true` by esbuild during `pnpm build:npm`; undefined in dev (tsx). */
  78. declare const __IS_NPM_BUILD__: boolean | undefined;
  79. function isLegacyRuntimeEnvAllowed(): boolean {
  80. return process.env.__MAVIS_ALLOW_LEGACY_RUNTIME_ENV === "1";
  81. }
  82. // ---------------------------------------------------------------------------
  83. // Runtime environment types & helpers (MAVIS_* plus Electron cold-start fallbacks)
  84. // ---------------------------------------------------------------------------
  85. export type MavisRegion = "cn" | "en";
  86. export type MavisBuildEnv = "test" | "prod" | "dev" | "staging";
  87. // Electron loads the config package before local-runtime's managed-env
  88. // bootstrap has copied the build-time NEXT_PUBLIC_* values into MAVIS_*.
  89. // Keep this mapping local to config so the first (sticky) beta-flag read sees
  90. // the packaged build environment. Electron's dev build uses the test runtime.
  91. const ELECTRON_BUILD_ENV_TO_RUNTIME: Readonly<Record<string, MavisBuildEnv>> = {
  92. dev: "test",
  93. test: "test",
  94. staging: "staging",
  95. prod: "prod",
  96. };
  97. function isValidRuntimeRegion(value: string | undefined): value is MavisRegion {
  98. return value === "cn" || value === "en";
  99. }
  100. function isValidRuntimeBuildEnv(
  101. value: string | undefined,
  102. ): value is MavisBuildEnv {
  103. return (
  104. value === "test" ||
  105. value === "prod" ||
  106. value === "dev" ||
  107. value === "staging"
  108. );
  109. }
  110. export function getRuntimeRegion(): MavisRegion {
  111. const val = process.env.MAVIS_REGION;
  112. if (isValidRuntimeRegion(val)) return val;
  113. if (isElectronProcess()) {
  114. const locale = process.env.NEXT_PUBLIC_LOCALE;
  115. if (locale === "zh") return "cn";
  116. if (locale === "en") return "en";
  117. }
  118. return "en";
  119. }
  120. export function getRuntimeBuildEnv(): MavisBuildEnv {
  121. const val = process.env.MAVIS_BUILD_ENV;
  122. if (isValidRuntimeBuildEnv(val)) return val;
  123. if (isElectronProcess()) {
  124. const nextBuildEnv = process.env.NEXT_PUBLIC_BUILD_ENV;
  125. const mapped =
  126. nextBuildEnv &&
  127. Object.prototype.hasOwnProperty.call(
  128. ELECTRON_BUILD_ENV_TO_RUNTIME,
  129. nextBuildEnv,
  130. )
  131. ? ELECTRON_BUILD_ENV_TO_RUNTIME[nextBuildEnv]
  132. : undefined;
  133. if (mapped) return mapped;
  134. }
  135. return "dev";
  136. }
  137. /**
  138. * Whether this process is running inside the managed runtime (Electron app or
  139. * packaged desktop runtime).
  140. *
  141. * Detection priority:
  142. * 1. Explicit __MAVIS_RUNTIME_MANAGED env var ('1'/'0') — for overrides
  143. * - '1': force-enable (e.g. `__MAVIS_RUNTIME_MANAGED=1 pnpm dev` to test C-end locally)
  144. * - '0': force-disable (used by internal/no-safety Electron builds to opt out)
  145. * 2. Auto-detect Electron (main process or ELECTRON_RUN_AS_NODE=1 helpers)
  146. * 3. Auto-detect production build (MAVIS_BUILD_ENV=prod)
  147. * 4. Default: false (pnpm dev / npm package)
  148. *
  149. * C-end features (safety hooks, remote models, managed token injection,
  150. * remote skill hub) should ONLY activate when this returns true.
  151. */
  152. export function isManagedRuntime(): boolean {
  153. if (hasCliFlag("managed")) return true;
  154. const explicit = process.env.__MAVIS_RUNTIME_MANAGED;
  155. if (explicit === "1") return true;
  156. if (explicit === "0") return false;
  157. if (isElectronProcess()) return true;
  158. // Production builds always enable managed runtime
  159. if (getRuntimeBuildEnv() === "prod" || getRuntimeBuildEnv() === "staging")
  160. return true;
  161. return false;
  162. }
  163. function isElectronProcess(): boolean {
  164. const versions = process.versions as NodeJS.ProcessVersions & {
  165. electron?: string;
  166. };
  167. // ELECTRON_RUN_AS_NODE is kept for older helper subprocesses. The unified
  168. // local runtime runs inside Electron main and intentionally clears it.
  169. return (
  170. process.env.ELECTRON_RUN_AS_NODE === "1" ||
  171. typeof versions.electron === "string"
  172. );
  173. }
  174. export type PresetKey = `${MavisRegion}-${MavisBuildEnv}`;
  175. export function getRuntimePresetKey(): PresetKey {
  176. return `${getRuntimeRegion()}-${getRuntimeBuildEnv()}` as PresetKey;
  177. }
  178. export type PermissionMode =
  179. | "default"
  180. | "acceptEdits"
  181. | "bypassPermissions"
  182. | "auto"
  183. | "off";
  184. /** Upstream-defined reasoning effort stored verbatim for model configuration. */
  185. export type EffortLevel = string;
  186. export interface ThinkingConfig {
  187. /** User-defined choices exposed by the message input model selector. */
  188. effortOptions?: EffortLevel[];
  189. /** Explicit provider default. Managed models receive this from Apollo. */
  190. defaultEffort?: EffortLevel;
  191. }
  192. export type ModelThinkingMode =
  193. | "switchable"
  194. | "forced_on"
  195. | "forced_off"
  196. | "hidden";
  197. export interface ModelThinkingConfig {
  198. /** Frontend thinking toggle display mode from remote model capability config. */
  199. mode?: ModelThinkingMode;
  200. /** Initial switch state for switchable models. Expected values: "true" or "false". */
  201. default_value?: string;
  202. }
  203. export interface SSEErrorPushConfig {
  204. /** Whether to publish history API errors to global SSE (`system.error`). */
  205. history: boolean;
  206. /** Whether to publish stream pipeline errors to global SSE (`system.error`). */
  207. stream: boolean;
  208. }
  209. export {
  210. isProposalEligibleAgent,
  211. type SkillEvolveConfig,
  212. type SkillEvolveInSessionConfig,
  213. type SkillEvolveLifecycleConfig,
  214. type SkillEvolveProposalConfig,
  215. } from "./skill-evolve-config.js";
  216. export interface NotificationsConfig {
  217. /** Alert root session when a branch session finishes without reporting. Default: false. */
  218. branchFinish?: boolean;
  219. }
  220. export interface PromptConfig {
  221. /** Automatic prompt delivery switch; enabled by default in official prod and inside builds, disabled in internal and non-prod builds. */
  222. autoUpdate: boolean;
  223. }
  224. // ── Session Rotation ─────────────────────────────────────────────
  225. export interface SessionRotateConfig {
  226. /**
  227. * Master switch for session rotation (Main and Branch).
  228. * When false, `POST /api/agent/:name/session/rotate` returns 403 FEATURE_DISABLED.
  229. * Default: true. Set to false to disable rotation entirely.
  230. */
  231. enabled: boolean;
  232. /**
  233. * Lookback window used by rotate bootstrap to list recently active sessions.
  234. * Sessions with updatedAt within this many hours are shown to the new session
  235. * so it can explain why follow-up messages may arrive after rotation.
  236. *
  237. * Default: 12. Valid range: positive finite number.
  238. */
  239. activeSessionLookbackHours: number;
  240. }
  241. /**
  242. * `AgentStopDetector` runtime tunables — wired into the daemon at boot
  243. * via the runtime container so operators can tune the debounce window
  244. * and active-span backstop without rebuilding the binary.
  245. *
  246. * ```yaml
  247. * agentStop:
  248. * debounceMs: 500 # 0 disables debouncing entirely
  249. * maxActiveSpanMs: 1800000 # 30 min; 0 disables the backstop
  250. * ```
  251. */
  252. export interface AgentStopDetectorConfig {
  253. /**
  254. * Window in ms for coalescing terminal `session.*` events before the
  255. * detector evaluates AgentStop gates. Default 500ms. Setting `0`
  256. * effectively disables debouncing — every terminal event triggers a
  257. * synchronous re-evaluation, which is generally only useful in tests.
  258. */
  259. debounceMs: number;
  260. /**
  261. * Maximum continuous producer-active span (in ms) before the detector
  262. * forces an `AgentStop` even when the inbox is non-empty. Default 30
  263. * minutes. Set to `0` to disable the backstop entirely (the detector
  264. * still fires on natural idle).
  265. */
  266. maxActiveSpanMs: number;
  267. }
  268. export type * from "./asr.js";
  269. // ── Beta Features ────────────────────────────────────────────────
  270. /**
  271. * Centralized switches for beta/experimental features.
  272. * Each feature is declared in `BETA_FEATURE_DEFS` with one default visibility
  273. * and one explicit-configuration ceiling.
  274. *
  275. * ```yaml
  276. * beta:
  277. * autoMemory: false
  278. * skillEvolve: false
  279. * browserBridge: false
  280. * filePanelBrowser: false
  281. * filePanelBrowserMultiTab: false
  282. * browserUseTooling: false
  283. * browserUseAutoOpenPanel: false
  284. * browserAgentCursor: false
  285. * desktopPlanMode: true
  286. * desktopPlanModeAgentEntry: false
  287. * taskHistoryProjectGrouping: false
  288. * threadGoal: false
  289. * mcodeTools: false
  290. * codexOAuth: false
  291. * ```
  292. */
  293. export interface BetaConfig {
  294. /** Auto-memory extraction + daily digest + session promoter. */
  295. autoMemory: boolean;
  296. /**
  297. * Skill self-evolution — signal collection, scanning, editor spawning,
  298. * and the nightly evolve cron.
  299. *
  300. * `defaultVisibility: 'test', configurableVisibility: 'online'` — dev/test
  301. * ships ON by default so contributors get the feedback loop without extra
  302. * setup; production ships OFF by default and requires `beta.skillEvolve:
  303. * true` opt-in (model gating + nightly cron + filesystem writes are
  304. * non-trivial side effects that prod users should explicitly accept).
  305. *
  306. * Note: `skillEvolveBuiltinMr` is the finer-grained gate for the built-in
  307. * MR path specifically; it is configurable only through the test channel
  308. * and is relevant only when this parent gate is on.
  309. */
  310. skillEvolve: boolean;
  311. /**
  312. * Built-in skill evolution via MR — when set, the nightly evolver may
  313. * dispatch a worker that opens a GitLab MR against the daemon source repo
  314. * for each built-in skill needing changes. Gated separately from
  315. * `skillEvolve` so users with a source repo (dev installs) can still opt
  316. * out of MR-driven built-in evolution while keeping user/agent/project
  317. * skill evolution enabled. Its visibility ceiling is `test` because prod
  318. * npm installs have no source repo to push to.
  319. */
  320. skillEvolveBuiltinMr: boolean;
  321. /**
  322. * v3 skill creation proposal pipeline — session-end fallback re-prompt
  323. * asks eligible agents to reflect on whether the just-finished session
  324. * revealed a reusable pattern worth crystallizing into a new skill.
  325. * Wires up the ProposalStore CRUD and the fallback prompt's "proposal"
  326. * section. `defaultVisibility: 'test', configurableVisibility: 'online'`:
  327. * dev/test ships ON by default so contributors collect proposals
  328. * automatically; prod ships OFF and requires `beta.skillProposal: true`
  329. * opt-in (extra session-end LLM tokens + ProposalStore writes are
  330. * explicit-consent surface).
  331. */
  332. skillProposal: boolean;
  333. /**
  334. * Browser bridge HTTP API and UI panel — drives a real Chrome session via
  335. * the Mavis Browser Bridge extension (logged-in sites, persistent cookies,
  336. * extensions). `defaultVisibility: 'test', configurableVisibility:
  337. * 'online'` — ships ON in dev/test for daily use and OFF in prod by
  338. * default; prod users opt in via `beta.browserBridge: true` once they've
  339. * installed the Chrome extension and confirmed the broker socket.
  340. */
  341. browserBridge: boolean;
  342. /**
  343. * FilePanel embedded browser — an Electron-only WebContentsView target
  344. * shown inside the right-side panel. Both visibility fields are `online`,
  345. * so it ships ON by default in every environment while retaining
  346. * `beta.filePanelBrowser: false` as an emergency kill switch.
  347. */
  348. filePanelBrowser: boolean;
  349. /**
  350. * Multiple logical tabs inside the FilePanel embedded browser.
  351. *
  352. * Both visibility fields are `online`, so it ships ON by default in every
  353. * environment while retaining `beta.filePanelBrowserMultiTab: false` as an
  354. * emergency rollback to the established single-tab behavior.
  355. */
  356. filePanelBrowserMultiTab: boolean;
  357. /** Explicit Browser tool/Skill opt-in for CLI/TUI; Desktop activation is Plugin-managed. */
  358. browserUseTooling: boolean;
  359. /**
  360. * Whether model-driven Browser actions reveal the right-side Browser panel.
  361. * This is a presentation preference only: disabling it does not revoke
  362. * Browser Use permission or prevent the Agent from operating an existing
  363. * Browser tab in the background.
  364. *
  365. * The preference defaults ON in every environment to preserve the existing
  366. * visible-action behavior, while an explicit `false` keeps Browser actions
  367. * in the background until the user opens the panel manually.
  368. */
  369. browserUseAutoOpenPanel: boolean;
  370. /**
  371. * Visible pointer animation for model-driven Browser click, double-click,
  372. * and hover actions. Kept separate from both the CLI/TUI
  373. * `browserUseTooling` opt-in and Desktop Plugin activation so Browser Use
  374. * can remain available while the presentation layer is rolled out safely.
  375. *
  376. * Both visibility fields are `online`, so dev/test, Preview, Inside, and
  377. * external production builds show the pointer by default. An explicit
  378. * `beta.browserAgentCursor: false` remains available as a kill switch.
  379. */
  380. browserAgentCursor: boolean;
  381. /**
  382. * Desktop Plan Mode. Available online by default, with explicit `false` as
  383. * an emergency kill switch for new entry. Runtime owners must keep exit and
  384. * persisted-state recovery available while this switch is off.
  385. */
  386. desktopPlanMode: boolean;
  387. /**
  388. * Model-facing Desktop Plan Mode entry guidance and `EnterPlanMode` tool.
  389. * Kept separate from `desktopPlanMode` so users retain manual `/plan` and
  390. * composer entry while Agent-initiated entry stays opt-in.
  391. *
  392. * `defaultVisibility: 'none', configurableVisibility: 'online'` — every
  393. * channel starts with Agent entry disabled; explicit `true` is available as
  394. * a controlled rollback while the parent Plan Mode switch remains enabled.
  395. */
  396. desktopPlanModeAgentEntry: boolean;
  397. /**
  398. * /btw side-question peek command (the UI's "Aside" slash palette row). Both visibility fields
  399. * are `test`, so dev/test ships ON by default while prod is force-off regardless of config.yaml
  400. * (even `beta.peek: true` cannot open it).
  401. * Fail-closed contract: local-runtime `/mavis/api/config` returns the resolved `beta.peek`, UI
  402. * hydrates `runtimeFlagStore.peekEnabled` strictly from `beta?.peek === true`, and the composer
  403. * only exposes `/btw` when that flag is true.
  404. */
  405. peek: boolean;
  406. /**
  407. * Legacy OpenCode keep-alive pool. New local sessions do not use this path,
  408. * but the daemon package remains in the workspace compile surface while old
  409. * opencode sessions are still resumable through the legacy boundary.
  410. */
  411. keepAlive: boolean;
  412. /**
  413. * Memory prompt override via filesystem — when enabled, memory-related
  414. * LLM prompts check `{dataDir}/internal/prompts/{name}.md` first.
  415. * If the file exists, its content replaces the hardcoded prompt entirely.
  416. * Its visibility ceiling is `test` because prompt file paths are not yet
  417. * stable for end-users.
  418. */
  419. promptOverride: boolean;
  420. /**
  421. * Computer Use mode — agent-driven mouse/keyboard/screen control via the archon Electron
  422. * renderer. Adds a CU toggle to the chat input toolbar, a CUBanner above MessageInput, a Computer
  423. * Use permissions section in SettingsModal/Desktop, and the dock-restore abort behaviour.
  424. *
  425. * Both visibility fields are `online`, so CU is available in every environment. CU controls the
  426. * user's host machine via macOS TCC-gated screen recording / accessibility / input synthesis, but
  427. * the toggle still defaults to OFF — user must explicitly click it and grant macOS TCC
  428. * permissions.
  429. *
  430. * Even when this gate is true, the toggle still defaults to OFF and the user must explicitly
  431. * click it (and grant the macOS TCC permission on first run) before any CU tool call can fire.
  432. * The gate controls whether the toggle/banner/permission section are *available* in the UI — not
  433. * whether CU is *active*.
  434. */
  435. cuMode: boolean;
  436. asr: boolean;
  437. /**
  438. * Sidebar Task History project-grouping overflow entry (`recents` ↔
  439. * `projects`). Replaces the prior `isWebVariant` platform gate. Hydrated
  440. * from `beta?.taskHistoryProjectGrouping === true` (strict); fail-closed
  441. * keeps trigger hidden + `viewMode` locked to `recents`. Both visibility
  442. * fields are `online`, keeping the desktop selector available by default in
  443. * every channel. See runtime-flags.ts.
  444. */
  445. taskHistoryProjectGrouping: boolean;
  446. /**
  447. * Thread Goal UI, tools, accounting, and auto-continuation. Dev/test and
  448. * internal prod builds default ON for dogfooding; external and inside prod
  449. * builds default OFF but can be explicitly enabled with
  450. * `beta.threadGoal: true` in config.yaml.
  451. */
  452. threadGoal: boolean;
  453. /**
  454. * Bundled mcode-tools CLI and Electron Device Flow integration. Packaged
  455. * dev/test/staging/prod builds default ON on macOS/Linux/Windows. An explicit
  456. * config.yaml false value may opt any supported build out. This switch does
  457. * not control native web_search; Electron, TUI and CLI use the native tool
  458. * without starting the built-in Matrix MCP.
  459. */
  460. mcodeTools: boolean;
  461. /**
  462. * OpenAI Codex OAuth settings entry. Enabled by default in internal builds and development
  463. * environments, regardless of the connected backend environment. Public prod / external staging /
  464. * Inside / test builds expose the OAuth connection button in desktop model settings via
  465. * `beta.codexOAuth: true`. Provider configuration stays in `config.yaml` and OAuth credentials
  466. * stay in `<dataDir>/codex-auth.json`.
  467. */
  468. codexOAuth: boolean;
  469. }
  470. export type FeatureVisibility = "none" | "test" | "internal" | "online";
  471. export type FeatureChannel = Exclude<FeatureVisibility, "none">;
  472. export type BetaBuildVariant = "internal" | "inside";
  473. export interface BetaFeatureDef {
  474. /** Furthest channel where the feature is enabled without explicit config. */
  475. defaultVisibility: FeatureVisibility;
  476. /** Exact build environments where the feature is enabled without explicit config. */
  477. defaultBuildEnvironments?: readonly MavisBuildEnv[];
  478. /** Platforms where any default rollout may enable the feature. */
  479. defaultPlatforms?: readonly NodeJS.Platform[];
  480. /**
  481. * Features enabled by default for build variants (internal / inside), independent of buildEnv.
  482. * Variant flags are injected by the packaging lane; internal builds use a staging backend but
  483. * must retain internal-build feature defaults.
  484. */
  485. defaultBuildVariants?: readonly BetaBuildVariant[];
  486. /** Furthest channel where explicit `true` may enable the feature. */
  487. configurableVisibility: FeatureVisibility;
  488. }
  489. export const VISIBILITY_RANK: Readonly<Record<FeatureVisibility, number>> = {
  490. none: 0,
  491. test: 1,
  492. internal: 2,
  493. online: 3,
  494. };
  495. const BUILD_VARIANT_VISIBILITY: Readonly<
  496. Record<BetaBuildVariant, FeatureChannel>
  497. > = {
  498. internal: "internal",
  499. inside: "online",
  500. };
  501. /**
  502. * Fail fast when a feature's default rollout is wider than its opt-in ceiling.
  503. * Silently correcting this would hide a release-policy error and could expose a
  504. * feature to a broader channel than intended.
  505. */
  506. export function assertBetaFeatureDefinitions(
  507. defs: Readonly<Record<string, BetaFeatureDef>>,
  508. ): void {
  509. for (const [feature, def] of Object.entries(defs)) {
  510. if (
  511. VISIBILITY_RANK[def.defaultVisibility] >
  512. VISIBILITY_RANK[def.configurableVisibility]
  513. ) {
  514. throw new Error(
  515. `Invalid beta feature definition "${feature}": defaultVisibility ` +
  516. `(${def.defaultVisibility}) must not exceed configurableVisibility ` +
  517. `(${def.configurableVisibility})`,
  518. );
  519. }
  520. for (const variant of def.defaultBuildVariants ?? []) {
  521. const variantVisibility = BUILD_VARIANT_VISIBILITY[variant];
  522. if (
  523. VISIBILITY_RANK[variantVisibility] >
  524. VISIBILITY_RANK[def.configurableVisibility]
  525. ) {
  526. throw new Error(
  527. `Invalid beta feature definition "${feature}": defaultBuildVariant ` +
  528. `(${variant}) must not exceed configurableVisibility ` +
  529. `(${def.configurableVisibility})`,
  530. );
  531. }
  532. }
  533. for (const buildEnv of def.defaultBuildEnvironments ?? []) {
  534. const buildEnvVisibility: FeatureChannel =
  535. buildEnv === "prod" ? "online" : "test";
  536. if (
  537. VISIBILITY_RANK[buildEnvVisibility] >
  538. VISIBILITY_RANK[def.configurableVisibility]
  539. ) {
  540. throw new Error(
  541. `Invalid beta feature definition "${feature}": defaultBuildEnvironment ` +
  542. `(${buildEnv}) must not exceed configurableVisibility ` +
  543. `(${def.configurableVisibility})`,
  544. );
  545. }
  546. }
  547. }
  548. }
  549. export const BETA_FEATURE_DEFS = {
  550. autoMemory: { defaultVisibility: "online", configurableVisibility: "online" },
  551. skillEvolve: { defaultVisibility: "test", configurableVisibility: "online" },
  552. skillEvolveBuiltinMr: {
  553. defaultVisibility: "none",
  554. configurableVisibility: "test",
  555. },
  556. skillProposal: {
  557. defaultVisibility: "test",
  558. configurableVisibility: "online",
  559. },
  560. browserBridge: {
  561. defaultVisibility: "test",
  562. configurableVisibility: "online",
  563. },
  564. filePanelBrowser: {
  565. defaultVisibility: "online",
  566. configurableVisibility: "online",
  567. },
  568. filePanelBrowserMultiTab: {
  569. defaultVisibility: "online",
  570. configurableVisibility: "online",
  571. },
  572. browserUseTooling: {
  573. defaultVisibility: "online",
  574. configurableVisibility: "online",
  575. },
  576. browserUseAutoOpenPanel: {
  577. defaultVisibility: "online",
  578. configurableVisibility: "online",
  579. },
  580. browserAgentCursor: {
  581. defaultVisibility: "online",
  582. configurableVisibility: "online",
  583. },
  584. desktopPlanMode: {
  585. defaultVisibility: "online",
  586. configurableVisibility: "online",
  587. },
  588. desktopPlanModeAgentEntry: {
  589. defaultVisibility: "none",
  590. configurableVisibility: "online",
  591. },
  592. peek: { defaultVisibility: "test", configurableVisibility: "test" },
  593. keepAlive: { defaultVisibility: "test", configurableVisibility: "test" },
  594. promptOverride: { defaultVisibility: "test", configurableVisibility: "test" },
  595. cuMode: { defaultVisibility: "online", configurableVisibility: "online" },
  596. asr: { defaultVisibility: "online", configurableVisibility: "online" },
  597. taskHistoryProjectGrouping: {
  598. defaultVisibility: "online",
  599. configurableVisibility: "online",
  600. },
  601. threadGoal: { defaultVisibility: "online", configurableVisibility: "online" },
  602. mcodeTools: {
  603. defaultVisibility: "none",
  604. defaultBuildEnvironments: ["dev", "test", "staging", "prod"],
  605. defaultPlatforms: ["darwin", "linux", "win32"],
  606. configurableVisibility: "online",
  607. },
  608. codexOAuth: {
  609. defaultVisibility: "none",
  610. defaultBuildEnvironments: ["dev"],
  611. defaultBuildVariants: ["internal"],
  612. configurableVisibility: "online",
  613. },
  614. } satisfies Record<keyof BetaConfig, BetaFeatureDef>;
  615. assertBetaFeatureDefinitions(BETA_FEATURE_DEFS);
  616. export interface BetaFeatureResolutionContext {
  617. buildEnv?: MavisBuildEnv;
  618. defaultBuildEnvironment?: MavisBuildEnv;
  619. internalBuild?: boolean;
  620. insideBuild?: boolean;
  621. platform?: NodeJS.Platform;
  622. mcodeToolsDevMode?: "published";
  623. }
  624. function getBetaFeatureChannel(
  625. context: BetaFeatureResolutionContext,
  626. ): FeatureChannel {
  627. const buildEnv = context.buildEnv ?? getRuntimeBuildEnv();
  628. if (buildEnv !== "prod") return "test";
  629. return context.internalBuild === true ? "internal" : "online";
  630. }
  631. // Variant defaults depend only on variant flags: internal builds use buildEnv=staging but remain on the internal release lane
  632. // and must retain internal defaults such as codexOAuth. Inside builds still use buildEnv=prod.
  633. function isDefaultEnabledForBuildVariant(
  634. def: BetaFeatureDef,
  635. context: BetaFeatureResolutionContext,
  636. ): boolean {
  637. const variants = def.defaultBuildVariants;
  638. if (!variants) return false;
  639. return (
  640. (context.internalBuild === true && variants.includes("internal")) ||
  641. (context.insideBuild === true && variants.includes("inside"))
  642. );
  643. }
  644. function isDefaultEnabledForBuildEnvironment(
  645. def: BetaFeatureDef,
  646. context: BetaFeatureResolutionContext,
  647. ): boolean {
  648. const buildEnv =
  649. context.defaultBuildEnvironment ??
  650. context.buildEnv ??
  651. getBetaDefaultBuildEnvironment();
  652. return def.defaultBuildEnvironments?.includes(buildEnv) === true;
  653. }
  654. function getBetaDefaultBuildEnvironment(): MavisBuildEnv {
  655. const electronBuildEnv = isElectronProcess()
  656. ? process.env.NEXT_PUBLIC_BUILD_ENV
  657. : undefined;
  658. return isValidRuntimeBuildEnv(electronBuildEnv)
  659. ? electronBuildEnv
  660. : getRuntimeBuildEnv();
  661. }
  662. function isDefaultEnabledForPlatform(
  663. def: BetaFeatureDef,
  664. context: BetaFeatureResolutionContext,
  665. ): boolean {
  666. return (
  667. def.defaultPlatforms?.includes(context.platform ?? process.platform) !==
  668. false
  669. );
  670. }
  671. /**
  672. * Resolve every beta flag with one channel model. `defaultVisibility` controls
  673. * the channel rollout, exact build-environment/platform defaults narrow special
  674. * releases, `defaultBuildVariants` adds build-variant defaults independent of the
  675. * build environment, and `configurableVisibility` controls explicit opt-in.
  676. * Published-resource dev commands are explicit opt-ins; other environments
  677. * remain fail-closed. Inside builds map to online unless declared otherwise.
  678. */
  679. export function resolveBetaFeature(
  680. feature: keyof BetaConfig,
  681. configured: unknown,
  682. context: BetaFeatureResolutionContext = {},
  683. ): boolean {
  684. const def: BetaFeatureDef = BETA_FEATURE_DEFS[feature];
  685. const channelRank = VISIBILITY_RANK[getBetaFeatureChannel(context)];
  686. const defaultBuildEnvironment =
  687. context.defaultBuildEnvironment ??
  688. context.buildEnv ??
  689. getBetaDefaultBuildEnvironment();
  690. if (
  691. feature === "mcodeTools" &&
  692. defaultBuildEnvironment === "dev" &&
  693. context.mcodeToolsDevMode === "published" &&
  694. isDefaultEnabledForPlatform(def, context)
  695. )
  696. return true;
  697. if (configured === false) return false;
  698. if (configured === true)
  699. return channelRank <= VISIBILITY_RANK[def.configurableVisibility];
  700. if (!isDefaultEnabledForPlatform(def, context)) return false;
  701. if (isDefaultEnabledForBuildEnvironment(def, context)) return true;
  702. if (isDefaultEnabledForBuildVariant(def, context)) return true;
  703. return channelRank <= VISIBILITY_RANK[def.defaultVisibility];
  704. }
  705. /** @deprecated Prefer `resolveBetaFeature`; retained for CLI compatibility. */
  706. export function isBetaFeatureProdReady(feature: keyof BetaConfig): boolean {
  707. return BETA_FEATURE_DEFS[feature].configurableVisibility === "online";
  708. }
  709. export function isInternalBuild(env: NodeJS.ProcessEnv = process.env): boolean {
  710. return env.__MAVIS_BUILD_INTERNAL === "true";
  711. }
  712. function isInsideBuild(env: NodeJS.ProcessEnv = process.env): boolean {
  713. return env.__MAVIS_BUILD_INSIDE === "true";
  714. }
  715. export type { AskUserConfig } from "./ask-user-config.js";
  716. // ── Session Title Generation ──────────────────────────────────────
  717. /**
  718. * LLM session-title generation flag. Default `true`. Set
  719. * `sessionTitle.enabled: false` to drop the extra title model request
  720. * (e.g. headless / evaluation runs that don't want it in the trajectory).
  721. */
  722. export interface SessionTitleConfig {
  723. enabled: boolean;
  724. }
  725. // ── CLI Feature Flags ─────────────────────────────────────────────
  726. export interface CliSpawnConfig {
  727. /**
  728. * Expose `mavis session spawn` CLI command.
  729. * `spawn` lets users / external scripts manually create child sessions for an agent
  730. * (with parent linkage, initial prompt, and optional agent auto-creation).
  731. * Mavis itself and its agents do NOT need this — team plans spawn worker sessions
  732. * via the in-process daemon API, not via CLI.
  733. * Default: false. Enable only if you want external tooling to drive spawn.
  734. */
  735. enabled: boolean;
  736. }
  737. export interface CliConfig {
  738. spawn: CliSpawnConfig;
  739. }
  740. // ── Legacy OpenCode Adapter (daemon compile compatibility) ───────
  741. export interface OpenCodeKeepAliveConfig {
  742. enabled: boolean;
  743. maxProcesses: number;
  744. maxLifetimeMs: number;
  745. agents: string[];
  746. }
  747. export type OpenCodeStartupImportMode = "off" | "background" | "blocking";
  748. export interface OpenCodeXdgConfig {
  749. dataIsolation: boolean;
  750. startupImport: OpenCodeStartupImportMode;
  751. }
  752. export interface OpenCodeAdapterConfig {
  753. keepAlive: OpenCodeKeepAliveConfig;
  754. xdg: OpenCodeXdgConfig;
  755. spawnConcurrency: number;
  756. }
  757. // ── Context Management ──────────────────────────────────────────
  758. export interface DailyDigestConfig {
  759. /**
  760. * Generate daily digest files under `<dataDir>/agents/<name>/daily/`.
  761. *
  762. * This only gates digest generation and daily TTL archival. It does NOT
  763. * disable the scheduler itself: session-level fallback re-prompts and
  764. * memory-tracking cleanup continue to run.
  765. *
  766. * Default: false.
  767. */
  768. enabled: boolean;
  769. }
  770. export interface MemoryConfig {
  771. /**
  772. * Master switch for desktop memory behavior.
  773. *
  774. * When false, the desktop daemon/plugin stop injecting memory, showing
  775. * memory reminders, auto-generating/cleaning memory, and accepting memory
  776. * writes through Mavis APIs. Existing files are preserved and read/search
  777. * remains available for inspection.
  778. *
  779. * Default: true.
  780. */
  781. enabled: boolean;
  782. /**
  783. * Opt-in hot-path reminder that asks the main agent to evaluate durable memory.
  784. *
  785. * Default: false.
  786. */
  787. proactive: boolean;
  788. dailyDigest: DailyDigestConfig;
  789. }
  790. export interface ContextManagementConfig {
  791. /**
  792. * Models for which the per-message `<system-reminder>` injection is fully
  793. * disabled.
  794. *
  795. * Used by models with very tight context budgets where repeated SR
  796. * injection is too costly (e.g. minimax M2.7). Each turn the daemon would
  797. * normally append a `<system-reminder>` block to the user message; for
  798. * listed models the block is skipped entirely.
  799. *
  800. * Format: array of `"providerID/modelID"` strings.
  801. * Default: empty (SR enabled for every model).
  802. *
  803. * Note: this only affects the per-message SR (path B). The static
  804. * `<agent_memory>` / `<global_memory>` / `<daily_digest>` blocks injected
  805. * into the system prompt (path A) are unaffected.
  806. */
  807. disableSystemReminderModels: string[];
  808. /**
  809. * Maximum number of Computer Use screenshots to keep as inline image data
  810. * in the conversation context sent to the LLM.
  811. *
  812. * CU screenshots (from `desktop_screenshot`, `desktop_zoom`,
  813. * `desktop_screenshot_region` tools) are large base64-encoded images that
  814. * accumulate rapidly during CU sessions. When the total count exceeds
  815. * this limit, older screenshots are replaced with a text placeholder
  816. * containing the on-disk file path, so the model can re-read them via
  817. * the Read tool if needed.
  818. *
  819. * Set to `0` to disable (keep all screenshots).
  820. * Default: 5.
  821. */
  822. cuMaxScreenshotsInContext: number;
  823. }
  824. /**
  825. * MCP progressive-disclosure ("tool search") tunables.
  826. *
  827. * All fields optional; unset fields fall back to the disclosure defaults
  828. * applied by the local-runtime resolver. When the whole block is absent the
  829. * value is `undefined` and the feature stays off (empty whitelist matches no
  830. * model). See `packages/local-runtime/src/mcp/disclosure-options.ts`.
  831. */
  832. export interface McpToolSearchConfig {
  833. enabled?: boolean;
  834. modelWhitelist?: string[];
  835. thresholdPct?: number;
  836. minDeferCount?: number;
  837. topKDefault?: number;
  838. topKMax?: number;
  839. systemHint?: boolean;
  840. maxSchemaTextLen?: number;
  841. }
  842. export interface ReviewConfig {
  843. mode: "inline" | "subagent";
  844. /** Generated during parsing to distinguish product defaults from explicit user choices; not read from the config file. */
  845. modeSource?: "default" | "explicit";
  846. }
  847. export interface TelemetryConfig {
  848. /** Send anonymous TUI usage events. Disabled until the user opts in. */
  849. enabled: boolean;
  850. /** Send runtime performance metrics. Separate opt-in, disabled by default. */
  851. metrics?: boolean;
  852. /** Send minimized, account-linked automatic error reports. Separate opt-in, disabled by default. */
  853. diagnostics?: boolean;
  854. }
  855. export interface Config {
  856. logLevel: string;
  857. devPort: number;
  858. provider: ModelsConfig;
  859. /**
  860. * BYOK: user's own MiniMax API key. Written only through the ModelProvider
  861. * API — excluded from the generic config update whitelist so a sanitized
  862. * GET /config payload can never be written back over the real key.
  863. */
  864. minimax_api?: MinimaxApiConfig;
  865. /** User-owned Context selections for the managed MiniMax catalog. */
  866. minimaxModelContextLimits?: Record<string, number>;
  867. /** BYOK: user-created external providers (same write boundary as minimax_api). */
  868. custom_provider?: CustomProvidersConfig;
  869. /** BYOK: active model source — 'token_plan' uses managed-login, 'minimax_api_key' uses user's own API key. */
  870. minimaxModelSource?: "token_plan" | "minimax_api_key";
  871. nexus?: NexusConfig;
  872. /** Default model for new agents, format: "providerID/modelID" */
  873. defaultModel?: string;
  874. /** Persisted variant for the default model, such as a reasoning effort. */
  875. defaultModelVariant?: string;
  876. defaultModelThinking?: { effort?: string };
  877. defaultModelContextWindow?: number;
  878. /** Optional lightweight model for auxiliary tasks (title gen, etc.). Falls back to defaultModel. Format: "providerID/modelID" */
  879. defaultLightModel?: string;
  880. /** Permission mode for tool call authorization. */
  881. permissionMode: PermissionMode;
  882. permission: PermissionConfig;
  883. /** Global SSE error event publishing controls. */
  884. sseErrorPush: SSEErrorPushConfig;
  885. /** Notification controls. */
  886. notifications?: NotificationsConfig;
  887. dataDir: string;
  888. agentsDir: string;
  889. sessionsDir: string;
  890. memoryDir: string;
  891. skillsDir: string;
  892. /** Hidden directory for daemon-bundled built-in skills (read-only). */
  893. builtinSkillsDir: string;
  894. logsDir: string;
  895. pluginsDir: string;
  896. plansDir: string;
  897. harnessesDir: string;
  898. subAgentsDir: string;
  899. /** Beta / experimental feature switches. */
  900. beta: BetaConfig;
  901. /** Builtin capability defaults inherited by every Agent. */
  902. agents: AgentsConfig;
  903. /** Memory feature controls. */
  904. memory: MemoryConfig;
  905. /** Skill self-evolution configuration. */
  906. skillEvolve: SkillEvolveConfig;
  907. /** Session rotation configuration. */
  908. sessionRotate: SessionRotateConfig;
  909. /** AgentStop detector tunables (debounce, active-span backstop). */
  910. agentStop: AgentStopDetectorConfig;
  911. asr: AsrConfig; // cloud ASR (speech-to-text) — see ./asr.ts
  912. /** External skill source ingestion — see ./skills-config.ts */
  913. skills: SkillsConfig;
  914. /** ask_user tool feature flag — see `AskUserConfig`. */
  915. askUser: AskUserConfig;
  916. /** Session title auto-generation feature flag — see `SessionTitleConfig`. */
  917. sessionTitle: SessionTitleConfig;
  918. /** CLI feature flags. */
  919. cli: CliConfig;
  920. /** Browser provider options; activation is owned by V2 Plugin/config policy. */
  921. browser: BrowserConfig;
  922. /** TUI presentation options, such as the status line item order. */
  923. tui: TuiConfig;
  924. /** Anonymous TUI business telemetry. */
  925. telemetry: TelemetryConfig;
  926. /** Legacy OpenCode framework adapter tunables. */
  927. opencode: OpenCodeAdapterConfig;
  928. /** Per-model context management overrides (e.g. disable SR for low-context models). */
  929. contextManagement: ContextManagementConfig;
  930. /** Local Runaway Guard policy; valid Apollo booleans override it on Desktop. */
  931. runawayGuard: RunawayGuardSettings;
  932. /** ToolResult archive/trim thresholds shared by TUI, CLI and managed Desktop. */
  933. toolResultCompaction: ToolResultCompactionSettings;
  934. /** Runtime selection knobs (e.g. `defaultFramework` for new sessions). */
  935. agentRuntime: AgentRuntimeConfig;
  936. /**
  937. * Number of days to retain log files before automatic cleanup.
  938. * Default: 3. A value of 0 or undefined also defaults to 3.
  939. */
  940. logRetentionDays: number;
  941. /** Content review (safety) test controls. Production routing is fixed. */
  942. contentReview?: { enabled?: boolean; testBaseURL?: string };
  943. /** MCP progressive-disclosure ("tool search") tunables — undefined when absent. */
  944. mcpToolSearch?: McpToolSearchConfig;
  945. /** Computer Use backend: 'native' (default) for in-process Electron impl; 'mcp' reserved and throws via assertCuBackendSupported. See cu-backend.ts. */
  946. cuBackend: CuBackend;
  947. /** Built-in local code review behavior. */
  948. review: ReviewConfig;
  949. /** Automatic prompt delivery policy. */
  950. promptConfig: PromptConfig;
  951. /** Durable Goal policy, budgets, breaker, and verifier defaults. */
  952. goal: GoalConfig;
  953. /** Process sandbox product policy. Runtime-only fields are derived elsewhere. */
  954. sandbox: SandboxConfig;
  955. /** Non-fatal corrections made while parsing Goal policy. */
  956. goalWarnings: readonly string[];
  957. }
  958. // --- Modality & Status ---
  959. export type Modality = "text" | "audio" | "image" | "video" | "pdf";
  960. export type ModelStatus = "alpha" | "beta" | "deprecated";
  961. // --- Cost ---
  962. export interface ModelCostTier {
  963. input: number;
  964. output: number;
  965. cache_read?: number;
  966. cache_write?: number;
  967. }
  968. export interface ModelCost extends ModelCostTier {
  969. context_over_200k?: ModelCostTier;
  970. }
  971. // --- Limit & Modalities ---
  972. export interface ModelLimit {
  973. context: number;
  974. input?: number;
  975. output: number;
  976. }
  977. export interface ModelModalities {
  978. input: Modality[];
  979. output: Modality[];
  980. }
  981. // --- Model ---
  982. export interface ModelCapabilitiesConfig {
  983. support_image?: boolean;
  984. support_video?: boolean;
  985. /** Model endpoint enforces response_format: { type: 'json_object' }. */
  986. support_json_object_output?: boolean;
  987. support_files_api?: boolean;
  988. use_file_api?: boolean;
  989. files_api_upload_endpoint?: string;
  990. files_api_ref_scheme?: string;
  991. files_api_file_id_ttl_sec?: number;
  992. max_image_bytes_inline?: number | string;
  993. max_video_bytes_inline?: number | string;
  994. max_request_body_bytes?: number | string;
  995. max_attachments_count?: number | string;
  996. [key: string]: unknown;
  997. }
  998. export type ModelConfigurationSource = "manual" | "discovered";
  999. export type ModelContextWindowOptionHint = "higher_usage";
  1000. export interface ModelConfig {
  1001. id?: string;
  1002. name?: string;
  1003. enabled?: boolean;
  1004. family?: string;
  1005. release_date?: string;
  1006. configuration_source?: ModelConfigurationSource;
  1007. attachment?: boolean;
  1008. reasoning?: boolean;
  1009. temperature?: boolean;
  1010. tool_call?: boolean;
  1011. interleaved?: true | { field: "reasoning_content" | "reasoning_details" };
  1012. cost?: ModelCost;
  1013. limit?: ModelLimit;
  1014. /** Ordered context choices advertised by the managed model catalog. */
  1015. contextWindowOptions?: number[];
  1016. /** Derived by managed catalogue sync; never read from a selection request. */
  1017. parameterErrors?: { contextOptions?: true; effortOptions?: true };
  1018. /** Semantic UI hints keyed by decimal context-window size. */
  1019. contextWindowOptionHints?: Record<string, ModelContextWindowOptionHint>;
  1020. modalities?: ModelModalities;
  1021. experimental?: boolean;
  1022. status?: ModelStatus;
  1023. thinking?: ThinkingConfig;
  1024. thinking_config?: ModelThinkingConfig;
  1025. options?: Record<string, unknown>;
  1026. headers?: Record<string, string>;
  1027. capabilities?: ModelCapabilitiesConfig;
  1028. provider?: { npm?: string; api?: string };
  1029. variants?: Record<string, { disabled?: boolean; [key: string]: unknown }>;
  1030. defaultVariant?: string;
  1031. }
  1032. // --- Provider ---
  1033. export interface ProviderOptions {
  1034. apiKey?: string;
  1035. baseURL?: string;
  1036. authMode?: ProviderAuthMode;
  1037. enterpriseUrl?: string;
  1038. setCacheKey?: boolean;
  1039. timeout?: number | false;
  1040. chunkTimeout?: number;
  1041. headers?: Record<string, string>;
  1042. [key: string]: unknown;
  1043. }
  1044. export interface ProviderConfig {
  1045. api?: string;
  1046. name?: string;
  1047. env?: string[];
  1048. id?: string;
  1049. npm?: string;
  1050. models?: Record<string, ModelConfig>;
  1051. /** Display order for managed models; omitted models retain their catalog order. */
  1052. model_order?: string[];
  1053. blacklist?: string[];
  1054. whitelist?: string[];
  1055. options?: ProviderOptions;
  1056. }
  1057. export type ModelsConfig = Record<string, ProviderConfig>;
  1058. // --- BYOK user providers (settings-page owned; see the BYOK model configuration technical design) ---
  1059. /**
  1060. * User's own MiniMax API key ("MiniMax API" settings tab). Stores the raw key
  1061. * locally; every API response must mask it. v1 is replace-only through the
  1062. * ModelProvider API (no remove/clear); `baseURL` is a hand-edited override
  1063. * only and is intentionally not exposed via the upsert endpoint. Model list
  1064. * and capabilities are derived by the runtime and never stored here.
  1065. */
  1066. export interface MinimaxApiConfig {
  1067. apiKey?: string;
  1068. /** Optional endpoint override; defaults to the runtime's builtin MiniMax API endpoint. */
  1069. baseURL?: string;
  1070. /** Hand-edited request headers; values may contain credentials and must not be displayed. */
  1071. headers?: Record<string, string>;
  1072. /** User-owned context selections applied only to the independent MiniMax API catalog. */
  1073. modelContextLimits?: Record<string, number>;
  1074. }
  1075. /**
  1076. * User-created external provider ("Custom Model" settings tab). Reuses the
  1077. * ProviderConfig field vocabulary. Map keys (`provider_key`) are generated
  1078. * once from the display name at creation time and are immutable afterwards —
  1079. * renames only change `name`.
  1080. */
  1081. export interface CustomProviderConfig extends ProviderConfig {
  1082. /** Provider kind; user-created providers are always 'custom'. */
  1083. kind?: string;
  1084. /** Disabled providers keep their config but drop out of the effective model list. */
  1085. enabled?: boolean;
  1086. }
  1087. export type CustomProvidersConfig = Record<string, CustomProviderConfig>;
  1088. // --- Nexus ---
  1089. export interface NexusModelConfig {
  1090. providerID: string;
  1091. modelID: string;
  1092. variant?: string;
  1093. }
  1094. export interface NexusConfig {
  1095. enabled?: boolean;
  1096. model?: NexusModelConfig;
  1097. }
  1098. // ---------------------------------------------------------------------------
  1099. // Brand constants — single source of truth for all brand-related strings.
  1100. // ---------------------------------------------------------------------------
  1101. export const BRAND = {
  1102. /** Data directory basename (e.g. '.minimax'). */
  1103. APP_DIR: ".minimax",
  1104. /** Environment variable prefix (e.g. 'minimax'). */
  1105. ENV_PREFIX: "minimax",
  1106. /** CLI binary name. */
  1107. CLI_NAME: "minimax",
  1108. } as const;
  1109. /** Legacy runtime env prefix. New runtime identity travels via args/files. */
  1110. export const RUNTIME_ENV_PREFIX = "__MAVIS_RUNTIME";
  1111. /**
  1112. * Read an internal runtime environment variable.
  1113. * This lazy approach works correctly even when env vars are set after module load
  1114. * (e.g., in test beforeEach hooks or dynamically by service managers).
  1115. */
  1116. function runtimeEnv(suffix: string): string | undefined {
  1117. return isLegacyRuntimeEnvAllowed()
  1118. ? process.env[`${RUNTIME_ENV_PREFIX}_${suffix}`]
  1119. : undefined;
  1120. }
  1121. function cliArgValue(name: string): string | undefined {
  1122. const flag = `--${name}`;
  1123. for (let i = 2; i < process.argv.length; i++) {
  1124. const arg = process.argv[i];
  1125. if (arg === flag) return process.argv[i + 1];
  1126. if (arg?.startsWith(`${flag}=`)) return arg.slice(flag.length + 1);
  1127. }
  1128. return undefined;
  1129. }
  1130. function hasCliFlag(name: string): boolean {
  1131. const flag = `--${name}`;
  1132. return process.argv
  1133. .slice(2)
  1134. .some((arg) => arg === flag || arg.startsWith(`${flag}=`));
  1135. }
  1136. export const DEFAULT_PORT = 5321;
  1137. const DEFAULT_UI_PORT = 5001;
  1138. const MAX_TCP_PORT = 65535;
  1139. const GIT_AUTO_PORT_SLOT_COUNT = 500;
  1140. const GIT_AUTO_PORT_STRIDE = 2;
  1141. const MAX_GIT_AUTO_PORT_OFFSET =
  1142. GIT_AUTO_PORT_SLOT_COUNT * GIT_AUTO_PORT_STRIDE;
  1143. export const OPENCODE_PORT_OFFSET =
  1144. MAX_GIT_AUTO_PORT_OFFSET + GIT_AUTO_PORT_STRIDE;
  1145. const OPENCODE_FALLBACK_OFFSET = 1;
  1146. const REPO_NAMES: ReadonlySet<string> = new Set(["agent-archon", "mavis"]);
  1147. // ---------------------------------------------------------------------------
  1148. // Git port / profile detection (inlined here to avoid tsx dual-module-instance
  1149. // issues that arise when importing across workspace package boundaries)
  1150. // ---------------------------------------------------------------------------
  1151. /** POSIX cksum CRC-32 table (polynomial 0x04C11DB7, big-endian) */
  1152. const CRC_TABLE = (() => {
  1153. const POLY = 0x04c11db7;
  1154. const table = new Uint32Array(256);
  1155. for (let i = 0; i < 256; i++) {
  1156. let c = i << 24;
  1157. for (let j = 0; j < 8; j++) {
  1158. c = (c & 0x80000000) !== 0 ? POLY ^ (c << 1) : c << 1;
  1159. c >>>= 0;
  1160. }
  1161. table[i] = c >>> 0;
  1162. }
  1163. return table;
  1164. })();
  1165. /**
  1166. * POSIX cksum on UTF-8(str + '\n'), matching `echo "$str" | cksum | awk '{print $1}'`
  1167. */
  1168. function posixCksum(str: string): number {
  1169. const buf = Buffer.from(`${str}\n`, "utf-8");
  1170. let crc = 0;
  1171. for (const byte of buf) {
  1172. crc = (CRC_TABLE[((crc >>> 24) ^ byte) & 0xff]! ^ (crc << 8)) >>> 0;
  1173. }
  1174. let len = buf.length;
  1175. while (len !== 0) {
  1176. crc = (CRC_TABLE[((crc >>> 24) ^ (len & 0xff)) & 0xff]! ^ (crc << 8)) >>> 0;
  1177. len >>>= 8;
  1178. }
  1179. return (crc ^ 0xffffffff) >>> 0;
  1180. }
  1181. function calcOffset(branchName: string): number {
  1182. // 500 slots with stride 2 (offsets: 2,4,6,...,1000).
  1183. // Keep even offsets to preserve historically stable branch ports and leave
  1184. // room for per-profile sidecars without collapsing adjacent assignments.
  1185. return (
  1186. (posixCksum(branchName) % GIT_AUTO_PORT_SLOT_COUNT) * GIT_AUTO_PORT_STRIDE +
  1187. 2
  1188. );
  1189. }
  1190. function runGit(args: string[], cwd?: string): string | null {
  1191. try {
  1192. const result = spawnSync("git", args, {
  1193. encoding: "utf-8",
  1194. timeout: 3000,
  1195. stdio: ["ignore", "pipe", "pipe"],
  1196. ...(cwd ? { cwd } : {}),
  1197. });
  1198. if (result.status === 0 && result.stdout) return result.stdout.trim();
  1199. return null;
  1200. } catch {
  1201. return null;
  1202. }
  1203. }
  1204. function parseRepoName(remoteUrl: string): string | null {
  1205. const match = remoteUrl.match(/[/:]([^/:]+?)(?:\.git)?$/);
  1206. return match?.[1] ?? null;
  1207. }
  1208. function getExplicitPublicDataDirEnv(): string | undefined {
  1209. return (
  1210. process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim()
  1211. );
  1212. }
  1213. function shouldUseGitAutoConfig(): boolean {
  1214. if (
  1215. hasCliFlag("disable-git-auto-config") ||
  1216. runtimeEnv("DISABLE_GIT_AUTO_CONFIG")
  1217. )
  1218. return false;
  1219. if (cliArgValue("data-dir")) return false;
  1220. if (getExplicitPublicDataDirEnv()) return false;
  1221. return true;
  1222. }
  1223. function getExplicitProfileEnv(): string | null {
  1224. const profile = cliArgValue("profile") ?? runtimeEnv("PROFILE");
  1225. return profile && profile.length > 0 ? profile : null;
  1226. }
  1227. function getExplicitPortEnv(): number | null {
  1228. const explicitPort = cliArgValue("port") ?? runtimeEnv("PORT");
  1229. const parsedExplicitPort = explicitPort ? parseInt(explicitPort, 10) : NaN;
  1230. return Number.isNaN(parsedExplicitPort) ? null : parsedExplicitPort;
  1231. }
  1232. function getExplicitDataDirArg(): string | null {
  1233. const dataDir =
  1234. cliArgValue("data-dir") ??
  1235. getExplicitPublicDataDirEnv() ??
  1236. runtimeEnv("DATA_DIR");
  1237. return dataDir && dataDir.length > 0 ? dataDir : null;
  1238. }
  1239. function shouldPreferExplicitDataDir(): boolean {
  1240. return Boolean(getExplicitProfileEnv() && getExplicitDataDirArg());
  1241. }
  1242. function shouldPreferExplicitPort(): boolean {
  1243. return Boolean(getExplicitProfileEnv() && getExplicitPortEnv() !== null);
  1244. }
  1245. interface GitPortInfo {
  1246. runtimePort: number;
  1247. uiPort: number;
  1248. profile: string | null;
  1249. autoDetected: boolean;
  1250. }
  1251. export type { GitPortInfo };
  1252. let _gitCached: GitPortInfo | null = null;
  1253. /** Reset cached git detection result (for testing) */
  1254. export function resetGitDetect(): void {
  1255. _gitCached = null;
  1256. }
  1257. /**
  1258. * Detect port and profile from git branch name.
  1259. * Any branch in the mavis repo gets a hash-based offset.
  1260. * Default port 5321 is reserved for non-git / non-mavis environments.
  1261. */
  1262. export function detectGitPortInfo(): GitPortInfo {
  1263. if (_gitCached !== null) return _gitCached;
  1264. const defaults: GitPortInfo = {
  1265. runtimePort: DEFAULT_PORT,
  1266. uiPort: DEFAULT_UI_PORT,
  1267. profile: null,
  1268. autoDetected: false,
  1269. };
  1270. // npm build: skip git detection entirely — always use default port 5321.
  1271. // esbuild constant-folds this to `true`, eliminating the git spawn code.
  1272. if (typeof __IS_NPM_BUILD__ !== "undefined") {
  1273. _gitCached = defaults;
  1274. return defaults;
  1275. }
  1276. // Try to detect from process.cwd() first, then fall back to the directory
  1277. // containing this config file. The fallback ensures correct detection when
  1278. // a runtime helper starts from a wrong cwd — the config file is always
  1279. // co-located with the source inside the git worktree.
  1280. const candidateDirs: Array<string | undefined> = [
  1281. undefined, // process.cwd() (default spawnSync behavior)
  1282. currentModuleDir(),
  1283. ];
  1284. for (const cwd of candidateDirs) {
  1285. try {
  1286. const remoteUrl = runGit(["remote", "get-url", "origin"], cwd);
  1287. if (!remoteUrl) continue;
  1288. const repoName = parseRepoName(remoteUrl);
  1289. if (!repoName || !REPO_NAMES.has(repoName)) continue;
  1290. const branch = runGit(["branch", "--show-current"], cwd);
  1291. if (!branch) continue;
  1292. const offset = calcOffset(branch);
  1293. _gitCached = {
  1294. runtimePort: DEFAULT_PORT + offset,
  1295. uiPort: DEFAULT_UI_PORT + offset,
  1296. profile: branch.replace(/\//g, "-"),
  1297. autoDetected: true,
  1298. };
  1299. return _gitCached;
  1300. } catch {
  1301. // try next candidate
  1302. }
  1303. }
  1304. _gitCached = defaults;
  1305. return defaults;
  1306. }
  1307. function currentModuleDir(): string | undefined {
  1308. try {
  1309. if (typeof __dirname === "string") return __dirname;
  1310. } catch {
  1311. /* ESM has no __dirname */
  1312. }
  1313. const stack = new Error().stack ?? "";
  1314. for (const line of stack.split("\n")) {
  1315. const fileUrl = /file:\/\/[^)\s]+/u
  1316. .exec(line)?.[0]
  1317. ?.replace(/:\d+:\d+$/u, "");
  1318. if (fileUrl) {
  1319. try {
  1320. return path.dirname(fileURLToPath(fileUrl));
  1321. } catch {
  1322. /* keep scanning */
  1323. }
  1324. }
  1325. const filePath =
  1326. /\(?((?:\/|[A-Za-z]:\\)[^()]+?\.(?:cjs|mjs|js|ts)):\d+:\d+\)?/u.exec(
  1327. line,
  1328. )?.[1];
  1329. if (filePath) return path.dirname(filePath);
  1330. }
  1331. return undefined;
  1332. }
  1333. // ---------------------------------------------------------------------------
  1334. // Config
  1335. // ---------------------------------------------------------------------------
  1336. export function getProfile(): string | null {
  1337. const profile = getExplicitProfileEnv();
  1338. if (profile) return profile;
  1339. if (!shouldUseGitAutoConfig()) return null;
  1340. return detectGitPortInfo().profile;
  1341. }
  1342. // ---------------------------------------------------------------------------
  1343. // Data directory resolution
  1344. // ---------------------------------------------------------------------------
  1345. export function getDataDir(): string {
  1346. // Data-dir resolution priority (mirrors port resolution in getConfig):
  1347. // 0. ${RUNTIME_ENV_PREFIX}_DISABLE_GIT_AUTO_CONFIG=1 → skip repo auto-detection entirely
  1348. // and fall back to the explicit env/default "user mode" resolution below.
  1349. // 1. Explicit profile-scoped data dir (service/supervisor) → fixed data dir
  1350. // 2. Git auto-detection (any branch in mavis repo) → profile-scoped dir
  1351. // This takes highest priority because the parent daemon process injects
  1352. // ${RUNTIME_ENV_PREFIX}_DATA_DIR into child process environments, which would
  1353. // incorrectly override the per-branch isolation that git detection provides.
  1354. // 3. ${RUNTIME_ENV_PREFIX}_DATA_DIR env var → used only when git detection is not active
  1355. // 4. ${RUNTIME_ENV_PREFIX}_PROFILE env var → manual profile override
  1356. // 5. resolveDataDir() → non-git / non-mavis default data directory
  1357. const explicitProfile = getExplicitProfileEnv();
  1358. if (shouldPreferExplicitDataDir()) {
  1359. return getExplicitDataDirArg()!;
  1360. }
  1361. if (shouldUseGitAutoConfig()) {
  1362. const gitInfo = detectGitPortInfo();
  1363. if (gitInfo.autoDetected && gitInfo.profile) {
  1364. return resolveDataDir({ profile: gitInfo.profile });
  1365. }
  1366. }
  1367. const explicitDataDir = getExplicitDataDirArg();
  1368. if (explicitDataDir) {
  1369. return explicitDataDir;
  1370. }
  1371. if (explicitProfile) {
  1372. return resolveDataDir({ profile: explicitProfile });
  1373. }
  1374. return resolveDataDir();
  1375. }
  1376. export function getConfigPath(): string {
  1377. return path.join(getDataDir(), "config.yaml");
  1378. }
  1379. // ---------------------------------------------------------------------------
  1380. // Default provider presets per environment combo (MAVIS_REGION x MAVIS_BUILD_ENV)
  1381. // ---------------------------------------------------------------------------
  1382. const MINIMAX_M3_FILE_API_CAPABILITIES: ModelCapabilitiesConfig = {
  1383. support_files_api: true,
  1384. files_api_upload_endpoint: "/v1/files/upload",
  1385. max_image_bytes_inline: 10_485_760,
  1386. max_video_bytes_inline: 52_428_800,
  1387. max_request_body_bytes: 67_108_864,
  1388. max_attachments_count: 4,
  1389. };
  1390. const MINIMAX_MODELS: Record<string, ModelConfig> = {
  1391. "MiniMax-M3": {
  1392. name: "MiniMax-M3",
  1393. attachment: true,
  1394. reasoning: true,
  1395. tool_call: true,
  1396. temperature: true,
  1397. modalities: { input: ["text", "image", "video"], output: ["text"] },
  1398. limit: { context: 512000, output: 128000 },
  1399. contextWindowOptions: [512000, 1000000],
  1400. contextWindowOptionHints: { "1000000": "higher_usage" },
  1401. options: { reasoningSummary: "auto" },
  1402. thinking_config: { mode: "switchable", default_value: "true" },
  1403. variants: {
  1404. "none-thinking": { thinking: { type: "disabled" } },
  1405. thinking: { thinking: { type: "adaptive" } },
  1406. },
  1407. capabilities: MINIMAX_M3_FILE_API_CAPABILITIES,
  1408. },
  1409. "MiniMax-M2.7-highspeed": {
  1410. name: "MiniMax-M2.7-highspeed",
  1411. attachment: false,
  1412. reasoning: true,
  1413. tool_call: true,
  1414. temperature: true,
  1415. modalities: { input: ["text"], output: ["text"] },
  1416. limit: { context: 200000, output: 128000 },
  1417. },
  1418. "MiniMax-M2.7": {
  1419. name: "MiniMax-M2.7",
  1420. attachment: false,
  1421. reasoning: true,
  1422. tool_call: true,
  1423. temperature: true,
  1424. modalities: { input: ["text"], output: ["text"] },
  1425. limit: { context: 200000, output: 128000 },
  1426. },
  1427. };
  1428. /** MiniMax models the user's own API key may call and the first-run managed fallback. */
  1429. export const MINIMAX_API_MODEL_CATALOG: Record<string, ModelConfig> =
  1430. MINIMAX_MODELS;
  1431. const PRESET_BASE_URLS: Record<PresetKey, string> = {
  1432. "cn-test": "https://matrix-test.example.invalid/mavis/api/v1/llm/v1",
  1433. "cn-dev": "https://matrix-test.example.invalid/mavis/api/v1/llm/v1",
  1434. "cn-staging": "https://matrix-pre.example.invalid/mavis/api/v1/llm/v1",
  1435. "en-test": "https://matrix-overseas-test.example.invalid/mavis/api/v1/llm/v1",
  1436. "en-dev": "https://matrix-overseas-test.example.invalid/mavis/api/v1/llm/v1",
  1437. "en-staging":
  1438. "https://matrix-overseas-pre.example.invalid/mavis/api/v1/llm/v1",
  1439. "cn-prod": "https://agent.minimax.cn/mavis/api/v1/llm/v1",
  1440. "en-prod": "https://agent.minimax.io/mavis/api/v1/llm/v1",
  1441. };
  1442. const LEGACY_MANAGED_PRESET_BASE_URLS = [
  1443. "https://agent.minimaxi.com/mavis/api/v1/llm/v1",
  1444. ] as const;
  1445. const MANAGED_PRESET_BASE_URLS = new Set([
  1446. ...Object.values(PRESET_BASE_URLS),
  1447. ...LEGACY_MANAGED_PRESET_BASE_URLS,
  1448. ]);
  1449. const MANAGED_PRESET_ORIGINS = new Set(
  1450. [...Object.values(PRESET_BASE_URLS), ...LEGACY_MANAGED_PRESET_BASE_URLS].map(
  1451. (baseURL) => new URL(baseURL).origin,
  1452. ),
  1453. );
  1454. function isManagedPresetBaseUrl(baseURL: string): boolean {
  1455. if (MANAGED_PRESET_BASE_URLS.has(baseURL)) return true;
  1456. try {
  1457. const parsed = new URL(baseURL);
  1458. return (
  1459. !parsed.username &&
  1460. !parsed.password &&
  1461. MANAGED_PRESET_ORIGINS.has(parsed.origin)
  1462. );
  1463. } catch {
  1464. return false;
  1465. }
  1466. }
  1467. /** Test desktop builds may route the builtin managed MiniMax provider through a local fault proxy. */
  1468. export function allowsManagedMinimaxProviderOverride(): boolean {
  1469. return getRuntimeBuildEnv() === "test";
  1470. }
  1471. function shouldEnforceManagedProviderProtection(): boolean {
  1472. return !allowsManagedMinimaxProviderOverride();
  1473. }
  1474. function syncManagedPresetBaseUrl(configPath: string): void {
  1475. if (!isManagedRuntime() || !fs.existsSync(configPath)) {
  1476. return;
  1477. }
  1478. const raw = readConfigFile(configPath);
  1479. const { provider } = raw;
  1480. if (
  1481. provider == null ||
  1482. typeof provider !== "object" ||
  1483. Array.isArray(provider)
  1484. )
  1485. return;
  1486. const { minimax } = provider as Record<string, unknown>;
  1487. if (minimax == null || typeof minimax !== "object" || Array.isArray(minimax))
  1488. return;
  1489. const { options } = minimax as Record<string, unknown>;
  1490. if (options == null || typeof options !== "object" || Array.isArray(options))
  1491. return;
  1492. const currentBaseURL = (options as Record<string, unknown>).baseURL;
  1493. if (typeof currentBaseURL !== "string") return;
  1494. const presetBaseURL = PRESET_BASE_URLS[getRuntimePresetKey()];
  1495. if (
  1496. currentBaseURL === presetBaseURL ||
  1497. !isManagedPresetBaseUrl(currentBaseURL)
  1498. )
  1499. return;
  1500. (options as Record<string, unknown>).baseURL = presetBaseURL;
  1501. writePrivateConfigFileSync(
  1502. configPath,
  1503. yaml.dump(raw, { indent: 2, lineWidth: -1, noRefs: true }),
  1504. );
  1505. }
  1506. function buildPresetEntry(key: PresetKey) {
  1507. const provider: ProviderConfig = {
  1508. name: "MiniMax",
  1509. npm: "@ai-sdk/anthropic",
  1510. options: {
  1511. authMode: "managed-login",
  1512. apiKey: "sk-xxx",
  1513. baseURL: PRESET_BASE_URLS[key],
  1514. },
  1515. models: MINIMAX_MODELS,
  1516. };
  1517. return {
  1518. provider: { minimax: provider } as ModelsConfig,
  1519. defaultModel: "minimax/MiniMax-M3",
  1520. };
  1521. }
  1522. export const DEFAULT_MODEL_PRESETS: Record<
  1523. PresetKey,
  1524. { provider: ModelsConfig; defaultModel: string }
  1525. > = {
  1526. "cn-test": buildPresetEntry("cn-test"),
  1527. "cn-dev": buildPresetEntry("cn-dev"),
  1528. "cn-staging": buildPresetEntry("cn-staging"),
  1529. "cn-prod": buildPresetEntry("cn-prod"),
  1530. "en-test": buildPresetEntry("en-test"),
  1531. "en-dev": buildPresetEntry("en-dev"),
  1532. "en-staging": buildPresetEntry("en-staging"),
  1533. "en-prod": buildPresetEntry("en-prod"),
  1534. } as const;
  1535. const DEFAULTS: Omit<
  1536. Config,
  1537. | "dataDir"
  1538. | "agentsDir"
  1539. | "sessionsDir"
  1540. | "memoryDir"
  1541. | "skillsDir"
  1542. | "builtinSkillsDir"
  1543. | "logsDir"
  1544. | "pluginsDir"
  1545. | "plansDir"
  1546. | "harnessesDir"
  1547. | "subAgentsDir"
  1548. | "provider"
  1549. | "permission"
  1550. | "promptConfig"
  1551. > = {
  1552. logLevel: "info",
  1553. devPort: DEFAULT_UI_PORT,
  1554. permissionMode: "auto",
  1555. sseErrorPush: {
  1556. history: true,
  1557. stream: true,
  1558. },
  1559. beta: Object.fromEntries(
  1560. (Object.keys(BETA_FEATURE_DEFS) as (keyof BetaConfig)[]).map((key) => [
  1561. key,
  1562. resolveBetaFeature(key, undefined, { buildEnv: "dev" }),
  1563. ]),
  1564. ) as unknown as BetaConfig,
  1565. agents: { default: {} },
  1566. memory: {
  1567. enabled: true,
  1568. proactive: false,
  1569. dailyDigest: {
  1570. enabled: false,
  1571. },
  1572. },
  1573. skillEvolve: {
  1574. enabled: true,
  1575. inSession: {
  1576. N: 20,
  1577. minIntervalSeconds: 30,
  1578. maxPendingPerSession: 1,
  1579. },
  1580. signalCooldownHours: 24,
  1581. minConfidence: 0.7,
  1582. excludeAgents: ["skill-editor"],
  1583. disableModelPrefixes: ["MiniMax-M2"],
  1584. builtinMrEnabled: false,
  1585. sourceRepo: undefined,
  1586. proposal: {
  1587. enabled: false,
  1588. eligibleAgents: ["mavis"],
  1589. minMessageCount: 40,
  1590. skipPassiveSessionEnd: true,
  1591. },
  1592. lifecycle: { staleThresholdDays: 15, archiveThresholdDays: 30 }, // tightened from legacy 30d/90d
  1593. },
  1594. sessionRotate: {
  1595. enabled: true,
  1596. activeSessionLookbackHours: 12,
  1597. },
  1598. agentStop: {
  1599. debounceMs: 500,
  1600. maxActiveSpanMs: 30 * 60 * 1000, // 30 min
  1601. },
  1602. asr: { ...ASR_DEFAULTS }, // Cloud ASR master switch only. Seed / Qwen client providers and their WS bridge were retired; Amadeus uses the authenticated HTTP+SSE proxy from Web/Electron. Legacy `asr.mode` / `asr.proxyBaseUrl` / `asr.primaryProvider` / `asr.fallbackProvider` / `asr.{seed,qwen}.*` are dropped on parse with a warn.
  1603. skills: DEFAULT_SKILLS_CONFIG,
  1604. askUser: { ...ASK_USER_CONFIG_DEFAULTS },
  1605. sessionTitle: {
  1606. // Default ON. See `SessionTitleConfig`.
  1607. enabled: true,
  1608. },
  1609. cli: {
  1610. spawn: {
  1611. enabled: false,
  1612. },
  1613. },
  1614. browser: { ...BROWSER_CONFIG_DEFAULTS },
  1615. // No status line items by default: the TUI picks its build-specific default
  1616. // when `tui.statusLine` is absent.
  1617. tui: {},
  1618. telemetry: { enabled: false, metrics: false, diagnostics: false },
  1619. opencode: {
  1620. xdg: {
  1621. dataIsolation: false,
  1622. startupImport: "off",
  1623. },
  1624. keepAlive: {
  1625. enabled: false,
  1626. maxProcesses: 5,
  1627. maxLifetimeMs: 28_800_000,
  1628. agents: ["mavis", "main", "verifier", "code-reviewer"],
  1629. },
  1630. spawnConcurrency: 3,
  1631. },
  1632. contextManagement: {
  1633. disableSystemReminderModels: [],
  1634. cuMaxScreenshotsInContext: 2,
  1635. },
  1636. runawayGuard: { enabled: true },
  1637. toolResultCompaction: { ...TOOL_RESULT_COMPACTION_DEFAULTS },
  1638. agentRuntime: {
  1639. // Single source of truth lives in `./agent-runtime-config.ts` so the
  1640. // default and the union type cannot drift.
  1641. defaultFramework: DEFAULT_AGENT_RUNTIME_FRAMEWORK,
  1642. },
  1643. logRetentionDays: 3,
  1644. cuBackend: DEFAULT_CU_BACKEND,
  1645. review: {
  1646. mode: "subagent",
  1647. modeSource: "default",
  1648. },
  1649. goal: structuredClone(GOAL_CONFIG_DEFAULTS),
  1650. sandbox: structuredClone(SANDBOX_CONFIG_DEFAULTS),
  1651. goalWarnings: [],
  1652. };
  1653. function ensureConfigFile(): void {
  1654. const configPath = getConfigPath();
  1655. const dir = path.dirname(configPath);
  1656. if (!fs.existsSync(dir)) {
  1657. fs.mkdirSync(dir, { recursive: true });
  1658. }
  1659. if (fs.existsSync(configPath)) {
  1660. prepareConfigFileForRead(configPath);
  1661. return;
  1662. }
  1663. // In non-managed runtime (pnpm dev / npm package), the UI onboarding flow
  1664. // owns config.yaml generation — it walks the user through getting an API
  1665. // key and writes the file. Daemon must NOT pre-seed a placeholder here,
  1666. // otherwise the UI flow has no way to know whether the user has actually
  1667. // configured anything.
  1668. //
  1669. // However, when a worktree daemon starts with a derived dataDir (e.g.
  1670. // <dataDir>-feature-foo/), the developer's API keys live in the default
  1671. // dataDir (<dataDir>/config.yaml). Copy it over so the worktree daemon
  1672. // inherits the existing configuration.
  1673. if (!isManagedRuntime()) {
  1674. const defaultDataDir = resolveDataDir({ homeDir: os.homedir() });
  1675. const defaultConfigPath = path.join(defaultDataDir, "config.yaml");
  1676. if (configPath !== defaultConfigPath && fs.existsSync(defaultConfigPath)) {
  1677. restrictConfigFileSync(defaultConfigPath);
  1678. writePrivateConfigFileSync(configPath, fs.readFileSync(defaultConfigPath), true);
  1679. }
  1680. return;
  1681. }
  1682. const preset = DEFAULT_MODEL_PRESETS[getRuntimePresetKey()];
  1683. const content = yaml.dump({
  1684. logLevel: DEFAULTS.logLevel,
  1685. provider: managedPresetBaseUrlSyncEnabled ? preset.provider : undefined,
  1686. defaultModel: preset.defaultModel,
  1687. });
  1688. writePrivateConfigFileSync(configPath, content, true);
  1689. }
  1690. function readConfigFile(configPath = getConfigPath()): Record<string, unknown> {
  1691. try {
  1692. const raw = fs.readFileSync(configPath, "utf-8");
  1693. const parsed = yaml.load(raw);
  1694. if (
  1695. parsed != null &&
  1696. typeof parsed === "object" &&
  1697. !Array.isArray(parsed)
  1698. ) {
  1699. return parsed as Record<string, unknown>;
  1700. }
  1701. return {};
  1702. } catch {
  1703. return {};
  1704. }
  1705. }
  1706. let _cached: Config | null = null;
  1707. function parseNotificationsConfig(
  1708. raw: unknown,
  1709. ): NotificationsConfig | undefined {
  1710. if (raw == null || typeof raw !== "object" || Array.isArray(raw))
  1711. return undefined;
  1712. const obj = raw as Record<string, unknown>;
  1713. return {
  1714. branchFinish:
  1715. typeof obj.branchFinish === "boolean" ? obj.branchFinish : false,
  1716. };
  1717. }
  1718. // ── BYOK config parsing + required provider overrides: see ./byok-config.ts ──
  1719. const REQUIRED_PROVIDER_OVERRIDE_DEPS: RequiredProviderOverrideDeps = {
  1720. isManagedRuntime,
  1721. shouldEnforceManagedProviderProtection,
  1722. getManagedPreset: () => DEFAULT_MODEL_PRESETS[getRuntimePresetKey()],
  1723. isManagedPresetBaseUrl,
  1724. };
  1725. let legacyByokProviderMigrationEnabled = true;
  1726. let managedPresetBaseUrlSyncEnabled = true;
  1727. export function setLegacyByokProviderMigrationEnabled(enabled: boolean): void {
  1728. legacyByokProviderMigrationEnabled = enabled;
  1729. }
  1730. /** Hosts sharing config with older clients can use the current preset without persisting it. */
  1731. export function setManagedPresetBaseUrlSyncEnabled(enabled: boolean): void {
  1732. managedPresetBaseUrlSyncEnabled = enabled;
  1733. }
  1734. export function prepareConfigFileForRead(configPath: string): void {
  1735. restrictConfigFileSync(configPath);
  1736. restrictLegacyByokBackups(configPath);
  1737. if (legacyByokProviderMigrationEnabled) {
  1738. migrateLegacyByokProvidersOnDisk(
  1739. configPath,
  1740. REQUIRED_PROVIDER_OVERRIDE_DEPS,
  1741. );
  1742. }
  1743. if (managedPresetBaseUrlSyncEnabled) syncManagedPresetBaseUrl(configPath);
  1744. }
  1745. export function resetConfig(): void {
  1746. _cached = null;
  1747. }
  1748. export function getConfig(): Config {
  1749. if (_cached) return _cached;
  1750. ensureConfigFile();
  1751. const raw = readConfigFile();
  1752. _cached = resolveConfigFromRaw(raw, getDataDir());
  1753. return _cached;
  1754. }
  1755. export function resolveConfigFromRaw(
  1756. raw: Record<string, unknown>,
  1757. dataDir: string,
  1758. ): Config {
  1759. const rawSSEErrorPush = raw.sseErrorPush;
  1760. const sseErrorPush =
  1761. rawSSEErrorPush != null &&
  1762. typeof rawSSEErrorPush === "object" &&
  1763. !Array.isArray(rawSSEErrorPush)
  1764. ? (rawSSEErrorPush as Record<string, unknown>)
  1765. : undefined;
  1766. // devPort resolution (kept in Config for UI dev server)
  1767. let devPort =
  1768. typeof raw.devPort === "number" ? raw.devPort : DEFAULTS.devPort;
  1769. if (shouldUseGitAutoConfig() && !shouldPreferExplicitPort()) {
  1770. const gitInfo = detectGitPortInfo();
  1771. if (gitInfo.autoDetected) {
  1772. devPort = gitInfo.uiPort;
  1773. }
  1774. }
  1775. const goalParsed = parseGoalConfig(raw.goal);
  1776. const managedProvider = applyRequiredProviderOverrides(
  1777. {
  1778. provider:
  1779. raw.provider != null &&
  1780. typeof raw.provider === "object" &&
  1781. !Array.isArray(raw.provider)
  1782. ? normalizeLegacyThinkingEfforts(raw.provider as ModelsConfig)
  1783. : {},
  1784. defaultModel:
  1785. typeof raw.defaultModel === "string" ? raw.defaultModel : undefined,
  1786. },
  1787. REQUIRED_PROVIDER_OVERRIDE_DEPS,
  1788. );
  1789. const minimaxModelContextLimits = parseModelContextLimits(
  1790. raw.minimaxModelContextLimits,
  1791. );
  1792. const beta = parseBetaConfig(raw);
  1793. return {
  1794. logLevel:
  1795. typeof raw.logLevel === "string" ? raw.logLevel : DEFAULTS.logLevel,
  1796. devPort,
  1797. ...managedProvider,
  1798. provider: applyManagedMinimaxContextLimits(
  1799. managedProvider.provider,
  1800. minimaxModelContextLimits,
  1801. ),
  1802. defaultModelVariant:
  1803. typeof raw.defaultModelVariant === "string"
  1804. ? raw.defaultModelVariant
  1805. : undefined,
  1806. defaultModelThinking:
  1807. raw.defaultModelThinking &&
  1808. typeof raw.defaultModelThinking === "object" &&
  1809. typeof (raw.defaultModelThinking as Record<string, unknown>).effort ===
  1810. "string"
  1811. ? { effort: (raw.defaultModelThinking as { effort: string }).effort }
  1812. : undefined,
  1813. defaultModelContextWindow:
  1814. Number.isSafeInteger(raw.defaultModelContextWindow) &&
  1815. Number(raw.defaultModelContextWindow) > 0 &&
  1816. Number(raw.defaultModelContextWindow) <= 2_147_483_647
  1817. ? Number(raw.defaultModelContextWindow)
  1818. : undefined,
  1819. minimax_api: parseMinimaxApiConfig(raw.minimax_api),
  1820. minimaxModelContextLimits,
  1821. custom_provider: parseCustomProvidersConfig(raw.custom_provider),
  1822. minimaxModelSource:
  1823. typeof raw.minimaxModelSource === "string" &&
  1824. (raw.minimaxModelSource === "token_plan" ||
  1825. raw.minimaxModelSource === "minimax_api_key")
  1826. ? raw.minimaxModelSource
  1827. : undefined,
  1828. nexus:
  1829. raw.nexus != null &&
  1830. typeof raw.nexus === "object" &&
  1831. !Array.isArray(raw.nexus)
  1832. ? (() => {
  1833. const parsed: NexusConfig = {};
  1834. if (typeof Reflect.get(raw.nexus, "enabled") === "boolean") {
  1835. parsed.enabled = Reflect.get(raw.nexus, "enabled") as boolean;
  1836. }
  1837. const rawModel = Reflect.get(raw.nexus, "model");
  1838. if (
  1839. rawModel != null &&
  1840. typeof rawModel === "object" &&
  1841. !Array.isArray(rawModel) &&
  1842. typeof Reflect.get(rawModel, "providerID") === "string" &&
  1843. typeof Reflect.get(rawModel, "modelID") === "string"
  1844. ) {
  1845. parsed.model = {
  1846. providerID: Reflect.get(rawModel, "providerID") as string,
  1847. modelID: Reflect.get(rawModel, "modelID") as string,
  1848. ...(typeof Reflect.get(rawModel, "variant") === "string"
  1849. ? {
  1850. variant: Reflect.get(rawModel, "variant") as string,
  1851. }
  1852. : {}),
  1853. };
  1854. }
  1855. return Object.keys(parsed).length > 0 ? parsed : undefined;
  1856. })()
  1857. : undefined,
  1858. defaultLightModel:
  1859. typeof raw.defaultLightModel === "string"
  1860. ? raw.defaultLightModel
  1861. : undefined,
  1862. permissionMode:
  1863. typeof raw.permissionMode === "string" &&
  1864. ["default", "bypassPermissions", "auto", "off"].includes(
  1865. raw.permissionMode,
  1866. )
  1867. ? (raw.permissionMode as PermissionMode)
  1868. : DEFAULTS.permissionMode,
  1869. permission: parsePermissionConfig(raw),
  1870. sseErrorPush: {
  1871. history:
  1872. typeof sseErrorPush?.history === "boolean"
  1873. ? (sseErrorPush.history as boolean)
  1874. : DEFAULTS.sseErrorPush.history,
  1875. stream:
  1876. typeof sseErrorPush?.stream === "boolean"
  1877. ? (sseErrorPush.stream as boolean)
  1878. : DEFAULTS.sseErrorPush.stream,
  1879. },
  1880. notifications: parseNotificationsConfig(raw.notifications),
  1881. dataDir,
  1882. agentsDir: path.join(dataDir, "agents"),
  1883. sessionsDir: path.join(dataDir, "sessions"),
  1884. memoryDir: path.join(dataDir, "memory"),
  1885. skillsDir: path.join(dataDir, "skills"),
  1886. builtinSkillsDir: path.join(dataDir, ".builtin-skills"),
  1887. logsDir: path.join(dataDir, "logs"),
  1888. pluginsDir: path.join(dataDir, "plugins"),
  1889. plansDir: path.join(dataDir, "plans"),
  1890. harnessesDir: path.join(dataDir, "harnesses"),
  1891. subAgentsDir: path.join(dataDir, "subagents"),
  1892. beta,
  1893. agents: parseAgentsConfig(raw.agents),
  1894. memory: parseMemoryConfig(raw),
  1895. skillEvolve: parseSkillEvolveConfig(raw, beta),
  1896. sessionRotate: parseSessionRotateConfig(raw),
  1897. agentStop: parseAgentStopDetectorConfig(raw),
  1898. asr: parseAsrConfig(raw),
  1899. skills: parseSkillsConfig(raw),
  1900. askUser: parseAskUserConfig(raw, DEFAULTS.askUser),
  1901. sessionTitle: parseSessionTitleConfig(raw),
  1902. cli: parseCliConfig(raw),
  1903. browser: parseBrowserConfig(raw.browser),
  1904. tui: parseTuiConfig(raw),
  1905. telemetry: parseTelemetryConfig(raw.telemetry),
  1906. opencode: parseOpenCodeAdapterConfig(raw, DEFAULTS.opencode),
  1907. contextManagement: parseContextManagementConfig(raw),
  1908. runawayGuard: resolveRunawayGuardConfig(raw.runawayGuard),
  1909. toolResultCompaction: parseToolResultCompactionConfig(
  1910. raw.toolResultCompaction,
  1911. ),
  1912. agentRuntime: parseAgentRuntimeConfig(raw.agentRuntime),
  1913. logRetentionDays: parseLogRetentionDays(raw),
  1914. contentReview: parseContentReviewConfig(raw),
  1915. mcpToolSearch: parseMcpToolSearchConfig(raw),
  1916. cuBackend: parseCuBackend(raw.cuBackend),
  1917. review: parseReviewConfig(raw.review, DEFAULTS.review),
  1918. promptConfig: resolvePromptConfig(raw.promptConfig),
  1919. goal: goalParsed.config,
  1920. goalWarnings: goalParsed.warnings,
  1921. sandbox: parseSandboxConfig(raw.sandbox),
  1922. };
  1923. }
  1924. // ── Memory config parsing ──────────────────────────────────────
  1925. function parseTelemetryConfig(raw: unknown): TelemetryConfig {
  1926. if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
  1927. return { ...DEFAULTS.telemetry };
  1928. }
  1929. const enabled = Reflect.get(raw, "enabled");
  1930. return {
  1931. enabled: typeof enabled === "boolean" ? enabled : DEFAULTS.telemetry.enabled,
  1932. metrics: Reflect.get(raw, "metrics") === true,
  1933. diagnostics: Reflect.get(raw, "diagnostics") === true,
  1934. };
  1935. }
  1936. function parseMemoryConfig(raw: Record<string, unknown>): MemoryConfig {
  1937. const memoryRaw = raw.memory;
  1938. const memoryObj =
  1939. memoryRaw != null &&
  1940. typeof memoryRaw === "object" &&
  1941. !Array.isArray(memoryRaw)
  1942. ? (memoryRaw as Record<string, unknown>)
  1943. : {};
  1944. const dailyDigestRaw = memoryObj.dailyDigest;
  1945. const dailyDigestObj =
  1946. dailyDigestRaw != null &&
  1947. typeof dailyDigestRaw === "object" &&
  1948. !Array.isArray(dailyDigestRaw)
  1949. ? (dailyDigestRaw as Record<string, unknown>)
  1950. : {};
  1951. return {
  1952. enabled:
  1953. typeof memoryObj.enabled === "boolean"
  1954. ? memoryObj.enabled
  1955. : DEFAULTS.memory.enabled,
  1956. proactive:
  1957. typeof memoryObj.proactive === "boolean"
  1958. ? memoryObj.proactive
  1959. : DEFAULTS.memory.proactive,
  1960. dailyDigest: {
  1961. enabled:
  1962. typeof dailyDigestObj.enabled === "boolean"
  1963. ? dailyDigestObj.enabled
  1964. : DEFAULTS.memory.dailyDigest.enabled,
  1965. },
  1966. };
  1967. }
  1968. // ── Beta features config parsing ────────────────────────────────
  1969. function parseBetaConfig(raw: Record<string, unknown>): BetaConfig {
  1970. const obj =
  1971. raw.beta != null && typeof raw.beta === "object" && !Array.isArray(raw.beta)
  1972. ? (raw.beta as Record<string, unknown>)
  1973. : {};
  1974. const context: BetaFeatureResolutionContext = {
  1975. buildEnv: getRuntimeBuildEnv(),
  1976. defaultBuildEnvironment: getBetaDefaultBuildEnvironment(),
  1977. internalBuild: isInternalBuild(),
  1978. insideBuild: isInsideBuild(),
  1979. mcodeToolsDevMode:
  1980. process.env.MAVIS_DEV_MCODE_TOOLS_MODE === "published"
  1981. ? "published"
  1982. : undefined,
  1983. };
  1984. const result = {} as BetaConfig;
  1985. for (const key of Object.keys(BETA_FEATURE_DEFS) as (keyof BetaConfig)[]) {
  1986. result[key] = resolveBetaFeature(key, obj[key], context);
  1987. }
  1988. return result;
  1989. }
  1990. // ── Skill Evolve config parsing ─────────────────────────────────
  1991. /**
  1992. * Collect all model IDs from the provider config.
  1993. * Returns an empty array when no models are configured.
  1994. */
  1995. function collectModelIds(raw: Record<string, unknown>): string[] {
  1996. const providerRaw = raw.provider;
  1997. if (
  1998. providerRaw == null ||
  1999. typeof providerRaw !== "object" ||
  2000. Array.isArray(providerRaw)
  2001. ) {
  2002. return [];
  2003. }
  2004. const ids: string[] = [];
  2005. for (const prov of Object.values(providerRaw as Record<string, unknown>)) {
  2006. if (prov == null || typeof prov !== "object" || Array.isArray(prov))
  2007. continue;
  2008. const { models } = prov as Record<string, unknown>;
  2009. if (models == null || typeof models !== "object" || Array.isArray(models))
  2010. continue;
  2011. ids.push(...Object.keys(models as Record<string, unknown>));
  2012. }
  2013. return ids;
  2014. }
  2015. /**
  2016. * Auto-derive the `skillEvolve.enabled` flag from the configured model list.
  2017. *
  2018. * When **every** configured model ID starts with one of the
  2019. * `disableModelPrefixes` (case-insensitive), skill-evolve has no capable
  2020. * model to work with, so it is disabled automatically.
  2021. * If at least one model does NOT match, the feature is enabled.
  2022. *
  2023. * Edge cases: no providers / no models configured → `false`
  2024. * (no capable model means the feature cannot operate).
  2025. */
  2026. function deriveSkillEvolveEnabled(
  2027. raw: Record<string, unknown>,
  2028. disableModelPrefixes: string[],
  2029. ): boolean {
  2030. if (disableModelPrefixes.length === 0) return true;
  2031. const modelIds = collectModelIds(raw);
  2032. if (modelIds.length === 0) return false;
  2033. const lowerPrefixes = disableModelPrefixes.map((p) => p.toLowerCase());
  2034. return !modelIds.every((id) =>
  2035. lowerPrefixes.some((p) => id.toLowerCase().startsWith(p)),
  2036. );
  2037. }
  2038. function parsePositiveDays(value: unknown, fallback: number): number {
  2039. return typeof value === "number" && Number.isFinite(value) && value > 0
  2040. ? value
  2041. : fallback;
  2042. }
  2043. function parseSkillEvolveConfig(
  2044. raw: Record<string, unknown>,
  2045. betaConfig: BetaConfig,
  2046. ): SkillEvolveConfig {
  2047. const defaults = DEFAULTS.skillEvolve;
  2048. const se = raw.skillEvolve;
  2049. const hasSection = se != null && typeof se === "object" && !Array.isArray(se);
  2050. const obj = hasSection
  2051. ? (se as Record<string, unknown>)
  2052. : ({} as Record<string, unknown>);
  2053. const inSessionRaw = obj.inSession;
  2054. let { inSession } = defaults;
  2055. if (
  2056. inSessionRaw != null &&
  2057. typeof inSessionRaw === "object" &&
  2058. !Array.isArray(inSessionRaw)
  2059. ) {
  2060. const ins = inSessionRaw as Record<string, unknown>;
  2061. inSession = {
  2062. N: typeof ins.N === "number" && ins.N > 0 ? ins.N : defaults.inSession.N,
  2063. minIntervalSeconds:
  2064. typeof ins.minIntervalSeconds === "number" &&
  2065. ins.minIntervalSeconds >= 0
  2066. ? ins.minIntervalSeconds
  2067. : defaults.inSession.minIntervalSeconds,
  2068. maxPendingPerSession:
  2069. typeof ins.maxPendingPerSession === "number" &&
  2070. ins.maxPendingPerSession >= 1
  2071. ? ins.maxPendingPerSession
  2072. : defaults.inSession.maxPendingPerSession,
  2073. };
  2074. }
  2075. const excludeRaw = obj.excludeAgents;
  2076. const excludeAgents =
  2077. Array.isArray(excludeRaw) && excludeRaw.every((e) => typeof e === "string")
  2078. ? (excludeRaw as string[])
  2079. : defaults.excludeAgents;
  2080. const disableModelPrefixes =
  2081. Array.isArray(obj.disableModelPrefixes) &&
  2082. obj.disableModelPrefixes.every((e: unknown) => typeof e === "string")
  2083. ? (obj.disableModelPrefixes as string[])
  2084. : defaults.disableModelPrefixes;
  2085. // `enabled` — beta gate wins first; then explicit config; then auto-derive from model list.
  2086. const enabled = !betaConfig.skillEvolve
  2087. ? false
  2088. : typeof obj.enabled === "boolean"
  2089. ? obj.enabled
  2090. : deriveSkillEvolveEnabled(raw, disableModelPrefixes);
  2091. // `builtinMrEnabled` — beta gate wins first; then explicit config; then default.
  2092. // Implicitly false when the parent `enabled` is false (no point evolving built-ins
  2093. // when the pipeline as a whole is off).
  2094. const builtinMrEnabled = !enabled
  2095. ? false
  2096. : !betaConfig.skillEvolveBuiltinMr
  2097. ? false
  2098. : typeof obj.builtinMrEnabled === "boolean"
  2099. ? obj.builtinMrEnabled
  2100. : defaults.builtinMrEnabled;
  2101. const sourceRepoRaw = obj.sourceRepo;
  2102. const sourceRepo =
  2103. typeof sourceRepoRaw === "string" && sourceRepoRaw.trim().length > 0
  2104. ? sourceRepoRaw.trim()
  2105. : defaults.sourceRepo;
  2106. // v3: `proposal` — beta gate + parent gate must both be true; otherwise
  2107. // resolved sub-config still parses but `enabled` is forced false. Other
  2108. // fields (eligibleAgents, minMessageCount, skipPassiveSessionEnd) are
  2109. // honored even when the gate is off so operators can pre-stage config.
  2110. const proposalRaw = obj.proposal;
  2111. const proposalDefaults = defaults.proposal;
  2112. const proposalObj =
  2113. proposalRaw != null &&
  2114. typeof proposalRaw === "object" &&
  2115. !Array.isArray(proposalRaw)
  2116. ? (proposalRaw as Record<string, unknown>)
  2117. : ({} as Record<string, unknown>);
  2118. const proposalEligibleAgents =
  2119. Array.isArray(proposalObj.eligibleAgents) &&
  2120. proposalObj.eligibleAgents.every((e) => typeof e === "string")
  2121. ? (proposalObj.eligibleAgents as string[])
  2122. : proposalDefaults.eligibleAgents;
  2123. const proposalMinMessageCount =
  2124. typeof proposalObj.minMessageCount === "number" &&
  2125. proposalObj.minMessageCount >= 1
  2126. ? Math.floor(proposalObj.minMessageCount)
  2127. : proposalDefaults.minMessageCount;
  2128. const proposalSkipPassiveSessionEnd =
  2129. typeof proposalObj.skipPassiveSessionEnd === "boolean"
  2130. ? proposalObj.skipPassiveSessionEnd
  2131. : proposalDefaults.skipPassiveSessionEnd;
  2132. const proposalEnabledExplicit =
  2133. typeof proposalObj.enabled === "boolean" ? proposalObj.enabled : null;
  2134. const proposalEnabled = !enabled
  2135. ? false
  2136. : !betaConfig.skillProposal
  2137. ? false
  2138. : (proposalEnabledExplicit ?? true);
  2139. // `lifecycle` — strict invariant stale < archive (fail-fast at boot).
  2140. const lcRaw = obj.lifecycle;
  2141. const lc =
  2142. lcRaw && typeof lcRaw === "object" && !Array.isArray(lcRaw)
  2143. ? (lcRaw as Record<string, unknown>)
  2144. : {};
  2145. const staleThresholdDays = parsePositiveDays(lc.staleThresholdDays, defaults.lifecycle.staleThresholdDays); // prettier-ignore
  2146. const archiveThresholdDays = parsePositiveDays(lc.archiveThresholdDays, defaults.lifecycle.archiveThresholdDays); // prettier-ignore
  2147. if (!(staleThresholdDays < archiveThresholdDays)) {
  2148. throw new Error(
  2149. `Invalid skillEvolve.lifecycle config: staleThresholdDays (${staleThresholdDays}) must be strictly less than archiveThresholdDays (${archiveThresholdDays}).`,
  2150. );
  2151. }
  2152. return {
  2153. enabled,
  2154. inSession,
  2155. signalCooldownHours:
  2156. typeof obj.signalCooldownHours === "number" && obj.signalCooldownHours > 0
  2157. ? obj.signalCooldownHours
  2158. : defaults.signalCooldownHours,
  2159. minConfidence:
  2160. typeof obj.minConfidence === "number" &&
  2161. obj.minConfidence >= 0 &&
  2162. obj.minConfidence <= 1
  2163. ? obj.minConfidence
  2164. : defaults.minConfidence,
  2165. scannerModel:
  2166. typeof obj.scannerModel === "string" ? obj.scannerModel : undefined,
  2167. excludeAgents,
  2168. disableModelPrefixes,
  2169. builtinMrEnabled,
  2170. sourceRepo,
  2171. proposal: {
  2172. enabled: proposalEnabled,
  2173. eligibleAgents: proposalEligibleAgents,
  2174. minMessageCount: proposalMinMessageCount,
  2175. skipPassiveSessionEnd: proposalSkipPassiveSessionEnd,
  2176. },
  2177. lifecycle: { staleThresholdDays, archiveThresholdDays },
  2178. };
  2179. }
  2180. /**
  2181. * v3 helper: `isProposalEligibleAgent` lives in `./skill-evolve-config.ts`
  2182. * — re-exported above with the rest of the SkillEvolve types.
  2183. */
  2184. // ── Session Rotate config parsing ───────────────────────────────
  2185. function parseSessionRotateConfig(
  2186. raw: Record<string, unknown>,
  2187. ): SessionRotateConfig {
  2188. const defaults = DEFAULTS.sessionRotate;
  2189. const sr = raw.sessionRotate;
  2190. if (sr == null || typeof sr !== "object" || Array.isArray(sr))
  2191. return { ...defaults };
  2192. const obj = sr as Record<string, unknown>;
  2193. const rawLookback = obj.activeSessionLookbackHours;
  2194. return {
  2195. enabled: typeof obj.enabled === "boolean" ? obj.enabled : defaults.enabled,
  2196. activeSessionLookbackHours:
  2197. typeof rawLookback === "number" &&
  2198. Number.isFinite(rawLookback) &&
  2199. rawLookback > 0
  2200. ? rawLookback
  2201. : defaults.activeSessionLookbackHours,
  2202. };
  2203. }
  2204. // ── AgentStop detector config parsing ───────────────────────────
  2205. function parseAgentStopDetectorConfig(
  2206. raw: Record<string, unknown>,
  2207. ): AgentStopDetectorConfig {
  2208. const defaults = DEFAULTS.agentStop;
  2209. const obj = raw.agentStop;
  2210. if (obj == null || typeof obj !== "object" || Array.isArray(obj)) {
  2211. return { ...defaults };
  2212. }
  2213. const o = obj as Record<string, unknown>;
  2214. const rawDebounce = o.debounceMs;
  2215. const rawSpan = o.maxActiveSpanMs;
  2216. // `0` is a meaningful operator opt-out for both knobs (no debounce, no
  2217. // active-span backstop). Reject negatives / non-finite values back to
  2218. // defaults so a malformed config can't silently disable the detector.
  2219. return {
  2220. debounceMs:
  2221. typeof rawDebounce === "number" &&
  2222. Number.isFinite(rawDebounce) &&
  2223. rawDebounce >= 0
  2224. ? rawDebounce
  2225. : defaults.debounceMs,
  2226. maxActiveSpanMs:
  2227. typeof rawSpan === "number" && Number.isFinite(rawSpan) && rawSpan >= 0
  2228. ? rawSpan
  2229. : defaults.maxActiveSpanMs,
  2230. };
  2231. }
  2232. export function resolvePromptConfig(obj: unknown): PromptConfig {
  2233. // The startup environment is injected after module loading; compute defaults during config parsing.
  2234. const defaultAutoUpdate =
  2235. getRuntimeBuildEnv() === "prod" && !isInternalBuild();
  2236. if (obj == null || typeof obj !== "object" || Array.isArray(obj)) {
  2237. return { autoUpdate: defaultAutoUpdate };
  2238. }
  2239. const rawAutoUpdate = (obj as Record<string, unknown>).autoUpdate;
  2240. return {
  2241. autoUpdate:
  2242. typeof rawAutoUpdate === "boolean" ? rawAutoUpdate : defaultAutoUpdate,
  2243. };
  2244. }
  2245. // ── session title config parsing ────────────────────────────────
  2246. function parseSessionTitleConfig(
  2247. raw: Record<string, unknown>,
  2248. ): SessionTitleConfig {
  2249. const defaults = DEFAULTS.sessionTitle;
  2250. const rawSessionTitle = raw.sessionTitle;
  2251. if (
  2252. rawSessionTitle == null ||
  2253. typeof rawSessionTitle !== "object" ||
  2254. Array.isArray(rawSessionTitle)
  2255. ) {
  2256. return { ...defaults };
  2257. }
  2258. const obj = rawSessionTitle as Record<string, unknown>;
  2259. return {
  2260. enabled: typeof obj.enabled === "boolean" ? obj.enabled : defaults.enabled,
  2261. };
  2262. }
  2263. // ── CLI config parsing ──────────────────────────────────────────
  2264. function parseCliConfig(raw: Record<string, unknown>): CliConfig {
  2265. const defaults = DEFAULTS.cli;
  2266. const rawCli = raw.cli;
  2267. if (rawCli == null || typeof rawCli !== "object" || Array.isArray(rawCli)) {
  2268. return { spawn: { ...defaults.spawn } };
  2269. }
  2270. const rawSpawn = (rawCli as Record<string, unknown>).spawn;
  2271. if (
  2272. rawSpawn == null ||
  2273. typeof rawSpawn !== "object" ||
  2274. Array.isArray(rawSpawn)
  2275. ) {
  2276. return { spawn: { ...defaults.spawn } };
  2277. }
  2278. const spawnObj = rawSpawn as Record<string, unknown>;
  2279. return {
  2280. spawn: {
  2281. enabled:
  2282. typeof spawnObj.enabled === "boolean"
  2283. ? spawnObj.enabled
  2284. : defaults.spawn.enabled,
  2285. },
  2286. };
  2287. }
  2288. // ── Context Management config parsing ───────────────────────────
  2289. function parseContextManagementConfig(
  2290. raw: Record<string, unknown>,
  2291. ): ContextManagementConfig {
  2292. const defaults = DEFAULTS.contextManagement;
  2293. const rawCm = raw.contextManagement;
  2294. if (rawCm == null || typeof rawCm !== "object" || Array.isArray(rawCm)) {
  2295. return {
  2296. disableSystemReminderModels: [...defaults.disableSystemReminderModels],
  2297. cuMaxScreenshotsInContext: defaults.cuMaxScreenshotsInContext,
  2298. };
  2299. }
  2300. const obj = rawCm as Record<string, unknown>;
  2301. const rawList = obj.disableSystemReminderModels;
  2302. const disableSystemReminderModels =
  2303. Array.isArray(rawList) &&
  2304. rawList.every((e) => typeof e === "string" && e.length > 0)
  2305. ? (rawList as string[])
  2306. : [...defaults.disableSystemReminderModels];
  2307. const rawCuMax = obj.cuMaxScreenshotsInContext;
  2308. const cuMaxScreenshotsInContext =
  2309. typeof rawCuMax === "number" && Number.isFinite(rawCuMax) && rawCuMax >= 0
  2310. ? Math.floor(rawCuMax)
  2311. : defaults.cuMaxScreenshotsInContext;
  2312. return { disableSystemReminderModels, cuMaxScreenshotsInContext };
  2313. }
  2314. // ── Agent Runtime config parsing — see ./agent-runtime-config.ts for the
  2315. // canonical implementation. Re-exposed here so the public `getConfig()`
  2316. // surface keeps a single import point for callers; the helper is the
  2317. // source of truth for the `AgentRuntimeFramework` string union and the
  2318. // Pi-only runtime selection parser.
  2319. // ── Log Retention config parsing ────────────────────────────────
  2320. function parseLogRetentionDays(raw: Record<string, unknown>): number {
  2321. const val = raw.logRetentionDays;
  2322. if (typeof val === "number" && val >= 1 && Number.isFinite(val)) {
  2323. return Math.floor(val);
  2324. }
  2325. return DEFAULTS.logRetentionDays;
  2326. }
  2327. // ── Content Review config parsing ───────────────────────────────
  2328. function parseContentReviewConfig(
  2329. raw: Record<string, unknown>,
  2330. ): { enabled?: boolean; testBaseURL?: string } | undefined {
  2331. const obj = raw.contentReview;
  2332. if (obj == null || typeof obj !== "object" || Array.isArray(obj))
  2333. return undefined;
  2334. const result: { enabled?: boolean; testBaseURL?: string } = {};
  2335. const enabled = Reflect.get(obj, "enabled");
  2336. if (typeof enabled === "boolean") result.enabled = enabled;
  2337. const testBaseURL = Reflect.get(obj, "testBaseURL");
  2338. if (typeof testBaseURL === "string" && testBaseURL.trim()) {
  2339. result.testBaseURL = testBaseURL.trim();
  2340. }
  2341. return Object.keys(result).length > 0 ? result : undefined;
  2342. }
  2343. // ── MCP tool-search config parsing ──────────────────────────────
  2344. function parseMcpToolSearchConfig(
  2345. raw: Record<string, unknown>,
  2346. ): McpToolSearchConfig | undefined {
  2347. const obj = raw.mcpToolSearch;
  2348. if (obj == null || typeof obj !== "object" || Array.isArray(obj))
  2349. return undefined;
  2350. const result: McpToolSearchConfig = {};
  2351. const enabled = Reflect.get(obj, "enabled");
  2352. if (typeof enabled === "boolean") result.enabled = enabled;
  2353. const systemHint = Reflect.get(obj, "systemHint");
  2354. if (typeof systemHint === "boolean") result.systemHint = systemHint;
  2355. const thresholdPct = Reflect.get(obj, "thresholdPct");
  2356. if (typeof thresholdPct === "number") result.thresholdPct = thresholdPct;
  2357. const minDeferCount = Reflect.get(obj, "minDeferCount");
  2358. if (typeof minDeferCount === "number") result.minDeferCount = minDeferCount;
  2359. const topKDefault = Reflect.get(obj, "topKDefault");
  2360. if (typeof topKDefault === "number") result.topKDefault = topKDefault;
  2361. const topKMax = Reflect.get(obj, "topKMax");
  2362. if (typeof topKMax === "number") result.topKMax = topKMax;
  2363. const maxSchemaTextLen = Reflect.get(obj, "maxSchemaTextLen");
  2364. if (typeof maxSchemaTextLen === "number")
  2365. result.maxSchemaTextLen = maxSchemaTextLen;
  2366. const modelWhitelist = Reflect.get(obj, "modelWhitelist");
  2367. if (Array.isArray(modelWhitelist)) {
  2368. result.modelWhitelist = modelWhitelist.filter(
  2369. (v): v is string => typeof v === "string",
  2370. );
  2371. }
  2372. return Object.keys(result).length > 0 ? result : undefined;
  2373. }
  2374. // ---------------------------------------------------------------------------
  2375. // Port resolution — compute the target local runtime port from env / git / defaults
  2376. // ---------------------------------------------------------------------------
  2377. /**
  2378. * Resolve the target local runtime port.
  2379. *
  2380. * Priority:
  2381. * 0. DISABLE_GIT_AUTO_CONFIG=1 → skip git auto-detection
  2382. * 1. Explicit profile-scoped port (__MAVIS_RUNTIME_PROFILE + __MAVIS_RUNTIME_PORT both set)
  2383. * 2. Git auto-detection (hash-based offset from branch name in mavis repo)
  2384. * 3. __MAVIS_RUNTIME_PORT env var (only when git detection is not active)
  2385. * 4. DEFAULT_PORT (5321)
  2386. *
  2387. * Not cached — env vars and git state can change between calls.
  2388. */
  2389. export function resolvePort(): number {
  2390. const explicitPort = getExplicitPortEnv();
  2391. if (shouldUseGitAutoConfig() && !shouldPreferExplicitPort()) {
  2392. const gitInfo = detectGitPortInfo();
  2393. if (gitInfo.autoDetected) {
  2394. return gitInfo.runtimePort;
  2395. }
  2396. }
  2397. return explicitPort ?? DEFAULT_PORT;
  2398. }
  2399. /**
  2400. * Legacy OpenCode listens on a dedicated offset above the runtime port range.
  2401. * New sessions do not use this; existing daemon callers still compile against it.
  2402. */
  2403. export function getOpenCodePort(runtimePort = resolvePort()): number {
  2404. const preferredPort = runtimePort + OPENCODE_PORT_OFFSET;
  2405. if (preferredPort <= MAX_TCP_PORT) {
  2406. return preferredPort;
  2407. }
  2408. const fallbackPort = runtimePort + OPENCODE_FALLBACK_OFFSET;
  2409. if (fallbackPort <= MAX_TCP_PORT) {
  2410. return fallbackPort;
  2411. }
  2412. throw new Error(
  2413. `Cannot allocate an OpenCode sidecar port for runtime port ${String(runtimePort)}; choose a runtime port <= ${String(MAX_TCP_PORT - OPENCODE_FALLBACK_OFFSET)}.`,
  2414. );
  2415. }