interactions.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. import * as acp from '@agentclientprotocol/sdk';
  2. import type { TuiSession } from '../runtime/port.js';
  3. import type {
  4. TuiPendingPermission,
  5. TuiQuestionnaireReplyAnswer,
  6. TuiQuestionnaireRequest,
  7. TuiQuestionnaireStep,
  8. } from '../types/runtime-models.js';
  9. import type { TuiRuntimeEvent } from '../types/runtime-events.js';
  10. import { isTuiAcpAbsolutePath } from './paths.js';
  11. import type { TuiAcpRuntime } from './runtime.js';
  12. import { tuiAcpToolKind } from './updates.js';
  13. const MAX_PENDING_PROJECTIONS = 64;
  14. const MAX_ACTIVE_PROJECTIONS = 8;
  15. const MAX_PENDING_INTERACTIONS = 64;
  16. const MAX_ACTIVE_INTERACTIONS = 8;
  17. const INTERACTION_CANCEL_CONCURRENCY = 8;
  18. const INTERACTION_CANCEL_TIMEOUT_MS = 1_000;
  19. const MAX_DETACHED_INTERACTIONS_PER_ATTACHMENT = 2;
  20. const MAX_DETACHED_INTERACTIONS_TOTAL = 32;
  21. const MAX_TERMINAL_TARGETS = 128;
  22. interface ResolvedInteractionSession {
  23. readonly acpSessionId: string;
  24. readonly session: TuiSession;
  25. readonly attachmentSignal: AbortSignal;
  26. readonly isCurrent: () => boolean;
  27. }
  28. interface TuiAcpRuntimeInteraction {
  29. readonly id: string;
  30. readonly terminalIds: readonly string[];
  31. readonly key: string;
  32. readonly attachmentSignal: AbortSignal;
  33. run(signal: AbortSignal): Promise<void>;
  34. cancel(): Promise<void>;
  35. terminated(): void;
  36. }
  37. class RuntimeInteractionTerminated extends Error {}
  38. export interface RunTuiAcpInteractionsOptions {
  39. readonly runtime: TuiAcpRuntime;
  40. readonly connection: acp.AgentConnection;
  41. readonly resolveSession: (runtimeSessionId: string) => ResolvedInteractionSession | undefined;
  42. readonly clientCapabilities: () => acp.ClientCapabilities;
  43. readonly onRuntimeEvent?: (event: TuiRuntimeEvent) => void;
  44. readonly createRuntimeEventProjections?: (
  45. event: TuiRuntimeEvent,
  46. ) => readonly TuiAcpRuntimeProjection[];
  47. readonly projectionTimeoutMs?: number;
  48. readonly onQuestionnaireSettled?: (event: {
  49. readonly sessionId: string;
  50. readonly requestId: string;
  51. readonly continued: boolean;
  52. }) => readonly TuiAcpRuntimeProjection[];
  53. }
  54. export interface TuiAcpRuntimeProjection {
  55. readonly key: string;
  56. readonly required?: boolean;
  57. onDrop?(): void;
  58. run(signal: AbortSignal): void | Promise<void>;
  59. }
  60. export async function runTuiAcpInteractions(options: RunTuiAcpInteractionsOptions): Promise<void> {
  61. const projections = createProjectionScheduler(
  62. options.connection,
  63. options.projectionTimeoutMs ?? 5_000,
  64. );
  65. const interactions = createInteractionScheduler(options.connection);
  66. try {
  67. for await (const event of options.runtime.watchEvents(options.connection.signal)) {
  68. if (options.connection.signal.aborted) return;
  69. try {
  70. options.onRuntimeEvent?.(event);
  71. } catch {
  72. // Critical event observation is fail-open for permission/questionnaire handling.
  73. }
  74. try {
  75. for (const projection of options.createRuntimeEventProjections?.(event) ?? []) {
  76. projections.enqueue(projection);
  77. }
  78. } catch {
  79. // Control-plane projection creation is fail-open for later Runtime interactions.
  80. }
  81. const terminalIds = runtimeInteractionTerminalIds(event);
  82. if (terminalIds) interactions.terminate(terminalIds);
  83. const interaction = createRuntimeInteraction(options, event, projections.enqueue);
  84. if (interaction && !interactions.enqueue(interaction)) return;
  85. }
  86. } catch {
  87. // Losing the auxiliary interaction stream must not corrupt the ACP transport.
  88. } finally {
  89. projections.close();
  90. interactions.close();
  91. }
  92. }
  93. function createInteractionScheduler(connection: acp.AgentConnection): {
  94. enqueue(interaction: TuiAcpRuntimeInteraction): boolean;
  95. terminate(terminalIds: readonly string[]): void;
  96. close(): void;
  97. } {
  98. const active = new Map<
  99. string,
  100. {
  101. readonly controller: AbortController;
  102. readonly interaction: TuiAcpRuntimeInteraction;
  103. detached: boolean;
  104. }
  105. >();
  106. const pending: TuiAcpRuntimeInteraction[] = [];
  107. const detachedByAttachment = new Map<AbortSignal, number>();
  108. const terminalTargets = new Map<
  109. string,
  110. Array<{
  111. readonly interaction: TuiAcpRuntimeInteraction;
  112. readonly terminalIds: readonly string[];
  113. }>
  114. >();
  115. let detachedCount = 0;
  116. let terminalTargetCount = 0;
  117. let closed = false;
  118. const releaseDetached = (attachmentSignal: AbortSignal) => {
  119. const remaining = (detachedByAttachment.get(attachmentSignal) ?? 1) - 1;
  120. if (remaining > 0) detachedByAttachment.set(attachmentSignal, remaining);
  121. else detachedByAttachment.delete(attachmentSignal);
  122. detachedCount -= 1;
  123. };
  124. const close = (
  125. overflow?: TuiAcpRuntimeInteraction,
  126. error = new Error('ACP Runtime interaction queue capacity exceeded.'),
  127. ) => {
  128. if (closed) return;
  129. closed = true;
  130. const activeInteractions = [...active.values()].map(({ interaction }) => interaction);
  131. for (const { controller } of active.values()) {
  132. controller.abort(new Error('ACP interaction stream closed.'));
  133. }
  134. terminalTargets.clear();
  135. terminalTargetCount = 0;
  136. const cancelled = [
  137. ...activeInteractions,
  138. ...pending.splice(0),
  139. ...(overflow ? [overflow] : []),
  140. ];
  141. void cancelInteractions(cancelled).finally(() => {
  142. if (overflow) connection.close(error);
  143. });
  144. };
  145. const detachActive = (
  146. key: string,
  147. entry: {
  148. readonly controller: AbortController;
  149. readonly interaction: TuiAcpRuntimeInteraction;
  150. detached: boolean;
  151. },
  152. reason: Error,
  153. ): boolean => {
  154. const { controller, interaction } = entry;
  155. if (
  156. (detachedByAttachment.get(interaction.attachmentSignal) ?? 0) >=
  157. MAX_DETACHED_INTERACTIONS_PER_ATTACHMENT ||
  158. detachedCount >= MAX_DETACHED_INTERACTIONS_TOTAL
  159. ) {
  160. controller.abort(reason);
  161. close();
  162. connection.close(new Error('Too many detached ACP Client interactions remain pending.'));
  163. return false;
  164. }
  165. active.delete(key);
  166. entry.detached = true;
  167. detachedByAttachment.set(
  168. interaction.attachmentSignal,
  169. (detachedByAttachment.get(interaction.attachmentSignal) ?? 0) + 1,
  170. );
  171. detachedCount += 1;
  172. controller.abort(reason);
  173. return true;
  174. };
  175. const drain = () => {
  176. if (closed || active.size >= MAX_ACTIVE_INTERACTIONS) return;
  177. for (let index = 0; index < pending.length; ) {
  178. if (active.size >= MAX_ACTIVE_INTERACTIONS) return;
  179. const interaction = pending[index];
  180. if (!interaction || active.has(interaction.key)) {
  181. index += 1;
  182. continue;
  183. }
  184. pending.splice(index, 1);
  185. const controller = new AbortController();
  186. const entry = { controller, interaction, detached: false };
  187. active.set(interaction.key, entry);
  188. void interaction
  189. .run(controller.signal)
  190. .catch(() => undefined)
  191. .finally(() => {
  192. if (entry.detached) releaseDetached(interaction.attachmentSignal);
  193. if (active.get(interaction.key)?.controller === controller) {
  194. active.delete(interaction.key);
  195. }
  196. drain();
  197. });
  198. }
  199. };
  200. return {
  201. enqueue(interaction) {
  202. if (closed) {
  203. void cancelInteractions([interaction]);
  204. return false;
  205. }
  206. const staleActive = active.get(interaction.key);
  207. if (
  208. staleActive &&
  209. staleActive.interaction.attachmentSignal !== interaction.attachmentSignal &&
  210. !detachActive(
  211. interaction.key,
  212. staleActive,
  213. new Error('ACP Session attachment was replaced.'),
  214. )
  215. ) {
  216. void cancelInteractions([interaction]);
  217. return false;
  218. }
  219. const stalePending = pending.filter(
  220. (candidate) =>
  221. candidate.key === interaction.key &&
  222. candidate.attachmentSignal !== interaction.attachmentSignal,
  223. );
  224. if (stalePending.length > 0) {
  225. for (const candidate of stalePending) pending.splice(pending.indexOf(candidate), 1);
  226. void cancelInteractions(stalePending);
  227. }
  228. if (pending.length >= MAX_PENDING_INTERACTIONS) {
  229. close(interaction);
  230. return false;
  231. }
  232. if (terminalTargetCount >= MAX_TERMINAL_TARGETS) {
  233. close(
  234. interaction,
  235. new Error('ACP Runtime interaction terminal tracking capacity exceeded.'),
  236. );
  237. return false;
  238. }
  239. const target = {
  240. interaction,
  241. terminalIds: interaction.terminalIds,
  242. };
  243. for (const terminalId of interaction.terminalIds) {
  244. const targets = terminalTargets.get(terminalId) ?? [];
  245. targets.push(target);
  246. terminalTargets.set(terminalId, targets);
  247. }
  248. terminalTargetCount += 1;
  249. pending.push(interaction);
  250. drain();
  251. return true;
  252. },
  253. terminate(terminalIds) {
  254. const terminalId = terminalIds.find((candidate) => terminalTargets.get(candidate)?.length);
  255. if (!terminalId) return;
  256. const target = terminalTargets.get(terminalId)?.shift();
  257. if (!target) return;
  258. terminalTargetCount -= 1;
  259. for (const alias of target.terminalIds) {
  260. const targets = terminalTargets.get(alias);
  261. if (!targets) continue;
  262. const index = targets.indexOf(target);
  263. if (index >= 0) targets.splice(index, 1);
  264. if (targets.length === 0) terminalTargets.delete(alias);
  265. }
  266. for (let index = pending.length - 1; index >= 0; index -= 1) {
  267. const interaction = pending[index];
  268. if (interaction !== target.interaction) continue;
  269. pending.splice(index, 1);
  270. interaction.terminated();
  271. }
  272. for (const [key, entry] of active) {
  273. const { interaction } = entry;
  274. if (interaction !== target.interaction) continue;
  275. if (!detachActive(key, entry, new RuntimeInteractionTerminated())) {
  276. interaction.terminated();
  277. return;
  278. }
  279. interaction.terminated();
  280. }
  281. drain();
  282. },
  283. close,
  284. };
  285. }
  286. async function cancelInteractions(
  287. interactions: readonly TuiAcpRuntimeInteraction[],
  288. ): Promise<void> {
  289. let next = 0;
  290. const worker = async () => {
  291. for (;;) {
  292. const interaction = interactions[next++];
  293. if (!interaction) return;
  294. await withTimeout(interaction.cancel(), INTERACTION_CANCEL_TIMEOUT_MS);
  295. }
  296. };
  297. await Promise.all(
  298. Array.from({ length: Math.min(INTERACTION_CANCEL_CONCURRENCY, interactions.length) }, worker),
  299. );
  300. }
  301. async function withTimeout(promise: Promise<void>, timeoutMs: number): Promise<void> {
  302. let timer: ReturnType<typeof setTimeout> | undefined;
  303. try {
  304. await Promise.race([
  305. promise.catch(() => undefined),
  306. new Promise<void>((resolve) => {
  307. timer = setTimeout(resolve, timeoutMs);
  308. timer.unref();
  309. }),
  310. ]);
  311. } finally {
  312. if (timer) clearTimeout(timer);
  313. }
  314. }
  315. function createProjectionScheduler(
  316. connection: acp.AgentConnection,
  317. timeoutMs: number,
  318. ): {
  319. enqueue(projection: TuiAcpRuntimeProjection): void;
  320. close(): void;
  321. } {
  322. interface PendingProjection {
  323. readonly projection: TuiAcpRuntimeProjection;
  324. readonly deadlineAt?: number;
  325. deadlineTimer?: ReturnType<typeof setTimeout>;
  326. }
  327. const active = new Map<string, AbortController>();
  328. const pending = new Map<string, PendingProjection>();
  329. let closed = false;
  330. const drain = () => {
  331. if (closed || active.size >= MAX_ACTIVE_PROJECTIONS) return;
  332. for (const [key, entry] of pending) {
  333. if (active.size >= MAX_ACTIVE_PROJECTIONS) return;
  334. if (active.has(key)) continue;
  335. pending.delete(key);
  336. if (entry.deadlineTimer) clearTimeout(entry.deadlineTimer);
  337. start(key, entry);
  338. }
  339. };
  340. function start(key: string, entry: PendingProjection): void {
  341. if (closed || active.has(key) || active.size >= MAX_ACTIVE_PROJECTIONS) return;
  342. const { projection } = entry;
  343. const controller = new AbortController();
  344. active.set(key, controller);
  345. const remainingMs = entry.deadlineAt
  346. ? Math.max(0, entry.deadlineAt - Date.now())
  347. : Math.max(0, timeoutMs);
  348. const timer = setTimeout(() => {
  349. const error = new Error('ACP Runtime event projection timed out.');
  350. controller.abort(error);
  351. if (projection.required) {
  352. closeScheduler();
  353. connection.close(error);
  354. }
  355. }, remainingMs);
  356. timer.unref();
  357. void Promise.resolve()
  358. .then(() => projection.run(controller.signal))
  359. .catch((error) => {
  360. if (!projection.required) return;
  361. closeScheduler();
  362. connection.close(
  363. error instanceof Error ? error : new Error('ACP required projection failed.'),
  364. );
  365. })
  366. .finally(() => {
  367. clearTimeout(timer);
  368. if (active.get(key) === controller) active.delete(key);
  369. drain();
  370. });
  371. }
  372. const closeScheduler = () => {
  373. if (closed) return;
  374. closed = true;
  375. for (const entry of pending.values()) {
  376. if (entry.deadlineTimer) clearTimeout(entry.deadlineTimer);
  377. entry.projection.onDrop?.();
  378. }
  379. pending.clear();
  380. for (const controller of active.values()) {
  381. controller.abort(new Error('ACP interaction stream closed.'));
  382. }
  383. };
  384. return {
  385. enqueue(projection) {
  386. if (closed) return;
  387. const key = projection.key;
  388. const existing = pending.get(key);
  389. if (existing?.projection.required && !projection.required) {
  390. projection.onDrop?.();
  391. return;
  392. }
  393. if (!pending.has(key) && pending.size >= MAX_PENDING_PROJECTIONS) {
  394. const evicted = [...pending].find(([, candidate]) => !candidate.projection.required);
  395. if (!evicted) {
  396. projection.onDrop?.();
  397. if (projection.required) {
  398. closeScheduler();
  399. connection.close(new Error('ACP Runtime required projection queue capacity exceeded.'));
  400. }
  401. return;
  402. }
  403. pending.delete(evicted[0]);
  404. if (evicted[1].deadlineTimer) clearTimeout(evicted[1].deadlineTimer);
  405. evicted[1].projection.onDrop?.();
  406. }
  407. if (existing?.deadlineTimer) clearTimeout(existing.deadlineTimer);
  408. existing?.projection.onDrop?.();
  409. const entry: PendingProjection = {
  410. projection,
  411. ...(projection.required
  412. ? {
  413. deadlineAt: existing?.deadlineAt ?? Date.now() + Math.max(0, timeoutMs),
  414. }
  415. : {}),
  416. };
  417. if (entry.deadlineAt !== undefined) {
  418. entry.deadlineTimer = setTimeout(
  419. () => {
  420. if (pending.get(key) !== entry) return;
  421. const error = new Error('ACP required projection timed out while pending.');
  422. closeScheduler();
  423. connection.close(error);
  424. },
  425. Math.max(0, entry.deadlineAt - Date.now()),
  426. );
  427. entry.deadlineTimer.unref();
  428. }
  429. pending.set(key, entry);
  430. drain();
  431. },
  432. close: closeScheduler,
  433. };
  434. }
  435. function createRuntimeInteraction(
  436. options: RunTuiAcpInteractionsOptions,
  437. event: TuiRuntimeEvent,
  438. enqueueProjection: (projection: TuiAcpRuntimeProjection) => void,
  439. ): TuiAcpRuntimeInteraction | undefined {
  440. if (event.type === 'questionnaire.ask') {
  441. const runtimeSessionId = event.request.requester?.sessionId ?? event.sessionId;
  442. const agentName = event.agentName ?? event.request.requester?.agentName;
  443. if (!runtimeSessionId || !agentName) return undefined;
  444. const resolved = options.resolveSession(runtimeSessionId);
  445. if (!resolved) return undefined;
  446. return {
  447. id: runtimeInteractionId('questionnaire', resolved.acpSessionId, event.request.id),
  448. terminalIds: runtimeInteractionTerminalAliases(
  449. 'questionnaire',
  450. event.request.id,
  451. resolved.acpSessionId,
  452. runtimeSessionId,
  453. ),
  454. key: resolved.acpSessionId,
  455. attachmentSignal: resolved.attachmentSignal,
  456. run: (signal) =>
  457. handleQuestionnaire(options, event, resolved, agentName, signal, enqueueProjection),
  458. cancel: async () => {
  459. await options.runtime.dismissQuestionnaire(agentName, event.request.id).catch(() => false);
  460. },
  461. terminated: () => {
  462. for (const projection of options.onQuestionnaireSettled?.({
  463. sessionId: resolved.acpSessionId,
  464. requestId: event.request.id,
  465. continued: false,
  466. }) ?? []) {
  467. enqueueProjection(projection);
  468. }
  469. },
  470. };
  471. }
  472. if (event.type !== 'permission.ask') return undefined;
  473. const runtimeSessionId = event.request.sessionId ?? event.sessionId;
  474. const requestId = event.request.requestId;
  475. if (!runtimeSessionId || !requestId) return undefined;
  476. const resolved = options.resolveSession(runtimeSessionId);
  477. const agentName = event.request.agentName ?? resolved?.session.agentName;
  478. if (!agentName || !resolved) return undefined;
  479. return {
  480. id: runtimeInteractionId('permission', resolved.acpSessionId, requestId),
  481. terminalIds: runtimeInteractionTerminalAliases(
  482. 'permission',
  483. requestId,
  484. resolved.acpSessionId,
  485. runtimeSessionId,
  486. ),
  487. key: resolved.acpSessionId,
  488. attachmentSignal: resolved.attachmentSignal,
  489. run: (signal) => handlePermission(options, event, resolved, agentName, requestId, signal),
  490. cancel: async () => {
  491. await options.runtime.replyPermission(agentName, requestId, 'deny');
  492. },
  493. terminated: () => undefined,
  494. };
  495. }
  496. function runtimeInteractionTerminalIds(event: TuiRuntimeEvent): readonly string[] | undefined {
  497. if (event.type === 'questionnaire.dismiss' || event.type === 'questionnaire.superseded') {
  498. return runtimeInteractionTerminalAliases('questionnaire', event.requestId, event.sessionId);
  499. }
  500. if (event.type === 'permission.resolved') {
  501. return runtimeInteractionTerminalAliases('permission', event.requestId, event.sessionId);
  502. }
  503. return undefined;
  504. }
  505. function runtimeInteractionTerminalAliases(
  506. kind: 'permission' | 'questionnaire',
  507. requestId: string,
  508. ...sessionIds: readonly (string | undefined)[]
  509. ): readonly string[] {
  510. return [
  511. ...new Set(
  512. sessionIds
  513. .filter((sessionId): sessionId is string => sessionId !== undefined)
  514. .map((sessionId) => `${kind}:${sessionId}:${requestId}`),
  515. ),
  516. `${kind}:${requestId}`,
  517. ];
  518. }
  519. function runtimeInteractionId(
  520. kind: 'permission' | 'questionnaire',
  521. runtimeSessionId: string,
  522. requestId: string,
  523. ): string {
  524. return `${kind}:${runtimeSessionId}:${requestId}`;
  525. }
  526. async function handlePermission(
  527. options: RunTuiAcpInteractionsOptions,
  528. event: Extract<TuiRuntimeEvent, { type: 'permission.ask' }>,
  529. resolved: ResolvedInteractionSession,
  530. agentName: string,
  531. requestId: string,
  532. schedulerSignal: AbortSignal,
  533. ): Promise<void> {
  534. let decision: 'allowOnce' | 'allowAlways' | 'deny' = 'deny';
  535. try {
  536. const response = await options.connection.client.request(
  537. acp.methods.client.session.requestPermission,
  538. permissionRequest(resolved.acpSessionId, requestId, event.request),
  539. {
  540. cancellationSignal: AbortSignal.any([
  541. options.connection.signal,
  542. resolved.attachmentSignal,
  543. schedulerSignal,
  544. ]),
  545. },
  546. );
  547. if (response.outcome.outcome === 'selected') {
  548. decision =
  549. response.outcome.optionId === 'allow-always' && event.request.allowAlwaysSupported
  550. ? 'allowAlways'
  551. : response.outcome.optionId === 'allow-once'
  552. ? 'allowOnce'
  553. : 'deny';
  554. }
  555. } catch {
  556. decision = 'deny';
  557. }
  558. if (schedulerSignal.reason instanceof RuntimeInteractionTerminated) return;
  559. if (!resolved.isCurrent()) decision = 'deny';
  560. await options.runtime.replyPermission(agentName, requestId, decision);
  561. }
  562. async function handleQuestionnaire(
  563. options: RunTuiAcpInteractionsOptions,
  564. event: Extract<TuiRuntimeEvent, { type: 'questionnaire.ask' }>,
  565. resolved: ResolvedInteractionSession,
  566. agentName: string,
  567. schedulerSignal: AbortSignal,
  568. enqueueProjection: (projection: TuiAcpRuntimeProjection) => void,
  569. ): Promise<void> {
  570. const request = event.request;
  571. const sessionId = resolved.acpSessionId;
  572. const requestSignal = AbortSignal.any([
  573. options.connection.signal,
  574. resolved.attachmentSignal,
  575. schedulerSignal,
  576. ]);
  577. let continued = false;
  578. try {
  579. if (options.clientCapabilities().elicitation?.form != null) {
  580. let response: acp.CreateElicitationResponse | undefined;
  581. try {
  582. response = await options.connection.client.request(
  583. acp.methods.client.elicitation.create,
  584. questionnaireElicitation(sessionId, request),
  585. { cancellationSignal: requestSignal },
  586. );
  587. } catch {
  588. if (!resolved.isCurrent()) return;
  589. continued = await answerSimpleQuestionnaireWithPermission(
  590. options,
  591. sessionId,
  592. agentName,
  593. request,
  594. requestSignal,
  595. resolved.isCurrent,
  596. );
  597. }
  598. if (response && acp.CreateElicitationResponse.isAccept(response) && resolved.isCurrent()) {
  599. const content = response.content ?? ({} as Record<string, acp.ElicitationContentValue>);
  600. continued = await options.runtime.replyQuestionnaire(
  601. agentName,
  602. request.id,
  603. questionnaireAnswers(request, content),
  604. );
  605. }
  606. } else {
  607. continued = await answerSimpleQuestionnaireWithPermission(
  608. options,
  609. sessionId,
  610. agentName,
  611. request,
  612. requestSignal,
  613. resolved.isCurrent,
  614. );
  615. }
  616. } catch {
  617. // The fail-closed path below dismisses the Runtime request.
  618. } finally {
  619. if (!continued && !(schedulerSignal.reason instanceof RuntimeInteractionTerminated)) {
  620. await options.runtime.dismissQuestionnaire(agentName, request.id).catch(() => false);
  621. }
  622. if (resolved.isCurrent()) {
  623. for (const projection of options.onQuestionnaireSettled?.({
  624. sessionId,
  625. requestId: request.id,
  626. continued,
  627. }) ?? []) {
  628. enqueueProjection(projection);
  629. }
  630. }
  631. }
  632. }
  633. async function answerSimpleQuestionnaireWithPermission(
  634. options: RunTuiAcpInteractionsOptions,
  635. sessionId: string,
  636. agentName: string,
  637. request: TuiQuestionnaireRequest,
  638. requestSignal: AbortSignal,
  639. isCurrent: () => boolean,
  640. ): Promise<boolean> {
  641. const [step, ...remainingSteps] = request.steps;
  642. if (!step || isMultiple(step) || step.allowOther || !step.options?.length) {
  643. return false;
  644. }
  645. const prefix = `questionnaire:${request.id}:`;
  646. try {
  647. const response = await options.connection.client.request<
  648. acp.RequestPermissionResponse,
  649. acp.RequestPermissionRequest
  650. >(
  651. acp.methods.client.session.requestPermission,
  652. {
  653. sessionId,
  654. toolCall: {
  655. toolCallId: request.id,
  656. title: step.question,
  657. kind: 'other',
  658. status: 'pending',
  659. },
  660. options: [
  661. ...step.options.map((option) => ({
  662. optionId: `${prefix}${option.id}`,
  663. name: option.label,
  664. kind: 'allow_once' as const,
  665. })),
  666. {
  667. optionId: `${prefix}cancel`,
  668. name: 'Cancel',
  669. kind: 'reject_once' as const,
  670. },
  671. ],
  672. },
  673. { cancellationSignal: requestSignal },
  674. );
  675. if (response.outcome.outcome !== 'selected') return false;
  676. const selectedId = response.outcome.optionId.startsWith(prefix)
  677. ? response.outcome.optionId.slice(prefix.length)
  678. : undefined;
  679. if (!selectedId || selectedId === 'cancel') return false;
  680. const selected = step.options.some((option) => option.id === selectedId);
  681. if (!selected) return false;
  682. if (!isCurrent()) return false;
  683. return await options.runtime.replyQuestionnaire(agentName, request.id, [
  684. { stepId: step.id, selectedOptionIds: [selectedId] },
  685. ...remainingSteps.map((remaining) => ({ stepId: remaining.id, skipped: true as const })),
  686. ]);
  687. } catch {
  688. return false;
  689. }
  690. }
  691. function questionnaireElicitation(
  692. sessionId: string,
  693. request: TuiQuestionnaireRequest,
  694. ): acp.CreateElicitationRequest {
  695. const properties: Record<string, acp.ElicitationPropertySchema> = {};
  696. const required: string[] = [];
  697. const fieldLayout = questionnaireFieldLayout(request);
  698. for (const step of request.steps) {
  699. properties[step.id] = questionnaireProperty(step);
  700. const otherFieldId = fieldLayout.get(step.id)?.otherFieldId;
  701. if (otherFieldId) {
  702. properties[otherFieldId] = compact({
  703. type: 'string' as const,
  704. title: `${step.question} — Other`,
  705. description: step.otherPlaceholder || step.description,
  706. });
  707. }
  708. if (step.required && !otherFieldId) required.push(step.id);
  709. }
  710. const title = request.title ?? 'MiniMax Code needs your input';
  711. return {
  712. mode: 'form',
  713. sessionId,
  714. message: title,
  715. requestedSchema: {
  716. type: 'object',
  717. properties,
  718. ...(required.length > 0 ? { required } : {}),
  719. },
  720. };
  721. }
  722. function questionnaireProperty(step: TuiQuestionnaireStep): acp.ElicitationPropertySchema {
  723. const options = step.options ?? [];
  724. const description =
  725. step.description ??
  726. (options.length === 0 && step.allowOther ? step.otherPlaceholder : undefined);
  727. if (isMultiple(step) && options.length > 0) {
  728. return compact({
  729. type: 'array' as const,
  730. title: step.question,
  731. description,
  732. items: {
  733. anyOf: questionnaireEnumOptions(step),
  734. },
  735. });
  736. }
  737. if (options.length > 0) {
  738. return compact({
  739. type: 'string' as const,
  740. title: step.question,
  741. description,
  742. oneOf: questionnaireEnumOptions(step),
  743. });
  744. }
  745. return compact({
  746. type: 'string' as const,
  747. title: step.question,
  748. description,
  749. });
  750. }
  751. function questionnaireAnswers(
  752. request: TuiQuestionnaireRequest,
  753. content: Record<string, acp.ElicitationContentValue>,
  754. ): TuiQuestionnaireReplyAnswer[] {
  755. const fieldLayout = questionnaireFieldLayout(request);
  756. return request.steps.flatMap((step): TuiQuestionnaireReplyAnswer[] => {
  757. const value = content[step.id];
  758. if (isMultiple(step)) {
  759. const options = step.options ?? [];
  760. if (options.length === 0) {
  761. if (step.allowOther && typeof value === 'string' && value.trim().length > 0) {
  762. return [{ stepId: step.id, selectedOther: true, otherText: value }];
  763. }
  764. return step.required ? [] : [{ stepId: step.id, skipped: true }];
  765. }
  766. const selectedOptionIds = questionnaireOptionIds(
  767. step,
  768. Array.isArray(value) ? value : [value],
  769. );
  770. const otherFieldId = fieldLayout.get(step.id)?.otherFieldId;
  771. const otherText = otherFieldId ? content[otherFieldId] : undefined;
  772. const selectedOther = typeof otherText === 'string' && otherText.trim().length > 0;
  773. if (selectedOptionIds.length > 0 || selectedOther) {
  774. return [
  775. {
  776. stepId: step.id,
  777. ...(selectedOptionIds.length > 0 ? { selectedOptionIds } : {}),
  778. ...(selectedOther ? { selectedOther: true, otherText } : {}),
  779. },
  780. ];
  781. }
  782. return step.required ? [] : [{ stepId: step.id, skipped: true }];
  783. }
  784. const otherFieldId = fieldLayout.get(step.id)?.otherFieldId;
  785. const otherText = otherFieldId ? content[otherFieldId] : undefined;
  786. if (typeof otherText === 'string' && otherText.trim().length > 0) {
  787. return [{ stepId: step.id, selectedOther: true, otherText }];
  788. }
  789. if (typeof value !== 'string') {
  790. return step.required ? [] : [{ stepId: step.id, skipped: true }];
  791. }
  792. const [selectedOptionId] = questionnaireOptionIds(step, [value]);
  793. if (selectedOptionId) {
  794. return [{ stepId: step.id, selectedOptionIds: [selectedOptionId] }];
  795. }
  796. if (step.allowOther && !otherFieldId) {
  797. return [{ stepId: step.id, selectedOther: true, otherText: value }];
  798. }
  799. return step.required ? [] : [{ stepId: step.id, skipped: true }];
  800. });
  801. }
  802. function questionnaireFieldLayout(
  803. request: TuiQuestionnaireRequest,
  804. ): ReadonlyMap<string, { readonly otherFieldId?: string }> {
  805. const used = new Set(request.steps.map(({ id }) => id));
  806. const layout = new Map<string, { readonly otherFieldId?: string }>();
  807. for (const step of request.steps) {
  808. if (!step.allowOther || (step.options ?? []).length === 0) {
  809. layout.set(step.id, {});
  810. continue;
  811. }
  812. let otherFieldId = `${step.id}__other`;
  813. while (used.has(otherFieldId)) otherFieldId += '_';
  814. used.add(otherFieldId);
  815. layout.set(step.id, { otherFieldId });
  816. }
  817. return layout;
  818. }
  819. function questionnaireOptionIds(step: TuiQuestionnaireStep, values: readonly unknown[]): string[] {
  820. const selected = values.flatMap((value) => {
  821. if (typeof value !== 'string') return [];
  822. const options = step.options ?? [];
  823. const optionById = options.find((candidate) => candidate.id === value);
  824. if (optionById) return [optionById.id];
  825. const optionsByLabel = options.filter((candidate) => candidate.label === value);
  826. const [onlyLabelMatch] = optionsByLabel;
  827. return optionsByLabel.length === 1 && onlyLabelMatch ? [onlyLabelMatch.id] : [];
  828. });
  829. return [...new Set(selected)];
  830. }
  831. function questionnaireEnumOptions(step: TuiQuestionnaireStep): acp.EnumOption[] {
  832. return (step.options ?? []).map((option) =>
  833. compact({
  834. const: option.id,
  835. title: option.label,
  836. description: option.description,
  837. }),
  838. );
  839. }
  840. function isMultiple(step: TuiQuestionnaireStep): boolean {
  841. return step.selectionMode === 'multiple' || step.selectionMode === 1;
  842. }
  843. function permissionRequest(
  844. sessionId: string,
  845. requestId: string,
  846. request: TuiPendingPermission,
  847. ): acp.RequestPermissionRequest {
  848. const rawInput = parseToolInput(request.toolInput);
  849. const locations = permissionLocations(request, rawInput);
  850. return {
  851. sessionId,
  852. toolCall: compact({
  853. toolCallId: requestId,
  854. title: request.toolDescription ?? request.toolName ?? 'MiniMax Code tool',
  855. name: request.toolName,
  856. kind: tuiAcpToolKind(request.toolName ?? ''),
  857. status: 'pending' as const,
  858. rawInput,
  859. locations,
  860. }),
  861. options: [
  862. { optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' },
  863. ...(request.allowAlwaysSupported
  864. ? [{ optionId: 'allow-always', name: 'Always allow', kind: 'allow_always' as const }]
  865. : []),
  866. { optionId: 'deny', name: 'Deny', kind: 'reject_once' },
  867. ],
  868. };
  869. }
  870. function parseToolInput(value: string | undefined): unknown {
  871. if (value === undefined) return undefined;
  872. try {
  873. return JSON.parse(value);
  874. } catch {
  875. return value;
  876. }
  877. }
  878. function permissionLocations(
  879. request: TuiPendingPermission,
  880. rawInput: unknown,
  881. ): acp.ToolCallLocation[] | undefined {
  882. const paths = new Set<string>();
  883. for (const block of request.structuredPreview?.blocks ?? []) {
  884. if (block.path && isTuiAcpAbsolutePath(block.path)) paths.add(block.path);
  885. }
  886. if (rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)) {
  887. const record = rawInput as Record<string, unknown>;
  888. for (const key of ['path', 'filePath', 'file_path']) {
  889. const path = record[key];
  890. if (typeof path === 'string' && isTuiAcpAbsolutePath(path)) paths.add(path);
  891. }
  892. }
  893. return paths.size > 0 ? [...paths].map((path) => ({ path })) : undefined;
  894. }
  895. function compact<T extends object>(value: T): T {
  896. return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;
  897. }