forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSSEStream.ts
More file actions
225 lines (199 loc) · 6.18 KB
/
useSSEStream.ts
File metadata and controls
225 lines (199 loc) · 6.18 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
215
216
217
218
219
220
221
222
223
224
225
import { useRef, useCallback } from 'react';
import type { SSEEvent, TokenUsage, PermissionRequestEvent } from '@/types';
interface ToolUseInfo {
id: string;
name: string;
input: unknown;
}
interface ToolResultInfo {
tool_use_id: string;
content: string;
}
export interface SSECallbacks {
onText: (accumulated: string) => void;
onToolUse: (tool: ToolUseInfo) => void;
onToolResult: (result: ToolResultInfo) => void;
onToolOutput: (data: string) => void;
onToolProgress: (toolName: string, elapsedSeconds: number) => void;
onStatus: (text: string | undefined) => void;
onResult: (usage: TokenUsage | null) => void;
onPermissionRequest: (data: PermissionRequestEvent) => void;
onToolTimeout: (toolName: string, elapsedSeconds: number) => void;
onError: (accumulated: string) => void;
}
/**
* Parse a single SSE line (after stripping "data: " prefix) and dispatch
* to the appropriate callback. Returns the updated accumulated text.
*/
function handleSSEEvent(
event: SSEEvent,
accumulated: string,
callbacks: SSECallbacks,
): string {
switch (event.type) {
case 'text': {
const next = accumulated + event.data;
callbacks.onText(next);
return next;
}
case 'tool_use': {
try {
const toolData = JSON.parse(event.data);
callbacks.onToolUse({
id: toolData.id,
name: toolData.name,
input: toolData.input,
});
} catch {
// skip malformed tool_use data
}
return accumulated;
}
case 'tool_result': {
try {
const resultData = JSON.parse(event.data);
callbacks.onToolResult({
tool_use_id: resultData.tool_use_id,
content: resultData.content,
});
} catch {
// skip malformed tool_result data
}
return accumulated;
}
case 'tool_output': {
try {
const parsed = JSON.parse(event.data);
if (parsed._progress) {
callbacks.onToolProgress(parsed.tool_name, Math.round(parsed.elapsed_time_seconds));
return accumulated;
}
} catch {
// Not JSON - raw stderr output, fall through
}
callbacks.onToolOutput(event.data);
return accumulated;
}
case 'status': {
try {
const statusData = JSON.parse(event.data);
if (statusData.session_id) {
callbacks.onStatus(`Connected (${statusData.model || 'claude'})`);
} else if (statusData.notification) {
callbacks.onStatus(statusData.message || statusData.title || undefined);
} else {
callbacks.onStatus(typeof event.data === 'string' ? event.data : undefined);
}
} catch {
callbacks.onStatus(event.data || undefined);
}
return accumulated;
}
case 'result': {
try {
const resultData = JSON.parse(event.data);
callbacks.onResult(resultData.usage || null);
} catch {
callbacks.onResult(null);
}
callbacks.onStatus(undefined);
return accumulated;
}
case 'permission_request': {
try {
const permData: PermissionRequestEvent = JSON.parse(event.data);
callbacks.onPermissionRequest(permData);
} catch {
// skip malformed permission_request data
}
return accumulated;
}
case 'tool_timeout': {
try {
const timeoutData = JSON.parse(event.data);
callbacks.onToolTimeout(timeoutData.tool_name, timeoutData.elapsed_seconds);
} catch {
// skip malformed timeout data
}
return accumulated;
}
case 'error': {
const next = accumulated + '\n\n**Error:** ' + event.data;
callbacks.onError(next);
return next;
}
case 'done': {
return accumulated;
}
default:
return accumulated;
}
}
/**
* Reads an SSE response body and dispatches parsed events through callbacks.
* Returns the final accumulated text and token usage.
*/
export async function consumeSSEStream(
reader: ReadableStreamDefaultReader<Uint8Array>,
callbacks: SSECallbacks,
): Promise<{ accumulated: string; tokenUsage: TokenUsage | null }> {
const decoder = new TextDecoder();
let buffer = '';
let accumulated = '';
let tokenUsage: TokenUsage | null = null;
const wrappedCallbacks: SSECallbacks = {
...callbacks,
onResult: (usage) => {
tokenUsage = usage;
callbacks.onResult(usage);
},
};
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const event: SSEEvent = JSON.parse(line.slice(6));
accumulated = handleSSEEvent(event, accumulated, wrappedCallbacks);
} catch {
// skip malformed SSE lines
}
}
}
return { accumulated, tokenUsage };
}
/**
* Hook that provides a stable consumeSSEStream function bound to the latest
* callbacks via a ref, avoiding stale closures.
*/
export function useSSEStream() {
const callbacksRef = useRef<SSECallbacks | null>(null);
const processStream = useCallback(
async (
reader: ReadableStreamDefaultReader<Uint8Array>,
callbacks: SSECallbacks,
) => {
callbacksRef.current = callbacks;
// Proxy through ref so callers always hit the latest callbacks
const proxied: SSECallbacks = {
onText: (a) => callbacksRef.current?.onText(a),
onToolUse: (t) => callbacksRef.current?.onToolUse(t),
onToolResult: (r) => callbacksRef.current?.onToolResult(r),
onToolOutput: (d) => callbacksRef.current?.onToolOutput(d),
onToolProgress: (n, s) => callbacksRef.current?.onToolProgress(n, s),
onStatus: (t) => callbacksRef.current?.onStatus(t),
onResult: (u) => callbacksRef.current?.onResult(u),
onPermissionRequest: (d) => callbacksRef.current?.onPermissionRequest(d),
onToolTimeout: (n, s) => callbacksRef.current?.onToolTimeout(n, s),
onError: (a) => callbacksRef.current?.onError(a),
};
return consumeSSEStream(reader, proxied);
},
[],
);
return { processStream };
}