converters.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. import { describe, it, expect } from 'vitest';
  2. import {
  3. buildAbortedTerminalStatusEvent,
  4. buildCompletedAssistantMessage,
  5. buildCompletedTerminalStatusEvent,
  6. buildDebugTraceEvent,
  7. buildFailedTerminalStatusEvent,
  8. buildFinishChunk,
  9. buildRunningSessionStatusEvent,
  10. buildStreamRespEvent,
  11. buildTextDeltaChunk,
  12. buildThinkingDeltaChunk,
  13. buildToolCallChunk,
  14. extractAssistantErrorMessage,
  15. extractAssistantStopReason,
  16. extractAssistantText,
  17. extractAssistantThinking,
  18. extractAssistantToolCalls,
  19. extractAssistantUsage,
  20. extractDeltaUpdate,
  21. extractFinalAssistantText,
  22. extractFinalAssistantUsageFromBuffer,
  23. isAssistantError,
  24. toolCallFromRuntime,
  25. } from '../../../src/event-bridge/converters.js';
  26. import { MsgType, RespDataType, ToolCallStatus } from '../../../src/protocol/agent-message.js';
  27. import { RUNTIME_EVENT_SCHEMA } from '../../../src/protocol/runtime-event.js';
  28. import { buildRuntimeWarningEvent } from '../../../src/event-bridge/runtime-warning.js';
  29. import type { RuntimeEvent, StreamRespEvent } from '../../../src/protocol/runtime-event.js';
  30. import {
  31. ProtocolErrorCode,
  32. RuntimeDebugTraceLevel,
  33. RuntimeEventStatus,
  34. RuntimeEventType,
  35. RuntimeStopReasonType,
  36. } from '@mavis/protocol';
  37. const fixture = {
  38. sessionId: 'sess-1',
  39. turnId: 'turn-1',
  40. msgId: 'msg-1',
  41. nowMs: 1_700_000_000_000,
  42. };
  43. describe('event-bridge/converters: extractDeltaUpdate', () => {
  44. it('returns text delta for text_delta event', () => {
  45. expect(extractDeltaUpdate({ type: 'text_delta', delta: 'hello', contentIndex: 0 })).toEqual({
  46. kind: 'text',
  47. delta: 'hello',
  48. });
  49. });
  50. it('returns thinking delta for thinking_delta event', () => {
  51. expect(
  52. extractDeltaUpdate({ type: 'thinking_delta', delta: 'hmm', contentIndex: 0 }),
  53. ).toEqual({
  54. kind: 'thinking',
  55. delta: 'hmm',
  56. });
  57. });
  58. it('returns undefined for unrelated event types', () => {
  59. expect(extractDeltaUpdate({ type: 'start' })).toBeUndefined();
  60. expect(extractDeltaUpdate({ type: 'tool_call_start', delta: 'x' })).toBeUndefined();
  61. });
  62. it('returns undefined when payload is not an object', () => {
  63. expect(extractDeltaUpdate(null)).toBeUndefined();
  64. expect(extractDeltaUpdate(undefined)).toBeUndefined();
  65. expect(extractDeltaUpdate('text_delta')).toBeUndefined();
  66. expect(extractDeltaUpdate(42)).toBeUndefined();
  67. });
  68. it('returns undefined when delta is not a string', () => {
  69. expect(extractDeltaUpdate({ type: 'text_delta', delta: 42 })).toBeUndefined();
  70. });
  71. });
  72. describe('event-bridge/converters: extractAssistantText / Thinking / ToolCalls', () => {
  73. it('joins all text blocks into a single string', () => {
  74. const message = {
  75. role: 'assistant',
  76. content: [
  77. { type: 'text', text: 'Hello' },
  78. { type: 'text', text: ' world' },
  79. { type: 'thinking', thinking: 'hidden' },
  80. ],
  81. };
  82. expect(extractAssistantText(message)).toBe('Hello world');
  83. });
  84. it('returns empty string when content is missing or non-array', () => {
  85. expect(extractAssistantText({})).toBe('');
  86. expect(extractAssistantText(null)).toBe('');
  87. expect(extractAssistantText({ content: 42 })).toBe('');
  88. });
  89. it('returns string content directly when content is a string', () => {
  90. expect(extractAssistantText({ content: 'plain string' })).toBe('plain string');
  91. });
  92. it('joins all thinking blocks', () => {
  93. const message = {
  94. content: [
  95. { type: 'thinking', thinking: 'plan' },
  96. { type: 'text', text: 'visible' },
  97. { type: 'thinking', thinking: ' more' },
  98. ],
  99. };
  100. expect(extractAssistantThinking(message)).toBe('plan more');
  101. });
  102. it('returns empty thinking when content is a string (no thinking blocks)', () => {
  103. expect(extractAssistantThinking({ content: 'plain' })).toBe('');
  104. });
  105. it('extracts toolCall blocks into RuntimeToolCall[]', () => {
  106. const message = {
  107. content: [
  108. { type: 'text', text: 'plan' },
  109. { type: 'toolCall', id: 'call-1', name: 'read', arguments: { path: '/x' } },
  110. { type: 'toolCall', id: 'call-2', name: 'bash', arguments: { command: 'ls' } },
  111. ],
  112. };
  113. expect(extractAssistantToolCalls(message)).toEqual([
  114. { tool_name: 'read', tool_call_id: 'call-1', status: 'started', args: { path: '/x' } },
  115. { tool_name: 'bash', tool_call_id: 'call-2', status: 'started', args: { command: 'ls' } },
  116. ]);
  117. });
  118. it('omits args field when arguments is missing or not an object', () => {
  119. const message = {
  120. content: [
  121. { type: 'toolCall', id: 'call-1', name: 'noop' },
  122. { type: 'toolCall', id: 'call-2', name: 'foo', arguments: 'bad-args' },
  123. ],
  124. };
  125. expect(extractAssistantToolCalls(message)).toEqual([
  126. { tool_name: 'noop', tool_call_id: 'call-1', status: 'started' },
  127. { tool_name: 'foo', tool_call_id: 'call-2', status: 'started' },
  128. ]);
  129. });
  130. it('returns empty list for invalid input', () => {
  131. expect(extractAssistantToolCalls(null)).toEqual([]);
  132. expect(extractAssistantToolCalls({ content: 'not array' })).toEqual([]);
  133. expect(extractAssistantToolCalls({ content: [{ type: 'toolCall', id: 42 }] })).toEqual([]);
  134. });
  135. });
  136. describe('event-bridge/converters: isAssistantError / extractAssistantErrorMessage / extractAssistantStopReason', () => {
  137. it('isAssistantError true when role=assistant and stopReason=error', () => {
  138. expect(isAssistantError({ role: 'assistant', stopReason: 'error' })).toBe(true);
  139. });
  140. it('isAssistantError false when stopReason !== error', () => {
  141. expect(isAssistantError({ role: 'assistant', stopReason: 'stop' })).toBe(false);
  142. });
  143. it('isAssistantError false when role !== assistant', () => {
  144. expect(isAssistantError({ role: 'user', stopReason: 'error' })).toBe(false);
  145. });
  146. it('isAssistantError false for invalid input', () => {
  147. expect(isAssistantError(null)).toBe(false);
  148. expect(isAssistantError(undefined)).toBe(false);
  149. expect(isAssistantError('not-a-message')).toBe(false);
  150. });
  151. it('extractAssistantErrorMessage returns string when present', () => {
  152. expect(extractAssistantErrorMessage({ errorMessage: 'rate limited' })).toBe('rate limited');
  153. });
  154. it('extractAssistantErrorMessage returns undefined when missing', () => {
  155. expect(extractAssistantErrorMessage({})).toBeUndefined();
  156. expect(extractAssistantErrorMessage(null)).toBeUndefined();
  157. expect(extractAssistantErrorMessage({ errorMessage: '' })).toBeUndefined();
  158. });
  159. it('extractAssistantStopReason returns string when present', () => {
  160. expect(extractAssistantStopReason({ stopReason: 'stop' })).toBe('stop');
  161. expect(extractAssistantStopReason({ stopReason: 'toolUse' })).toBe('toolUse');
  162. });
  163. it('extractAssistantStopReason returns undefined when missing or empty', () => {
  164. expect(extractAssistantStopReason({})).toBeUndefined();
  165. expect(extractAssistantStopReason({ stopReason: '' })).toBeUndefined();
  166. expect(extractAssistantStopReason(null)).toBeUndefined();
  167. });
  168. });
  169. describe('event-bridge/converters: toolCallFromRuntime', () => {
  170. it('maps started status to ToolCallStatus.Start', () => {
  171. expect(
  172. toolCallFromRuntime({
  173. tool_name: 'bash',
  174. tool_call_id: 'c1',
  175. status: 'started',
  176. args: { command: 'ls' },
  177. }),
  178. ).toEqual({
  179. tool_name: 'bash',
  180. tool_call_id: 'c1',
  181. tool_call_status: ToolCallStatus.Start,
  182. tool_call_args: '{"command":"ls"}',
  183. });
  184. });
  185. it('maps completed status to ToolCallStatus.Finished and serialises result', () => {
  186. expect(
  187. toolCallFromRuntime({
  188. tool_name: 'read',
  189. tool_call_id: 'c2',
  190. status: 'completed',
  191. result: { lines: 10 },
  192. }),
  193. ).toEqual({
  194. tool_name: 'read',
  195. tool_call_id: 'c2',
  196. tool_call_status: ToolCallStatus.Finished,
  197. tool_call_result_data: '{"lines":10}',
  198. });
  199. });
  200. it('maps failed status to ToolCallStatus.Failed and wraps error', () => {
  201. const out = toolCallFromRuntime({
  202. tool_name: 'bash',
  203. tool_call_id: 'c3',
  204. status: 'failed',
  205. error: { code: ProtocolErrorCode.INTERNAL_ERROR, message: 'boom' },
  206. });
  207. expect(out.tool_call_status).toBe(ToolCallStatus.Failed);
  208. expect(out.tool_call_result_data).toBe('{"error":{"code":50001,"message":"boom"}}');
  209. });
  210. it('maps `running` status defensively to Start', () => {
  211. expect(toolCallFromRuntime({ tool_name: 'x', tool_call_id: 'c', status: 'running' })).toEqual({
  212. tool_name: 'x',
  213. tool_call_id: 'c',
  214. tool_call_status: ToolCallStatus.Start,
  215. });
  216. });
  217. it('serialises duration_ms onto tool_call_duration_ms when present', () => {
  218. expect(
  219. toolCallFromRuntime({
  220. tool_name: 'read',
  221. tool_call_id: 'c4',
  222. status: 'completed',
  223. result: { lines: 1 },
  224. duration_ms: 321,
  225. }),
  226. ).toEqual({
  227. tool_name: 'read',
  228. tool_call_id: 'c4',
  229. tool_call_status: ToolCallStatus.Finished,
  230. tool_call_result_data: '{"lines":1}',
  231. tool_call_duration_ms: 321,
  232. });
  233. });
  234. it('omits tool_call_duration_ms when duration_ms is absent', () => {
  235. const out = toolCallFromRuntime({ tool_name: 'x', tool_call_id: 'c5', status: 'completed' });
  236. expect(out).not.toHaveProperty('tool_call_duration_ms');
  237. });
  238. it('strips inline image base64 from tool_call_result_data', () => {
  239. const bigBase64 = 'A'.repeat(3_500_000); // 3.5 MB base64 payload
  240. const result = toolCallFromRuntime({
  241. tool_name: 'read',
  242. tool_call_id: 'c-image',
  243. status: 'completed',
  244. result: {
  245. content: [
  246. { type: 'text', text: 'Read image file [image/png]' },
  247. { type: 'image', data: bigBase64, mimeType: 'image/png' },
  248. ],
  249. details: {},
  250. },
  251. });
  252. const decoded = JSON.parse(result.tool_call_result_data!);
  253. expect(decoded.content).toEqual([
  254. { type: 'text', text: 'Read image file [image/png]' },
  255. ]);
  256. expect(result.tool_call_result_data!.length).toBeLessThan(200);
  257. });
  258. it('strips inline video base64 (read tool image block with video/* mime)', () => {
  259. const bigBase64 = 'B'.repeat(12_000_000); // 12 MB video payload
  260. const result = toolCallFromRuntime({
  261. tool_name: 'read',
  262. tool_call_id: 'c-video',
  263. status: 'completed',
  264. result: {
  265. content: [
  266. { type: 'text', text: 'Read video file [video/mp4]' },
  267. { type: 'image', data: bigBase64, mimeType: 'video/mp4' },
  268. ],
  269. details: { media: { kind: 'video', mime_type: 'video/mp4', size_bytes: 9_000_000 } },
  270. },
  271. });
  272. const decoded = JSON.parse(result.tool_call_result_data!);
  273. expect(decoded.content).toEqual([
  274. { type: 'text', text: 'Read video file [video/mp4]' },
  275. ]);
  276. expect(decoded.details).toEqual({
  277. media: { kind: 'video', mime_type: 'video/mp4', size_bytes: 9_000_000 },
  278. });
  279. expect(result.tool_call_result_data!.length).toBeLessThan(400);
  280. });
  281. it('leaves text-only results untouched', () => {
  282. const out = toolCallFromRuntime({
  283. tool_name: 'bash',
  284. tool_call_id: 'c-bash',
  285. status: 'completed',
  286. result: { content: [{ type: 'text', text: 'hi' }], details: { ok: true } },
  287. });
  288. expect(out.tool_call_result_data).toBe(
  289. JSON.stringify({ content: [{ type: 'text', text: 'hi' }], details: { ok: true } }),
  290. );
  291. });
  292. it('does NOT mutate the original tc.result object (pi retains it for LLM ctx)', () => {
  293. const bigBase64 = 'C'.repeat(2_000_000);
  294. const original = {
  295. content: [
  296. { type: 'text', text: 'Read image file [image/jpeg]' },
  297. { type: 'image', data: bigBase64, mimeType: 'image/jpeg' },
  298. ],
  299. details: {},
  300. };
  301. toolCallFromRuntime({
  302. tool_name: 'read',
  303. tool_call_id: 'c-mut',
  304. status: 'completed',
  305. result: original,
  306. });
  307. expect(original.content).toHaveLength(2);
  308. expect((original.content[1] as { data: string }).data).toBe(bigBase64);
  309. });
  310. });
  311. describe('event-bridge/converters: stream-event builders', () => {
  312. it('buildRuntimeWarningEvent uses a SystemEvent envelope rather than model history content', () => {
  313. const event = buildRuntimeWarningEvent({
  314. sessionId: fixture.sessionId,
  315. turnId: fixture.turnId,
  316. eventId: 'warning-1',
  317. runtimeSeq: 1,
  318. message: 'A Plugin Hook failed open.',
  319. source: 'plugin-hook',
  320. hookEvent: 'PreToolUse',
  321. nowMs: 123,
  322. });
  323. const envelope = JSON.parse(event.payload.stream_resp) as {
  324. type: number;
  325. agent_message: { msg_type: number; msg_content: string };
  326. };
  327. expect(envelope.type).toBe(RespDataType.AgentMessage);
  328. expect(envelope.agent_message.msg_type).toBe(MsgType.SystemEvent);
  329. expect(JSON.parse(envelope.agent_message.msg_content)).toEqual({
  330. eventType: 'runtime.warning',
  331. message: 'A Plugin Hook failed open.',
  332. source: 'plugin-hook',
  333. hookEvent: 'PreToolUse',
  334. });
  335. });
  336. it('buildStreamRespEvent serialises RespData into payload.stream_resp', () => {
  337. const ev = buildStreamRespEvent({
  338. sessionId: fixture.sessionId,
  339. turnId: fixture.turnId,
  340. eventId: 'evt-1',
  341. runtimeSeq: 7,
  342. respData: {
  343. type: RespDataType.AgentMessageChunk,
  344. agent_message_chunk: { msg_id: fixture.msgId, chunk_index: 0, msg_content: 'hi' },
  345. },
  346. });
  347. expect(ev.schema).toBe(RUNTIME_EVENT_SCHEMA);
  348. expect(ev.type).toBe(RuntimeEventType.STREAM_RESP);
  349. expect(ev.event_id).toBe('evt-1');
  350. expect(ev.runtime_seq).toBe(7);
  351. expect(typeof ev.payload.stream_resp).toBe('string');
  352. expect(ev.payload).toEqual({ stream_resp: ev.payload.stream_resp });
  353. const inner = JSON.parse(ev.payload.stream_resp!);
  354. expect(inner).toEqual({
  355. type: RespDataType.AgentMessageChunk,
  356. agent_message_chunk: { msg_id: fixture.msgId, chunk_index: 0, msg_content: 'hi' },
  357. });
  358. expect(inner).not.toHaveProperty('schema');
  359. expect(inner).not.toHaveProperty('event_id');
  360. expect(inner).not.toHaveProperty('payload');
  361. });
  362. it('buildTextDeltaChunk packs delta as msg_content with role=assistant', () => {
  363. const ev = buildTextDeltaChunk({
  364. sessionId: fixture.sessionId,
  365. turnId: fixture.turnId,
  366. eventId: 'evt-2',
  367. runtimeSeq: 1,
  368. msgId: fixture.msgId,
  369. chunkIndex: 0,
  370. delta: 'hello',
  371. nowMs: fixture.nowMs,
  372. });
  373. const respData = JSON.parse(ev.payload.stream_resp!);
  374. expect(respData.type).toBe(RespDataType.AgentMessageChunk);
  375. expect(respData.agent_message_chunk.msg_content).toBe('hello');
  376. expect(respData.agent_message_chunk.role).toBe('assistant');
  377. expect(respData.agent_message_chunk.turn_id).toBe(fixture.turnId);
  378. expect(respData.agent_message_chunk.timestamp).toBe(fixture.nowMs);
  379. });
  380. it('buildThinkingDeltaChunk packs delta as thinking_content', () => {
  381. const ev = buildThinkingDeltaChunk({
  382. sessionId: fixture.sessionId,
  383. turnId: fixture.turnId,
  384. eventId: 'evt-3',
  385. runtimeSeq: 2,
  386. msgId: fixture.msgId,
  387. chunkIndex: 1,
  388. delta: 'thought',
  389. nowMs: fixture.nowMs,
  390. });
  391. const respData = JSON.parse(ev.payload.stream_resp!);
  392. expect(respData.agent_message_chunk.thinking_content).toBe('thought');
  393. expect(respData.agent_message_chunk.msg_content).toBeUndefined();
  394. });
  395. it('buildToolCallChunk wraps a single RuntimeToolCall', () => {
  396. const ev = buildToolCallChunk({
  397. sessionId: fixture.sessionId,
  398. turnId: fixture.turnId,
  399. eventId: 'evt-4',
  400. runtimeSeq: 3,
  401. msgId: fixture.msgId,
  402. chunkIndex: 2,
  403. toolCall: {
  404. tool_name: 'read',
  405. tool_call_id: 'tc-1',
  406. status: 'started',
  407. args: { path: '/x' },
  408. },
  409. nowMs: fixture.nowMs,
  410. });
  411. const respData = JSON.parse(ev.payload.stream_resp!);
  412. expect(respData.agent_message_chunk.tool_calls).toHaveLength(1);
  413. expect(respData.agent_message_chunk.tool_calls[0]).toEqual({
  414. tool_name: 'read',
  415. tool_call_id: 'tc-1',
  416. tool_call_status: ToolCallStatus.Start,
  417. tool_call_args: '{"path":"/x"}',
  418. });
  419. });
  420. it('buildFinishChunk emits a finish=true chunk with optional reason and thinking_duration_ms', () => {
  421. const ev = buildFinishChunk({
  422. sessionId: fixture.sessionId,
  423. turnId: fixture.turnId,
  424. eventId: 'evt-5',
  425. runtimeSeq: 4,
  426. msgId: fixture.msgId,
  427. chunkIndex: 3,
  428. finishReason: 'stop',
  429. thinkingDurationMs: 1234,
  430. nowMs: fixture.nowMs,
  431. });
  432. const respData = JSON.parse(ev.payload.stream_resp!);
  433. expect(respData.agent_message_chunk.finish).toBe(true);
  434. expect(respData.agent_message_chunk.finish_reason).toBe('stop');
  435. expect(respData.agent_message_chunk.thinking_duration_ms).toBe(1234);
  436. });
  437. it('buildFinishChunk omits finish_reason and thinking_duration_ms when not provided', () => {
  438. const ev = buildFinishChunk({
  439. sessionId: fixture.sessionId,
  440. turnId: fixture.turnId,
  441. eventId: 'evt-6',
  442. runtimeSeq: 5,
  443. msgId: fixture.msgId,
  444. chunkIndex: 4,
  445. nowMs: fixture.nowMs,
  446. });
  447. const respData = JSON.parse(ev.payload.stream_resp!);
  448. expect(respData.agent_message_chunk.finish).toBe(true);
  449. expect(respData.agent_message_chunk.finish_reason).toBeUndefined();
  450. expect(respData.agent_message_chunk.thinking_duration_ms).toBeUndefined();
  451. });
  452. it('buildCompletedAssistantMessage emits an AgentMessage with text/thinking/tools/usage', async () => {
  453. const ev = await buildCompletedAssistantMessage({
  454. sessionId: fixture.sessionId,
  455. turnId: fixture.turnId,
  456. eventId: 'evt-7',
  457. runtimeSeq: 6,
  458. msgId: fixture.msgId,
  459. text: 'final text',
  460. thinking: 'final thinking',
  461. thinkingDurationMs: 500,
  462. finishReason: 'stop',
  463. toolCalls: [{ tool_name: 'read', tool_call_id: 'tc-1', status: 'completed', result: 42 }],
  464. usage: { total_tokens: 100, context_window: 200_000 },
  465. nowMs: fixture.nowMs,
  466. });
  467. const respData = JSON.parse(ev.payload.stream_resp!);
  468. expect(respData.type).toBe(RespDataType.AgentMessage);
  469. expect(respData.agent_message.msg_content).toBe('final text');
  470. expect(respData.agent_message.turn_id).toBe(fixture.turnId);
  471. expect(respData.agent_message.thinking_content).toBe('final thinking');
  472. expect(respData.agent_message.thinking_duration_ms).toBe(500);
  473. expect(respData.agent_message.finish_reason).toBe('stop');
  474. expect(respData.agent_message.tool_calls).toHaveLength(1);
  475. expect(respData.agent_message.tool_calls[0].tool_call_status).toBe(ToolCallStatus.Finished);
  476. expect(respData.agent_message.usage).toEqual({ total_tokens: 100, context_window: 200_000 });
  477. });
  478. it('buildCompletedAssistantMessage omits optional fields when missing', async () => {
  479. const ev = await buildCompletedAssistantMessage({
  480. sessionId: fixture.sessionId,
  481. turnId: fixture.turnId,
  482. eventId: 'evt-8',
  483. runtimeSeq: 7,
  484. msgId: fixture.msgId,
  485. text: 'plain',
  486. nowMs: fixture.nowMs,
  487. });
  488. const respData = JSON.parse(ev.payload.stream_resp!);
  489. expect(respData.agent_message.thinking_content).toBeUndefined();
  490. expect(respData.agent_message.tool_calls).toBeUndefined();
  491. expect(respData.agent_message.usage).toBeUndefined();
  492. expect(respData.agent_message.thinking_duration_ms).toBeUndefined();
  493. });
  494. it('buildCompletedAssistantMessage applies respDataTransform when supplied', async () => {
  495. let captured: { sessionId: string; turnId: string } | undefined;
  496. const ev = await buildCompletedAssistantMessage(
  497. {
  498. sessionId: fixture.sessionId,
  499. turnId: fixture.turnId,
  500. eventId: 'evt-9',
  501. runtimeSeq: 8,
  502. msgId: fixture.msgId,
  503. text: 'orig',
  504. nowMs: fixture.nowMs,
  505. },
  506. async (respData, ctx) => {
  507. captured = ctx;
  508. if (!respData.agent_message) return respData;
  509. return {
  510. ...respData,
  511. agent_message: { ...respData.agent_message, msg_content: 'rewritten' },
  512. };
  513. },
  514. );
  515. const respData = JSON.parse(ev.payload.stream_resp!);
  516. expect(respData.agent_message.msg_content).toBe('rewritten');
  517. expect(captured).toEqual({ sessionId: fixture.sessionId, turnId: fixture.turnId });
  518. });
  519. it('buildCompletedAssistantMessage falls back to original RespData when transform throws', async () => {
  520. const ev = await buildCompletedAssistantMessage(
  521. {
  522. sessionId: fixture.sessionId,
  523. turnId: fixture.turnId,
  524. eventId: 'evt-10',
  525. runtimeSeq: 9,
  526. msgId: fixture.msgId,
  527. text: 'unchanged',
  528. nowMs: fixture.nowMs,
  529. },
  530. () => {
  531. throw new Error('transform boom');
  532. },
  533. );
  534. const respData = JSON.parse(ev.payload.stream_resp!);
  535. expect(respData.agent_message.msg_content).toBe('unchanged');
  536. });
  537. });
  538. describe('event-bridge/converters: terminal pair builders', () => {
  539. it('buildRunningSessionStatusEvent returns running status', () => {
  540. const status = buildRunningSessionStatusEvent({
  541. sessionId: fixture.sessionId,
  542. turnId: fixture.turnId,
  543. eventId: 's-running',
  544. });
  545. expect(status.type).toBe(RuntimeEventType.SESSION_STATUS);
  546. expect(status.payload.status).toBe(RuntimeEventStatus.RUNNING);
  547. expect(status.payload.stop_reason).toBeUndefined();
  548. });
  549. it('buildCompletedTerminalStatusEvent returns completed status', () => {
  550. const status = buildCompletedTerminalStatusEvent({
  551. sessionId: fixture.sessionId,
  552. turnId: fixture.turnId,
  553. statusEventId: 's-1',
  554. });
  555. expect(status.type).toBe(RuntimeEventType.SESSION_STATUS);
  556. expect(status.payload.status).toBe(RuntimeEventStatus.COMPLETED);
  557. expect(status.payload.stop_reason).toEqual({ type: RuntimeStopReasonType.END_TURN });
  558. });
  559. it('buildCompletedTerminalStatusEvent includes optional usage when supplied', () => {
  560. const status = buildCompletedTerminalStatusEvent({
  561. sessionId: fixture.sessionId,
  562. turnId: fixture.turnId,
  563. statusEventId: 's-1',
  564. terminalUsage: { input_tokens: 10, output_tokens: 20, total_tokens: 30 },
  565. });
  566. expect(status.payload.usage).toEqual({ input_tokens: 10, output_tokens: 20, total_tokens: 30 });
  567. });
  568. it('buildAbortedTerminalStatusEvent returns aborted status', () => {
  569. const status = buildAbortedTerminalStatusEvent({
  570. sessionId: fixture.sessionId,
  571. turnId: fixture.turnId,
  572. statusEventId: 's-2',
  573. });
  574. expect(status.payload.status).toBe(RuntimeEventStatus.ABORTED);
  575. expect(status.payload.stop_reason).toEqual({
  576. type: RuntimeStopReasonType.ABORT,
  577. message: 'aborted',
  578. });
  579. });
  580. it('buildFailedTerminalStatusEvent packs message into stop_reason and protocol error', () => {
  581. const status = buildFailedTerminalStatusEvent({
  582. sessionId: fixture.sessionId,
  583. turnId: fixture.turnId,
  584. statusEventId: 's-3',
  585. message: 'kaboom',
  586. });
  587. expect(status.payload.status).toBe(RuntimeEventStatus.FAILED);
  588. expect(status.payload.stop_reason).toEqual({
  589. type: RuntimeStopReasonType.ERROR,
  590. message: 'kaboom',
  591. });
  592. expect(status.payload.error).toEqual({ code: ProtocolErrorCode.INTERNAL_ERROR, message: 'kaboom' });
  593. });
  594. it('buildFailedTerminalStatusEvent forwards explicit protocol error code', () => {
  595. const status = buildFailedTerminalStatusEvent({
  596. sessionId: fixture.sessionId,
  597. turnId: fixture.turnId,
  598. statusEventId: 's-4',
  599. message: 'denied',
  600. error: { code: ProtocolErrorCode.INTERNAL_ERROR, message: 'denied' },
  601. });
  602. expect(status.payload.error?.code).toBe(ProtocolErrorCode.INTERNAL_ERROR);
  603. });
  604. });
  605. describe('event-bridge/converters: buildDebugTraceEvent', () => {
  606. it('packs phase + level + attrs + duration_ms (attrs JSON-stringified into attrs_json)', () => {
  607. const ev = buildDebugTraceEvent({
  608. sessionId: fixture.sessionId,
  609. turnId: fixture.turnId,
  610. eventId: 'dbg-1',
  611. phase: 'tool_call_started',
  612. message: 'started',
  613. level: 'info',
  614. attrs: { tool: 'read', n: 1, flag: true },
  615. durationMs: 42,
  616. });
  617. expect(ev.type).toBe(RuntimeEventType.DEBUG_TRACE);
  618. expect(ev.payload).toBeDefined();
  619. if (ev.type === RuntimeEventType.DEBUG_TRACE) {
  620. expect(ev.payload.trace!.phase).toBe('tool_call_started');
  621. expect(ev.payload.trace!.level).toBe(RuntimeDebugTraceLevel.INFO);
  622. expect(ev.payload.trace!.message).toBe('started');
  623. expect(JSON.parse(ev.payload.trace!.attrs_json!)).toEqual({
  624. tool: 'read',
  625. n: 1,
  626. flag: true,
  627. });
  628. expect(ev.payload.trace!.duration_ms).toBe(42);
  629. }
  630. });
  631. it('defaults level to debug', () => {
  632. const ev = buildDebugTraceEvent({
  633. sessionId: fixture.sessionId,
  634. turnId: fixture.turnId,
  635. eventId: 'dbg-2',
  636. phase: 'phase-x',
  637. message: 'msg',
  638. });
  639. if (ev.type === RuntimeEventType.DEBUG_TRACE) {
  640. expect(ev.payload.trace!.level).toBe(RuntimeDebugTraceLevel.DEBUG);
  641. expect(ev.payload.trace!.duration_ms).toBeUndefined();
  642. }
  643. });
  644. });
  645. describe('extractAssistantUsage', () => {
  646. it('returns undefined for non-object input', () => {
  647. expect(extractAssistantUsage(undefined, 200_000)).toBeUndefined();
  648. expect(extractAssistantUsage(null, 200_000)).toBeUndefined();
  649. expect(extractAssistantUsage(42, 200_000)).toBeUndefined();
  650. });
  651. it('returns undefined when message role is not assistant', () => {
  652. expect(extractAssistantUsage({ role: 'user', usage: { totalTokens: 100 } }, 200_000)).toBeUndefined();
  653. });
  654. it('returns undefined when stopReason is aborted or error (pi suppresses usage)', () => {
  655. expect(
  656. extractAssistantUsage(
  657. { role: 'assistant', stopReason: 'aborted', usage: { totalTokens: 100 } },
  658. 200_000,
  659. ),
  660. ).toBeUndefined();
  661. expect(
  662. extractAssistantUsage(
  663. { role: 'assistant', stopReason: 'error', usage: { totalTokens: 100 } },
  664. 200_000,
  665. ),
  666. ).toBeUndefined();
  667. });
  668. it('returns undefined when usage block is missing', () => {
  669. expect(extractAssistantUsage({ role: 'assistant' }, 200_000)).toBeUndefined();
  670. expect(extractAssistantUsage({ role: 'assistant', usage: null }, 200_000)).toBeUndefined();
  671. });
  672. it('prefers totalTokens over input+output+cacheRead+cacheWrite', () => {
  673. const result = extractAssistantUsage(
  674. {
  675. role: 'assistant',
  676. stopReason: 'end_turn',
  677. usage: { input: 100, output: 50, cacheRead: 0, cacheWrite: 0, totalTokens: 999 },
  678. },
  679. 200_000,
  680. );
  681. expect(result).toEqual({
  682. total_tokens: 999,
  683. context_window: 200_000,
  684. input_tokens: 100,
  685. output_tokens: 50,
  686. });
  687. });
  688. it('falls back to input+output+cacheRead+cacheWrite when totalTokens is missing or zero', () => {
  689. const result = extractAssistantUsage(
  690. {
  691. role: 'assistant',
  692. stopReason: 'end_turn',
  693. usage: { input: 100, output: 50, cacheRead: 30, cacheWrite: 20 },
  694. },
  695. 200_000,
  696. );
  697. // Cache hits/writes are also surfaced so observability can distinguish
  698. // a true zero from "provider did not report cache stats".
  699. expect(result).toEqual({
  700. total_tokens: 200,
  701. context_window: 200_000,
  702. input_tokens: 100,
  703. output_tokens: 50,
  704. cache_read: 30,
  705. cache_write: 20,
  706. });
  707. });
  708. it('uses caller-provided contextWindow (per-model metadata)', () => {
  709. const result = extractAssistantUsage(
  710. { role: 'assistant', usage: { totalTokens: 500 } },
  711. 131_072,
  712. );
  713. expect(result?.context_window).toBe(131_072);
  714. });
  715. it('coerces non-finite usage values to 0', () => {
  716. const result = extractAssistantUsage(
  717. {
  718. role: 'assistant',
  719. usage: { input: NaN, output: 'oops', cacheRead: 30, cacheWrite: 20 },
  720. },
  721. 200_000,
  722. );
  723. // input/output coerce to 0 but valid cacheRead/cacheWrite still surface.
  724. expect(result).toEqual({
  725. total_tokens: 50,
  726. context_window: 200_000,
  727. cache_read: 30,
  728. cache_write: 20,
  729. });
  730. });
  731. it('keeps an explicit zero input or output instead of dropping the field', () => {
  732. // Full prompt-cache hits report input: 0 alongside cacheRead. Dropping the
  733. // zero makes downstream usage summaries treat a known count as unknown and
  734. // flag the turn incomplete, so explicit finite zeros must survive.
  735. const result = extractAssistantUsage(
  736. {
  737. role: 'assistant',
  738. stopReason: 'end_turn',
  739. usage: { input: 0, output: 20, cacheRead: 50, cacheWrite: 0, totalTokens: 70 },
  740. },
  741. 200_000,
  742. );
  743. expect(result).toEqual({
  744. total_tokens: 70,
  745. context_window: 200_000,
  746. input_tokens: 0,
  747. output_tokens: 20,
  748. cache_read: 50,
  749. });
  750. });
  751. it('still omits input and output when the provider did not report them', () => {
  752. const result = extractAssistantUsage(
  753. { role: 'assistant', stopReason: 'end_turn', usage: { totalTokens: 500 } },
  754. 200_000,
  755. );
  756. expect(result).toEqual({ total_tokens: 500, context_window: 200_000 });
  757. });
  758. });
  759. // ─── Buffer-walk helpers (sub-agent extraction) ─────────────────────────
  760. /** Build a minimal `stream.resp` RuntimeEvent from a serialised RespData. */
  761. function fakeStreamResp(respData: object): StreamRespEvent {
  762. return {
  763. schema: RUNTIME_EVENT_SCHEMA,
  764. event_id: 'ev-fake',
  765. session_id: fixture.sessionId,
  766. turn_id: fixture.turnId,
  767. runtime_seq: 0,
  768. type: RuntimeEventType.STREAM_RESP,
  769. payload: { stream_resp: JSON.stringify(respData) },
  770. };
  771. }
  772. describe('extractFinalAssistantText (buffer-walk helper)', () => {
  773. it('returns the AgentMessage msg_content even when followed by tool-call chunks', () => {
  774. const buffered: RuntimeEvent[] = [
  775. // [0] AgentMessageChunk with partial text
  776. fakeStreamResp({
  777. type: RespDataType.AgentMessageChunk,
  778. agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0, msg_content: 'partial' },
  779. }),
  780. // [1] Completed AgentMessage with final text
  781. fakeStreamResp({
  782. type: RespDataType.AgentMessage,
  783. agent_message: {
  784. msg_id: 'msg-1',
  785. msg_type: MsgType.AgentContent,
  786. role: 'assistant',
  787. msg_content: 'FINAL TEXT',
  788. timestamp: fixture.nowMs,
  789. },
  790. }),
  791. // [2] AgentMessageChunk with tool_calls (arrives after the closed message)
  792. fakeStreamResp({
  793. type: RespDataType.AgentMessageChunk,
  794. agent_message_chunk: {
  795. msg_id: 'msg-1',
  796. chunk_index: 1,
  797. tool_calls: [{ tool_name: 'bash', tool_call_id: 'tc-1', tool_call_status: 1 }],
  798. },
  799. }),
  800. // [3] terminal session.status
  801. {
  802. schema: RUNTIME_EVENT_SCHEMA,
  803. event_id: 'ev-term',
  804. session_id: fixture.sessionId,
  805. turn_id: fixture.turnId,
  806. type: RuntimeEventType.SESSION_STATUS,
  807. payload: {
  808. status: RuntimeEventStatus.COMPLETED,
  809. stop_reason: { type: RuntimeStopReasonType.END_TURN },
  810. },
  811. } as RuntimeEvent,
  812. ];
  813. expect(extractFinalAssistantText(buffered)).toBe('FINAL TEXT');
  814. });
  815. it('returns empty string when buffer has no AgentMessage frame', () => {
  816. const buffered: RuntimeEvent[] = [
  817. fakeStreamResp({
  818. type: RespDataType.AgentMessageChunk,
  819. agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0, msg_content: 'chunk only' },
  820. }),
  821. fakeStreamResp({
  822. type: RespDataType.AgentMessageChunk,
  823. agent_message_chunk: { msg_id: 'msg-1', chunk_index: 1, finish: true },
  824. }),
  825. {
  826. schema: RUNTIME_EVENT_SCHEMA,
  827. event_id: 'ev-term',
  828. session_id: fixture.sessionId,
  829. turn_id: fixture.turnId,
  830. type: RuntimeEventType.SESSION_STATUS,
  831. payload: {
  832. status: RuntimeEventStatus.COMPLETED,
  833. stop_reason: { type: RuntimeStopReasonType.END_TURN },
  834. },
  835. } as RuntimeEvent,
  836. ];
  837. expect(extractFinalAssistantText(buffered)).toBe('');
  838. });
  839. });
  840. describe('extractFinalAssistantUsageFromBuffer', () => {
  841. it('returns usage from the last AgentMessage', () => {
  842. const buffered: RuntimeEvent[] = [
  843. fakeStreamResp({
  844. type: RespDataType.AgentMessage,
  845. agent_message: {
  846. msg_id: 'msg-1',
  847. msg_type: MsgType.AgentContent,
  848. role: 'assistant',
  849. msg_content: 'done',
  850. timestamp: fixture.nowMs,
  851. usage: { total_tokens: 500, context_window: 200_000 },
  852. },
  853. }),
  854. ];
  855. expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
  856. total_tokens: 500,
  857. context_window: 200_000,
  858. });
  859. });
  860. it('returns undefined when buffer has no AgentMessage', () => {
  861. const buffered: RuntimeEvent[] = [
  862. fakeStreamResp({
  863. type: RespDataType.AgentMessageChunk,
  864. agent_message_chunk: { msg_id: 'msg-1', chunk_index: 0 },
  865. }),
  866. ];
  867. expect(extractFinalAssistantUsageFromBuffer(buffered)).toBeUndefined();
  868. });
  869. // Regression: sub-agent buffer path (cloud-task.ts:207) must propagate
  870. // cache_read / cache_write so sub-agent cache metrics aren't silently
  871. // dropped — symmetric with extractAssistantUsage on the direct event path.
  872. it('propagates cache_read / cache_write when present in usage', () => {
  873. const buffered: RuntimeEvent[] = [
  874. fakeStreamResp({
  875. type: RespDataType.AgentMessage,
  876. agent_message: {
  877. msg_id: 'msg-1',
  878. msg_type: MsgType.AgentContent,
  879. role: 'assistant',
  880. msg_content: 'done',
  881. timestamp: fixture.nowMs,
  882. usage: {
  883. total_tokens: 1500,
  884. context_window: 200_000,
  885. cache_read: 800,
  886. cache_write: 200,
  887. },
  888. },
  889. }),
  890. ];
  891. expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
  892. total_tokens: 1500,
  893. context_window: 200_000,
  894. cache_read: 800,
  895. cache_write: 200,
  896. });
  897. });
  898. it('omits cache_read / cache_write when zero or missing', () => {
  899. const buffered: RuntimeEvent[] = [
  900. fakeStreamResp({
  901. type: RespDataType.AgentMessage,
  902. agent_message: {
  903. msg_id: 'msg-1',
  904. msg_type: MsgType.AgentContent,
  905. role: 'assistant',
  906. msg_content: 'done',
  907. timestamp: fixture.nowMs,
  908. usage: {
  909. total_tokens: 500,
  910. context_window: 200_000,
  911. cache_read: 0,
  912. cache_write: 0,
  913. },
  914. },
  915. }),
  916. ];
  917. expect(extractFinalAssistantUsageFromBuffer(buffered)).toEqual({
  918. total_tokens: 500,
  919. context_window: 200_000,
  920. });
  921. });
  922. });