control-state.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import type * as acp from '@agentclientprotocol/sdk';
  2. import {
  3. formatTuiPermissionMode,
  4. MINIMAX_CODE_PERMISSION_MODES,
  5. type TuiPermissionMode,
  6. } from '../application/permission-mode.js';
  7. import type { TuiModel, TuiSession, TuiSessionUsage } from '../runtime/port.js';
  8. import { modelSupportsVariant } from './model-selection.js';
  9. import type { TuiAcpRuntime } from './runtime.js';
  10. export const ACP_MODE_DEFAULT = 'default';
  11. export const ACP_MODE_PLAN = 'plan';
  12. export const ACP_CONFIG_PERMISSION_MODE = 'permissionMode';
  13. export const ACP_CONFIG_MODEL = 'model';
  14. export const ACP_CONFIG_THINKING_EFFORT = 'thinkingEffort';
  15. export interface TuiAcpSessionControlState {
  16. readonly modes: acp.SessionModeState;
  17. readonly configOptions: acp.SessionConfigOption[];
  18. }
  19. export async function getTuiAcpSessionControlState(
  20. runtime: TuiAcpRuntime,
  21. session: TuiSession,
  22. ): Promise<TuiAcpSessionControlState> {
  23. const [planCapabilities, permissionMode, models] = await Promise.all([
  24. runtime.getPlanModeCapabilities().catch(() => ({ entryEnabled: false })),
  25. runtime.getPermissionMode().catch(() => undefined),
  26. runtime.listModels(session.sessionId).catch(() => [] as TuiModel[]),
  27. ]);
  28. return {
  29. modes: modeState(session, planCapabilities.entryEnabled),
  30. configOptions: configOptions(session, permissionMode, models),
  31. };
  32. }
  33. export function modeState(session: TuiSession, planEntryEnabled = true): acp.SessionModeState {
  34. return {
  35. currentModeId: session.interactionMode === 'plan' ? ACP_MODE_PLAN : ACP_MODE_DEFAULT,
  36. availableModes: [
  37. {
  38. id: ACP_MODE_DEFAULT,
  39. name: 'Default',
  40. description: 'Work normally with the configured tools and permission policy.',
  41. },
  42. ...(planEntryEnabled || session.interactionMode === 'plan'
  43. ? [
  44. {
  45. id: ACP_MODE_PLAN,
  46. name: 'Plan',
  47. description: 'Research and prepare an implementation plan before making changes.',
  48. },
  49. ]
  50. : []),
  51. ],
  52. };
  53. }
  54. export function configOptions(
  55. session: TuiSession,
  56. permissionMode: TuiPermissionMode | undefined,
  57. models: readonly TuiModel[],
  58. ): acp.SessionConfigOption[] {
  59. const options: acp.SessionConfigOption[] = [];
  60. const permissionOption = permissionModeOption(permissionMode);
  61. if (permissionOption) options.push(permissionOption);
  62. const modelOption = sessionModelOption(session, models);
  63. if (modelOption) options.push(modelOption);
  64. const effortOption = thinkingEffortOption(session, models);
  65. if (effortOption) options.push(effortOption);
  66. return options;
  67. }
  68. export function parseModelConfigValue(value: string): {
  69. providerId: string;
  70. modelId: string;
  71. variant?: string;
  72. } {
  73. const [prefix, provider, model, variantKind, variant, ...extra] = value.split(':');
  74. if (
  75. prefix !== 'm' ||
  76. !provider ||
  77. !model ||
  78. (variantKind !== 'u' && variantKind !== 'v') ||
  79. (variantKind === 'u' && variant !== undefined) ||
  80. (variantKind === 'v' && variant === undefined) ||
  81. extra.length > 0
  82. ) {
  83. throw new Error(`Invalid model config value: ${value}`);
  84. }
  85. return {
  86. providerId: decodeURIComponent(provider),
  87. modelId: decodeURIComponent(model),
  88. ...(variantKind === 'v' ? { variant: decodeURIComponent(variant ?? '') } : {}),
  89. };
  90. }
  91. export function modelConfigValue(selection: {
  92. readonly providerId: string;
  93. readonly modelId: string;
  94. readonly variant?: string;
  95. }): string {
  96. const prefix = [
  97. 'm',
  98. encodeURIComponent(selection.providerId),
  99. encodeURIComponent(selection.modelId),
  100. ];
  101. return selection.variant === undefined
  102. ? [...prefix, 'u'].join(':')
  103. : [...prefix, 'v', encodeURIComponent(selection.variant)].join(':');
  104. }
  105. export function usageUpdate(
  106. snapshot: Awaited<ReturnType<TuiAcpRuntime['getContextSnapshot']>>,
  107. usage: TuiSessionUsage,
  108. ): acp.UsageUpdate | undefined {
  109. const context = snapshot.contextUsage;
  110. if (!context || context.contextWindowTokens <= 0) return undefined;
  111. const costUsd = usage.summary?.costUsd;
  112. return {
  113. used: context.usedTokens,
  114. size: context.contextWindowTokens,
  115. ...(costUsd === undefined
  116. ? {}
  117. : {
  118. cost: {
  119. amount: costUsd,
  120. currency: 'USD',
  121. },
  122. }),
  123. };
  124. }
  125. function permissionModeOption(
  126. permissionMode: TuiPermissionMode | undefined,
  127. ): acp.SessionConfigOption | undefined {
  128. const current = MINIMAX_CODE_PERMISSION_MODES.find((mode) => mode === permissionMode);
  129. if (!current) return undefined;
  130. return {
  131. type: 'select',
  132. id: ACP_CONFIG_PERMISSION_MODE,
  133. name: 'Permission mode',
  134. description: 'Controls how MiniMax Code handles tool permission requests in this process.',
  135. category: '_permission',
  136. currentValue: current,
  137. options: MINIMAX_CODE_PERMISSION_MODES.map((mode) => ({
  138. value: mode,
  139. name: formatTuiPermissionMode(mode),
  140. })),
  141. _meta: { 'minimax-code/scope': 'process' },
  142. };
  143. }
  144. function sessionModelOption(
  145. session: TuiSession,
  146. models: readonly TuiModel[],
  147. ): acp.SessionConfigOption | undefined {
  148. const values = uniqueModelValues(models);
  149. if (values.length === 0) return undefined;
  150. const persistedSelection = selectedModel(session, models);
  151. if (
  152. persistedSelection &&
  153. !values.some(
  154. ({ selection }) => modelConfigValue(selection) === modelConfigValue(persistedSelection),
  155. )
  156. ) {
  157. return undefined;
  158. }
  159. const selected = persistedSelection ?? values[0]?.selection;
  160. if (!selected) return undefined;
  161. return {
  162. type: 'select',
  163. id: ACP_CONFIG_MODEL,
  164. name: 'Model',
  165. description: 'Selects the model used by subsequent turns in this Session.',
  166. category: 'model',
  167. currentValue: modelConfigValue(selected),
  168. options: values.map(({ selection, name }) => ({
  169. value: modelConfigValue(selection),
  170. name,
  171. })),
  172. };
  173. }
  174. function thinkingEffortOption(
  175. session: TuiSession,
  176. models: readonly TuiModel[],
  177. ): acp.SessionConfigOption | undefined {
  178. const selected = selectedModel(session, models);
  179. if (!selected) return undefined;
  180. const model = models.find(
  181. (candidate) =>
  182. candidate.providerId === selected.providerId &&
  183. candidate.modelId === selected.modelId &&
  184. modelSupportsVariant(candidate, selected.variant),
  185. );
  186. const efforts = model?.effortOptions ?? [];
  187. if (efforts.length === 0) return undefined;
  188. const persistedEffort = session.model?.thinking?.effort;
  189. if (persistedEffort && !efforts.includes(persistedEffort)) return undefined;
  190. const configuredDefault = model?.thinkingConfig?.defaultValue;
  191. const current =
  192. persistedEffort ??
  193. (configuredDefault && efforts.includes(configuredDefault) ? configuredDefault : efforts[0]);
  194. if (!current) return undefined;
  195. return {
  196. type: 'select',
  197. id: ACP_CONFIG_THINKING_EFFORT,
  198. name: 'Thinking effort',
  199. description: 'Controls the reasoning effort for the selected model in this Session.',
  200. category: 'thought_level',
  201. currentValue: current,
  202. options: efforts.map((effort) => ({ value: effort, name: labelEffort(effort) })),
  203. };
  204. }
  205. function uniqueModelValues(models: readonly TuiModel[]): Array<{
  206. readonly selection: {
  207. readonly providerId: string;
  208. readonly modelId: string;
  209. readonly variant?: string;
  210. };
  211. readonly name: string;
  212. }> {
  213. const seen = new Set<string>();
  214. const values = [];
  215. for (const model of models) {
  216. const variants = model.supportedVariants?.length
  217. ? model.supportedVariants
  218. : [model.variant].filter((variant): variant is string => variant !== undefined);
  219. const selections: Array<{ providerId: string; modelId: string; variant?: string }> =
  220. variants.length > 0
  221. ? variants.map((variant) => ({
  222. providerId: model.providerId,
  223. modelId: model.modelId,
  224. variant,
  225. }))
  226. : [{ providerId: model.providerId, modelId: model.modelId }];
  227. for (const selection of selections) {
  228. const value = modelConfigValue(selection);
  229. if (seen.has(value)) continue;
  230. seen.add(value);
  231. values.push({
  232. selection,
  233. name: `${model.displayName ?? model.modelId}${selection.variant ? ` · ${selection.variant}` : ''}`,
  234. });
  235. }
  236. }
  237. return values;
  238. }
  239. function selectedModel(
  240. session: TuiSession,
  241. models: readonly TuiModel[],
  242. ): { providerId: string; modelId: string; variant?: string } | undefined {
  243. if (session.model?.providerId && session.model.modelId) {
  244. return {
  245. providerId: session.model.providerId,
  246. modelId: session.model.modelId,
  247. ...(session.model.variant !== undefined ? { variant: session.model.variant } : {}),
  248. };
  249. }
  250. const selected = models.find((model) => model.selected);
  251. return selected
  252. ? {
  253. providerId: selected.providerId,
  254. modelId: selected.modelId,
  255. ...(selected.variant !== undefined ? { variant: selected.variant } : {}),
  256. }
  257. : undefined;
  258. }
  259. function labelEffort(value: string): string {
  260. return value.length > 0 ? `${value.slice(0, 1).toUpperCase()}${value.slice(1)}` : value;
  261. }