返回 CodeWhale
sse.ts
根目录 / extensions / vscode / src / sse.ts
1 /**
2 * Minimal text/event-stream parser for `GET /v1/threads/{id}/events`.
3 *
4 * Pure and dependency-free: callers feed raw network chunks in, parsed frames
5 * come out. The Codewhale runtime encodes each event as a JSON object in the
6 * frame data, so a frame with parseable JSON yields one RuntimeEvent; frames
7 * without JSON (heartbeats, comments) yield nothing.
8 */
9
10 export interface RuntimeEvent {
11 seq: number;
12 previousSeq?: number;
13 event: string;
14 threadId?: string;
15 turnId?: string;
16 itemId?: string;
17 timestamp?: string;
18 payload: unknown;
19 }
20
21 export const MAX_SSE_FRAME_CHARS = 2 * 1024 * 1024;
22
23 export class SseParser {
24 private buffer = "";
25
26 constructor(private readonly maxFrameChars = MAX_SSE_FRAME_CHARS) {}
27
28 /** Feed one raw chunk; returns the complete events it finished. Throws when an unterminated frame outgrows the limit. */
29 push(chunk: string): RuntimeEvent[] {
30 this.buffer += chunk;
31 const events: RuntimeEvent[] = [];
32 let boundary = this.nextBoundary();
33 while (boundary !== -1) {
34 const frame = this.buffer.slice(0, boundary.index);
35 this.buffer = this.buffer.slice(boundary.index + boundary.length);
36 const event = parseFrame(frame);
37 if (event) {
38 events.push(event);
39 }
40 boundary = this.nextBoundary();
41 }
42 if (this.buffer.length > this.maxFrameChars) {
43 this.buffer = "";
44 throw new Error("Runtime event frame exceeds the size limit.");
45 }
46 return events;
47 }
48
49 private nextBoundary(): { index: number; length: number } | -1 {
50 const lf = this.buffer.indexOf("\n\n");
51 const crlf = this.buffer.indexOf("\r\n\r\n");
52 if (lf === -1 && crlf === -1) {
53 return -1;
54 }
55 if (crlf === -1 || (lf !== -1 && lf < crlf)) {
56 return { index: lf, length: 2 };
57 }
58 return { index: crlf, length: 4 };
59 }
60 }
61
62 export function parseFrame(frame: string): RuntimeEvent | undefined {
63 let data = "";
64 for (const rawLine of frame.split(/\r?\n/)) {
65 if (rawLine === "" || rawLine.startsWith(":")) {
66 continue;
67 }
68 const colon = rawLine.indexOf(":");
69 const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
70 let value = colon === -1 ? "" : rawLine.slice(colon + 1);
71 if (value.startsWith(" ")) {
72 value = value.slice(1);
73 }
74 if (field === "data") {
75 data += (data ? "\n" : "") + value;
76 }
77 // `event`, `id`, and `retry` are ignored: the runtime envelope carries the
78 // event name in its own `event` field, which is the stable contract.
79 }
80 if (!data) {
81 return undefined;
82 }
83 return readEvent(data);
84 }
85
86 function readEvent(data: string): RuntimeEvent | undefined {
87 let body: unknown;
88 try {
89 body = JSON.parse(data);
90 } catch {
91 return undefined;
92 }
93 if (!body || typeof body !== "object") {
94 return undefined;
95 }
96 const record = body as Record<string, unknown>;
97 const seq = readNumber(record.seq);
98 const event = readString(record.event);
99 if (seq === undefined || !event) {
100 return undefined;
101 }
102 return {
103 seq,
104 previousSeq: readNumber(record.previous_seq),
105 event,
106 threadId: readString(record.thread_id),
107 turnId: readString(record.turn_id),
108 itemId: readString(record.item_id),
109 timestamp: readString(record.timestamp) ?? readString(record.created_at),
110 payload: record.payload,
111 };
112 }
113
114 function readString(value: unknown): string | undefined {
115 return typeof value === "string" ? value : undefined;
116 }
117
118 function readNumber(value: unknown): number | undefined {
119 return typeof value === "number" && Number.isFinite(value) ? value : undefined;
120 }
121
121 lines TYPESCRIPT