返回 CodeWhale
index.js
根目录 / npm / runtime-sdk / index.js
1 const DEFAULT_BASE_URL = "http://127.0.0.1:7878";
2
3 export class RuntimeApiError extends Error {
4 constructor(message, options = {}) {
5 super(message);
6 this.name = "RuntimeApiError";
7 this.status = options.status;
8 this.method = options.method;
9 this.path = options.path;
10 this.body = options.body;
11 }
12 }
13
14 export class RuntimeCapabilityError extends RuntimeApiError {
15 constructor(capability, message, options = {}) {
16 super(message, options);
17 this.name = "RuntimeCapabilityError";
18 this.capability = capability;
19 }
20 }
21
22 export class CodeWhaleRuntimeClient {
23 constructor(options = {}) {
24 this.baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
25 this.token = options.token ?? null;
26 this.fetchImpl = options.fetch ?? globalThis.fetch;
27 if (typeof this.fetchImpl !== "function") {
28 throw new TypeError("CodeWhaleRuntimeClient requires a fetch implementation");
29 }
30 }
31
32 async deliverDynamicToolResult(call, result, options = {}) {
33 const path = `/v1/threads/${segment(call.thread_id)}/turns/${segment(call.turn_id)}/tool-calls/${segment(call.call_id)}/result`;
34 const response = await this.#rawRequest(path, {
35 method: "POST", body: result, signal: options.signal, redirect: "error",
36 });
37 await response.body?.cancel();
38 if (response.status !== 202) {
39 throw new RuntimeApiError("Runtime dynamic-tool result did not return the expected acceptance", {
40 method: "POST", path, status: response.status,
41 });
42 }
43 }
44
45 async createFleetRun(spec) {
46 return this.#jsonRequest("/v1/fleet/runs", {
47 method: "POST",
48 body: spec,
49 capability: "fleet_run_create",
50 });
51 }
52
53 async startFleetRun(runId) {
54 return this.#jsonRequest(`/v1/fleet/runs/${segment(runId)}/start`, {
55 method: "POST",
56 capability: "fleet_run_start",
57 });
58 }
59
60 async replayFleetEvents(runId, options = {}) {
61 const path = fleetEventPath(
62 options.path ?? `/v1/fleet/runs/${segment(runId)}/events/replay`,
63 options,
64 );
65 return this.#jsonRequest(path, {
66 capability: "fleet_event_replay",
67 });
68 }
69
70 async listFleetRuns() {
71 return this.#jsonRequest("/v1/fleet/runs");
72 }
73
74 async getFleetRun(runId) {
75 return this.#jsonRequest(`/v1/fleet/runs/${segment(runId)}`);
76 }
77
78 async listFleetWorkers(runId) {
79 return this.#jsonRequest(`/v1/fleet/runs/${segment(runId)}/workers`);
80 }
81
82 async getFleetWorker(workerId) {
83 return this.#jsonRequest(`/v1/fleet/workers/${segment(workerId)}`);
84 }
85
86 async interruptWorker(workerId) {
87 return this.#jsonRequest(`/v1/fleet/workers/${segment(workerId)}/interrupt`, {
88 method: "POST",
89 });
90 }
91
92 async stopWorker(workerId) {
93 return this.#jsonRequest(`/v1/fleet/workers/${segment(workerId)}/stop`, {
94 method: "POST",
95 });
96 }
97
98 async restartWorker(workerId) {
99 return this.#jsonRequest(`/v1/fleet/workers/${segment(workerId)}/restart`, {
100 method: "POST",
101 });
102 }
103
104 async stopFleetRun(runId) {
105 return this.#jsonRequest(`/v1/fleet/runs/${segment(runId)}/stop`, {
106 method: "POST",
107 });
108 }
109
110 async *fleetEvents(runId, options = {}) {
111 const path = fleetEventPath(
112 options.path ?? `/v1/fleet/runs/${segment(runId)}/events`,
113 options,
114 );
115 const response = await this.#rawRequest(path, {
116 method: "GET",
117 capability: "fleet_event_stream",
118 accept: "text/event-stream",
119 signal: options.signal,
120 });
121 const contentType = response.headers.get("content-type") ?? "";
122 if (/^[ \t]*application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:[ \t]*;|$)/i.test(contentType)) {
123 const payload = await response.json();
124 const events = Array.isArray(payload) ? payload : (payload.events ?? []);
125 for (const event of events) {
126 yield event;
127 }
128 return;
129 }
130 if (!response.body) {
131 throw new RuntimeApiError("Runtime API event response did not include a readable body", {
132 method: "GET",
133 path,
134 });
135 }
136 for await (const event of parseEventStream(response.body)) {
137 yield event;
138 }
139 }
140
141 /** Read the existing durable thread journal. This never starts a turn. */
142 async *threadEvents(threadId, options = {}) {
143 const query = new URLSearchParams();
144 for (const [key, value] of [["since_seq", options.sinceSeq], ["replay_limit", options.replayLimit]]) {
145 if (value === undefined) continue;
146 if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${key} must be a nonnegative safe integer`);
147 query.set(key, String(value));
148 }
149 if (options.includeProgress !== undefined && typeof options.includeProgress !== "boolean")
150 throw new TypeError("includeProgress must be a boolean");
151 if (options.includeProgress) query.set("progress", "true");
152 const path = `/v1/threads/${segment(threadId)}/events?${query}`;
153 const response = await this.#rawRequest(path, {
154 method: "GET", capability: "thread_event_stream", accept: "text/event-stream",
155 signal: options.signal, redirect: "error",
156 });
157 if (!response.body || !/^[ \t]*text\/event-stream(?:[ \t]*;|$)/i.test(response.headers.get("content-type") ?? "")) {
158 await response.body?.cancel();
159 throw new RuntimeApiError("Runtime thread response is not an event stream", { method: "GET", path });
160 }
161 if (options.includeProgress && response.headers.get("x-codewhale-event-progress") !== "1") {
162 await response.body.cancel();
163 throw new RuntimeCapabilityError("thread_event_progress", "Runtime does not support thread replay progress", { method: "GET", path, status: 501 });
164 }
165 yield* parseEventStream(response.body, { maxFrameChars: 2 * 1024 * 1024, requireBoundary: true });
166 }
167
168 async #jsonRequest(path, options = {}) {
169 const response = await this.#rawRequest(path, options);
170 if (response.status === 204) {
171 return null;
172 }
173 return response.json();
174 }
175
176 async #rawRequest(path, options = {}) {
177 const method = options.method ?? "GET";
178 const base = new URL(this.baseUrl);
179 const url = new URL(path, base);
180 if (!["http:", "https:"].includes(url.protocol) || url.origin !== base.origin || url.username || url.password) {
181 throw new TypeError("Runtime API requests must stay on the configured HTTP(S) origin without URL credentials");
182 }
183 const headers = new Headers(options.headers);
184 headers.set("accept", options.accept ?? "application/json");
185 if (this.token) {
186 headers.set("authorization", `Bearer ${this.token}`);
187 }
188 const init = { method, headers };
189 if (options.signal) init.signal = options.signal;
190 // A redirect can change the request's destination or repeat a mutation.
191 // Authenticated requests must not leave the origin checked above.
192 if (headers.has("authorization")) init.redirect = "error";
193 else if (options.redirect) init.redirect = options.redirect;
194 if (options.body !== undefined) {
195 headers.set("content-type", "application/json");
196 init.body = JSON.stringify(options.body);
197 }
198
199 const response = await this.fetchImpl(url, init);
200 if (response.ok) {
201 return response;
202 }
203
204 const body = await readErrorBody(response);
205 const errorOptions = { status: response.status, method, path, body };
206 if (options.capability && [404, 405, 501].includes(response.status)) {
207 throw new RuntimeCapabilityError(
208 options.capability,
209 `Runtime API capability '${options.capability}' is not available at ${method} ${path}`,
210 errorOptions,
211 );
212 }
213 throw new RuntimeApiError(
214 `Runtime API request failed (${response.status}) for ${method} ${path}`,
215 errorOptions,
216 );
217 }
218 }
219
220 export function createRuntimeClient(options = {}) {
221 return new CodeWhaleRuntimeClient(options);
222 }
223
224 /** Distinguish a stream-end transport frame from thread journal/progress events. */
225 export function isThreadStreamEnd(event) {
226 return event.event === "stream.end";
227 }
228
229 function normalizeBaseUrl(value) {
230 return value.endsWith("/") ? value : `${value}/`;
231 }
232
233 function segment(value) {
234 if (value === null || value === undefined || String(value).trim() === "") {
235 throw new TypeError("Runtime API path segment must be a non-empty value");
236 }
237 const text = String(value);
238 if (text === "." || text === ".." || /[\u0000-\u001f\u007f]/u.test(text)) {
239 throw new TypeError("Runtime API path segment must identify a resource");
240 }
241 return encodeURIComponent(text);
242 }
243
244 function fleetEventPath(path, options) {
245 const query = new URLSearchParams();
246 if (options.after !== undefined && options.after !== null && String(options.after) !== "") {
247 query.set("after", String(options.after));
248 }
249 if (options.limit !== undefined && options.limit !== null) {
250 query.set("limit", String(options.limit));
251 }
252 if (query.size === 0) return path;
253 return path.replace(/^([^?#]*)(\?[^#]*)?/, (_match, resource, existingQuery) => {
254 const params = new URLSearchParams(existingQuery);
255 for (const [key, value] of query) params.set(key, value);
256 return `${resource}?${params}`;
257 });
258 }
259
260 async function readErrorBody(response) {
261 try {
262 const text = await response.text();
263 return text.length > 4096 ? `${text.slice(0, 4096)}...` : text;
264 } catch {
265 return "";
266 }
267 }
268
269 async function* parseEventStream(body, { maxFrameChars = Infinity, requireBoundary = false } = {}) {
270 const decoder = new TextDecoder("utf-8", { fatal: requireBoundary });
271 let buffer = "";
272 let skipLeadingLf = false;
273 for await (const chunk of body) {
274 const text = decoder.decode(chunk, { stream: true });
275 if (!text) continue;
276 buffer += skipLeadingLf && text.startsWith("\n") ? text.slice(1) : text;
277 skipLeadingLf = false;
278 let boundary;
279 while ((boundary = eventStreamBoundary(buffer)) !== null) {
280 if (boundary.index > maxFrameChars) throw new Error("Runtime event frame exceeds the size limit");
281 const frame = buffer.slice(0, boundary.index);
282 const next = boundary.index + boundary.length;
283 // The LF of a split CRLF still belongs to the boundary just consumed.
284 skipLeadingLf = next === buffer.length && buffer.endsWith("\r");
285 buffer = buffer.slice(next);
286 const event = parseSseFrame(frame);
287 if (event !== undefined) {
288 yield event;
289 }
290 }
291 if (buffer.length > maxFrameChars) {
292 // A trailing line ending can still become part of the frame separator.
293 const lineEnding = /\r\n$|[\r\n]$/.exec(buffer.slice(-2))?.[0] ?? "";
294 if (buffer.length - lineEnding.length > maxFrameChars) {
295 throw new Error("Runtime event frame exceeds the size limit");
296 }
297 }
298 }
299 buffer += decoder.decode();
300 if (requireBoundary && buffer.trim()) throw new Error("Runtime event stream ended inside a frame");
301 const event = parseSseFrame(buffer);
302 if (event !== undefined) {
303 yield event;
304 }
305 }
306
307 function eventStreamBoundary(buffer) {
308 const match = /(?:\r?\n|\r(?!\n))(?:\r\n|[\r\n])/.exec(buffer);
309 return match ? { index: match.index, length: match[0].length } : null;
310 }
311
312 function parseSseFrame(frame) {
313 const lines = frame.split(/\r\n|[\r\n]/);
314 const eventName = lines
315 .findLast((line) => line.startsWith("event:"))
316 ?.slice("event:".length)
317 .trimStart();
318 const eventId = lines
319 .findLast((line) => line.startsWith("id:") && !line.includes("\u0000"))
320 ?.slice("id:".length)
321 .trimStart();
322 const data = lines
323 .filter((line) => line.startsWith("data:"))
324 .map((line) => line.slice("data:".length).trimStart())
325 .join("\n");
326 if (!data || data === "[DONE]") {
327 return undefined;
328 }
329 const parsed = JSON.parse(data);
330 if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
331 if (eventName && parsed.event === undefined) {
332 parsed.event = eventName;
333 }
334 if (eventId && parsed.cursor === undefined) {
335 parsed.cursor = eventId;
336 }
337 }
338 return parsed;
339 }
340
340 lines JAVASCRIPT