summaryrefslogtreecommitdiffhomepage
path: root/packages/cli/src/http.ts
blob: 5e61afb28b0177b69fdcf0f6fd92fe797bfd7f69 (plain)
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
/**
 * Shell — HTTP transport layer (effects injected at the edges).
 *
 * streamChat: POST /chat, returns an async iterable of AgentEvents.
 * fetchModels: GET /models, returns the ModelsResponse.
 *
 * The fetchImpl dependency is injected (outermost edge mock allowed).
 */

import type { AgentEvent, ChatRequest, ModelsResponse } from "@dispatch/transport-contract";
import { splitNdjsonLines } from "./ndjson.js";

interface FetchDeps {
	readonly fetchImpl: typeof fetch;
}

interface StreamChatOpts {
	readonly server: string;
	readonly request: ChatRequest;
}

export async function streamChat(
	deps: FetchDeps,
	opts: StreamChatOpts,
): Promise<{ conversationId: string | null; events: AsyncIterable<AgentEvent> }> {
	const url = `${opts.server}/chat`;
	const res = await deps.fetchImpl(url, {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify(opts.request),
	});

	if (!res.ok) {
		const body = await res.text();
		throw new Error(`POST /chat failed with status ${res.status}: ${body}`);
	}

	const conversationId = res.headers.get("X-Conversation-Id");

	if (!res.body) {
		throw new Error("POST /chat returned no body");
	}

	const events = readNdjsonStream(res.body);
	return { conversationId, events };
}

async function* readNdjsonStream(body: ReadableStream<Uint8Array>): AsyncIterable<AgentEvent> {
	const reader = body.getReader();
	const decoder = new TextDecoder();
	let buffer = "";

	try {
		while (true) {
			const { done, value } = await reader.read();
			if (done) break;
			buffer += decoder.decode(value, { stream: true });
			const { lines, rest } = splitNdjsonLines(buffer);
			buffer = rest;
			for (const line of lines) {
				yield JSON.parse(line) as AgentEvent;
			}
		}
		if (buffer.length > 0) {
			yield JSON.parse(buffer) as AgentEvent;
		}
	} finally {
		reader.releaseLock();
	}
}

interface FetchModelsOpts {
	readonly server: string;
}

export async function fetchModels(deps: FetchDeps, opts: FetchModelsOpts): Promise<ModelsResponse> {
	const url = `${opts.server}/models`;
	const res = await deps.fetchImpl(url);

	if (!res.ok) {
		const body = await res.text();
		throw new Error(`GET /models failed with status ${res.status}: ${body}`);
	}

	return (await res.json()) as ModelsResponse;
}