@@ -3,6 +3,7 @@ import { NextResponse } from 'next/server'
33
44import type { NextRequest } from 'next/server'
55
6+ import { getAgentRunFromId } from '@/db/agent-run'
67import { getUserInfoFromApiKey } from '@/db/user'
78import { handleOpenRouterStream } from '@/llm-api/openrouter'
89import { extractApiKeyFromHeader } from '@/util/auth'
@@ -45,37 +46,51 @@ export async function POST(req: NextRequest) {
4546 )
4647 }
4748
48- if ( body . stream ) {
49- try {
50- const stream = await handleOpenRouterStream ( {
51- body ,
52- userId ,
53- } )
49+ if ( ! body . stream ) {
50+ return NextResponse . json (
51+ { message : 'Not implemented. Use stream=true.' } ,
52+ { status : 500 }
53+ )
54+ }
5455
55- return new NextResponse ( stream , {
56- headers : {
57- 'Content-Type' : 'text/event-stream' ,
58- 'Cache-Control' : 'no-cache' ,
59- Connection : 'keep-alive' ,
60- 'Access-Control-Allow-Origin' : '*' ,
61- } ,
62- } )
63- } catch ( error ) {
64- logger . error (
65- errorToObject ( error ) ,
66- 'Error setting up OpenRouter stream:'
67- )
68- return NextResponse . json (
69- { error : 'Failed to initialize stream' } ,
70- { status : 500 }
71- )
72- }
56+ const runIdFromBody = body . codebuff_metadata ?. agentRunId
57+ if ( ! runIdFromBody ) {
58+ return NextResponse . json (
59+ { message : 'No agent run ID found in request body' } ,
60+ { status : 400 }
61+ )
62+ }
63+ const runId = runIdFromBody
64+ ? getAgentRunFromId ( { agentRunId : runIdFromBody , userId, fields : [ 'id' ] } )
65+ : null
66+ if ( ! runId ) {
67+ return NextResponse . json (
68+ { message : `Agent Run ID Not Found: ${ runIdFromBody } ` } ,
69+ { status : 404 }
70+ )
7371 }
7472
75- return NextResponse . json (
76- { message : 'Not implemented. Use stream=true.' } ,
77- { status : 500 }
78- )
73+ try {
74+ const stream = await handleOpenRouterStream ( {
75+ body,
76+ userId,
77+ } )
78+
79+ return new NextResponse ( stream , {
80+ headers : {
81+ 'Content-Type' : 'text/event-stream' ,
82+ 'Cache-Control' : 'no-cache' ,
83+ Connection : 'keep-alive' ,
84+ 'Access-Control-Allow-Origin' : '*' ,
85+ } ,
86+ } )
87+ } catch ( error ) {
88+ logger . error ( errorToObject ( error ) , 'Error setting up OpenRouter stream:' )
89+ return NextResponse . json (
90+ { error : 'Failed to initialize stream' } ,
91+ { status : 500 }
92+ )
93+ }
7994 } catch ( error ) {
8095 logger . error (
8196 errorToObject ( error ) ,
0 commit comments