(
@Param('agentRunId') agentRunId: string,
@Body(new ZodValidationPipe(AgentChatRequestSchema)) body: AgentChatRequestDto,
@CurrentAuth() auth: AuthContext | null,
@Res() res: Response,
@Req() req: Request,
)
| 73 | @Post('/:agentRunId/chat') |
| 74 | @ApiOkResponse({ description: 'AI SDK-compatible SSE for agent run' }) |
| 75 | async chat( |
| 76 | @Param('agentRunId') agentRunId: string, |
| 77 | @Body(new ZodValidationPipe(AgentChatRequestSchema)) body: AgentChatRequestDto, |
| 78 | @CurrentAuth() auth: AuthContext | null, |
| 79 | @Res() res: Response, |
| 80 | @Req() req: Request, |
| 81 | ): Promise<void> { |
| 82 | const metadata = await this.agentTraceService.getRunMetadata(agentRunId); |
| 83 | if (!metadata) { |
| 84 | throw new NotFoundException(`Agent run ${agentRunId} not found`); |
| 85 | } |
| 86 | await this.workflowsService.ensureRunAccess(metadata.workflowRunId, auth); |
| 87 | |
| 88 | let lastSequence = typeof body?.cursor === 'number' ? body.cursor : 0; |
| 89 | let seenFinish = false; |
| 90 | let aborted = false; |
| 91 | |
| 92 | req.on('close', () => { |
| 93 | aborted = true; |
| 94 | }); |
| 95 | |
| 96 | const stream = createUIMessageStream({ |
| 97 | execute: async ({ writer }) => { |
| 98 | while (!seenFinish && !aborted) { |
| 99 | const events = await this.agentTraceService.list(agentRunId, lastSequence); |
| 100 | if (events.length > 0) { |
| 101 | events.forEach((event) => { |
| 102 | const chunk = convertAgentTraceToUiChunk(event); |
| 103 | if (chunk) { |
| 104 | writer.write(chunk); |
| 105 | if (chunk.type === 'finish') { |
| 106 | seenFinish = true; |
| 107 | } |
| 108 | } |
| 109 | }); |
| 110 | lastSequence = events[events.length - 1]?.sequence ?? lastSequence; |
| 111 | continue; |
| 112 | } |
| 113 | await sleep(1000); |
| 114 | } |
| 115 | }, |
| 116 | onError: (error) => { |
| 117 | this.logger.error( |
| 118 | `Agent chat stream failed for agent ${agentRunId}`, |
| 119 | error instanceof Error ? error.stack : String(error), |
| 120 | ); |
| 121 | return error instanceof Error ? error.message : String(error); |
| 122 | }, |
| 123 | }); |
| 124 | |
| 125 | pipeUIMessageStreamToResponse({ |
| 126 | response: res, |
| 127 | stream, |
| 128 | }); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
no test coverage detected