terminal-response-recovery.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import type {
  2. AfterLlmCallHandler,
  3. AgentExtension,
  4. StepEndHandler,
  5. TurnAssemblyCtx,
  6. } from '@mavis/agent-runtime';
  7. export interface TerminalRecoveryObservation {
  8. readonly sessionId: string;
  9. readonly turnId: string;
  10. readonly attempts: number;
  11. }
  12. export interface TerminalResponseRecoveryExtensionOptions {
  13. readonly retryPrompt?: string;
  14. readonly onRecovered?: (observation: TerminalRecoveryObservation) => void | Promise<void>;
  15. readonly onFailed?: (observation: TerminalRecoveryObservation) => void | Promise<void>;
  16. readonly id?: string;
  17. readonly description?: string;
  18. }
  19. interface RecoveryState {
  20. lastToolBatch: 'none' | 'success' | 'error';
  21. attempts: number;
  22. recoveryPending: boolean;
  23. }
  24. const DEFAULT_RETRY_PROMPT =
  25. 'The tools completed, but your response was empty. Provide a concise final response summarizing the result for the user.';
  26. /**
  27. * Gives a post-tool empty assistant response one bounded recovery request.
  28. * A second empty response fails the product turn with `terminal_empty` rather
  29. * than reporting a blank success.
  30. */
  31. export function terminalResponseRecoveryExtension(
  32. options: TerminalResponseRecoveryExtensionOptions = {},
  33. ): AgentExtension {
  34. const states = new Map<string, RecoveryState>();
  35. const onStepEnd: StepEndHandler = (event, ctx) => {
  36. const state = stateFor(states, ctx);
  37. state.lastToolBatch =
  38. event.toolResults.length === 0
  39. ? 'none'
  40. : event.toolResults.some((result) => result.isError)
  41. ? 'error'
  42. : 'success';
  43. };
  44. const afterLlmCall: AfterLlmCallHandler = async (event, ctx) => {
  45. const state = stateFor(states, ctx);
  46. if (event.message.stopReason === 'error' || event.message.stopReason === 'aborted') {
  47. return { type: 'continue' };
  48. }
  49. const hasToolIntent = event.message.content.some((block) => block.type === 'toolCall');
  50. const hasVisibleText = event.message.content.some(
  51. (block) => block.type === 'text' && block.text.trim().length > 0,
  52. );
  53. if (hasToolIntent || hasVisibleText) {
  54. if (state.recoveryPending && hasVisibleText) {
  55. await notify(options.onRecovered, observation(ctx, state.attempts));
  56. state.recoveryPending = false;
  57. }
  58. return { type: 'continue' };
  59. }
  60. if (state.recoveryPending) {
  61. state.attempts += 1;
  62. await notify(options.onFailed, observation(ctx, state.attempts));
  63. return { type: 'fail', reason: 'terminal_empty' };
  64. }
  65. if (state.lastToolBatch !== 'success') return { type: 'continue' };
  66. state.attempts = 1;
  67. state.recoveryPending = true;
  68. return {
  69. type: 'retry',
  70. reason: 'terminal_empty',
  71. prompt: options.retryPrompt ?? DEFAULT_RETRY_PROMPT,
  72. };
  73. };
  74. return {
  75. id: options.id ?? 'terminal-response-recovery',
  76. description:
  77. options.description ??
  78. 'Retry one empty post-tool terminal response, then fail visibly with terminal_empty.',
  79. init(pi) {
  80. pi.on('on_step_end', onStepEnd);
  81. pi.on('after_llm_call', afterLlmCall);
  82. pi.on('turn_end', (_event, ctx) => {
  83. states.delete(runKey(ctx));
  84. });
  85. },
  86. };
  87. }
  88. function runKey(ctx: Pick<TurnAssemblyCtx, 'sessionId' | 'turnId'>): string {
  89. return `${ctx.sessionId}\u0000${ctx.turnId}`;
  90. }
  91. function stateFor(states: Map<string, RecoveryState>, ctx: TurnAssemblyCtx): RecoveryState {
  92. const key = runKey(ctx);
  93. let state = states.get(key);
  94. if (!state) {
  95. state = { lastToolBatch: 'none', attempts: 0, recoveryPending: false };
  96. states.set(key, state);
  97. }
  98. return state;
  99. }
  100. function observation(ctx: TurnAssemblyCtx, attempts: number): TerminalRecoveryObservation {
  101. return { sessionId: ctx.sessionId, turnId: ctx.turnId, attempts };
  102. }
  103. async function notify(
  104. observer:
  105. | TerminalResponseRecoveryExtensionOptions['onRecovered']
  106. | TerminalResponseRecoveryExtensionOptions['onFailed'],
  107. value: TerminalRecoveryObservation,
  108. ): Promise<void> {
  109. if (!observer) return;
  110. try {
  111. await observer(value);
  112. } catch {
  113. // Observability must not change recovery semantics.
  114. }
  115. }