adapter.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. import type {
  2. AbortSessionReq,
  3. CliSendMessageReq,
  4. CliSendMessageOptions,
  5. CliService,
  6. ConversationSteerInput,
  7. ConversationSteerResult,
  8. } from "@mavis/local-runtime-v2/cli-service";
  9. import { MINIMAX_CODE_DEFAULT_AGENT_NAME } from "../product-context.js";
  10. import { TuiEventAccess } from "./adapters/event-access.js";
  11. import { TuiRuntimeAccessContext } from "./adapters/access-context.js";
  12. import { TuiWorkspaceAccess } from "./adapters/workspace-access.js";
  13. import { TuiSessionAccess } from "./adapters/session-access.js";
  14. import { TuiProductAccess } from "./adapters/product-access.js";
  15. import { TuiInteractionAccess } from "./adapters/interaction-access.js";
  16. import { TuiDelegationAccess } from "./adapters/delegation-access.js";
  17. import { TuiConversationAccess } from "./adapters/conversation-access.js";
  18. import { TuiPluginAccess } from "./adapters/plugin-access.js";
  19. import { TuiGoalAccess } from "./adapters/goal-access.js";
  20. import type { TuiMessage, TuiStreamEvent } from "./stream-events.js";
  21. import type {
  22. CreateTuiSessionInput,
  23. EnqueueTuiMessageOptions,
  24. ForkTuiSessionInput,
  25. ListTuiSessionPageInput,
  26. ListTuiSessionsOptions,
  27. TuiAccountStatus,
  28. TuiAccountStatusOptions,
  29. TuiActiveRunSnapshot,
  30. TuiBackgroundTask,
  31. TuiCompactionResult,
  32. TuiDelegationSnapshot,
  33. TuiDelegationStopReceipt,
  34. TuiFeedbackPreview,
  35. TuiFeedbackSubmitOptions,
  36. TuiFeedbackReceipt,
  37. TuiEditMessageInput,
  38. TuiEditMessageResult,
  39. TuiInstructionSource,
  40. TuiMcpServer,
  41. TuiProjectMcpPreview,
  42. TuiMessagePage,
  43. TuiMessagePageInput,
  44. TuiModel,
  45. TuiModelSelection,
  46. TuiPendingPermission,
  47. TuiPermissionDecision,
  48. TuiQuestionnaireReplyAnswer,
  49. TuiQuestionnaireRequest,
  50. TuiQueueReceipt,
  51. TuiQueuedMessage,
  52. TuiQueueSnapshot,
  53. TuiRewindInput,
  54. TuiRewindPreview,
  55. TuiRewindResult,
  56. TuiRuntimeDiagnostics,
  57. TuiRuntimeEvent,
  58. TuiSession,
  59. TuiSessionForkOptions,
  60. TuiSessionForkResult,
  61. TuiSessionInputSummary,
  62. TuiSessionMcpServer,
  63. TuiSessionPage,
  64. TuiSessionUsage,
  65. TuiSkillList,
  66. TuiRuntime,
  67. TuiWorkspaceFileCandidate,
  68. TuiWorkspaceFileEntry,
  69. TuiWorkspaceGitMetadata,
  70. TuiWorkspaceRoot,
  71. TuiWorkspaceTreeCandidate,
  72. WatchTuiSessionTurnOptions,
  73. } from "./port.js";
  74. import type { TuiPermissionMode } from "../application/permission-mode.js";
  75. import { resolveTuiEffortChoice } from "../application/model-effort.js";
  76. import type { TuiObservability } from "../observability/index.js";
  77. import type { TuiTokenPlanAccountStatus } from "../account/matrix-account-client.js";
  78. import type { TuiDailyCheckinOutcome } from "../checkin/application.js";
  79. export * from "./port.js";
  80. export interface TuiRuntimeAdapterOptions {
  81. createQueueRequestId?: () => string;
  82. defaultAgentName?: string;
  83. onSessionDeleted?: (sessionId: string) => void | Promise<void>;
  84. workspaceDir?: string;
  85. synchronizeAuth?: () => Promise<void>;
  86. accountIdentityGetter?: () => TuiAccountStatus["identity"];
  87. observability?: TuiObservability;
  88. tokenPlanAccountStatusGetter?: (options?: {
  89. readonly forceRefresh?: boolean;
  90. }) => Promise<TuiTokenPlanAccountStatus>;
  91. feedback?: {
  92. prepare(input: {
  93. readonly description: string;
  94. readonly sessionId?: string;
  95. }): TuiFeedbackPreview | Promise<TuiFeedbackPreview>;
  96. submit(
  97. draftId: string,
  98. options?: TuiFeedbackSubmitOptions,
  99. ): Promise<TuiFeedbackReceipt>;
  100. cancel(draftId: string): boolean | Promise<boolean>;
  101. };
  102. dailyCheckin?: {
  103. run(): Promise<TuiDailyCheckinOutcome>;
  104. };
  105. }
  106. export class TuiRuntimeAdapter implements TuiRuntime {
  107. private readonly cliService: CliService;
  108. private readonly context: TuiRuntimeAccessContext;
  109. private readonly workspaceAccess: TuiWorkspaceAccess;
  110. private readonly sessionAccess: TuiSessionAccess;
  111. private readonly productAccess: TuiProductAccess;
  112. private readonly interactionAccess: TuiInteractionAccess;
  113. private readonly eventAccess: TuiEventAccess;
  114. private readonly delegationAccess: TuiDelegationAccess;
  115. private readonly conversationAccess: TuiConversationAccess;
  116. private readonly pluginAccess: TuiPluginAccess;
  117. private readonly goalAccess: TuiGoalAccess;
  118. private readonly tokenPlanAccountStatusGetter:
  119. | ((options?: {
  120. readonly forceRefresh?: boolean;
  121. }) => Promise<TuiTokenPlanAccountStatus>)
  122. | undefined;
  123. private readonly synchronizeAuth: TuiRuntimeAdapterOptions["synchronizeAuth"];
  124. private readonly accountIdentityGetter: TuiRuntimeAdapterOptions["accountIdentityGetter"];
  125. private readonly feedback: TuiRuntimeAdapterOptions["feedback"];
  126. private readonly dailyCheckin: TuiRuntimeAdapterOptions["dailyCheckin"];
  127. constructor(cliService: CliService, options: TuiRuntimeAdapterOptions = {}) {
  128. this.cliService = cliService;
  129. const defaultAgentName =
  130. options.defaultAgentName ?? MINIMAX_CODE_DEFAULT_AGENT_NAME;
  131. this.tokenPlanAccountStatusGetter = options.tokenPlanAccountStatusGetter;
  132. this.synchronizeAuth = options.synchronizeAuth;
  133. this.accountIdentityGetter = options.accountIdentityGetter;
  134. this.feedback = options.feedback;
  135. this.dailyCheckin = options.dailyCheckin;
  136. this.conversationAccess = new TuiConversationAccess(cliService);
  137. this.pluginAccess = new TuiPluginAccess(cliService);
  138. this.context = new TuiRuntimeAccessContext({
  139. cliService,
  140. ...(options.observability
  141. ? { observability: options.observability }
  142. : {}),
  143. });
  144. this.goalAccess = new TuiGoalAccess(this.context);
  145. this.workspaceAccess = new TuiWorkspaceAccess(this.context);
  146. this.sessionAccess = new TuiSessionAccess(
  147. cliService,
  148. defaultAgentName,
  149. options.onSessionDeleted,
  150. );
  151. this.productAccess = new TuiProductAccess(
  152. this.context,
  153. defaultAgentName,
  154. options.workspaceDir,
  155. );
  156. this.interactionAccess = new TuiInteractionAccess(
  157. options.createQueueRequestId ?? createTuiQueueRequestId,
  158. cliService,
  159. );
  160. this.eventAccess = new TuiEventAccess(cliService, options.observability);
  161. this.delegationAccess = new TuiDelegationAccess({
  162. listSessionPage: (input) => this.sessionAccess.listSessionPage(input),
  163. abortSession: (req) => this.abortSession(req),
  164. });
  165. }
  166. sendMessage(
  167. req: CliSendMessageReq,
  168. signal?: AbortSignal,
  169. options?: CliSendMessageOptions,
  170. ): AsyncGenerator<TuiStreamEvent> {
  171. return this.conversationAccess.sendMessage(req, signal, options);
  172. }
  173. abortSession(req: AbortSessionReq): Promise<boolean> {
  174. return this.conversationAccess.abortSession(req);
  175. }
  176. steer(input: ConversationSteerInput): Promise<ConversationSteerResult> {
  177. return this.conversationAccess.steer(input);
  178. }
  179. async createSession(input: CreateTuiSessionInput): Promise<TuiSession> {
  180. const defaultModel = await this.productAccess
  181. .listModels()
  182. .then((models) => models.find((model) => model.selected === true))
  183. .catch(() => undefined);
  184. if (!defaultModel) return this.sessionAccess.createSession(input);
  185. // Inherit Runtime's saved global selection before catalog defaults, using
  186. // the same rule as the status line and without changing existing Sessions.
  187. const effort = resolveTuiEffortChoice(defaultModel)?.trim();
  188. return this.sessionAccess.createSession(input, {
  189. providerId: defaultModel.providerId,
  190. modelId: defaultModel.modelId,
  191. ...(defaultModel.variant !== undefined
  192. ? { variant: defaultModel.variant }
  193. : {}),
  194. ...(defaultModel.contextLimit !== undefined
  195. ? { contextLimit: defaultModel.contextLimit }
  196. : {}),
  197. ...(effort ? { thinking: { effort } } : {}),
  198. });
  199. }
  200. configureSessionMcpServers(
  201. sessionId: string,
  202. servers: readonly TuiSessionMcpServer[],
  203. ): Promise<void> {
  204. return this.sessionAccess.configureSessionMcpServers(sessionId, servers);
  205. }
  206. clearSessionMcpServers(sessionId: string): Promise<void> {
  207. return this.sessionAccess.clearSessionMcpServers(sessionId);
  208. }
  209. listSessions(
  210. agentName?: string,
  211. options?: ListTuiSessionsOptions,
  212. ): Promise<TuiSession[]> {
  213. return this.sessionAccess.listSessions(agentName, options);
  214. }
  215. listSessionPage(
  216. input?: ListTuiSessionPageInput | string,
  217. options?: ListTuiSessionsOptions,
  218. ): Promise<TuiSessionPage> {
  219. return this.sessionAccess.listSessionPage(input, options);
  220. }
  221. getSession(sessionId: string): Promise<TuiSession> {
  222. return this.sessionAccess.getSession(sessionId);
  223. }
  224. getMessages(sessionId: string, limit?: number): Promise<TuiMessage[]> {
  225. return this.sessionAccess.getMessages(sessionId, limit);
  226. }
  227. listMessagePage(
  228. sessionId: string,
  229. input?: TuiMessagePageInput,
  230. ): Promise<TuiMessagePage> {
  231. return this.sessionAccess.listMessagePage(sessionId, input);
  232. }
  233. getSessionForkOptions(
  234. sessionId: string,
  235. assistantMessageId?: string,
  236. ): Promise<TuiSessionForkOptions> {
  237. return this.sessionAccess.getSessionForkOptions(
  238. sessionId,
  239. assistantMessageId,
  240. );
  241. }
  242. forkSession(input: ForkTuiSessionInput): Promise<TuiSessionForkResult> {
  243. return this.sessionAccess.forkSession(input);
  244. }
  245. renameSession(sessionId: string, title: string): Promise<TuiSession> {
  246. return this.sessionAccess.renameSession(sessionId, title);
  247. }
  248. archiveSession(sessionId: string, archived: boolean): Promise<void> {
  249. return this.sessionAccess.archiveSession(sessionId, archived);
  250. }
  251. deleteSession(sessionId: string): Promise<void> {
  252. return this.sessionAccess.deleteSession(sessionId);
  253. }
  254. listSessionInputSummaries(
  255. sessionId: string,
  256. input?: { limit?: number; before?: string },
  257. ): Promise<readonly TuiSessionInputSummary[]> {
  258. return this.sessionAccess.listSessionInputSummaries(sessionId, input);
  259. }
  260. getSessionRewindPreview(input: {
  261. sessionId: string;
  262. userMessageId: string;
  263. }): Promise<TuiRewindPreview> {
  264. return this.sessionAccess.getSessionRewindPreview(input);
  265. }
  266. rewindSession(input: TuiRewindInput): Promise<TuiRewindResult> {
  267. return this.sessionAccess.rewindSession(input);
  268. }
  269. editSessionMessage(
  270. input: TuiEditMessageInput,
  271. ): Promise<TuiEditMessageResult> {
  272. return this.sessionAccess.editSessionMessage(input);
  273. }
  274. isGoalEnabled(): boolean {
  275. return this.goalAccess.isEnabled();
  276. }
  277. getGoal(sessionId: string) {
  278. return this.goalAccess.get(sessionId);
  279. }
  280. createGoal(input: Parameters<TuiGoalAccess["create"]>[0]) {
  281. return this.goalAccess.create(input);
  282. }
  283. patchGoal(sessionId: string, patch: Parameters<TuiGoalAccess["patch"]>[1]) {
  284. return this.goalAccess.patch(sessionId, patch);
  285. }
  286. clearGoal(sessionId: string): Promise<boolean> {
  287. return this.goalAccess.clear(sessionId);
  288. }
  289. getWorkspaceGitMetadata(
  290. workspaceDir: string,
  291. ): Promise<TuiWorkspaceGitMetadata> {
  292. return this.workspaceAccess.getWorkspaceGitMetadata(workspaceDir);
  293. }
  294. listWorkspaceFileTree(
  295. workspaceDir: string,
  296. path?: string,
  297. signal?: AbortSignal,
  298. ): Promise<TuiWorkspaceFileEntry[]> {
  299. return this.workspaceAccess.listWorkspaceFileTree(
  300. workspaceDir,
  301. path,
  302. signal,
  303. );
  304. }
  305. searchWorkspaceFiles(
  306. workspaceDir: string,
  307. query: string,
  308. limit?: number,
  309. signal?: AbortSignal,
  310. ): Promise<string[]> {
  311. return this.workspaceAccess.searchWorkspaceFiles(
  312. workspaceDir,
  313. query,
  314. limit,
  315. signal,
  316. );
  317. }
  318. listWorkspaceFileTreeCandidates(
  319. request: { roots: readonly TuiWorkspaceRoot[]; path?: string },
  320. signal?: AbortSignal,
  321. ): Promise<TuiWorkspaceTreeCandidate[]> {
  322. return this.workspaceAccess.listWorkspaceFileTreeCandidates(
  323. request,
  324. signal,
  325. );
  326. }
  327. searchWorkspaceFileCandidates(
  328. request: {
  329. roots: readonly TuiWorkspaceRoot[];
  330. query: string;
  331. limit?: number;
  332. },
  333. signal?: AbortSignal,
  334. ): Promise<TuiWorkspaceFileCandidate[]> {
  335. return this.workspaceAccess.searchWorkspaceFileCandidates(request, signal);
  336. }
  337. async getAccountStatus(
  338. sessionId?: string,
  339. options?: TuiAccountStatusOptions,
  340. ): Promise<TuiAccountStatus> {
  341. let account = await this.productAccess.getAccountStatus(sessionId, options);
  342. const usesManagedAuth = account.modelSource
  343. ? account.modelSource === "token-plan"
  344. : account.authMode === "managed-login";
  345. if (
  346. this.synchronizeAuth &&
  347. (usesManagedAuth || options?.requireManagedAuth)
  348. ) {
  349. await this.synchronizeAuth();
  350. account = await this.productAccess.getAccountStatus(sessionId, options);
  351. }
  352. const identity = account.managedTokenPresent
  353. ? this.accountIdentityGetter?.()
  354. : undefined;
  355. if (identity)
  356. account = {
  357. ...account,
  358. identity: { email: identity.email, name: identity.name },
  359. };
  360. const membershipRequested = options?.includeMembership !== false;
  361. const explicitUsageInspection = options?.includeMembership === true;
  362. if (
  363. !membershipRequested ||
  364. (!explicitUsageInspection &&
  365. (account.modelSource !== "token-plan" ||
  366. account.managedTokenPresent !== true)) ||
  367. !this.tokenPlanAccountStatusGetter
  368. ) {
  369. return account;
  370. }
  371. const tokenPlan = await (
  372. options?.forceRefresh
  373. ? this.tokenPlanAccountStatusGetter({ forceRefresh: true })
  374. : this.tokenPlanAccountStatusGetter()
  375. ).catch(() => undefined);
  376. if (!tokenPlan) return account;
  377. return {
  378. ...account,
  379. ...(tokenPlan.quotaState
  380. ? { tokenPlanQuotaState: tokenPlan.quotaState }
  381. : {}),
  382. ...(tokenPlan.quota ? { tokenPlanQuota: tokenPlan.quota } : {}),
  383. ...(explicitUsageInspection && tokenPlan.summary
  384. ? { tokenPlanSummary: tokenPlan.summary }
  385. : {}),
  386. };
  387. }
  388. getRuntimeDiagnostics(): Promise<TuiRuntimeDiagnostics> {
  389. return this.productAccess.getRuntimeDiagnostics();
  390. }
  391. getInstructionSources(
  392. workspaceDir: string,
  393. ): Promise<readonly TuiInstructionSource[]> {
  394. return this.productAccess.getInstructionSources(workspaceDir);
  395. }
  396. async prepareFeedback(input: {
  397. description: string;
  398. sessionId?: string;
  399. }): Promise<TuiFeedbackPreview> {
  400. if (!this.feedback)
  401. throw new Error("MiniMax Code feedback is unavailable.");
  402. return this.feedback.prepare(input);
  403. }
  404. submitFeedback(
  405. draftId: string,
  406. options?: TuiFeedbackSubmitOptions,
  407. ): Promise<TuiFeedbackReceipt> {
  408. if (!this.feedback)
  409. return Promise.reject(new Error("MiniMax Code feedback is unavailable."));
  410. return this.feedback.submit(draftId, options);
  411. }
  412. cancelFeedback(draftId: string): Promise<boolean> {
  413. if (!this.feedback) return Promise.resolve(false);
  414. return Promise.resolve(this.feedback.cancel(draftId));
  415. }
  416. runDailyCheckin(): Promise<TuiDailyCheckinOutcome> {
  417. if (!this.dailyCheckin) {
  418. return Promise.reject(new Error("Daily check-in is unavailable."));
  419. }
  420. return this.dailyCheckin.run();
  421. }
  422. getPermissionMode(): Promise<TuiPermissionMode | undefined> {
  423. return this.productAccess.getPermissionMode();
  424. }
  425. setPermissionMode(mode: TuiPermissionMode): Promise<TuiPermissionMode> {
  426. return this.productAccess.setPermissionMode(mode);
  427. }
  428. listModels(sessionId?: string): Promise<TuiModel[]> {
  429. return this.productAccess.listModels(sessionId);
  430. }
  431. selectModel(model: TuiModelSelection, sessionId?: string): Promise<boolean> {
  432. return this.productAccess.selectModel(model, sessionId);
  433. }
  434. selectSessionModel(
  435. model: TuiModelSelection,
  436. sessionId: string,
  437. ): Promise<boolean> {
  438. return this.productAccess.selectSessionModel(model, sessionId);
  439. }
  440. listUserModelProviders() {
  441. return this.productAccess.listUserModelProviders();
  442. }
  443. listProviderPresets() {
  444. return this.productAccess.listProviderPresets();
  445. }
  446. getCodexOAuthStatus() {
  447. return this.productAccess.getCodexOAuthStatus();
  448. }
  449. startCodexOAuthLogin(
  450. options?: Parameters<TuiProductAccess["startCodexOAuthLogin"]>[0],
  451. ) {
  452. return this.productAccess.startCodexOAuthLogin(options);
  453. }
  454. cancelCodexOAuthLogin(loginId: string) {
  455. return this.productAccess.cancelCodexOAuthLogin(loginId);
  456. }
  457. getMiniMaxApiKeyStatus() {
  458. return this.productAccess.getMiniMaxApiKeyStatus();
  459. }
  460. getMiniMaxModelSource() {
  461. return this.productAccess.getMiniMaxModelSource();
  462. }
  463. setMiniMaxModelSource(
  464. source: import("../provider/contract.js").McodeMiniMaxModelSource,
  465. ) {
  466. return this.productAccess.setMiniMaxModelSource(source);
  467. }
  468. upsertMiniMaxApiKey(input: { apiKey: string; saveAndUse?: boolean }) {
  469. return this.productAccess.upsertMiniMaxApiKey(input);
  470. }
  471. createUserModelProvider(
  472. input: import("../provider/contract.js").McodeCreateProviderInput,
  473. ) {
  474. return this.productAccess.createUserModelProvider(input);
  475. }
  476. discoverUserModelsCandidate(
  477. input: import("../provider/contract.js").McodeDiscoverProviderModelsInput,
  478. ) {
  479. return this.productAccess.discoverUserModelsCandidate(input);
  480. }
  481. saveUserModelProviderCandidate(
  482. input: import("../provider/contract.js").McodeSaveProviderCandidateInput,
  483. ) {
  484. return this.productAccess.saveUserModelProviderCandidate(input);
  485. }
  486. updateUserModelProvider(
  487. input: import("../provider/contract.js").McodeUpdateProviderInput,
  488. ) {
  489. return this.productAccess.updateUserModelProvider(input);
  490. }
  491. deleteUserModelProvider(providerId: string) {
  492. return this.productAccess.deleteUserModelProvider(providerId);
  493. }
  494. testUserModelProvider(providerId: string) {
  495. return this.productAccess.testUserModelProvider(providerId);
  496. }
  497. testUserModel(providerId: string, modelId: string) {
  498. return this.productAccess.testUserModel(providerId, modelId);
  499. }
  500. getSessionUsage(sessionId: string): Promise<TuiSessionUsage> {
  501. return this.productAccess.getSessionUsage(sessionId);
  502. }
  503. getSessionUsageSummary(sessionId: string) {
  504. return this.productAccess.getSessionUsageSummary(sessionId);
  505. }
  506. watchSessionUsageCommits(signal: AbortSignal): AsyncGenerator<string> {
  507. return this.eventAccess.watchSessionUsageCommits(signal);
  508. }
  509. requestCompaction(
  510. sessionId: string,
  511. agentName?: string,
  512. customInstructions?: string,
  513. ): Promise<TuiCompactionResult> {
  514. return this.productAccess.requestCompaction(
  515. sessionId,
  516. agentName,
  517. customInstructions,
  518. );
  519. }
  520. getContextSnapshot(sessionId: string) {
  521. return this.productAccess.getContextSnapshot(sessionId);
  522. }
  523. getActiveRun(sessionId: string): Promise<TuiActiveRunSnapshot> {
  524. return this.productAccess.getActiveRun(sessionId);
  525. }
  526. listSkills(
  527. agentName?: string,
  528. keyword?: string,
  529. workspaceDir?: string,
  530. ): Promise<TuiSkillList> {
  531. return this.productAccess.listSkills(agentName, keyword, workspaceDir);
  532. }
  533. inspectProjectMcp(
  534. sessionId: string,
  535. ): Promise<TuiProjectMcpPreview | undefined> {
  536. return this.productAccess.inspectProjectMcp(sessionId);
  537. }
  538. listMcpServers(
  539. keyword?: string,
  540. sessionId?: string,
  541. ): Promise<TuiMcpServer[]> {
  542. return this.productAccess.listMcpServers(keyword, sessionId);
  543. }
  544. listInstalledPlugins(
  545. input?: Parameters<TuiPluginAccess["listInstalledPlugins"]>[0],
  546. ) {
  547. return this.pluginAccess.listInstalledPlugins(input);
  548. }
  549. listMarketplacePlugins(
  550. input: Parameters<TuiPluginAccess["listMarketplacePlugins"]>[0],
  551. ) {
  552. return this.pluginAccess.listMarketplacePlugins(input);
  553. }
  554. mutatePlugin(input: Parameters<TuiPluginAccess["mutatePlugin"]>[0]) {
  555. return this.pluginAccess.mutatePlugin(input);
  556. }
  557. refreshPlugins(): Promise<void> {
  558. return this.pluginAccess.refreshPlugins();
  559. }
  560. listQueuedMessages(sessionId: string): Promise<TuiQueuedMessage[]> {
  561. return this.interactionAccess.listQueuedMessages(sessionId);
  562. }
  563. getQueueSnapshot(sessionId: string): Promise<TuiQueueSnapshot> {
  564. return this.interactionAccess.getQueueSnapshot(sessionId);
  565. }
  566. continueQueue(sessionId: string): Promise<void> {
  567. return this.interactionAccess.continueQueue(sessionId);
  568. }
  569. steerQueuedMessage(
  570. sessionId: string,
  571. itemId: string,
  572. ): Promise<{ queueItemId: string; turnId: string }> {
  573. return this.interactionAccess.steerQueuedMessage(sessionId, itemId);
  574. }
  575. enqueueMessage(
  576. sessionId: string,
  577. content: string,
  578. options?: EnqueueTuiMessageOptions,
  579. ): Promise<TuiQueueReceipt> {
  580. return this.interactionAccess.enqueueMessage(sessionId, content, options);
  581. }
  582. updateQueuedMessageContent(
  583. sessionId: string,
  584. itemId: string,
  585. content: string,
  586. ): Promise<TuiQueuedMessage | undefined> {
  587. return this.interactionAccess.updateQueuedMessageContent(
  588. sessionId,
  589. itemId,
  590. content,
  591. );
  592. }
  593. deleteQueuedMessage(
  594. sessionId: string,
  595. itemId: string,
  596. ): Promise<TuiQueuedMessage | undefined> {
  597. return this.interactionAccess.deleteQueuedMessage(sessionId, itemId);
  598. }
  599. getPendingQuestionnaire(
  600. agentName: string,
  601. sessionId: string,
  602. signal?: AbortSignal,
  603. ): Promise<TuiQuestionnaireRequest | undefined> {
  604. return this.interactionAccess.getPendingQuestionnaire(
  605. agentName,
  606. sessionId,
  607. signal,
  608. );
  609. }
  610. getLatestPlanReview(
  611. agentName: string,
  612. sessionId: string,
  613. signal?: AbortSignal,
  614. ): Promise<TuiQuestionnaireRequest | undefined> {
  615. return this.interactionAccess.getLatestPlanReview(
  616. agentName,
  617. sessionId,
  618. signal,
  619. );
  620. }
  621. getPlanModeCapabilities(): Promise<{ readonly entryEnabled: boolean }> {
  622. return this.interactionAccess.getPlanModeCapabilities();
  623. }
  624. replyQuestionnaire(
  625. agentName: string,
  626. requestId: string,
  627. answers: TuiQuestionnaireReplyAnswer[],
  628. ): Promise<boolean> {
  629. return this.interactionAccess.replyQuestionnaire(
  630. agentName,
  631. requestId,
  632. answers,
  633. );
  634. }
  635. dismissQuestionnaire(agentName: string, requestId: string): Promise<boolean> {
  636. return this.interactionAccess.dismissQuestionnaire(agentName, requestId);
  637. }
  638. listPendingPermissions(
  639. signal?: AbortSignal,
  640. ): Promise<TuiPendingPermission[]> {
  641. return this.interactionAccess.listPendingPermissions(signal);
  642. }
  643. replyPermission(
  644. agentName: string,
  645. requestId: string,
  646. decision: TuiPermissionDecision,
  647. ): Promise<boolean> {
  648. return this.interactionAccess.replyPermission(
  649. agentName,
  650. requestId,
  651. decision,
  652. );
  653. }
  654. watchEvents(signal: AbortSignal): AsyncGenerator<TuiRuntimeEvent> {
  655. return this.eventAccess.watch(signal);
  656. }
  657. watchSessionTurn(
  658. sessionId: string,
  659. turnId: string,
  660. signal: AbortSignal,
  661. options?: WatchTuiSessionTurnOptions,
  662. ): AsyncGenerator<TuiStreamEvent> {
  663. return this.conversationAccess.resumeSession(
  664. {
  665. id: sessionId,
  666. ...(options?.afterMsgId ? { afterMsgId: options.afterMsgId } : {}),
  667. ...(options?.afterCursor ? { afterCursor: options.afterCursor } : {}),
  668. },
  669. turnId,
  670. signal,
  671. );
  672. }
  673. getDelegationSnapshot(rootSessionId: string): Promise<TuiDelegationSnapshot> {
  674. return this.delegationAccess.getSnapshot(rootSessionId);
  675. }
  676. async listBackgroundTasks(
  677. ownerSessionId: string,
  678. ): Promise<readonly TuiBackgroundTask[]> {
  679. const activeStatuses = ["queued", "running", "stopping"] as const;
  680. const terminalStatuses = [
  681. "succeeded",
  682. "failed",
  683. "canceled",
  684. "lost",
  685. ] as const;
  686. const [active, terminal] = await Promise.all([
  687. this.cliService.listBackgroundTasks({
  688. ownerSessionId,
  689. statuses: activeStatuses,
  690. kinds: ["bash", "workflow", "custom"],
  691. limit: 100,
  692. }),
  693. this.cliService.listBackgroundTasks({
  694. ownerSessionId,
  695. statuses: terminalStatuses,
  696. kinds: ["bash", "workflow", "custom"],
  697. limit: 100,
  698. }),
  699. ]);
  700. const tasks = new Map(
  701. [...active, ...terminal].map((task) => [task.taskId, task]),
  702. );
  703. return [...tasks.values()]
  704. .filter(
  705. (
  706. task,
  707. ): task is typeof task & { readonly kind: TuiBackgroundTask["kind"] } =>
  708. task.kind !== "subagent",
  709. )
  710. .sort((left, right) => right.updatedAt - left.updatedAt)
  711. .map((task) => ({
  712. taskId: task.taskId,
  713. kind: task.kind,
  714. status: task.status,
  715. ownerSessionId: task.ownerSessionId,
  716. ...(task.description ? { description: task.description } : {}),
  717. ...(task.kind === "bash" && typeof task.metadata?.command === "string"
  718. ? { command: task.metadata.command }
  719. : {}),
  720. createdAtMs: task.createdAt,
  721. updatedAtMs: task.updatedAt,
  722. ...(task.startedAt !== undefined
  723. ? { startedAtMs: task.startedAt }
  724. : {}),
  725. ...(task.endedAt !== undefined ? { endedAtMs: task.endedAt } : {}),
  726. ...(task.deliveredAt !== undefined
  727. ? { deliveredAtMs: task.deliveredAt }
  728. : {}),
  729. ...(task.lastError?.message
  730. ? { lastError: task.lastError.message }
  731. : {}),
  732. }));
  733. }
  734. stopDelegation(rootSessionId: string): Promise<TuiDelegationStopReceipt> {
  735. return this.delegationAccess.stop(rootSessionId);
  736. }
  737. }
  738. export function createTuiQueueRequestId(): string {
  739. return `minimax-code_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
  740. }