result-event-projection.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { RuntimeEventType, type RuntimeEvent } from '@mavis/agent-core/protocol';
  2. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  3. import type { ReviewActivityIdentity } from './activity-events.js';
  4. import type { ReviewOutcome } from './types.js';
  5. export function projectReviewResultEvent(
  6. event: RuntimeEvent,
  7. activity: (ReviewActivityIdentity & { terminal?: boolean }) | undefined,
  8. turnId: string,
  9. outcome: ReviewOutcome | undefined,
  10. ): RuntimeEvent {
  11. if (!outcome) return event;
  12. if (event.type !== RuntimeEventType.STREAM_RESP) return event;
  13. const raw = event.payload.stream_resp;
  14. if (typeof raw !== 'string') return event;
  15. try {
  16. const data = JSON.parse(raw) as {
  17. type?: number;
  18. agent_message?: Record<string, unknown>;
  19. };
  20. if (
  21. data.type !== RespDataType.AgentMessage ||
  22. !data.agent_message ||
  23. typeof data.agent_message.msg_content !== 'string'
  24. ) {
  25. return event;
  26. }
  27. const annotationResult = /^\s*<annotation-result\b/iu.test(data.agent_message.msg_content);
  28. const replacesActivity = annotationResult && activity && !activity.terminal;
  29. const currentOrigin =
  30. data.agent_message.origin &&
  31. typeof data.agent_message.origin === 'object' &&
  32. !Array.isArray(data.agent_message.origin)
  33. ? data.agent_message.origin
  34. : {};
  35. return {
  36. ...event,
  37. payload: {
  38. ...event.payload,
  39. stream_resp: JSON.stringify({
  40. ...data,
  41. agent_message: {
  42. ...data.agent_message,
  43. ...(replacesActivity
  44. ? {
  45. msg_id: activity.messageId,
  46. source: 'code_review',
  47. kind: 'review_result',
  48. }
  49. : {}),
  50. origin: {
  51. ...currentOrigin,
  52. ...(replacesActivity
  53. ? {
  54. type: 'code-review-activity',
  55. reviewRunId: activity.reviewRunId,
  56. turnId,
  57. }
  58. : {}),
  59. reviewOutcome: outcome,
  60. },
  61. },
  62. }),
  63. },
  64. };
  65. } catch {
  66. return event;
  67. }
  68. }