conversation-renderer.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. /**
  2. * Conversation-context renderer for the cloud gateway.
  3. *
  4. * The cloud endpoint `POST /mavis/api/v1/permission/check` expects a
  5. * pre-rendered text block in its `conversation_context` field; the rendering
  6. * algorithm must match what the server-side prompt expects byte-for-byte.
  7. *
  8. * Output shape:
  9. *
  10. * <empty> if no messages
  11. *
  12. * "\n\n## Recent User Instructions\n<msg1>\n---\n<msg2>\n\n## Recent Conversation\n[role] msg\n[role] msg"
  13. *
  14. * - User messages: keep first and last 250 chars with "...[truncated]..."
  15. * in the middle when length > 500
  16. * - Other messages (assistant / system / tool): truncated to 200 chars
  17. * with trailing "..."
  18. * - Tool calls are flattened to "tool:<name> args=<truncated> result=<truncated>"
  19. * - User msg_ids already shown in the "## Recent User Instructions"
  20. * section are excluded from "## Recent Conversation"
  21. *
  22. * Section presence: each section appears only when its source list is
  23. * non-empty AND has at least one renderable entry. Leading "\n\n" is
  24. * preserved at the start of the whole block (the cloud prompt template puts
  25. * the action block first).
  26. */
  27. import type { AgentMessageProtocol } from '@mavis/agent-core/protocol/agent-message';
  28. // ---------------------------------------------------------------------------
  29. // Constants
  30. // ---------------------------------------------------------------------------
  31. const TRUNCATE_LIMIT = 200;
  32. const USER_MSG_LIMIT = 500;
  33. const USER_MSG_HALF = 250;
  34. // ---------------------------------------------------------------------------
  35. // Input
  36. // ---------------------------------------------------------------------------
  37. export interface RenderConversationContextInput {
  38. /**
  39. * Latest 3 user messages (excluding permission-response envelopes).
  40. * These render under "## Recent User Instructions".
  41. *
  42. * Caller responsibility:
  43. * - Filter out permission-response messages BEFORE passing in.
  44. * The legacy daemon does this in `MessageStorePort.getRecent`
  45. * via `{ excludePermissionResponses: true }`.
  46. * - Limit count (caller picks 3 to match legacy behavior).
  47. */
  48. latestUserMessages?: ReadonlyArray<AgentMessageProtocol>;
  49. /**
  50. * Latest N messages from the whole conversation (mixed roles).
  51. * Caller picks count (legacy picks 5). Render order is whatever the
  52. * input array gives; the renderer does not sort.
  53. */
  54. recentMessages?: ReadonlyArray<AgentMessageProtocol>;
  55. }
  56. // ---------------------------------------------------------------------------
  57. // Public
  58. // ---------------------------------------------------------------------------
  59. /**
  60. * Render the conversation-context text block.
  61. *
  62. * Pure function — no I/O. The MessageStore lookup happens in the caller so
  63. * this module is trivially testable without DB / fixtures.
  64. */
  65. export function renderConversationContext(input: RenderConversationContextInput): string {
  66. const sections: string[] = [];
  67. const userMsgIds = new Set<string>();
  68. // Section 1: Recent User Instructions
  69. if (input.latestUserMessages && input.latestUserMessages.length > 0) {
  70. const userLines: string[] = [];
  71. for (const m of input.latestUserMessages) {
  72. if (!m.msg_content) continue;
  73. userMsgIds.add(m.msg_id);
  74. userLines.push(truncateUserMessage(m.msg_content));
  75. }
  76. if (userLines.length > 0) {
  77. sections.push(`## Recent User Instructions\n${userLines.join('\n---\n')}`);
  78. }
  79. }
  80. // Section 2: Recent Conversation (dedup against the user IDs above)
  81. if (input.recentMessages && input.recentMessages.length > 0) {
  82. const formatted = formatRecentMessages(input.recentMessages, userMsgIds);
  83. if (formatted) {
  84. sections.push(`## Recent Conversation\n${formatted}`);
  85. }
  86. }
  87. return sections.length > 0 ? `\n\n${sections.join('\n\n')}` : '';
  88. }
  89. // ---------------------------------------------------------------------------
  90. // Helpers — verbatim from yolo-classifier
  91. // ---------------------------------------------------------------------------
  92. function truncateStr(s: string | undefined, limit = TRUNCATE_LIMIT): string {
  93. if (!s) return '';
  94. return s.length > limit ? `${s.slice(0, limit)}...` : s;
  95. }
  96. function truncateUserMessage(s: string): string {
  97. if (s.length <= USER_MSG_LIMIT) return s;
  98. return `${s.slice(0, USER_MSG_HALF)}\n...[truncated]...\n${s.slice(-USER_MSG_HALF)}`;
  99. }
  100. interface ToolCallLike {
  101. tool_name?: string;
  102. tool_call_args?: string;
  103. tool_call_result_data?: string;
  104. }
  105. function formatToolCall(tc: ToolCallLike): string {
  106. const args = truncateStr(tc.tool_call_args);
  107. const result = truncateStr(tc.tool_call_result_data);
  108. const parts = [`tool:${tc.tool_name ?? ''}`];
  109. if (args) parts.push(`args=${args}`);
  110. if (result) parts.push(`result=${result}`);
  111. return parts.join(' ');
  112. }
  113. function formatRecentMessages(
  114. messages: ReadonlyArray<AgentMessageProtocol>,
  115. excludeMsgIds: ReadonlySet<string>,
  116. ): string {
  117. const lines: string[] = [];
  118. for (const msg of messages) {
  119. const role = msg.role ?? 'unknown';
  120. // Skip user messages already shown in user instructions section
  121. if (role === 'user' && excludeMsgIds.has(msg.msg_id)) continue;
  122. if (msg.tool_calls && msg.tool_calls.length > 0) {
  123. const toolSummary = msg.tool_calls.map(formatToolCall).join('; ');
  124. const contentPart = msg.msg_content ? `${truncateStr(msg.msg_content)} | ` : '';
  125. lines.push(`[${role}] ${contentPart}${toolSummary}`);
  126. } else if (msg.msg_content) {
  127. const content =
  128. role === 'user' ? truncateUserMessage(msg.msg_content) : truncateStr(msg.msg_content);
  129. lines.push(`[${role}] ${content}`);
  130. }
  131. }
  132. return lines.join('\n');
  133. }