Files
tiny-worlds/server/provider.mjs
T

186 lines
8.7 KiB
JavaScript
Raw Normal View History

// server/provider.mjs -- the provider client. One client per
// configured provider entity (state/config.json, written by the
// server from the SPA); model specs name the provider slug, and
// providerFor walks the map to the client that owns it.
2026-11-17 02:21:38 +00:00
//
// Every completion streams (SSE) and is assembled back into the one
// response shape the callers consume -- no caller distinguishes
// streaming from not. Streaming is not a UI feature here, it is
// transport hygiene: a max-effort turn can think for minutes, and a
// held-open non-streaming response is a proxy-timeout risk besides
// being invisible (with streaming, the deltas prove liveness -- the
// progress callback is the meter's feed, {phase, chars} per delta).
// The log is unaffected: it records the assembled message, whole.
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
2026-11-17 02:21:38 +00:00
/** @typedef {import('./shapes.mjs').ToolDef} ToolDef */
/** @typedef {import('./shapes.mjs').ChatResponse} ChatResponse */
2026-11-17 02:21:38 +00:00
/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */
/** The progress callback: what the meter reads. `phase` is what is
* arriving right now, `chars` that phase's running total. */
/** @typedef {(p: { phase: 'thinking'|'prose', chars: number }) => void} ProgressFn */
/**
* @param {{ baseUrl?: string, apiKey?: string }} provider
*/
export function makeProvider(provider) {
const base = String(provider.baseUrl ?? '').replace(/\/+$/, '');
if (!base) throw new Error('the provider entry has no baseUrl');
const key = provider.apiKey ?? '';
// the auth header rides only when a key exists: an EMPTY Bearer is
// not the same as no auth (opencode.ai 401s the empty spelling and
// serves the anonymous listing to the headerless request -- found
// live in the fresh-path test, 2026-11-18)
const headers = { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) };
/** An API failure carries its HTTP status on the error object --
* the SPA branches on it (a 401/403 asks for the key), never on
* message parsing.
* @param {Response} res @returns {Promise<Error>} */
const apiError = async (res) => {
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`));
err.status = res.status;
return err;
};
return {
/**
* @param {?string} model @param {ViewMessage[]} messages
2026-11-17 02:21:38 +00:00
* @param {?ToolDef[]} [tools] @param {Record<string, unknown>} [params]
* @param {?ProgressFn} [onProgress]
* @returns {Promise<ChatResponse>}
*/
2026-11-17 02:21:38 +00:00
async chat(model, messages, tools, params = {}, onProgress = null) {
const res = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers,
2026-11-17 02:21:38 +00:00
// stream rides after the caller's params so nothing can
// un-stream a call; include_usage puts the full usage on the
// tail chunk (the assembled response must not lose it)
body: JSON.stringify({
model, messages, ...(tools ? { tools, tool_choice: 'auto' } : {}),
...params, stream: true, stream_options: { include_usage: true },
}),
});
if (!res.ok) {
throw await apiError(res);
}
2026-11-17 02:21:38 +00:00
// the SSE assembly: content and reasoning concatenate in order,
// tool_calls stitch by index (id and name land on the first
// fragment, the arguments arrive as string shards), usage rides
// the final chunk. A malformed data line fails loud -- a skipped
// one would silently truncate the turn.
/** @type {string} */ let content = '';
/** @type {string} */ let reasoning = '';
/** @type {?string} */ let finishReason = null;
/** @type {?import('./shapes.mjs').Usage} */ let usage = null;
/** @type {Map<number, { id: string, name: string, args: string }>} */
const calls = new Map();
if (!res.body) throw new Error('the endpoint returned no stream body');
const reader = res.body.getReader();
const decoder = new TextDecoder();
/** @param {string} chunk @returns {void} */
const take = (chunk) => {
for (const line of chunk.split('\n')) {
const s = line.trim();
if (!s.startsWith('data:')) continue; // SSE comments and keeps blank
const payload = s.slice(5).trim();
if (!payload || payload === '[DONE]') continue;
/** @type {{ choices?: { finish_reason?: ?string, delta?: { content?: ?string, reasoning_content?: ?string, tool_calls?: { index: number, id?: ?string, function?: { name?: ?string, arguments?: ?string } }[] } }[], usage?: import('./shapes.mjs').Usage }} */
let j;
try {
j = JSON.parse(payload);
} catch (e) {
throw new Error(`the endpoint sent a malformed stream chunk: ${String(e.message ?? e).slice(0, 120)}`);
}
const ch = j.choices?.[0];
if (ch) {
if (ch.finish_reason) finishReason = ch.finish_reason;
const d = ch.delta ?? {};
if (typeof d.reasoning_content === 'string' && d.reasoning_content) {
reasoning += d.reasoning_content;
onProgress?.({ phase: 'thinking', chars: reasoning.length });
}
if (typeof d.content === 'string' && d.content) {
content += d.content;
onProgress?.({ phase: 'prose', chars: content.length });
}
for (const tc of d.tool_calls ?? []) {
const slot = calls.get(tc.index) ?? { id: '', name: '', args: '' };
if (tc.id) slot.id = tc.id;
if (tc.function?.name) slot.name = tc.function.name;
if (typeof tc.function?.arguments === 'string') slot.args += tc.function.arguments;
calls.set(tc.index, slot);
}
}
if (j.usage) usage = j.usage;
}
};
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const nl = buf.lastIndexOf('\n');
if (nl >= 0) {
take(buf.slice(0, nl));
buf = buf.slice(nl + 1);
}
}
buf += decoder.decode(); // flush the decoder's tail
if (buf.trim()) take(buf); // a final line without its newline
const toolCalls = [...calls.entries()].sort((a, b) => a[0] - b[0])
.map(([, t]) => ({ id: t.id, type: 'function', function: { name: t.name, arguments: t.args } }));
/** @type {import('./shapes.mjs').WireMessage} */
const message = {
role: 'assistant',
// the wire shape: a tool-call turn carries null content, the
// same as the endpoint's non-streaming message
content: toolCalls.length && !content ? null : content,
};
if (reasoning) message.reasoning_content = reasoning;
if (toolCalls.length) message.tool_calls = /** @type {ToolCall[]} */ (toolCalls);
return { choices: [{ message, finish_reason: finishReason }], ...(usage ? { usage } : {}) };
},
/** @returns {Promise<string[]>} */
async models() {
const res = await fetch(`${base}/models`, { headers });
if (!res.ok) {
throw await apiError(res);
}
const data = /** @type {{ data: { id: string }[] }} */ (await res.json());
return (data.data ?? []).map((m) => m.id).sort();
},
2026-11-16 21:32:02 +00:00
/** The listing with the API metadata the scrape carries into the
2026-11-17 02:21:38 +00:00
* preliminary registry (token ceilings when the provider states
* them).
2026-11-16 21:32:02 +00:00
* @returns {Promise<{ id: string, input: ?number, output: ?number }[]>} */
async modelsMeta() {
const res = await fetch(`${base}/models`, { headers });
if (!res.ok) {
throw await apiError(res);
2026-11-16 21:32:02 +00:00
}
const data = /** @type {{ data: { id: string, max_input_tokens?: ?number, max_output_tokens?: ?number }[] }} */ (await res.json());
return (data.data ?? []).map((m) => ({ id: m.id, input: m.max_input_tokens ?? null, output: m.max_output_tokens ?? null }));
},
};
}
// The routing: the client that owns a provider slug. Model specs
// name the provider; the config holds the entity. A missing entry
// means the config dropped a provider the run still rides -- loud,
// never a silent fallback to some other provider (the model may not
// exist there, and the auth certainly differs).
/** @param {import('./shapes.mjs').Ctx} ctx @param {?string} slug @returns {ReturnType<typeof makeProvider>} */
export function providerFor(ctx, slug) {
const p = ctx.providers.get(String(slug ?? ''));
if (!p) {
const err = /** @type {import('./shapes.mjs').HttpError} */ (new Error(`the provider '${slug}' is not configured -- the run rides a route that is gone (re-add the provider, or re-pick the run's model)`));
err.status = 409;
throw err;
}
return p;
}