contracts.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import type { Api } from '@earendil-works/pi-ai';
  2. import type { StreamFn } from '@earendil-works/pi-agent-core';
  3. import type { LLMModelConfig } from '@mavis/agent-core/pi-turn-runner';
  4. import type {
  5. AgentCapabilityConfig,
  6. Config,
  7. LocalByokConfigDraft,
  8. ModelConfig,
  9. ProviderAuthMode,
  10. ResolvedAgentCapabilities,
  11. } from '@mavis/config';
  12. import type { IAgentConfig } from '@mavis/protocol';
  13. import type { ModelProviderApi, ModelProviderSource } from './identity.js';
  14. export type { LocalByokConfigDraft };
  15. export type { ModelProviderSource } from './identity.js';
  16. type LocalModelLimit = Partial<NonNullable<ModelConfig['limit']>>;
  17. type LocalModelModalities = Partial<NonNullable<ModelConfig['modalities']>>;
  18. type LocalModelCapabilities = Partial<NonNullable<ModelConfig['capabilities']>>;
  19. /**
  20. * Protocol compatibility overrides a BYOK custom provider may declare per model.
  21. *
  22. * Pi auto-detects these from `provider` and `baseUrl`. A gateway that forwards an
  23. * upstream vendor under its own provider id and host masks that identity, so every
  24. * fingerprint misses and the detected defaults describe the wrong upstream. These
  25. * overrides let the provider config state the upstream's real protocol surface; pi
  26. * applies each declared field ahead of its own detection.
  27. */
  28. export interface LocalModelCompatOverrides {
  29. supportsStore?: boolean;
  30. supportsDeveloperRole?: boolean;
  31. supportsReasoningEffort?: boolean;
  32. supportsUsageInStreaming?: boolean;
  33. requiresToolResultName?: boolean;
  34. requiresAssistantAfterToolResult?: boolean;
  35. requiresThinkingAsText?: boolean;
  36. requiresReasoningContentOnAssistantMessages?: boolean;
  37. supportsStrictMode?: boolean;
  38. supportsLongCacheRetention?: boolean;
  39. supportsEagerToolInputStreaming?: boolean;
  40. supportsCacheControlOnTools?: boolean;
  41. supportsTemperature?: boolean;
  42. sendSessionAffinityHeaders?: boolean;
  43. sendSessionIdHeader?: boolean;
  44. zaiToolStream?: boolean;
  45. forceAdaptiveThinking?: boolean;
  46. allowEmptySignature?: boolean;
  47. maxTokensField?: 'max_tokens' | 'max_completion_tokens';
  48. thinkingFormat?:
  49. | 'openai'
  50. | 'openrouter'
  51. | 'together'
  52. | 'deepseek'
  53. | 'zai'
  54. | 'qwen'
  55. | 'qwen-chat-template'
  56. | 'string-thinking'
  57. | 'ant-ling';
  58. cacheControlFormat?: 'anthropic';
  59. }
  60. export interface LocalModelConfig extends Omit<
  61. Partial<ModelConfig>,
  62. 'limit' | 'modalities' | 'capabilities'
  63. > {
  64. reasoning?: boolean;
  65. capabilities?: LocalModelCapabilities;
  66. limit?: LocalModelLimit;
  67. modalities?: LocalModelModalities;
  68. compat?: LocalModelCompatOverrides;
  69. }
  70. export interface LocalProviderOptions {
  71. apiKey?: string;
  72. baseURL?: string;
  73. authMode?: ProviderAuthMode;
  74. headers?: Record<string, string>;
  75. [key: string]: unknown;
  76. }
  77. export interface LocalProviderConfig {
  78. name?: string;
  79. api?: string;
  80. options?: LocalProviderOptions;
  81. models?: Record<string, LocalModelConfig>;
  82. model_order?: string[];
  83. }
  84. export type LocalModelsConfig = Record<string, LocalProviderConfig>;
  85. export interface LocalMinimaxApiConfig {
  86. apiKey?: string;
  87. baseURL?: string;
  88. modelContextLimits?: Record<string, number>;
  89. }
  90. export interface LocalCustomProviderConfig extends LocalProviderConfig {
  91. kind?: string;
  92. npm?: string;
  93. enabled?: boolean;
  94. }
  95. export type LocalCustomProvidersConfig = Record<string, LocalCustomProviderConfig>;
  96. export type LocalBetaConfig = Partial<Config['beta']>;
  97. /** Model configuration read by the resolution and management capabilities. */
  98. export interface LocalRuntimeConfig {
  99. provider: LocalModelsConfig;
  100. minimax_api?: LocalMinimaxApiConfig;
  101. custom_provider?: LocalCustomProvidersConfig;
  102. minimaxModelSource?: 'token_plan' | 'minimax_api_key';
  103. defaultModel?: string;
  104. defaultModelVariant?: string;
  105. defaultModelThinking?: { effort?: string };
  106. defaultModelContextWindow?: number;
  107. permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'auto' | 'off';
  108. dataDir: string;
  109. beta?: LocalBetaConfig;
  110. }
  111. /** Conversation-owned read model of the process config. */
  112. export interface LocalConversationRuntimeConfig extends LocalRuntimeConfig {
  113. readonly defaultLightModel?: string;
  114. /** Goal verifier policy consumed by process-local auxiliary model calls. */
  115. readonly goal?: Config['goal'];
  116. readonly memory?: Partial<Config['memory']>;
  117. /** Session title auto-generation flag — see @mavis/config SessionTitleConfig. */
  118. readonly sessionTitle?: Config['sessionTitle'];
  119. /** Runaway Guard local policy resolved from config.yaml. */
  120. readonly runawayGuard?: Config['runawayGuard'];
  121. /** ToolResult compaction values resolved from config.yaml. */
  122. readonly toolResultCompaction?: Config['toolResultCompaction'];
  123. /**
  124. * Widened past `Config['agents']`: the v2 Agent cutover also threads
  125. * already-resolved capabilities through this read model, and `default` is
  126. * absent until the config supplies it.
  127. */
  128. readonly agents?: {
  129. readonly default?: AgentCapabilityConfig | ResolvedAgentCapabilities;
  130. };
  131. readonly mcpToolSearch?: {
  132. readonly enabled?: boolean;
  133. readonly modelWhitelist?: readonly string[];
  134. readonly thresholdPct?: number;
  135. readonly minDeferCount?: number;
  136. readonly topKDefault?: number;
  137. readonly topKMax?: number;
  138. readonly systemHint?: boolean;
  139. readonly maxSchemaTextLen?: number;
  140. };
  141. }
  142. /** One profile-bound read/write authority for all Model System configuration. */
  143. export interface ModelSystemConfigPort {
  144. readonly read: () => LocalRuntimeConfig;
  145. readonly updateByok: (
  146. mutate: (
  147. draft: LocalByokConfigDraft,
  148. currentConfig: LocalRuntimeConfig,
  149. ) => void | Promise<void>,
  150. ) => Promise<unknown>;
  151. readonly compareAndSetModelContext: (
  152. input: {
  153. readonly providerId: string;
  154. readonly modelId: string;
  155. readonly expectedContextLimit: number;
  156. readonly contextLimit: number;
  157. },
  158. beforeCommit: (currentConfig: LocalRuntimeConfig) => Promise<boolean>,
  159. ) => Promise<boolean>;
  160. readonly setDefaultModel: (
  161. modelKey: string,
  162. variant?: string,
  163. selection?: {
  164. readonly contextLimit?: number;
  165. readonly thinking?: { readonly effort?: string };
  166. },
  167. ) => Promise<void>;
  168. readonly removeProvider: (providerId: string) => Promise<unknown>;
  169. }
  170. /** Live local-runtime identity used by managed model and content-safety requests. */
  171. export interface LocalRuntimeAuthContext {
  172. readonly accessToken?: string;
  173. readonly loginEpoch?: string;
  174. readonly realUserID?: string;
  175. readonly userEmail?: string;
  176. readonly userName?: string;
  177. readonly subUserName?: string;
  178. /** Electron-internal propagation state; omitted by non-Desktop hosts. */
  179. readonly authState?: 'pending' | 'authenticated' | 'logged_out';
  180. }
  181. export interface LocalByokProviderConfig {
  182. readonly minimax_api?: LocalMinimaxApiConfig;
  183. readonly custom_provider?: LocalCustomProvidersConfig;
  184. readonly minimaxModelSource?: 'token_plan' | 'minimax_api_key';
  185. }
  186. export interface LocalModelResolverLogger {
  187. info(fields: Readonly<Record<string, unknown>>, message: string): void;
  188. warn(fields: Readonly<Record<string, unknown>>, message: string): void;
  189. }
  190. export interface LocalModelResolverOptions {
  191. readonly providerConfig?: LocalModelsConfig;
  192. readonly providerConfigGetter?: () => LocalModelsConfig;
  193. readonly byokConfigGetter?: () => LocalByokProviderConfig | undefined;
  194. readonly authContextGetter?: () => LocalRuntimeAuthContext | undefined;
  195. /** Owner-side generation-aware recovery for a rejected managed OAuth request. */
  196. readonly authContextInvalidator?: (
  197. rejectedAccessToken?: string,
  198. loginEpoch?: string,
  199. ) => void | Promise<void>;
  200. readonly routingContextGetter?: () =>
  201. | import('@mavis/agent-tools/desktop').ManagedBackendRoutingContext
  202. | undefined;
  203. readonly providerAuthGetter?: (
  204. provider: string,
  205. ) => Promise<string | undefined> | string | undefined;
  206. readonly defaultApi?: Api;
  207. readonly streamFn?: StreamFn;
  208. readonly fetchImpl?: LLMModelConfig['fetch'];
  209. readonly logger?: LocalModelResolverLogger;
  210. /** Enables metadata-free custom-provider thinking only for the new TUI product. */
  211. readonly implicitCustomProviderThinking?: boolean;
  212. }
  213. export interface LocalModelResolveInput {
  214. readonly sessionId: string;
  215. readonly turnId: string;
  216. readonly agentConfig: IAgentConfig;
  217. }
  218. export interface LocalResolvedModelConfig extends LLMModelConfig {
  219. /** Final resolved ModelRef capability for OpenAI-compatible JSON object output. */
  220. readonly supportsJsonObjectOutput?: boolean;
  221. /** Provider-specific payload fields that preserve explicit Thinking Off on the wire. */
  222. readonly thinkingRequestPatch?: Readonly<Record<string, unknown>>;
  223. /** True only for the platform-owned Token Plan / Credits inference path. */
  224. readonly managedProvider?: boolean;
  225. /** Selected Model byte authority for Local Serialized Footprint admission; not wire-exact. */
  226. readonly maxRequestBodyBytes?: number;
  227. /** Managed-login File API transport identity; absent for every BYOK route. */
  228. readonly fileApiGatewayAuth?: {
  229. readonly gatewayHeaders: Readonly<Record<string, string>>;
  230. readonly callerIdentityHash: string;
  231. };
  232. }
  233. export interface LocalModelResolverLike {
  234. resolveModel(input: LocalModelResolveInput): Promise<LocalResolvedModelConfig>;
  235. }
  236. export type MiniMaxM3ThinkingMode = 'on' | 'off';
  237. export type ModelProviderTestApi = ModelProviderApi;
  238. export type ModelCacheState = 'unknown' | 'available' | 'failed';
  239. export interface ModelCacheStatusEntry {
  240. state: ModelCacheState;
  241. /** Unix ms (repo rule: never ISO strings in storage). */
  242. last_tested_at?: number;
  243. last_error_code?: string;
  244. last_error_message?: string;
  245. /** SHA-256 of the effective provider + model request configuration. */
  246. config_fingerprint?: string;
  247. }
  248. export interface ModelCacheData {
  249. version: 3;
  250. provider_status: Record<string, ModelCacheStatusEntry>;
  251. model_status: Record<string, ModelCacheStatusEntry>;
  252. }
  253. export interface LocalModelCacheLike {
  254. load(): ModelCacheData;
  255. setProviderStatus(providerId: string, entry: ModelCacheStatusEntry): Promise<void>;
  256. setModelStatus(modelKey: string, entry: ModelCacheStatusEntry): Promise<void>;
  257. replaceModelStatus(
  258. modelKey: string,
  259. entry: ModelCacheStatusEntry,
  260. ): Promise<ModelCacheStatusEntry | undefined>;
  261. restoreModelStatusIfCurrent(
  262. modelKey: string,
  263. expectedCurrent: ModelCacheStatusEntry,
  264. previous: ModelCacheStatusEntry | undefined,
  265. ): Promise<boolean>;
  266. removeModelStatus(modelKey: string): Promise<void>;
  267. removeProvider(providerId: string): Promise<void>;
  268. }
  269. export interface ModelCacheStatusView {
  270. state: string;
  271. lastTestedAt?: number;
  272. lastErrorCode?: string;
  273. lastErrorMessage?: string;
  274. }
  275. export type ModelProviderKind = 'minimax-managed' | 'minimax-api-key' | 'oauth' | 'custom';
  276. export interface ModelThinkingConfigView {
  277. mode: 'switchable' | 'forced_on' | 'forced_off' | 'hidden';
  278. default_value?: 'true' | 'false';
  279. }
  280. export interface ModelProviderModelEntry {
  281. providerId: string;
  282. modelId: string;
  283. modelConfigId: string;
  284. displayName: string;
  285. configurationSource?: 'manual' | 'discovered';
  286. enabled: boolean;
  287. selected: boolean;
  288. contextLimit?: number;
  289. defaultContextLimit?: number;
  290. thinking?: { effort?: string };
  291. contextWindowOptions?: number[];
  292. contextWindowOptionHints?: Record<string, 'higher_usage'>;
  293. maxOutputTokens?: number;
  294. effortOptions?: string[];
  295. defaultEffort?: string;
  296. supportedVariants?: string[];
  297. thinkingConfig?: ModelThinkingConfigView;
  298. variant?: string;
  299. providerSource: ModelProviderSource;
  300. providerKind: ModelProviderKind;
  301. providerName: string;
  302. apiFormat?: string;
  303. modalities?: { input?: string[]; output?: string[] };
  304. status?: ModelCacheStatusView;
  305. }
  306. export interface ModelProviderView {
  307. providerId: string;
  308. name: string;
  309. source: ModelProviderSource;
  310. kind: ModelProviderKind;
  311. enabled: boolean;
  312. baseUrl?: string;
  313. apiFormat?: string;
  314. hasApiKey: boolean;
  315. maskedApiKey?: string;
  316. headerNames?: string[];
  317. configRevision?: string;
  318. models: ModelProviderModelEntry[];
  319. status?: ModelCacheStatusView;
  320. }
  321. export interface ModelDiscoveryTarget {
  322. api: ModelProviderApi;
  323. baseUrl: string;
  324. apiKey: string;
  325. headers?: Record<string, string>;
  326. }
  327. export interface DiscoveredModel {
  328. modelId: string;
  329. displayName?: string;
  330. }
  331. export type ModelDiscoveryResult =
  332. | { ok: true; models: DiscoveredModel[] }
  333. | { ok: false; errorCode: string; errorMessage: string };
  334. export interface ModelDiscoveryClientLike {
  335. discover(target: ModelDiscoveryTarget): Promise<ModelDiscoveryResult>;
  336. }
  337. export interface ModelConnectionTestTarget {
  338. api: ModelProviderTestApi;
  339. baseUrl: string;
  340. apiKey: string;
  341. modelId: string;
  342. headers?: Record<string, string>;
  343. effort?: string;
  344. minimaxM3ThinkingMode?: MiniMaxM3ThinkingMode;
  345. /**
  346. * Output budget the probe requests, taken from the model's configured output
  347. * limit. Mirrors what a real turn sends so an output-budget rejection can
  348. * never be the reason a working model reports as unavailable.
  349. */
  350. outputLimit?: number;
  351. }
  352. export interface ModelConnectionTestResult {
  353. ok: boolean;
  354. errorCode?: string;
  355. errorMessage?: string;
  356. }
  357. export class LocalModelProviderError extends Error {
  358. override name = 'LocalModelProviderError';
  359. constructor(
  360. readonly status: number,
  361. message: string,
  362. readonly code: string,
  363. ) {
  364. super(message);
  365. }
  366. }
  367. export interface UserModelInputView {
  368. modelId: string;
  369. displayName?: string;
  370. configurationSource?: string;
  371. enabled?: boolean;
  372. attachment?: boolean;
  373. reasoning?: boolean;
  374. toolCall?: boolean;
  375. temperature?: boolean;
  376. capabilities?: LocalModelConfig['capabilities'];
  377. modalities?: { input?: string[]; output?: string[] };
  378. limit?: { context?: number; output?: number };
  379. thinkingConfig?: { mode?: string; defaultValue?: string };
  380. effortOptions?: string[];
  381. }
  382. export interface ByokProviderPresetView {
  383. providerId: string;
  384. name: string;
  385. baseUrl: string;
  386. apiFormat: ModelProviderApi;
  387. models: UserModelInputView[];
  388. iconUrl?: string;
  389. }
  390. export interface ModelProviderTestOutcome {
  391. ok: boolean;
  392. status: ModelCacheStatusView;
  393. }
  394. export interface UserModelProviderCandidateView {
  395. providerId?: string;
  396. expectedRevision?: string;
  397. name?: string;
  398. baseUrl: string;
  399. apiKey?: string;
  400. apiFormat?: string;
  401. models?: UserModelInputView[];
  402. headers?: Record<string, string>;
  403. removeHeaders?: string[];
  404. }
  405. export interface SaveUserModelProviderCandidateOutcome {
  406. ok: boolean;
  407. status?: ModelCacheStatusView;
  408. skippedTest?: boolean;
  409. provider?: ModelProviderView;
  410. }
  411. export interface ModelContextUpdateOutcome {
  412. ok: boolean;
  413. status?: ModelCacheStatusView;
  414. }
  415. export interface LocalModelProviderServiceDeps {
  416. configGetter: () => LocalRuntimeConfig;
  417. updateByokConfig: (
  418. mutate: (
  419. draft: LocalByokConfigDraft,
  420. currentConfig: LocalRuntimeConfig,
  421. ) => void | Promise<void>,
  422. ) => Promise<unknown>;
  423. cache: LocalModelCacheLike;
  424. tester: {
  425. test(dedupKey: string, target: ModelConnectionTestTarget): Promise<ModelConnectionTestResult>;
  426. };
  427. discoverer?: ModelDiscoveryClientLike;
  428. compareAndSetModelContext?: (
  429. input: {
  430. providerId: string;
  431. modelId: string;
  432. expectedContextLimit: number;
  433. contextLimit: number;
  434. },
  435. beforeCommit: (currentConfig: LocalRuntimeConfig) => Promise<boolean>,
  436. ) => Promise<boolean>;
  437. removeProviderCredentials?: (providerKey: string) => void | Promise<void>;
  438. selectModel: (modelKey: string) => Promise<void>;
  439. now?: () => number;
  440. randomHex?: () => string;
  441. /** Enables metadata-free thinking defaults only for the new TUI product. */
  442. implicitCustomProviderThinking?: boolean;
  443. }