config.ts 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653
  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. /** User-owned context selections applied only to the independent MiniMax API catalog. */
  1071. modelContextLimits?: Record<string, number>;
  1072. }
  1073. /**
  1074. * User-created external provider ("Custom Model" settings tab). Reuses the
  1075. * ProviderConfig field vocabulary. Map keys (`provider_key`) are generated
  1076. * once from the display name at creation time and are immutable afterwards —
  1077. * renames only change `name`.
  1078. */
  1079. export interface CustomProviderConfig extends ProviderConfig {
  1080. /** Provider kind; user-created providers are always 'custom'. */
  1081. kind?: string;
  1082. /** Disabled providers keep their config but drop out of the effective model list. */
  1083. enabled?: boolean;
  1084. }
  1085. export type CustomProvidersConfig = Record<string, CustomProviderConfig>;
  1086. // --- Nexus ---
  1087. export interface NexusModelConfig {
  1088. providerID: string;
  1089. modelID: string;
  1090. variant?: string;
  1091. }
  1092. export interface NexusConfig {
  1093. enabled?: boolean;
  1094. model?: NexusModelConfig;
  1095. }
  1096. // ---------------------------------------------------------------------------
  1097. // Brand constants — single source of truth for all brand-related strings.
  1098. // ---------------------------------------------------------------------------
  1099. export const BRAND = {
  1100. /** Data directory basename (e.g. '.minimax'). */
  1101. APP_DIR: ".minimax",
  1102. /** Environment variable prefix (e.g. 'minimax'). */
  1103. ENV_PREFIX: "minimax",
  1104. /** CLI binary name. */
  1105. CLI_NAME: "minimax",
  1106. } as const;
  1107. /** Legacy runtime env prefix. New runtime identity travels via args/files. */
  1108. export const RUNTIME_ENV_PREFIX = "__MAVIS_RUNTIME";
  1109. /**
  1110. * Read an internal runtime environment variable.
  1111. * This lazy approach works correctly even when env vars are set after module load
  1112. * (e.g., in test beforeEach hooks or dynamically by service managers).
  1113. */
  1114. function runtimeEnv(suffix: string): string | undefined {
  1115. return isLegacyRuntimeEnvAllowed()
  1116. ? process.env[`${RUNTIME_ENV_PREFIX}_${suffix}`]
  1117. : undefined;
  1118. }
  1119. function cliArgValue(name: string): string | undefined {
  1120. const flag = `--${name}`;
  1121. for (let i = 2; i < process.argv.length; i++) {
  1122. const arg = process.argv[i];
  1123. if (arg === flag) return process.argv[i + 1];
  1124. if (arg?.startsWith(`${flag}=`)) return arg.slice(flag.length + 1);
  1125. }
  1126. return undefined;
  1127. }
  1128. function hasCliFlag(name: string): boolean {
  1129. const flag = `--${name}`;
  1130. return process.argv
  1131. .slice(2)
  1132. .some((arg) => arg === flag || arg.startsWith(`${flag}=`));
  1133. }
  1134. export const DEFAULT_PORT = 5321;
  1135. const DEFAULT_UI_PORT = 5001;
  1136. const MAX_TCP_PORT = 65535;
  1137. const GIT_AUTO_PORT_SLOT_COUNT = 500;
  1138. const GIT_AUTO_PORT_STRIDE = 2;
  1139. const MAX_GIT_AUTO_PORT_OFFSET =
  1140. GIT_AUTO_PORT_SLOT_COUNT * GIT_AUTO_PORT_STRIDE;
  1141. export const OPENCODE_PORT_OFFSET =
  1142. MAX_GIT_AUTO_PORT_OFFSET + GIT_AUTO_PORT_STRIDE;
  1143. const OPENCODE_FALLBACK_OFFSET = 1;
  1144. const REPO_NAMES: ReadonlySet<string> = new Set(["agent-archon", "mavis"]);
  1145. // ---------------------------------------------------------------------------
  1146. // Git port / profile detection (inlined here to avoid tsx dual-module-instance
  1147. // issues that arise when importing across workspace package boundaries)
  1148. // ---------------------------------------------------------------------------
  1149. /** POSIX cksum CRC-32 table (polynomial 0x04C11DB7, big-endian) */
  1150. const CRC_TABLE = (() => {
  1151. const POLY = 0x04c11db7;
  1152. const table = new Uint32Array(256);
  1153. for (let i = 0; i < 256; i++) {
  1154. let c = i << 24;
  1155. for (let j = 0; j < 8; j++) {
  1156. c = (c & 0x80000000) !== 0 ? POLY ^ (c << 1) : c << 1;
  1157. c >>>= 0;
  1158. }
  1159. table[i] = c >>> 0;
  1160. }
  1161. return table;
  1162. })();
  1163. /**
  1164. * POSIX cksum on UTF-8(str + '\n'), matching `echo "$str" | cksum | awk '{print $1}'`
  1165. */
  1166. function posixCksum(str: string): number {
  1167. const buf = Buffer.from(`${str}\n`, "utf-8");
  1168. let crc = 0;
  1169. for (const byte of buf) {
  1170. crc = (CRC_TABLE[((crc >>> 24) ^ byte) & 0xff]! ^ (crc << 8)) >>> 0;
  1171. }
  1172. let len = buf.length;
  1173. while (len !== 0) {
  1174. crc = (CRC_TABLE[((crc >>> 24) ^ (len & 0xff)) & 0xff]! ^ (crc << 8)) >>> 0;
  1175. len >>>= 8;
  1176. }
  1177. return (crc ^ 0xffffffff) >>> 0;
  1178. }
  1179. function calcOffset(branchName: string): number {
  1180. // 500 slots with stride 2 (offsets: 2,4,6,...,1000).
  1181. // Keep even offsets to preserve historically stable branch ports and leave
  1182. // room for per-profile sidecars without collapsing adjacent assignments.
  1183. return (
  1184. (posixCksum(branchName) % GIT_AUTO_PORT_SLOT_COUNT) * GIT_AUTO_PORT_STRIDE +
  1185. 2
  1186. );
  1187. }
  1188. function runGit(args: string[], cwd?: string): string | null {
  1189. try {
  1190. const result = spawnSync("git", args, {
  1191. encoding: "utf-8",
  1192. timeout: 3000,
  1193. stdio: ["ignore", "pipe", "pipe"],
  1194. ...(cwd ? { cwd } : {}),
  1195. });
  1196. if (result.status === 0 && result.stdout) return result.stdout.trim();
  1197. return null;
  1198. } catch {
  1199. return null;
  1200. }
  1201. }
  1202. function parseRepoName(remoteUrl: string): string | null {
  1203. const match = remoteUrl.match(/[/:]([^/:]+?)(?:\.git)?$/);
  1204. return match?.[1] ?? null;
  1205. }
  1206. function getExplicitPublicDataDirEnv(): string | undefined {
  1207. return (
  1208. process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim()
  1209. );
  1210. }
  1211. function shouldUseGitAutoConfig(): boolean {
  1212. if (
  1213. hasCliFlag("disable-git-auto-config") ||
  1214. runtimeEnv("DISABLE_GIT_AUTO_CONFIG")
  1215. )
  1216. return false;
  1217. if (cliArgValue("data-dir")) return false;
  1218. if (getExplicitPublicDataDirEnv()) return false;
  1219. return true;
  1220. }
  1221. function getExplicitProfileEnv(): string | null {
  1222. const profile = cliArgValue("profile") ?? runtimeEnv("PROFILE");
  1223. return profile && profile.length > 0 ? profile : null;
  1224. }
  1225. function getExplicitPortEnv(): number | null {
  1226. const explicitPort = cliArgValue("port") ?? runtimeEnv("PORT");
  1227. const parsedExplicitPort = explicitPort ? parseInt(explicitPort, 10) : NaN;
  1228. return Number.isNaN(parsedExplicitPort) ? null : parsedExplicitPort;
  1229. }
  1230. function getExplicitDataDirArg(): string | null {
  1231. const dataDir =
  1232. cliArgValue("data-dir") ??
  1233. getExplicitPublicDataDirEnv() ??
  1234. runtimeEnv("DATA_DIR");
  1235. return dataDir && dataDir.length > 0 ? dataDir : null;
  1236. }
  1237. function shouldPreferExplicitDataDir(): boolean {
  1238. return Boolean(getExplicitProfileEnv() && getExplicitDataDirArg());
  1239. }
  1240. function shouldPreferExplicitPort(): boolean {
  1241. return Boolean(getExplicitProfileEnv() && getExplicitPortEnv() !== null);
  1242. }
  1243. interface GitPortInfo {
  1244. runtimePort: number;
  1245. uiPort: number;
  1246. profile: string | null;
  1247. autoDetected: boolean;
  1248. }
  1249. export type { GitPortInfo };
  1250. let _gitCached: GitPortInfo | null = null;
  1251. /** Reset cached git detection result (for testing) */
  1252. export function resetGitDetect(): void {
  1253. _gitCached = null;
  1254. }
  1255. /**
  1256. * Detect port and profile from git branch name.
  1257. * Any branch in the mavis repo gets a hash-based offset.
  1258. * Default port 5321 is reserved for non-git / non-mavis environments.
  1259. */
  1260. export function detectGitPortInfo(): GitPortInfo {
  1261. if (_gitCached !== null) return _gitCached;
  1262. const defaults: GitPortInfo = {
  1263. runtimePort: DEFAULT_PORT,
  1264. uiPort: DEFAULT_UI_PORT,
  1265. profile: null,
  1266. autoDetected: false,
  1267. };
  1268. // npm build: skip git detection entirely — always use default port 5321.
  1269. // esbuild constant-folds this to `true`, eliminating the git spawn code.
  1270. if (typeof __IS_NPM_BUILD__ !== "undefined") {
  1271. _gitCached = defaults;
  1272. return defaults;
  1273. }
  1274. // Try to detect from process.cwd() first, then fall back to the directory
  1275. // containing this config file. The fallback ensures correct detection when
  1276. // a runtime helper starts from a wrong cwd — the config file is always
  1277. // co-located with the source inside the git worktree.
  1278. const candidateDirs: Array<string | undefined> = [
  1279. undefined, // process.cwd() (default spawnSync behavior)
  1280. currentModuleDir(),
  1281. ];
  1282. for (const cwd of candidateDirs) {
  1283. try {
  1284. const remoteUrl = runGit(["remote", "get-url", "origin"], cwd);
  1285. if (!remoteUrl) continue;
  1286. const repoName = parseRepoName(remoteUrl);
  1287. if (!repoName || !REPO_NAMES.has(repoName)) continue;
  1288. const branch = runGit(["branch", "--show-current"], cwd);
  1289. if (!branch) continue;
  1290. const offset = calcOffset(branch);
  1291. _gitCached = {
  1292. runtimePort: DEFAULT_PORT + offset,
  1293. uiPort: DEFAULT_UI_PORT + offset,
  1294. profile: branch.replace(/\//g, "-"),
  1295. autoDetected: true,
  1296. };
  1297. return _gitCached;
  1298. } catch {
  1299. // try next candidate
  1300. }
  1301. }
  1302. _gitCached = defaults;
  1303. return defaults;
  1304. }
  1305. function currentModuleDir(): string | undefined {
  1306. try {
  1307. if (typeof __dirname === "string") return __dirname;
  1308. } catch {
  1309. /* ESM has no __dirname */
  1310. }
  1311. const stack = new Error().stack ?? "";
  1312. for (const line of stack.split("\n")) {
  1313. const fileUrl = /file:\/\/[^)\s]+/u
  1314. .exec(line)?.[0]
  1315. ?.replace(/:\d+:\d+$/u, "");
  1316. if (fileUrl) {
  1317. try {
  1318. return path.dirname(fileURLToPath(fileUrl));
  1319. } catch {
  1320. /* keep scanning */
  1321. }
  1322. }
  1323. const filePath =
  1324. /\(?((?:\/|[A-Za-z]:\\)[^()]+?\.(?:cjs|mjs|js|ts)):\d+:\d+\)?/u.exec(
  1325. line,
  1326. )?.[1];
  1327. if (filePath) return path.dirname(filePath);
  1328. }
  1329. return undefined;
  1330. }
  1331. // ---------------------------------------------------------------------------
  1332. // Config
  1333. // ---------------------------------------------------------------------------
  1334. export function getProfile(): string | null {
  1335. const profile = getExplicitProfileEnv();
  1336. if (profile) return profile;
  1337. if (!shouldUseGitAutoConfig()) return null;
  1338. return detectGitPortInfo().profile;
  1339. }
  1340. // ---------------------------------------------------------------------------
  1341. // Data directory resolution
  1342. // ---------------------------------------------------------------------------
  1343. export function getDataDir(): string {
  1344. // Data-dir resolution priority (mirrors port resolution in getConfig):
  1345. // 0. ${RUNTIME_ENV_PREFIX}_DISABLE_GIT_AUTO_CONFIG=1 → skip repo auto-detection entirely
  1346. // and fall back to the explicit env/default "user mode" resolution below.
  1347. // 1. Explicit profile-scoped data dir (service/supervisor) → fixed data dir
  1348. // 2. Git auto-detection (any branch in mavis repo) → profile-scoped dir
  1349. // This takes highest priority because the parent daemon process injects
  1350. // ${RUNTIME_ENV_PREFIX}_DATA_DIR into child process environments, which would
  1351. // incorrectly override the per-branch isolation that git detection provides.
  1352. // 3. ${RUNTIME_ENV_PREFIX}_DATA_DIR env var → used only when git detection is not active
  1353. // 4. ${RUNTIME_ENV_PREFIX}_PROFILE env var → manual profile override
  1354. // 5. resolveDataDir() → non-git / non-mavis default data directory
  1355. const explicitProfile = getExplicitProfileEnv();
  1356. if (shouldPreferExplicitDataDir()) {
  1357. return getExplicitDataDirArg()!;
  1358. }
  1359. if (shouldUseGitAutoConfig()) {
  1360. const gitInfo = detectGitPortInfo();
  1361. if (gitInfo.autoDetected && gitInfo.profile) {
  1362. return resolveDataDir({ profile: gitInfo.profile });
  1363. }
  1364. }
  1365. const explicitDataDir = getExplicitDataDirArg();
  1366. if (explicitDataDir) {
  1367. return explicitDataDir;
  1368. }
  1369. if (explicitProfile) {
  1370. return resolveDataDir({ profile: explicitProfile });
  1371. }
  1372. return resolveDataDir();
  1373. }
  1374. export function getConfigPath(): string {
  1375. return path.join(getDataDir(), "config.yaml");
  1376. }
  1377. // ---------------------------------------------------------------------------
  1378. // Default provider presets per environment combo (MAVIS_REGION x MAVIS_BUILD_ENV)
  1379. // ---------------------------------------------------------------------------
  1380. const MINIMAX_M3_FILE_API_CAPABILITIES: ModelCapabilitiesConfig = {
  1381. support_files_api: true,
  1382. files_api_upload_endpoint: "/v1/files/upload",
  1383. max_image_bytes_inline: 10_485_760,
  1384. max_video_bytes_inline: 52_428_800,
  1385. max_request_body_bytes: 67_108_864,
  1386. max_attachments_count: 4,
  1387. };
  1388. const MINIMAX_MODELS: Record<string, ModelConfig> = {
  1389. "MiniMax-M3": {
  1390. name: "MiniMax-M3",
  1391. attachment: true,
  1392. reasoning: true,
  1393. tool_call: true,
  1394. temperature: true,
  1395. modalities: { input: ["text", "image", "video"], output: ["text"] },
  1396. limit: { context: 512000, output: 128000 },
  1397. contextWindowOptions: [512000, 1000000],
  1398. contextWindowOptionHints: { "1000000": "higher_usage" },
  1399. options: { reasoningSummary: "auto" },
  1400. thinking_config: { mode: "switchable", default_value: "true" },
  1401. variants: {
  1402. "none-thinking": { thinking: { type: "disabled" } },
  1403. thinking: { thinking: { type: "adaptive" } },
  1404. },
  1405. capabilities: MINIMAX_M3_FILE_API_CAPABILITIES,
  1406. },
  1407. "MiniMax-M2.7-highspeed": {
  1408. name: "MiniMax-M2.7-highspeed",
  1409. attachment: false,
  1410. reasoning: true,
  1411. tool_call: true,
  1412. temperature: true,
  1413. modalities: { input: ["text"], output: ["text"] },
  1414. limit: { context: 200000, output: 128000 },
  1415. },
  1416. "MiniMax-M2.7": {
  1417. name: "MiniMax-M2.7",
  1418. attachment: false,
  1419. reasoning: true,
  1420. tool_call: true,
  1421. temperature: true,
  1422. modalities: { input: ["text"], output: ["text"] },
  1423. limit: { context: 200000, output: 128000 },
  1424. },
  1425. };
  1426. /** MiniMax models the user's own API key may call and the first-run managed fallback. */
  1427. export const MINIMAX_API_MODEL_CATALOG: Record<string, ModelConfig> =
  1428. MINIMAX_MODELS;
  1429. const PRESET_BASE_URLS: Record<PresetKey, string> = {
  1430. "cn-test": "https://matrix-test.example.invalid/mavis/api/v1/llm/v1",
  1431. "cn-dev": "https://matrix-test.example.invalid/mavis/api/v1/llm/v1",
  1432. "cn-staging": "https://matrix-pre.example.invalid/mavis/api/v1/llm/v1",
  1433. "en-test": "https://matrix-overseas-test.example.invalid/mavis/api/v1/llm/v1",
  1434. "en-dev": "https://matrix-overseas-test.example.invalid/mavis/api/v1/llm/v1",
  1435. "en-staging":
  1436. "https://matrix-overseas-pre.example.invalid/mavis/api/v1/llm/v1",
  1437. "cn-prod": "https://agent.minimax.cn/mavis/api/v1/llm/v1",
  1438. "en-prod": "https://agent.minimax.io/mavis/api/v1/llm/v1",
  1439. };
  1440. const LEGACY_MANAGED_PRESET_BASE_URLS = [
  1441. "https://agent.minimaxi.com/mavis/api/v1/llm/v1",
  1442. ] as const;
  1443. const MANAGED_PRESET_BASE_URLS = new Set([
  1444. ...Object.values(PRESET_BASE_URLS),
  1445. ...LEGACY_MANAGED_PRESET_BASE_URLS,
  1446. ]);
  1447. const MANAGED_PRESET_ORIGINS = new Set(
  1448. [...Object.values(PRESET_BASE_URLS), ...LEGACY_MANAGED_PRESET_BASE_URLS].map(
  1449. (baseURL) => new URL(baseURL).origin,
  1450. ),
  1451. );
  1452. function isManagedPresetBaseUrl(baseURL: string): boolean {
  1453. if (MANAGED_PRESET_BASE_URLS.has(baseURL)) return true;
  1454. try {
  1455. const parsed = new URL(baseURL);
  1456. return (
  1457. !parsed.username &&
  1458. !parsed.password &&
  1459. MANAGED_PRESET_ORIGINS.has(parsed.origin)
  1460. );
  1461. } catch {
  1462. return false;
  1463. }
  1464. }
  1465. /** Test desktop builds may route the builtin managed MiniMax provider through a local fault proxy. */
  1466. export function allowsManagedMinimaxProviderOverride(): boolean {
  1467. return getRuntimeBuildEnv() === "test";
  1468. }
  1469. function shouldEnforceManagedProviderProtection(): boolean {
  1470. return !allowsManagedMinimaxProviderOverride();
  1471. }
  1472. function syncManagedPresetBaseUrl(configPath: string): void {
  1473. if (!isManagedRuntime() || !fs.existsSync(configPath)) {
  1474. return;
  1475. }
  1476. const raw = readConfigFile(configPath);
  1477. const { provider } = raw;
  1478. if (
  1479. provider == null ||
  1480. typeof provider !== "object" ||
  1481. Array.isArray(provider)
  1482. )
  1483. return;
  1484. const { minimax } = provider as Record<string, unknown>;
  1485. if (minimax == null || typeof minimax !== "object" || Array.isArray(minimax))
  1486. return;
  1487. const { options } = minimax as Record<string, unknown>;
  1488. if (options == null || typeof options !== "object" || Array.isArray(options))
  1489. return;
  1490. const currentBaseURL = (options as Record<string, unknown>).baseURL;
  1491. if (typeof currentBaseURL !== "string") return;
  1492. const presetBaseURL = PRESET_BASE_URLS[getRuntimePresetKey()];
  1493. if (
  1494. currentBaseURL === presetBaseURL ||
  1495. !isManagedPresetBaseUrl(currentBaseURL)
  1496. )
  1497. return;
  1498. (options as Record<string, unknown>).baseURL = presetBaseURL;
  1499. writePrivateConfigFileSync(
  1500. configPath,
  1501. yaml.dump(raw, { indent: 2, lineWidth: -1, noRefs: true }),
  1502. );
  1503. }
  1504. function buildPresetEntry(key: PresetKey) {
  1505. const provider: ProviderConfig = {
  1506. name: "MiniMax",
  1507. npm: "@ai-sdk/anthropic",
  1508. options: {
  1509. authMode: "managed-login",
  1510. apiKey: "sk-xxx",
  1511. baseURL: PRESET_BASE_URLS[key],
  1512. },
  1513. models: MINIMAX_MODELS,
  1514. };
  1515. return {
  1516. provider: { minimax: provider } as ModelsConfig,
  1517. defaultModel: "minimax/MiniMax-M3",
  1518. };
  1519. }
  1520. export const DEFAULT_MODEL_PRESETS: Record<
  1521. PresetKey,
  1522. { provider: ModelsConfig; defaultModel: string }
  1523. > = {
  1524. "cn-test": buildPresetEntry("cn-test"),
  1525. "cn-dev": buildPresetEntry("cn-dev"),
  1526. "cn-staging": buildPresetEntry("cn-staging"),
  1527. "cn-prod": buildPresetEntry("cn-prod"),
  1528. "en-test": buildPresetEntry("en-test"),
  1529. "en-dev": buildPresetEntry("en-dev"),
  1530. "en-staging": buildPresetEntry("en-staging"),
  1531. "en-prod": buildPresetEntry("en-prod"),
  1532. } as const;
  1533. const DEFAULTS: Omit<
  1534. Config,
  1535. | "dataDir"
  1536. | "agentsDir"
  1537. | "sessionsDir"
  1538. | "memoryDir"
  1539. | "skillsDir"
  1540. | "builtinSkillsDir"
  1541. | "logsDir"
  1542. | "pluginsDir"
  1543. | "plansDir"
  1544. | "harnessesDir"
  1545. | "subAgentsDir"
  1546. | "provider"
  1547. | "permission"
  1548. | "promptConfig"
  1549. > = {
  1550. logLevel: "info",
  1551. devPort: DEFAULT_UI_PORT,
  1552. permissionMode: "auto",
  1553. sseErrorPush: {
  1554. history: true,
  1555. stream: true,
  1556. },
  1557. beta: Object.fromEntries(
  1558. (Object.keys(BETA_FEATURE_DEFS) as (keyof BetaConfig)[]).map((key) => [
  1559. key,
  1560. resolveBetaFeature(key, undefined, { buildEnv: "dev" }),
  1561. ]),
  1562. ) as unknown as BetaConfig,
  1563. agents: { default: {} },
  1564. memory: {
  1565. enabled: true,
  1566. proactive: false,
  1567. dailyDigest: {
  1568. enabled: false,
  1569. },
  1570. },
  1571. skillEvolve: {
  1572. enabled: true,
  1573. inSession: {
  1574. N: 20,
  1575. minIntervalSeconds: 30,
  1576. maxPendingPerSession: 1,
  1577. },
  1578. signalCooldownHours: 24,
  1579. minConfidence: 0.7,
  1580. excludeAgents: ["skill-editor"],
  1581. disableModelPrefixes: ["MiniMax-M2"],
  1582. builtinMrEnabled: false,
  1583. sourceRepo: undefined,
  1584. proposal: {
  1585. enabled: false,
  1586. eligibleAgents: ["mavis"],
  1587. minMessageCount: 40,
  1588. skipPassiveSessionEnd: true,
  1589. },
  1590. lifecycle: { staleThresholdDays: 15, archiveThresholdDays: 30 }, // tightened from legacy 30d/90d
  1591. },
  1592. sessionRotate: {
  1593. enabled: true,
  1594. activeSessionLookbackHours: 12,
  1595. },
  1596. agentStop: {
  1597. debounceMs: 500,
  1598. maxActiveSpanMs: 30 * 60 * 1000, // 30 min
  1599. },
  1600. 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.
  1601. skills: DEFAULT_SKILLS_CONFIG,
  1602. askUser: { ...ASK_USER_CONFIG_DEFAULTS },
  1603. sessionTitle: {
  1604. // Default ON. See `SessionTitleConfig`.
  1605. enabled: true,
  1606. },
  1607. cli: {
  1608. spawn: {
  1609. enabled: false,
  1610. },
  1611. },
  1612. browser: { ...BROWSER_CONFIG_DEFAULTS },
  1613. // No status line items by default: the TUI picks its build-specific default
  1614. // when `tui.statusLine` is absent.
  1615. tui: {},
  1616. telemetry: { enabled: false, metrics: false, diagnostics: false },
  1617. opencode: {
  1618. xdg: {
  1619. dataIsolation: false,
  1620. startupImport: "off",
  1621. },
  1622. keepAlive: {
  1623. enabled: false,
  1624. maxProcesses: 5,
  1625. maxLifetimeMs: 28_800_000,
  1626. agents: ["mavis", "main", "verifier", "code-reviewer"],
  1627. },
  1628. spawnConcurrency: 3,
  1629. },
  1630. contextManagement: {
  1631. disableSystemReminderModels: [],
  1632. cuMaxScreenshotsInContext: 2,
  1633. },
  1634. runawayGuard: { enabled: true },
  1635. toolResultCompaction: { ...TOOL_RESULT_COMPACTION_DEFAULTS },
  1636. agentRuntime: {
  1637. // Single source of truth lives in `./agent-runtime-config.ts` so the
  1638. // default and the union type cannot drift.
  1639. defaultFramework: DEFAULT_AGENT_RUNTIME_FRAMEWORK,
  1640. },
  1641. logRetentionDays: 3,
  1642. cuBackend: DEFAULT_CU_BACKEND,
  1643. review: {
  1644. mode: "subagent",
  1645. modeSource: "default",
  1646. },
  1647. goal: structuredClone(GOAL_CONFIG_DEFAULTS),
  1648. sandbox: structuredClone(SANDBOX_CONFIG_DEFAULTS),
  1649. goalWarnings: [],
  1650. };
  1651. function ensureConfigFile(): void {
  1652. const configPath = getConfigPath();
  1653. const dir = path.dirname(configPath);
  1654. if (!fs.existsSync(dir)) {
  1655. fs.mkdirSync(dir, { recursive: true });
  1656. }
  1657. if (fs.existsSync(configPath)) {
  1658. prepareConfigFileForRead(configPath);
  1659. return;
  1660. }
  1661. // In non-managed runtime (pnpm dev / npm package), the UI onboarding flow
  1662. // owns config.yaml generation — it walks the user through getting an API
  1663. // key and writes the file. Daemon must NOT pre-seed a placeholder here,
  1664. // otherwise the UI flow has no way to know whether the user has actually
  1665. // configured anything.
  1666. //
  1667. // However, when a worktree daemon starts with a derived dataDir (e.g.
  1668. // <dataDir>-feature-foo/), the developer's API keys live in the default
  1669. // dataDir (<dataDir>/config.yaml). Copy it over so the worktree daemon
  1670. // inherits the existing configuration.
  1671. if (!isManagedRuntime()) {
  1672. const defaultDataDir = resolveDataDir({ homeDir: os.homedir() });
  1673. const defaultConfigPath = path.join(defaultDataDir, "config.yaml");
  1674. if (configPath !== defaultConfigPath && fs.existsSync(defaultConfigPath)) {
  1675. restrictConfigFileSync(defaultConfigPath);
  1676. writePrivateConfigFileSync(configPath, fs.readFileSync(defaultConfigPath), true);
  1677. }
  1678. return;
  1679. }
  1680. const preset = DEFAULT_MODEL_PRESETS[getRuntimePresetKey()];
  1681. const content = yaml.dump({
  1682. logLevel: DEFAULTS.logLevel,
  1683. provider: managedPresetBaseUrlSyncEnabled ? preset.provider : undefined,
  1684. defaultModel: preset.defaultModel,
  1685. });
  1686. writePrivateConfigFileSync(configPath, content, true);
  1687. }
  1688. function readConfigFile(configPath = getConfigPath()): Record<string, unknown> {
  1689. try {
  1690. const raw = fs.readFileSync(configPath, "utf-8");
  1691. const parsed = yaml.load(raw);
  1692. if (
  1693. parsed != null &&
  1694. typeof parsed === "object" &&
  1695. !Array.isArray(parsed)
  1696. ) {
  1697. return parsed as Record<string, unknown>;
  1698. }
  1699. return {};
  1700. } catch {
  1701. return {};
  1702. }
  1703. }
  1704. let _cached: Config | null = null;
  1705. function parseNotificationsConfig(
  1706. raw: unknown,
  1707. ): NotificationsConfig | undefined {
  1708. if (raw == null || typeof raw !== "object" || Array.isArray(raw))
  1709. return undefined;
  1710. const obj = raw as Record<string, unknown>;
  1711. return {
  1712. branchFinish:
  1713. typeof obj.branchFinish === "boolean" ? obj.branchFinish : false,
  1714. };
  1715. }
  1716. // ── BYOK config parsing + required provider overrides: see ./byok-config.ts ──
  1717. const REQUIRED_PROVIDER_OVERRIDE_DEPS: RequiredProviderOverrideDeps = {
  1718. isManagedRuntime,
  1719. shouldEnforceManagedProviderProtection,
  1720. getManagedPreset: () => DEFAULT_MODEL_PRESETS[getRuntimePresetKey()],
  1721. isManagedPresetBaseUrl,
  1722. };
  1723. let legacyByokProviderMigrationEnabled = true;
  1724. let managedPresetBaseUrlSyncEnabled = true;
  1725. export function setLegacyByokProviderMigrationEnabled(enabled: boolean): void {
  1726. legacyByokProviderMigrationEnabled = enabled;
  1727. }
  1728. /** Hosts sharing config with older clients can use the current preset without persisting it. */
  1729. export function setManagedPresetBaseUrlSyncEnabled(enabled: boolean): void {
  1730. managedPresetBaseUrlSyncEnabled = enabled;
  1731. }
  1732. export function prepareConfigFileForRead(configPath: string): void {
  1733. restrictConfigFileSync(configPath);
  1734. restrictLegacyByokBackups(configPath);
  1735. if (legacyByokProviderMigrationEnabled) {
  1736. migrateLegacyByokProvidersOnDisk(
  1737. configPath,
  1738. REQUIRED_PROVIDER_OVERRIDE_DEPS,
  1739. );
  1740. }
  1741. if (managedPresetBaseUrlSyncEnabled) syncManagedPresetBaseUrl(configPath);
  1742. }
  1743. export function resetConfig(): void {
  1744. _cached = null;
  1745. }
  1746. export function getConfig(): Config {
  1747. if (_cached) return _cached;
  1748. ensureConfigFile();
  1749. const raw = readConfigFile();
  1750. _cached = resolveConfigFromRaw(raw, getDataDir());
  1751. return _cached;
  1752. }
  1753. export function resolveConfigFromRaw(
  1754. raw: Record<string, unknown>,
  1755. dataDir: string,
  1756. ): Config {
  1757. const rawSSEErrorPush = raw.sseErrorPush;
  1758. const sseErrorPush =
  1759. rawSSEErrorPush != null &&
  1760. typeof rawSSEErrorPush === "object" &&
  1761. !Array.isArray(rawSSEErrorPush)
  1762. ? (rawSSEErrorPush as Record<string, unknown>)
  1763. : undefined;
  1764. // devPort resolution (kept in Config for UI dev server)
  1765. let devPort =
  1766. typeof raw.devPort === "number" ? raw.devPort : DEFAULTS.devPort;
  1767. if (shouldUseGitAutoConfig() && !shouldPreferExplicitPort()) {
  1768. const gitInfo = detectGitPortInfo();
  1769. if (gitInfo.autoDetected) {
  1770. devPort = gitInfo.uiPort;
  1771. }
  1772. }
  1773. const goalParsed = parseGoalConfig(raw.goal);
  1774. const managedProvider = applyRequiredProviderOverrides(
  1775. {
  1776. provider:
  1777. raw.provider != null &&
  1778. typeof raw.provider === "object" &&
  1779. !Array.isArray(raw.provider)
  1780. ? normalizeLegacyThinkingEfforts(raw.provider as ModelsConfig)
  1781. : {},
  1782. defaultModel:
  1783. typeof raw.defaultModel === "string" ? raw.defaultModel : undefined,
  1784. },
  1785. REQUIRED_PROVIDER_OVERRIDE_DEPS,
  1786. );
  1787. const minimaxModelContextLimits = parseModelContextLimits(
  1788. raw.minimaxModelContextLimits,
  1789. );
  1790. const beta = parseBetaConfig(raw);
  1791. return {
  1792. logLevel:
  1793. typeof raw.logLevel === "string" ? raw.logLevel : DEFAULTS.logLevel,
  1794. devPort,
  1795. ...managedProvider,
  1796. provider: applyManagedMinimaxContextLimits(
  1797. managedProvider.provider,
  1798. minimaxModelContextLimits,
  1799. ),
  1800. defaultModelVariant:
  1801. typeof raw.defaultModelVariant === "string"
  1802. ? raw.defaultModelVariant
  1803. : undefined,
  1804. defaultModelThinking:
  1805. raw.defaultModelThinking &&
  1806. typeof raw.defaultModelThinking === "object" &&
  1807. typeof (raw.defaultModelThinking as Record<string, unknown>).effort ===
  1808. "string"
  1809. ? { effort: (raw.defaultModelThinking as { effort: string }).effort }
  1810. : undefined,
  1811. defaultModelContextWindow:
  1812. Number.isSafeInteger(raw.defaultModelContextWindow) &&
  1813. Number(raw.defaultModelContextWindow) > 0 &&
  1814. Number(raw.defaultModelContextWindow) <= 2_147_483_647
  1815. ? Number(raw.defaultModelContextWindow)
  1816. : undefined,
  1817. minimax_api: parseMinimaxApiConfig(raw.minimax_api),
  1818. minimaxModelContextLimits,
  1819. custom_provider: parseCustomProvidersConfig(raw.custom_provider),
  1820. minimaxModelSource:
  1821. typeof raw.minimaxModelSource === "string" &&
  1822. (raw.minimaxModelSource === "token_plan" ||
  1823. raw.minimaxModelSource === "minimax_api_key")
  1824. ? raw.minimaxModelSource
  1825. : undefined,
  1826. nexus:
  1827. raw.nexus != null &&
  1828. typeof raw.nexus === "object" &&
  1829. !Array.isArray(raw.nexus)
  1830. ? (() => {
  1831. const parsed: NexusConfig = {};
  1832. if (typeof Reflect.get(raw.nexus, "enabled") === "boolean") {
  1833. parsed.enabled = Reflect.get(raw.nexus, "enabled") as boolean;
  1834. }
  1835. const rawModel = Reflect.get(raw.nexus, "model");
  1836. if (
  1837. rawModel != null &&
  1838. typeof rawModel === "object" &&
  1839. !Array.isArray(rawModel) &&
  1840. typeof Reflect.get(rawModel, "providerID") === "string" &&
  1841. typeof Reflect.get(rawModel, "modelID") === "string"
  1842. ) {
  1843. parsed.model = {
  1844. providerID: Reflect.get(rawModel, "providerID") as string,
  1845. modelID: Reflect.get(rawModel, "modelID") as string,
  1846. ...(typeof Reflect.get(rawModel, "variant") === "string"
  1847. ? {
  1848. variant: Reflect.get(rawModel, "variant") as string,
  1849. }
  1850. : {}),
  1851. };
  1852. }
  1853. return Object.keys(parsed).length > 0 ? parsed : undefined;
  1854. })()
  1855. : undefined,
  1856. defaultLightModel:
  1857. typeof raw.defaultLightModel === "string"
  1858. ? raw.defaultLightModel
  1859. : undefined,
  1860. permissionMode:
  1861. typeof raw.permissionMode === "string" &&
  1862. ["default", "bypassPermissions", "auto", "off"].includes(
  1863. raw.permissionMode,
  1864. )
  1865. ? (raw.permissionMode as PermissionMode)
  1866. : DEFAULTS.permissionMode,
  1867. permission: parsePermissionConfig(raw),
  1868. sseErrorPush: {
  1869. history:
  1870. typeof sseErrorPush?.history === "boolean"
  1871. ? (sseErrorPush.history as boolean)
  1872. : DEFAULTS.sseErrorPush.history,
  1873. stream:
  1874. typeof sseErrorPush?.stream === "boolean"
  1875. ? (sseErrorPush.stream as boolean)
  1876. : DEFAULTS.sseErrorPush.stream,
  1877. },
  1878. notifications: parseNotificationsConfig(raw.notifications),
  1879. dataDir,
  1880. agentsDir: path.join(dataDir, "agents"),
  1881. sessionsDir: path.join(dataDir, "sessions"),
  1882. memoryDir: path.join(dataDir, "memory"),
  1883. skillsDir: path.join(dataDir, "skills"),
  1884. builtinSkillsDir: path.join(dataDir, ".builtin-skills"),
  1885. logsDir: path.join(dataDir, "logs"),
  1886. pluginsDir: path.join(dataDir, "plugins"),
  1887. plansDir: path.join(dataDir, "plans"),
  1888. harnessesDir: path.join(dataDir, "harnesses"),
  1889. subAgentsDir: path.join(dataDir, "subagents"),
  1890. beta,
  1891. agents: parseAgentsConfig(raw.agents),
  1892. memory: parseMemoryConfig(raw),
  1893. skillEvolve: parseSkillEvolveConfig(raw, beta),
  1894. sessionRotate: parseSessionRotateConfig(raw),
  1895. agentStop: parseAgentStopDetectorConfig(raw),
  1896. asr: parseAsrConfig(raw),
  1897. skills: parseSkillsConfig(raw),
  1898. askUser: parseAskUserConfig(raw, DEFAULTS.askUser),
  1899. sessionTitle: parseSessionTitleConfig(raw),
  1900. cli: parseCliConfig(raw),
  1901. browser: parseBrowserConfig(raw.browser),
  1902. tui: parseTuiConfig(raw),
  1903. telemetry: parseTelemetryConfig(raw.telemetry),
  1904. opencode: parseOpenCodeAdapterConfig(raw, DEFAULTS.opencode),
  1905. contextManagement: parseContextManagementConfig(raw),
  1906. runawayGuard: resolveRunawayGuardConfig(raw.runawayGuard),
  1907. toolResultCompaction: parseToolResultCompactionConfig(
  1908. raw.toolResultCompaction,
  1909. ),
  1910. agentRuntime: parseAgentRuntimeConfig(raw.agentRuntime),
  1911. logRetentionDays: parseLogRetentionDays(raw),
  1912. contentReview: parseContentReviewConfig(raw),
  1913. mcpToolSearch: parseMcpToolSearchConfig(raw),
  1914. cuBackend: parseCuBackend(raw.cuBackend),
  1915. review: parseReviewConfig(raw.review, DEFAULTS.review),
  1916. promptConfig: resolvePromptConfig(raw.promptConfig),
  1917. goal: goalParsed.config,
  1918. goalWarnings: goalParsed.warnings,
  1919. sandbox: parseSandboxConfig(raw.sandbox),
  1920. };
  1921. }
  1922. // ── Memory config parsing ──────────────────────────────────────
  1923. function parseTelemetryConfig(raw: unknown): TelemetryConfig {
  1924. if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
  1925. return { ...DEFAULTS.telemetry };
  1926. }
  1927. const enabled = Reflect.get(raw, "enabled");
  1928. return {
  1929. enabled: typeof enabled === "boolean" ? enabled : DEFAULTS.telemetry.enabled,
  1930. metrics: Reflect.get(raw, "metrics") === true,
  1931. diagnostics: Reflect.get(raw, "diagnostics") === true,
  1932. };
  1933. }
  1934. function parseMemoryConfig(raw: Record<string, unknown>): MemoryConfig {
  1935. const memoryRaw = raw.memory;
  1936. const memoryObj =
  1937. memoryRaw != null &&
  1938. typeof memoryRaw === "object" &&
  1939. !Array.isArray(memoryRaw)
  1940. ? (memoryRaw as Record<string, unknown>)
  1941. : {};
  1942. const dailyDigestRaw = memoryObj.dailyDigest;
  1943. const dailyDigestObj =
  1944. dailyDigestRaw != null &&
  1945. typeof dailyDigestRaw === "object" &&
  1946. !Array.isArray(dailyDigestRaw)
  1947. ? (dailyDigestRaw as Record<string, unknown>)
  1948. : {};
  1949. return {
  1950. enabled:
  1951. typeof memoryObj.enabled === "boolean"
  1952. ? memoryObj.enabled
  1953. : DEFAULTS.memory.enabled,
  1954. proactive:
  1955. typeof memoryObj.proactive === "boolean"
  1956. ? memoryObj.proactive
  1957. : DEFAULTS.memory.proactive,
  1958. dailyDigest: {
  1959. enabled:
  1960. typeof dailyDigestObj.enabled === "boolean"
  1961. ? dailyDigestObj.enabled
  1962. : DEFAULTS.memory.dailyDigest.enabled,
  1963. },
  1964. };
  1965. }
  1966. // ── Beta features config parsing ────────────────────────────────
  1967. function parseBetaConfig(raw: Record<string, unknown>): BetaConfig {
  1968. const obj =
  1969. raw.beta != null && typeof raw.beta === "object" && !Array.isArray(raw.beta)
  1970. ? (raw.beta as Record<string, unknown>)
  1971. : {};
  1972. const context: BetaFeatureResolutionContext = {
  1973. buildEnv: getRuntimeBuildEnv(),
  1974. defaultBuildEnvironment: getBetaDefaultBuildEnvironment(),
  1975. internalBuild: isInternalBuild(),
  1976. insideBuild: isInsideBuild(),
  1977. mcodeToolsDevMode:
  1978. process.env.MAVIS_DEV_MCODE_TOOLS_MODE === "published"
  1979. ? "published"
  1980. : undefined,
  1981. };
  1982. const result = {} as BetaConfig;
  1983. for (const key of Object.keys(BETA_FEATURE_DEFS) as (keyof BetaConfig)[]) {
  1984. result[key] = resolveBetaFeature(key, obj[key], context);
  1985. }
  1986. return result;
  1987. }
  1988. // ── Skill Evolve config parsing ─────────────────────────────────
  1989. /**
  1990. * Collect all model IDs from the provider config.
  1991. * Returns an empty array when no models are configured.
  1992. */
  1993. function collectModelIds(raw: Record<string, unknown>): string[] {
  1994. const providerRaw = raw.provider;
  1995. if (
  1996. providerRaw == null ||
  1997. typeof providerRaw !== "object" ||
  1998. Array.isArray(providerRaw)
  1999. ) {
  2000. return [];
  2001. }
  2002. const ids: string[] = [];
  2003. for (const prov of Object.values(providerRaw as Record<string, unknown>)) {
  2004. if (prov == null || typeof prov !== "object" || Array.isArray(prov))
  2005. continue;
  2006. const { models } = prov as Record<string, unknown>;
  2007. if (models == null || typeof models !== "object" || Array.isArray(models))
  2008. continue;
  2009. ids.push(...Object.keys(models as Record<string, unknown>));
  2010. }
  2011. return ids;
  2012. }
  2013. /**
  2014. * Auto-derive the `skillEvolve.enabled` flag from the configured model list.
  2015. *
  2016. * When **every** configured model ID starts with one of the
  2017. * `disableModelPrefixes` (case-insensitive), skill-evolve has no capable
  2018. * model to work with, so it is disabled automatically.
  2019. * If at least one model does NOT match, the feature is enabled.
  2020. *
  2021. * Edge cases: no providers / no models configured → `false`
  2022. * (no capable model means the feature cannot operate).
  2023. */
  2024. function deriveSkillEvolveEnabled(
  2025. raw: Record<string, unknown>,
  2026. disableModelPrefixes: string[],
  2027. ): boolean {
  2028. if (disableModelPrefixes.length === 0) return true;
  2029. const modelIds = collectModelIds(raw);
  2030. if (modelIds.length === 0) return false;
  2031. const lowerPrefixes = disableModelPrefixes.map((p) => p.toLowerCase());
  2032. return !modelIds.every((id) =>
  2033. lowerPrefixes.some((p) => id.toLowerCase().startsWith(p)),
  2034. );
  2035. }
  2036. function parsePositiveDays(value: unknown, fallback: number): number {
  2037. return typeof value === "number" && Number.isFinite(value) && value > 0
  2038. ? value
  2039. : fallback;
  2040. }
  2041. function parseSkillEvolveConfig(
  2042. raw: Record<string, unknown>,
  2043. betaConfig: BetaConfig,
  2044. ): SkillEvolveConfig {
  2045. const defaults = DEFAULTS.skillEvolve;
  2046. const se = raw.skillEvolve;
  2047. const hasSection = se != null && typeof se === "object" && !Array.isArray(se);
  2048. const obj = hasSection
  2049. ? (se as Record<string, unknown>)
  2050. : ({} as Record<string, unknown>);
  2051. const inSessionRaw = obj.inSession;
  2052. let { inSession } = defaults;
  2053. if (
  2054. inSessionRaw != null &&
  2055. typeof inSessionRaw === "object" &&
  2056. !Array.isArray(inSessionRaw)
  2057. ) {
  2058. const ins = inSessionRaw as Record<string, unknown>;
  2059. inSession = {
  2060. N: typeof ins.N === "number" && ins.N > 0 ? ins.N : defaults.inSession.N,
  2061. minIntervalSeconds:
  2062. typeof ins.minIntervalSeconds === "number" &&
  2063. ins.minIntervalSeconds >= 0
  2064. ? ins.minIntervalSeconds
  2065. : defaults.inSession.minIntervalSeconds,
  2066. maxPendingPerSession:
  2067. typeof ins.maxPendingPerSession === "number" &&
  2068. ins.maxPendingPerSession >= 1
  2069. ? ins.maxPendingPerSession
  2070. : defaults.inSession.maxPendingPerSession,
  2071. };
  2072. }
  2073. const excludeRaw = obj.excludeAgents;
  2074. const excludeAgents =
  2075. Array.isArray(excludeRaw) && excludeRaw.every((e) => typeof e === "string")
  2076. ? (excludeRaw as string[])
  2077. : defaults.excludeAgents;
  2078. const disableModelPrefixes =
  2079. Array.isArray(obj.disableModelPrefixes) &&
  2080. obj.disableModelPrefixes.every((e: unknown) => typeof e === "string")
  2081. ? (obj.disableModelPrefixes as string[])
  2082. : defaults.disableModelPrefixes;
  2083. // `enabled` — beta gate wins first; then explicit config; then auto-derive from model list.
  2084. const enabled = !betaConfig.skillEvolve
  2085. ? false
  2086. : typeof obj.enabled === "boolean"
  2087. ? obj.enabled
  2088. : deriveSkillEvolveEnabled(raw, disableModelPrefixes);
  2089. // `builtinMrEnabled` — beta gate wins first; then explicit config; then default.
  2090. // Implicitly false when the parent `enabled` is false (no point evolving built-ins
  2091. // when the pipeline as a whole is off).
  2092. const builtinMrEnabled = !enabled
  2093. ? false
  2094. : !betaConfig.skillEvolveBuiltinMr
  2095. ? false
  2096. : typeof obj.builtinMrEnabled === "boolean"
  2097. ? obj.builtinMrEnabled
  2098. : defaults.builtinMrEnabled;
  2099. const sourceRepoRaw = obj.sourceRepo;
  2100. const sourceRepo =
  2101. typeof sourceRepoRaw === "string" && sourceRepoRaw.trim().length > 0
  2102. ? sourceRepoRaw.trim()
  2103. : defaults.sourceRepo;
  2104. // v3: `proposal` — beta gate + parent gate must both be true; otherwise
  2105. // resolved sub-config still parses but `enabled` is forced false. Other
  2106. // fields (eligibleAgents, minMessageCount, skipPassiveSessionEnd) are
  2107. // honored even when the gate is off so operators can pre-stage config.
  2108. const proposalRaw = obj.proposal;
  2109. const proposalDefaults = defaults.proposal;
  2110. const proposalObj =
  2111. proposalRaw != null &&
  2112. typeof proposalRaw === "object" &&
  2113. !Array.isArray(proposalRaw)
  2114. ? (proposalRaw as Record<string, unknown>)
  2115. : ({} as Record<string, unknown>);
  2116. const proposalEligibleAgents =
  2117. Array.isArray(proposalObj.eligibleAgents) &&
  2118. proposalObj.eligibleAgents.every((e) => typeof e === "string")
  2119. ? (proposalObj.eligibleAgents as string[])
  2120. : proposalDefaults.eligibleAgents;
  2121. const proposalMinMessageCount =
  2122. typeof proposalObj.minMessageCount === "number" &&
  2123. proposalObj.minMessageCount >= 1
  2124. ? Math.floor(proposalObj.minMessageCount)
  2125. : proposalDefaults.minMessageCount;
  2126. const proposalSkipPassiveSessionEnd =
  2127. typeof proposalObj.skipPassiveSessionEnd === "boolean"
  2128. ? proposalObj.skipPassiveSessionEnd
  2129. : proposalDefaults.skipPassiveSessionEnd;
  2130. const proposalEnabledExplicit =
  2131. typeof proposalObj.enabled === "boolean" ? proposalObj.enabled : null;
  2132. const proposalEnabled = !enabled
  2133. ? false
  2134. : !betaConfig.skillProposal
  2135. ? false
  2136. : (proposalEnabledExplicit ?? true);
  2137. // `lifecycle` — strict invariant stale < archive (fail-fast at boot).
  2138. const lcRaw = obj.lifecycle;
  2139. const lc =
  2140. lcRaw && typeof lcRaw === "object" && !Array.isArray(lcRaw)
  2141. ? (lcRaw as Record<string, unknown>)
  2142. : {};
  2143. const staleThresholdDays = parsePositiveDays(lc.staleThresholdDays, defaults.lifecycle.staleThresholdDays); // prettier-ignore
  2144. const archiveThresholdDays = parsePositiveDays(lc.archiveThresholdDays, defaults.lifecycle.archiveThresholdDays); // prettier-ignore
  2145. if (!(staleThresholdDays < archiveThresholdDays)) {
  2146. throw new Error(
  2147. `Invalid skillEvolve.lifecycle config: staleThresholdDays (${staleThresholdDays}) must be strictly less than archiveThresholdDays (${archiveThresholdDays}).`,
  2148. );
  2149. }
  2150. return {
  2151. enabled,
  2152. inSession,
  2153. signalCooldownHours:
  2154. typeof obj.signalCooldownHours === "number" && obj.signalCooldownHours > 0
  2155. ? obj.signalCooldownHours
  2156. : defaults.signalCooldownHours,
  2157. minConfidence:
  2158. typeof obj.minConfidence === "number" &&
  2159. obj.minConfidence >= 0 &&
  2160. obj.minConfidence <= 1
  2161. ? obj.minConfidence
  2162. : defaults.minConfidence,
  2163. scannerModel:
  2164. typeof obj.scannerModel === "string" ? obj.scannerModel : undefined,
  2165. excludeAgents,
  2166. disableModelPrefixes,
  2167. builtinMrEnabled,
  2168. sourceRepo,
  2169. proposal: {
  2170. enabled: proposalEnabled,
  2171. eligibleAgents: proposalEligibleAgents,
  2172. minMessageCount: proposalMinMessageCount,
  2173. skipPassiveSessionEnd: proposalSkipPassiveSessionEnd,
  2174. },
  2175. lifecycle: { staleThresholdDays, archiveThresholdDays },
  2176. };
  2177. }
  2178. /**
  2179. * v3 helper: `isProposalEligibleAgent` lives in `./skill-evolve-config.ts`
  2180. * — re-exported above with the rest of the SkillEvolve types.
  2181. */
  2182. // ── Session Rotate config parsing ───────────────────────────────
  2183. function parseSessionRotateConfig(
  2184. raw: Record<string, unknown>,
  2185. ): SessionRotateConfig {
  2186. const defaults = DEFAULTS.sessionRotate;
  2187. const sr = raw.sessionRotate;
  2188. if (sr == null || typeof sr !== "object" || Array.isArray(sr))
  2189. return { ...defaults };
  2190. const obj = sr as Record<string, unknown>;
  2191. const rawLookback = obj.activeSessionLookbackHours;
  2192. return {
  2193. enabled: typeof obj.enabled === "boolean" ? obj.enabled : defaults.enabled,
  2194. activeSessionLookbackHours:
  2195. typeof rawLookback === "number" &&
  2196. Number.isFinite(rawLookback) &&
  2197. rawLookback > 0
  2198. ? rawLookback
  2199. : defaults.activeSessionLookbackHours,
  2200. };
  2201. }
  2202. // ── AgentStop detector config parsing ───────────────────────────
  2203. function parseAgentStopDetectorConfig(
  2204. raw: Record<string, unknown>,
  2205. ): AgentStopDetectorConfig {
  2206. const defaults = DEFAULTS.agentStop;
  2207. const obj = raw.agentStop;
  2208. if (obj == null || typeof obj !== "object" || Array.isArray(obj)) {
  2209. return { ...defaults };
  2210. }
  2211. const o = obj as Record<string, unknown>;
  2212. const rawDebounce = o.debounceMs;
  2213. const rawSpan = o.maxActiveSpanMs;
  2214. // `0` is a meaningful operator opt-out for both knobs (no debounce, no
  2215. // active-span backstop). Reject negatives / non-finite values back to
  2216. // defaults so a malformed config can't silently disable the detector.
  2217. return {
  2218. debounceMs:
  2219. typeof rawDebounce === "number" &&
  2220. Number.isFinite(rawDebounce) &&
  2221. rawDebounce >= 0
  2222. ? rawDebounce
  2223. : defaults.debounceMs,
  2224. maxActiveSpanMs:
  2225. typeof rawSpan === "number" && Number.isFinite(rawSpan) && rawSpan >= 0
  2226. ? rawSpan
  2227. : defaults.maxActiveSpanMs,
  2228. };
  2229. }
  2230. export function resolvePromptConfig(obj: unknown): PromptConfig {
  2231. // The startup environment is injected after module loading; compute defaults during config parsing.
  2232. const defaultAutoUpdate =
  2233. getRuntimeBuildEnv() === "prod" && !isInternalBuild();
  2234. if (obj == null || typeof obj !== "object" || Array.isArray(obj)) {
  2235. return { autoUpdate: defaultAutoUpdate };
  2236. }
  2237. const rawAutoUpdate = (obj as Record<string, unknown>).autoUpdate;
  2238. return {
  2239. autoUpdate:
  2240. typeof rawAutoUpdate === "boolean" ? rawAutoUpdate : defaultAutoUpdate,
  2241. };
  2242. }
  2243. // ── session title config parsing ────────────────────────────────
  2244. function parseSessionTitleConfig(
  2245. raw: Record<string, unknown>,
  2246. ): SessionTitleConfig {
  2247. const defaults = DEFAULTS.sessionTitle;
  2248. const rawSessionTitle = raw.sessionTitle;
  2249. if (
  2250. rawSessionTitle == null ||
  2251. typeof rawSessionTitle !== "object" ||
  2252. Array.isArray(rawSessionTitle)
  2253. ) {
  2254. return { ...defaults };
  2255. }
  2256. const obj = rawSessionTitle as Record<string, unknown>;
  2257. return {
  2258. enabled: typeof obj.enabled === "boolean" ? obj.enabled : defaults.enabled,
  2259. };
  2260. }
  2261. // ── CLI config parsing ──────────────────────────────────────────
  2262. function parseCliConfig(raw: Record<string, unknown>): CliConfig {
  2263. const defaults = DEFAULTS.cli;
  2264. const rawCli = raw.cli;
  2265. if (rawCli == null || typeof rawCli !== "object" || Array.isArray(rawCli)) {
  2266. return { spawn: { ...defaults.spawn } };
  2267. }
  2268. const rawSpawn = (rawCli as Record<string, unknown>).spawn;
  2269. if (
  2270. rawSpawn == null ||
  2271. typeof rawSpawn !== "object" ||
  2272. Array.isArray(rawSpawn)
  2273. ) {
  2274. return { spawn: { ...defaults.spawn } };
  2275. }
  2276. const spawnObj = rawSpawn as Record<string, unknown>;
  2277. return {
  2278. spawn: {
  2279. enabled:
  2280. typeof spawnObj.enabled === "boolean"
  2281. ? spawnObj.enabled
  2282. : defaults.spawn.enabled,
  2283. },
  2284. };
  2285. }
  2286. // ── Context Management config parsing ───────────────────────────
  2287. function parseContextManagementConfig(
  2288. raw: Record<string, unknown>,
  2289. ): ContextManagementConfig {
  2290. const defaults = DEFAULTS.contextManagement;
  2291. const rawCm = raw.contextManagement;
  2292. if (rawCm == null || typeof rawCm !== "object" || Array.isArray(rawCm)) {
  2293. return {
  2294. disableSystemReminderModels: [...defaults.disableSystemReminderModels],
  2295. cuMaxScreenshotsInContext: defaults.cuMaxScreenshotsInContext,
  2296. };
  2297. }
  2298. const obj = rawCm as Record<string, unknown>;
  2299. const rawList = obj.disableSystemReminderModels;
  2300. const disableSystemReminderModels =
  2301. Array.isArray(rawList) &&
  2302. rawList.every((e) => typeof e === "string" && e.length > 0)
  2303. ? (rawList as string[])
  2304. : [...defaults.disableSystemReminderModels];
  2305. const rawCuMax = obj.cuMaxScreenshotsInContext;
  2306. const cuMaxScreenshotsInContext =
  2307. typeof rawCuMax === "number" && Number.isFinite(rawCuMax) && rawCuMax >= 0
  2308. ? Math.floor(rawCuMax)
  2309. : defaults.cuMaxScreenshotsInContext;
  2310. return { disableSystemReminderModels, cuMaxScreenshotsInContext };
  2311. }
  2312. // ── Agent Runtime config parsing — see ./agent-runtime-config.ts for the
  2313. // canonical implementation. Re-exposed here so the public `getConfig()`
  2314. // surface keeps a single import point for callers; the helper is the
  2315. // source of truth for the `AgentRuntimeFramework` string union and the
  2316. // Pi-only runtime selection parser.
  2317. // ── Log Retention config parsing ────────────────────────────────
  2318. function parseLogRetentionDays(raw: Record<string, unknown>): number {
  2319. const val = raw.logRetentionDays;
  2320. if (typeof val === "number" && val >= 1 && Number.isFinite(val)) {
  2321. return Math.floor(val);
  2322. }
  2323. return DEFAULTS.logRetentionDays;
  2324. }
  2325. // ── Content Review config parsing ───────────────────────────────
  2326. function parseContentReviewConfig(
  2327. raw: Record<string, unknown>,
  2328. ): { enabled?: boolean; testBaseURL?: string } | undefined {
  2329. const obj = raw.contentReview;
  2330. if (obj == null || typeof obj !== "object" || Array.isArray(obj))
  2331. return undefined;
  2332. const result: { enabled?: boolean; testBaseURL?: string } = {};
  2333. const enabled = Reflect.get(obj, "enabled");
  2334. if (typeof enabled === "boolean") result.enabled = enabled;
  2335. const testBaseURL = Reflect.get(obj, "testBaseURL");
  2336. if (typeof testBaseURL === "string" && testBaseURL.trim()) {
  2337. result.testBaseURL = testBaseURL.trim();
  2338. }
  2339. return Object.keys(result).length > 0 ? result : undefined;
  2340. }
  2341. // ── MCP tool-search config parsing ──────────────────────────────
  2342. function parseMcpToolSearchConfig(
  2343. raw: Record<string, unknown>,
  2344. ): McpToolSearchConfig | undefined {
  2345. const obj = raw.mcpToolSearch;
  2346. if (obj == null || typeof obj !== "object" || Array.isArray(obj))
  2347. return undefined;
  2348. const result: McpToolSearchConfig = {};
  2349. const enabled = Reflect.get(obj, "enabled");
  2350. if (typeof enabled === "boolean") result.enabled = enabled;
  2351. const systemHint = Reflect.get(obj, "systemHint");
  2352. if (typeof systemHint === "boolean") result.systemHint = systemHint;
  2353. const thresholdPct = Reflect.get(obj, "thresholdPct");
  2354. if (typeof thresholdPct === "number") result.thresholdPct = thresholdPct;
  2355. const minDeferCount = Reflect.get(obj, "minDeferCount");
  2356. if (typeof minDeferCount === "number") result.minDeferCount = minDeferCount;
  2357. const topKDefault = Reflect.get(obj, "topKDefault");
  2358. if (typeof topKDefault === "number") result.topKDefault = topKDefault;
  2359. const topKMax = Reflect.get(obj, "topKMax");
  2360. if (typeof topKMax === "number") result.topKMax = topKMax;
  2361. const maxSchemaTextLen = Reflect.get(obj, "maxSchemaTextLen");
  2362. if (typeof maxSchemaTextLen === "number")
  2363. result.maxSchemaTextLen = maxSchemaTextLen;
  2364. const modelWhitelist = Reflect.get(obj, "modelWhitelist");
  2365. if (Array.isArray(modelWhitelist)) {
  2366. result.modelWhitelist = modelWhitelist.filter(
  2367. (v): v is string => typeof v === "string",
  2368. );
  2369. }
  2370. return Object.keys(result).length > 0 ? result : undefined;
  2371. }
  2372. // ---------------------------------------------------------------------------
  2373. // Port resolution — compute the target local runtime port from env / git / defaults
  2374. // ---------------------------------------------------------------------------
  2375. /**
  2376. * Resolve the target local runtime port.
  2377. *
  2378. * Priority:
  2379. * 0. DISABLE_GIT_AUTO_CONFIG=1 → skip git auto-detection
  2380. * 1. Explicit profile-scoped port (__MAVIS_RUNTIME_PROFILE + __MAVIS_RUNTIME_PORT both set)
  2381. * 2. Git auto-detection (hash-based offset from branch name in mavis repo)
  2382. * 3. __MAVIS_RUNTIME_PORT env var (only when git detection is not active)
  2383. * 4. DEFAULT_PORT (5321)
  2384. *
  2385. * Not cached — env vars and git state can change between calls.
  2386. */
  2387. export function resolvePort(): number {
  2388. const explicitPort = getExplicitPortEnv();
  2389. if (shouldUseGitAutoConfig() && !shouldPreferExplicitPort()) {
  2390. const gitInfo = detectGitPortInfo();
  2391. if (gitInfo.autoDetected) {
  2392. return gitInfo.runtimePort;
  2393. }
  2394. }
  2395. return explicitPort ?? DEFAULT_PORT;
  2396. }
  2397. /**
  2398. * Legacy OpenCode listens on a dedicated offset above the runtime port range.
  2399. * New sessions do not use this; existing daemon callers still compile against it.
  2400. */
  2401. export function getOpenCodePort(runtimePort = resolvePort()): number {
  2402. const preferredPort = runtimePort + OPENCODE_PORT_OFFSET;
  2403. if (preferredPort <= MAX_TCP_PORT) {
  2404. return preferredPort;
  2405. }
  2406. const fallbackPort = runtimePort + OPENCODE_FALLBACK_OFFSET;
  2407. if (fallbackPort <= MAX_TCP_PORT) {
  2408. return fallbackPort;
  2409. }
  2410. throw new Error(
  2411. `Cannot allocate an OpenCode sidecar port for runtime port ${String(runtimePort)}; choose a runtime port <= ${String(MAX_TCP_PORT - OPENCODE_FALLBACK_OFFSET)}.`,
  2412. );
  2413. }