the progress round: the provider streams, and the two long waits get honest meters -- the refine battery and her turn. The provider (provider.mjs): every completion now streams (vLLM SSE, probed live first: reasoning_content deltas arrive before content deltas, stream_options include_usage puts the full usage on the tail chunk) and assembles back into the one ChatResponse shape every caller already consumed -- content and reasoning in order, tool_calls stitched by index (id and name on the first fragment, arguments concatenated from shards, the assembled arguments parse), usage from the tail; a malformed data line fails loud where a skipped one would silently truncate, the log still records the assembled message whole, and an optional fifth param onProgress({phase, chars}) fires per delta as the meters' feed (ChatResponse names finish_reason, the wire shape the old typedef omitted). One cosmetic wire delta, named: streamed messages carry no provider_specific_fields (vLLM's duplicate reasoning channel plus refusal:null) -- nothing reads it. The refine meter (discovery.mjs + the home admin block): the job carries steps {total, done, label, chars} where the total is the scrape's model count plus the curator's two (thinking, writing), known the moment the scrape lands; the bar moves ONLY on real completions (GM, 2026-11-17: no step has a knowable duration, the point is meaningful feedback, not smooth fill), the label names the running call down to the effort-ladder sample, every completion lands a receipt line (elapsed seconds + the battery verdict), and the lines SURVIVE the job -- the receipt renders until the next refine (GM ruling: no reason to delete the log) and a rejected pass keeps its post-mortem; the curator's thinking step closes at the first prose delta (the streaming boundary -- why the provider went first), writing at the call's resolve, and a dead call closes both honestly; the 2s poll stays the transport (GM-ruled; SSE was rejected -- EventSource cannot send the Bearer header, and tokens in query strings are worse). The turn meter (loop.mjs + the progress route + the play view): the session carries a live progress record, one per provider call (a heal or tool round restarts it), fed by the streaming callback and cleared at every exit (the ask pause, the 422, the completing return, the failed request); GET /runs/:id/progress (owner-only, never queued) returns it plus the scale the bar guesstimates against -- the only true budget is max_tokens when the knobs set one (reasoning counts inside it, the usage arithmetic proves it; the route mirrors the loop's own param resolution at ~4 chars a token), else her own history: the longest past assistant turn in chars, thinking and prose both, the authored opening included (GM: a guesstimate, but an informed one). The 100% crossing pushes back geometrically: the scale grows by a quarter until the count fits, so the bar re-lands in the 80-100% band and climbs again, the same arithmetic every poll, never pinning (a count just under a grown bracket can still round to 100% for a moment -- named and accepted). No scale at all falls to the chunk-driven fallback: a twelve-segment strip, one lit, stepping ONLY when characters actually arrived -- never a free-running spinner, which would claim liveness the stream may not have; a stall shows as a stall. NO live partial prose in the transcript (the log is the one truth; streaming raw text would leak unpicked variants and half-formed heals onto the surface that shows them composed) -- the placeholder is a live div at the transcript foot, rebuilt when a render wipes it, sticking to bottom only when the scroller was already there, and the poll runs at 1s for turns (2s for refine). Verified: the provider live-probed against the real endpoint (prose+usage, thinking+progress transitions, a forced tool call with parseable arguments, the 403 path), a REAL refine run end to end on the GM's authorization (13 models, 541s, the meter exactly to spec with the curator's thinking ticking 4k-17k chars across polls) which also landed the effort measurements the registry was waiting for -- the deterministic re-pick is glm-5.3-max, and server.json's own pin still beats it until the op edits it -- smoke ALL PASS with the new assertions (the refine steps closed, the receipt's lines, the meter idle on a dormant run, idle-between-turns scaled by history, owner-gating; the first cut of the receipt assertion named the wrong mock tie-winner and the first cut of the dormant check clobbered a shared response variable -- both assertion bugs, the code was right), restart + reminder + repo checks green, typecheck green on both programs, and a disposable live run (created, three real turns, housekept, deleted) proving the meter in the browser with zero console errors: chars ticking, the phase flip at the streaming boundary, the scale re-anchoring to her new longest after each turn. Live findings on record: the measured effort default now rides every unset turn, and the test run's turns thought 12.1k/3.9k/6.5k chars against ~1.4k prose -- the max-observable default working as ruled, and the fresh-run decision the GM will make with the knob one click away; and the browser lesson pinned in AGENTS: the meter's DOM is invisible to a11y wait-text matching, so a whole frozen-meter scare during testing was a sampling artifact (the waits matched instantly against unrelated text) -- probe such widgets by DOM, never by wait

This commit is contained in:
2026-11-17 02:21:38 +00:00
parent eebc1993dd
commit bbaf33635c
13 changed files with 481 additions and 26 deletions
+103 -8
View File
@@ -1,9 +1,23 @@
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
// endpoint per deployment (server.json "endpoint"); the model name
// comes from the run (run.json override) or the config default.
//
// 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 */
/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */
/** @typedef {import('./shapes.mjs').ToolDef} ToolDef */
/** @typedef {import('./shapes.mjs').ChatResponse} ChatResponse */
/** @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, apiKeyEnv?: string }} endpoint
@@ -17,20 +31,101 @@ export function makeProvider(endpoint) {
return {
/**
* @param {?string} model @param {ViewMessage[]} messages
* @param {?import('./shapes.mjs').ToolDef[]} [tools] @param {Record<string, unknown>} [params]
* @param {?ToolDef[]} [tools] @param {Record<string, unknown>} [params]
* @param {?ProgressFn} [onProgress]
* @returns {Promise<ChatResponse>}
*/
async chat(model, messages, tools, params = {}) {
async chat(model, messages, tools, params = {}, onProgress = null) {
const res = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers,
body: JSON.stringify({ model, messages, ...(tools ? { tools, tool_choice: 'auto' } : {}), ...params }),
// 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 new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
}
const data = /** @type {ChatResponse} */ (await res.json());
return data;
// 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[]>} */
@@ -44,8 +139,8 @@ export function makeProvider(endpoint) {
},
/** The listing with the API metadata the scrape carries into the
* preliminary registry (token ceilings when the provider states
* them).
* preliminary registry (token ceilings when the provider states
* them).
* @returns {Promise<{ id: string, input: ?number, output: ?number }[]>} */
async modelsMeta() {
const res = await fetch(`${base}/models`, { headers });