-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
214 lines (192 loc) · 7.09 KB
/
route.ts
File metadata and controls
214 lines (192 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { NextRequest } from 'next/server';
import { appendSessionMessages } from '@/lib/agent-memory';
import { globalEventEmitter } from '@/lib/event-emitter';
// Type definitions for streaming events
interface AgentEventData {
sessionId: string;
status?: string;
message?: string;
content?: string;
fullContent?: string;
tool?: string;
response?: string;
sandboxUrl?: string;
error?: string;
hasSandbox?: boolean;
sandboxId?: string;
isNew?: boolean;
}
// Helper function to create SSE messages
function createSSEMessage(type: string, data: Record<string, unknown>): string {
return `data: ${JSON.stringify({ type, data })}\n\n`;
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const sessionId = searchParams.get('sessionId');
if (!sessionId) {
return new Response('Missing sessionId parameter', { status: 400 });
}
// Create a ReadableStream for Server-Sent Events
const stream = new ReadableStream({
start(controller) {
// Send headers to establish SSE connection
const encoder = new TextEncoder();
let isClosed = false;
const send = (data: string) => {
if (isClosed) {
return;
}
try {
controller.enqueue(encoder.encode(data));
} catch (error) {
console.error('[SSE Stream] Error sending data:', error);
isClosed = true;
}
};
// Initial connection message
send(createSSEMessage('connected', { sessionId }));
// Event handlers for different types of updates
const handleAgentUpdate = (data: AgentEventData) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('status', {
sessionId: data.sessionId,
status: data.status,
message: data.message,
hasSandbox: data.hasSandbox,
}));
}
};
const handlePartialContent = (data: AgentEventData) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('partial', {
sessionId: data.sessionId,
content: data.content,
fullContent: data.fullContent,
}));
}
};
const handleToolUsed = (data: AgentEventData & { args?: Record<string, unknown>; result?: string; status?: string }) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('tool', {
sessionId: data.sessionId,
tool: data.tool,
args: data.args,
result: data.result,
status: data.status,
}));
}
};
const handleSandboxStatus = (data: AgentEventData) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('sandbox', {
sessionId: data.sessionId,
sandboxId: data.sandboxId,
sandboxUrl: data.sandboxUrl,
isNew: data.isNew,
}));
}
};
const handleComplete = (data: AgentEventData) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('complete', {
sessionId: data.sessionId,
response: data.response,
sandboxUrl: data.sandboxUrl,
hasSandbox: data.hasSandbox,
}));
if (data.response) {
appendSessionMessages(sessionId, [{ role: 'ai', content: String(data.response), ts: Date.now() }]);
}
}
};
const handleError = (data: AgentEventData) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('error', {
sessionId: data.sessionId,
error: data.error,
}));
}
};
const handleReasoning = (data: AgentEventData & { reasoning?: string }) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('reasoning', {
sessionId: data.sessionId,
reasoning: data.reasoning,
}));
}
};
const handleFileUpdate = (data: AgentEventData & { filePath?: string; content?: string; action?: 'start' | 'update' | 'complete' }) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('file_update', {
sessionId: data.sessionId,
filePath: data.filePath,
content: data.content,
action: data.action,
}));
}
};
const handleCodePatch = (data: AgentEventData & { filePath?: string; content?: string; action?: 'start' | 'patch' | 'complete' }) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('code_patch', {
sessionId: data.sessionId,
filePath: data.filePath,
content: data.content,
action: data.action,
}));
}
};
const handleFileTreeSync = (data: AgentEventData & { fileTree?: unknown }) => {
if (data.sessionId === sessionId) {
send(createSSEMessage('file_tree_sync', {
sessionId: data.sessionId,
fileTree: data.fileTree,
}));
}
};
// Listen for different types of events
globalEventEmitter.on('agent:status', handleAgentUpdate);
globalEventEmitter.on('agent:partial', handlePartialContent);
globalEventEmitter.on('agent:tool', handleToolUsed);
globalEventEmitter.on('agent:sandbox', handleSandboxStatus);
globalEventEmitter.on('agent:complete', handleComplete);
globalEventEmitter.on('agent:error', handleError);
globalEventEmitter.on('agent:reasoning', handleReasoning);
globalEventEmitter.on('agent:fileUpdate', handleFileUpdate);
globalEventEmitter.on('agent:codePatch', handleCodePatch);
globalEventEmitter.on('agent:fileTreeSync', handleFileTreeSync);
// Keep connection alive with periodic heartbeat
const heartbeat = setInterval(() => {
send(createSSEMessage('heartbeat', { timestamp: Date.now() }));
}, 30000);
// Cleanup when client disconnects
request.signal.addEventListener('abort', () => {
isClosed = true;
clearInterval(heartbeat);
globalEventEmitter.off('agent:status', handleAgentUpdate);
globalEventEmitter.off('agent:partial', handlePartialContent);
globalEventEmitter.off('agent:tool', handleToolUsed);
globalEventEmitter.off('agent:sandbox', handleSandboxStatus);
globalEventEmitter.off('agent:complete', handleComplete);
globalEventEmitter.off('agent:error', handleError);
globalEventEmitter.off('agent:reasoning', handleReasoning);
globalEventEmitter.off('agent:fileUpdate', handleFileUpdate);
globalEventEmitter.off('agent:codePatch', handleCodePatch);
globalEventEmitter.off('agent:fileTreeSync', handleFileTreeSync);
try {
controller.close();
} catch {
// Controller already closed
}
});
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}