返回 CodeWhale
api.ts
根目录 / extensions / vscode / src / api.ts
1 /**
2 * Codewhale Runtime HTTP/SSE client — the `/v1` contract documented in
3 * `docs/RUNTIME_API.md`.
4 *
5 * This module is deliberately VS Code-free so it can be unit-tested with
6 * plain node. Callers pass the base URL and token explicitly; the VS Code
7 * side of token resolution lives in `secrets.ts` / `runtime.ts`.
8 */
9 import * as http from "node:http";
10 import { SseParser, type RuntimeEvent } from "./sse";
11
12 export type { RuntimeEvent };
13
14 export interface ApiConfig {
15 baseUrl: string;
16 token?: string;
17 }
18
19 export interface ThreadRecord {
20 id: string;
21 title?: string;
22 model?: string;
23 modelProvider?: string;
24 workspace?: string;
25 mode?: string;
26 latestTurnId?: string;
27 archived: boolean;
28 updatedAt: string;
29 }
30
31 export interface ItemRecord {
32 id: string;
33 turnId?: string;
34 kind: string;
35 status?: string;
36 summary: string;
37 detail?: string;
38 metadata?: Record<string, unknown>;
39 startedAt?: string;
40 endedAt?: string;
41 }
42
43 export interface TurnRecord {
44 id: string;
45 threadId?: string;
46 status?: string;
47 effectiveModel?: string;
48 error?: string;
49 }
50
51 export interface PendingApproval {
52 id: string;
53 turnId?: string;
54 toolName: string;
55 description: string;
56 intentSummary?: string;
57 }
58
59 export interface UserInputOption {
60 label: string;
61 description?: string;
62 }
63
64 export interface UserInputQuestion {
65 header?: string;
66 id: string;
67 question: string;
68 options: UserInputOption[];
69 allowFreeText?: boolean;
70 multiSelect?: boolean;
71 }
72
73 export interface PendingUserInput {
74 id: string;
75 turnId?: string;
76 questions: UserInputQuestion[];
77 }
78
79 export interface ThreadSummary {
80 id: string;
81 title: string;
82 preview: string;
83 model: string;
84 mode: string;
85 workspace?: string;
86 branch?: string;
87 head?: string;
88 dirty: boolean;
89 archived: boolean;
90 updatedAt: string;
91 latestTurnStatus?: string;
92 }
93
94 export interface SnapshotEntry {
95 id: string;
96 label: string;
97 timestamp: number;
98 }
99
100 export interface ThreadDetail {
101 thread: ThreadRecord;
102 turns: TurnRecord[];
103 items: ItemRecord[];
104 latestSeq: number;
105 pendingApprovals: PendingApproval[];
106 pendingUserInputs: PendingUserInput[];
107 }
108
109 export interface StartTurnResult {
110 thread: ThreadRecord;
111 turn: TurnRecord;
112 }
113
114 export interface ConnectionInfo {
115 kind: "connected" | "offline" | "auth-required" | "error";
116 detail: string;
117 version?: string;
118 }
119
120 const HEALTH_TIMEOUT_MS = 2500;
121 const READ_TIMEOUT_MS = 8000;
122 const MUTATE_TIMEOUT_MS = 20000;
123
124 export async function checkConnection(config: ApiConfig): Promise<ConnectionInfo> {
125 const health = await requestJson(`${config.baseUrl}/health`, config, {
126 timeoutMs: HEALTH_TIMEOUT_MS,
127 });
128 if (health.statusCode === 0) {
129 return { kind: "offline", detail: "Runtime is not reachable." };
130 }
131 if (health.statusCode === 401) {
132 return { kind: "auth-required", detail: "Runtime requires a token." };
133 }
134 if (!isOk(health.statusCode)) {
135 return { kind: "error", detail: `Health check returned HTTP ${health.statusCode}.` };
136 }
137
138 const info = await requestJson(`${config.baseUrl}/v1/runtime/info`, config, {
139 timeoutMs: HEALTH_TIMEOUT_MS,
140 });
141 if (info.statusCode === 401) {
142 return { kind: "auth-required", detail: "Runtime info requires a token." };
143 }
144
145 // `/health` and `/v1/runtime/info` are intentionally unauthenticated, so a
146 // token-protected runtime answers both with HTTP 200. The info body carries
147 // the real signal: `auth_required`.
148 if (readBoolean(readBody(info.body).auth_required) && !config.token) {
149 return {
150 kind: "auth-required",
151 detail: "Runtime requires a bearer token. Store one with CodeWhale: Set Runtime Token.",
152 };
153 }
154
155 const version = readString(readBody(info.body).version);
156 return {
157 kind: "connected",
158 detail: version ? `Connected to CodeWhale ${version}.` : "Connected to CodeWhale runtime.",
159 version,
160 };
161 }
162
163 export async function listThreadSummaries(config: ApiConfig, limit = 20): Promise<ThreadSummary[]> {
164 const response = await requestJson(
165 `${config.baseUrl}/v1/threads/summary?limit=${encodeURIComponent(String(limit))}`,
166 config,
167 { timeoutMs: READ_TIMEOUT_MS },
168 );
169 ensureOk(response, "Thread summaries");
170 return readThreadSummaries(response.body);
171 }
172
173 export async function getThreadDetail(config: ApiConfig, threadId: string): Promise<ThreadDetail> {
174 const response = await requestJson(
175 `${config.baseUrl}/v1/threads/${encodeURIComponent(threadId)}`,
176 config,
177 { timeoutMs: READ_TIMEOUT_MS },
178 );
179 ensureOk(response, "Thread detail");
180 return readThreadDetail(response.body);
181 }
182
183 export async function createThread(
184 config: ApiConfig,
185 body: { workspace?: string; model?: string; mode?: string } = {},
186 ): Promise<ThreadRecord> {
187 const response = await requestJson(`${config.baseUrl}/v1/threads`, config, {
188 method: "POST",
189 body: JSON.stringify(body),
190 timeoutMs: MUTATE_TIMEOUT_MS,
191 });
192 ensureOk(response, "Create thread");
193 return readThread(response.body);
194 }
195
196 export interface StartTurnBody {
197 prompt: string;
198 operationKey?: string;
199 }
200
201 export async function startTurn(
202 config: ApiConfig,
203 threadId: string,
204 body: StartTurnBody,
205 ): Promise<StartTurnResult> {
206 const wire: Record<string, unknown> = { prompt: body.prompt };
207 if (body.operationKey) {
208 wire.operation_key = body.operationKey;
209 }
210 const response = await requestJson(
211 `${config.baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns`,
212 config,
213 { method: "POST", body: JSON.stringify(wire), timeoutMs: MUTATE_TIMEOUT_MS },
214 );
215 ensureOk(response, "Start turn");
216 const record = readBody(response.body);
217 return {
218 thread: readThread(record.thread),
219 turn: readTurn(record.turn),
220 };
221 }
222
223 export async function steerTurn(
224 config: ApiConfig,
225 threadId: string,
226 turnId: string,
227 prompt: string,
228 ): Promise<void> {
229 const response = await requestJson(
230 `${config.baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns/${encodeURIComponent(turnId)}/steer`,
231 config,
232 { method: "POST", body: JSON.stringify({ prompt }), timeoutMs: MUTATE_TIMEOUT_MS },
233 );
234 ensureOk(response, "Steer");
235 }
236
237 /**
238 * Outcome of an interrupt. The runtime answers 409 when the turn is not
239 * running — that is "nothing to stop", not a failure, so it is reported as a
240 * value instead of thrown.
241 */
242 export type InterruptResult = "interrupted" | "not-running";
243
244 export async function interruptTurn(
245 config: ApiConfig,
246 threadId: string,
247 turnId: string,
248 ): Promise<InterruptResult> {
249 const response = await requestJson(
250 `${config.baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns/${encodeURIComponent(turnId)}/interrupt`,
251 config,
252 { method: "POST", timeoutMs: MUTATE_TIMEOUT_MS },
253 );
254 if (response.statusCode === 409) {
255 return "not-running";
256 }
257 ensureOk(response, "Interrupt");
258 return "interrupted";
259 }
260
261 export async function resolveApproval(
262 config: ApiConfig,
263 approvalId: string,
264 decision: "allow" | "deny",
265 remember = false,
266 ): Promise<void> {
267 const response = await requestJson(
268 `${config.baseUrl}/v1/approvals/${encodeURIComponent(approvalId)}`,
269 config,
270 {
271 method: "POST",
272 body: JSON.stringify({ decision, remember }),
273 timeoutMs: MUTATE_TIMEOUT_MS,
274 },
275 );
276 ensureOk(response, "Approval");
277 }
278
279 export async function answerUserInput(
280 config: ApiConfig,
281 threadId: string,
282 inputId: string,
283 answers: Array<{ id: string; label: string; value: string }>,
284 ): Promise<void> {
285 const response = await requestJson(
286 `${config.baseUrl}/v1/user-input/${encodeURIComponent(threadId)}/${encodeURIComponent(inputId)}`,
287 config,
288 { method: "POST", body: JSON.stringify({ answers }), timeoutMs: MUTATE_TIMEOUT_MS },
289 );
290 ensureOk(response, "User input");
291 }
292
293 export async function listSnapshots(config: ApiConfig, limit = 8): Promise<SnapshotEntry[]> {
294 const response = await requestJson(
295 `${config.baseUrl}/v1/snapshots?limit=${encodeURIComponent(String(limit))}`,
296 config,
297 { timeoutMs: READ_TIMEOUT_MS },
298 );
299 ensureOk(response, "Restore points");
300 return readSnapshots(response.body);
301 }
302
303 export interface EventStream {
304 readonly threadId: string;
305 onEvent: (event: RuntimeEvent) => void;
306 onError: (error: Error) => void;
307 close(): void;
308 }
309
310 /**
311 * Open the replay + live SSE stream for a thread. `sinceSeq` should be the
312 * last accepted per-thread sequence (0 for a fresh thread). The stream never
313 * reconnects on its own; callers decide the retry policy from `onError`.
314 */
315 export function openEventStream(
316 config: ApiConfig,
317 threadId: string,
318 sinceSeq: number,
319 parser = new SseParser(),
320 ): EventStream {
321 const url = `${config.baseUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=${String(sinceSeq)}`;
322 const request = http.get(
323 url,
324 {
325 headers: {
326 Accept: "text/event-stream",
327 ...(config.token ? { Authorization: `Bearer ${config.token}` } : {}),
328 },
329 },
330 (response) => {
331 if (!isOk(response.statusCode ?? 0)) {
332 response.resume();
333 stream.onError(apiError(response.statusCode ?? 0, undefined, "Event stream"));
334 return;
335 }
336 response.setEncoding("utf8");
337 response.on("data", (chunk: string) => {
338 let events: RuntimeEvent[];
339 try {
340 events = parser.push(chunk);
341 } catch (error: unknown) {
342 request.destroy();
343 stream.onError(error instanceof Error ? error : new Error(String(error)));
344 return;
345 }
346 for (const event of events) {
347 stream.onEvent(event);
348 }
349 });
350 response.on("end", () => {
351 stream.onError(new Error("Event stream closed."));
352 });
353 response.on("error", (error: Error) => {
354 stream.onError(error);
355 });
356 },
357 );
358 request.on("error", (error: Error) => {
359 stream.onError(error);
360 });
361
362 const stream: EventStream = {
363 threadId,
364 onEvent: () => undefined,
365 onError: () => undefined,
366 close: () => {
367 request.destroy();
368 },
369 };
370 return stream;
371 }
372
373 export class ApiError extends Error {
374 readonly statusCode: number;
375 readonly detail?: string;
376
377 constructor(message: string, statusCode: number, detail?: string) {
378 super(detail ? `${message} ${detail}` : message);
379 this.name = "ApiError";
380 this.statusCode = statusCode;
381 this.detail = detail;
382 }
383 }
384
385 /**
386 * HTTP 409 from the runtime: the request was well-formed but the resource is
387 * already in a state that refuses it — most often "thread already has an
388 * active turn". Callers catch this to say "a turn is already running" instead
389 * of reporting a generic failure.
390 */
391 export class ConflictError extends ApiError {
392 constructor(message: string, detail?: string) {
393 super(message, 409, detail);
394 this.name = "ConflictError";
395 }
396 }
397
398 interface RequestResult {
399 statusCode: number;
400 body: unknown;
401 }
402
403 /**
404 * Success is the whole 2xx range, mirroring `response.ok` in the embedded web
405 * client (`crates/app-server/src/runtime_web/app.mjs:873`). The runtime answers 201
406 * CREATED for `POST /v1/threads/{id}/turns`, so an equality check against a
407 * hand-picked list of codes rejects every real send.
408 */
409 function isOk(statusCode: number): boolean {
410 return statusCode >= 200 && statusCode < 300;
411 }
412
413 /** Build the typed error for a non-2xx status, surfacing the runtime's own message. */
414 function apiError(statusCode: number, body: unknown, label: string): ApiError {
415 const detail = readErrorDetail(body);
416 if (statusCode === 0) {
417 return new ApiError(`${label} could not reach the runtime.`, 0, detail);
418 }
419 if (statusCode === 401) {
420 return new ApiError(`${label} requires the runtime token.`, 401, detail);
421 }
422 if (statusCode === 409) {
423 return new ConflictError(`${label} conflicts with the runtime's current state.`, detail);
424 }
425 return new ApiError(`${label} returned HTTP ${statusCode}.`, statusCode, detail);
426 }
427
428 /** Throw unless the runtime answered 2xx. Every route's status check runs through here. */
429 function ensureOk(response: RequestResult, label: string): void {
430 if (!isOk(response.statusCode)) {
431 throw apiError(response.statusCode, response.body, label);
432 }
433 }
434
435 const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
436
437 async function requestJson(
438 url: string,
439 config: ApiConfig,
440 options: { method?: string; body?: string; timeoutMs: number },
441 ): Promise<RequestResult> {
442 try {
443 return await new Promise<RequestResult>((resolve, reject) => {
444 const request = http.request(
445 url,
446 {
447 method: options.method ?? "GET",
448 timeout: options.timeoutMs,
449 headers: {
450 Accept: "application/json",
451 ...(options.body ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(options.body) } : {}),
452 ...(config.token ? { Authorization: `Bearer ${config.token}` } : {}),
453 },
454 },
455 (response) => {
456 const tooLarge = () => request.destroy(new Error("Runtime response exceeds the 64 MiB limit."));
457 if (Number(response.headers["content-length"]) > MAX_RESPONSE_BYTES) {
458 tooLarge();
459 return;
460 }
461 const chunks: Buffer[] = [];
462 let size = 0;
463 response.on("data", (chunk: Buffer) => {
464 size += chunk.length;
465 if (size > MAX_RESPONSE_BYTES) {
466 tooLarge();
467 return;
468 }
469 chunks.push(chunk);
470 });
471 response.on("end", () => {
472 resolve({ statusCode: response.statusCode ?? 0, body: parseJson(Buffer.concat(chunks).toString("utf8")) });
473 });
474 },
475 );
476 if (options.body) {
477 request.write(options.body);
478 }
479 request.on("timeout", () => {
480 request.destroy(new Error("Runtime request timed out."));
481 });
482 request.on("error", reject);
483 request.end();
484 });
485 } catch (error: unknown) {
486 const detail = error instanceof Error ? error.message : String(error);
487 return { statusCode: 0, body: { error: detail } };
488 }
489 }
490
491 function parseJson(raw: string): unknown {
492 try {
493 return JSON.parse(raw);
494 } catch {
495 return undefined;
496 }
497 }
498
499 function readBody(body: unknown): Record<string, unknown> {
500 return body && typeof body === "object" ? (body as Record<string, unknown>) : {};
501 }
502
503 function readErrorDetail(body: unknown): string | undefined {
504 const record = readBody(body);
505 const error = record.error;
506 if (typeof error === "string") {
507 return error;
508 }
509 if (error && typeof error === "object") {
510 const message = readBody(error).message ?? readBody(error).code;
511 if (typeof message === "string") {
512 return message;
513 }
514 }
515 return undefined;
516 }
517
518 function readString(value: unknown): string | undefined {
519 return typeof value === "string" ? value : undefined;
520 }
521
522 function readNumber(value: unknown): number | undefined {
523 return typeof value === "number" && Number.isFinite(value) ? value : undefined;
524 }
525
526 function readBoolean(value: unknown): boolean {
527 return value === true;
528 }
529
530 function readThread(value: unknown): ThreadRecord {
531 const record = readBody(value);
532 return {
533 id: readString(record.id) ?? "",
534 title: readString(record.title),
535 model: readString(record.model),
536 modelProvider: readString(record.model_provider),
537 workspace: readString(record.workspace),
538 mode: readString(record.mode),
539 latestTurnId: readString(record.latest_turn_id),
540 archived: record.archived === true,
541 updatedAt: readString(record.updated_at) ?? "",
542 };
543 }
544
545 function readTurn(value: unknown): TurnRecord {
546 const record = readBody(value);
547 return {
548 id: readString(record.id) ?? "",
549 threadId: readString(record.thread_id),
550 status: readString(record.status),
551 effectiveModel: readString(record.effective_model),
552 error: readString(record.error),
553 };
554 }
555
556 function readItem(value: unknown): ItemRecord | undefined {
557 const record = readBody(value);
558 const id = readString(record.id);
559 if (!id) {
560 return undefined;
561 }
562 return {
563 id,
564 turnId: readString(record.turn_id),
565 kind: readString(record.kind) ?? "status",
566 status: readString(record.status),
567 summary: readString(record.summary) ?? "",
568 detail: readString(record.detail),
569 metadata:
570 record.metadata && typeof record.metadata === "object"
571 ? (record.metadata as Record<string, unknown>)
572 : undefined,
573 startedAt: readString(record.started_at),
574 endedAt: readString(record.ended_at),
575 };
576 }
577
578 function readThreadDetail(value: unknown): ThreadDetail {
579 const record = readBody(value);
580 const thread = readThread(record.thread);
581 const items = Array.isArray(record.items)
582 ? record.items.flatMap((item) => {
583 const parsed = readItem(item);
584 return parsed ? [parsed] : [];
585 })
586 : [];
587 const turns = Array.isArray(record.turns)
588 ? record.turns.flatMap((turn) => {
589 const parsed = readTurn(turn);
590 return parsed.id ? [parsed] : [];
591 })
592 : [];
593
594 const pendingApprovals = Array.isArray(record.pending_approvals)
595 ? record.pending_approvals.flatMap((entry) => {
596 const approval = readBody(entry);
597 const id = readString(approval.id);
598 if (!id) {
599 return [];
600 }
601 return [
602 {
603 id,
604 turnId: readString(approval.turn_id),
605 toolName: readString(approval.tool_name) ?? "tool",
606 description: readString(approval.description) ?? "",
607 intentSummary: readString(approval.intent_summary),
608 },
609 ];
610 })
611 : [];
612
613 const pendingUserInputs = Array.isArray(record.pending_user_inputs)
614 ? record.pending_user_inputs.flatMap((entry) => {
615 const input = readBody(entry);
616 const id = readString(input.id);
617 const request = readBody(input.request);
618 const questions = Array.isArray(request.questions)
619 ? request.questions.flatMap((raw) => {
620 const question = readBody(raw);
621 const questionId = readString(question.id);
622 if (!questionId) {
623 return [];
624 }
625 return [
626 {
627 header: readString(question.header),
628 id: questionId,
629 question: readString(question.question) ?? "",
630 allowFreeText: question.allow_free_text === true,
631 multiSelect: question.multi_select === true,
632 options: Array.isArray(question.options)
633 ? question.options.flatMap((option) => {
634 const recordOption = readBody(option);
635 const label = readString(recordOption.label);
636 return label ? [{ label, description: readString(recordOption.description) }] : [];
637 })
638 : [],
639 },
640 ];
641 })
642 : [];
643 if (!id) {
644 return [];
645 }
646 return [{ id, turnId: readString(input.turn_id), questions }];
647 })
648 : [];
649
650 return {
651 thread,
652 turns,
653 items,
654 latestSeq: readNumber(record.latest_seq) ?? 0,
655 pendingApprovals,
656 pendingUserInputs,
657 };
658 }
659
660 function readThreadSummaries(value: unknown): ThreadSummary[] {
661 if (!Array.isArray(value)) {
662 return [];
663 }
664 return value.flatMap((item) => {
665 const record = readBody(item);
666 const id = readString(record.id);
667 if (!id) {
668 return [];
669 }
670 return [
671 {
672 id,
673 title: readString(record.title) ?? "New Thread",
674 preview: readString(record.preview) ?? "",
675 model: readString(record.model) ?? "unknown",
676 mode: readString(record.mode) ?? "agent",
677 workspace: readString(record.workspace),
678 branch: readString(record.branch),
679 head: readString(record.head),
680 dirty: record.dirty === true,
681 archived: record.archived === true,
682 updatedAt: readString(record.updated_at) ?? "",
683 latestTurnStatus: readString(record.latest_turn_status),
684 },
685 ];
686 });
687 }
688
689 function readSnapshots(value: unknown): SnapshotEntry[] {
690 if (!Array.isArray(value)) {
691 return [];
692 }
693 return value.flatMap((item) => {
694 const record = readBody(item);
695 const id = readString(record.id);
696 const label = readString(record.label);
697 const timestamp = readNumber(record.timestamp);
698 if (!id || !label || timestamp === undefined) {
699 return [];
700 }
701 return [{ id, label, timestamp }];
702 });
703 }
704
704 lines TYPESCRIPT