diff --git a/AGENTS.md b/AGENTS.md index cccb38e..b1b2011 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -137,6 +137,83 @@ memory the agent owes itself across sessions. ## State pointers +- **The progress round is BUILT COMPLETE (2026-11-17, uncommitted, + staged): the streaming provider, the refine meter, and the turn + meter are all done and live-proven.** The GM's plan: abandon + Chloe, start a fresh run from the top (the huge max-effort result + prompted it -- her one max turn thought + 11,371 chars, 9x her session max, with real continuity work inside; + the comparison is in the 2026-11-17 conversation). The provider + (provider.mjs chat): every completion STREAMS (vLLM SSE, verified + live: reasoning_content deltas then content deltas, usage rides the + tail chunk via stream_options include_usage) and assembles back + into the same ChatResponse -- callers unchanged, the log records + the assembled message whole, tool_calls stitch by index, malformed + chunks fail loud; optional 5th param onProgress({phase, chars}) is + the meter's feed. One wire delta: streamed messages carry no + provider_specific_fields (vLLM's duplicate reasoning channel + + refusal:null) -- nothing reads it, cosmetic on raw surfaces only. + The refine meter (discovery.mjs + view-home admin block): the job + carries steps {total, done, label, chars} -- total = models + the + curator's two (thinking, writing), known at scrape; 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 ladder sample, every + completion lands a receipt line (elapsed seconds + verdict), and + the lines SURVIVE the job (the receipt renders until the next + refine -- GM ruling: no reason to delete the log); the curator's + thinking step closes at the first prose delta (the streaming + boundary -- why the provider went first), writing at the resolve, + a dead call closes both; a rejected job keeps its lines for the + post-mortem. The 2s poll is the transport (GM-ruled fine; SSE was + rejected -- EventSource can't send the Bearer header). The TURN + meter (loop.mjs s.progress per provider call, GET /progress route + + scale, view-play placeholder + 1s poll): no true max exists for + a turn except max_tokens when set (reasoning counts inside it -- + usage arithmetic proves it; the route mirrors the loop's param + resolution, ~4 chars a token); else the scale is her own history + -- the longest PAST assistant turn in chars, thinking and prose + both, the authored opening included (GM, 2026-11-17: a guesstimate, + an informed one). 100%-crossing push-back is GEOMETRIC: grow the + scale by 1.25x until the count fits, so the bar lands anywhere in + (80%,100%] per bracket and re-brackets on each crossing -- it never + pins (a count just under a grown bracket can still round to 100%, + named to the GM as working as designed). No scale (draft-before- + opening edge) falls to a chunk-driven strip: twelve segments, one + lit, stepping ONLY when chars arrived -- never a free-running + spinner. NO live partial prose in the transcript (the log is the + one truth; streaming raw text would leak unpicked variants and + half-formed heals) -- the placeholder is a live div at the + transcript foot, rebuilt when a render wipes it, stick-to-bottom + only when the scroller was already at the bottom. The placeholder + (and the refine meter's spans) are INVISIBLE to a11y wait-text + matching -- browser-test them via evaluate DOM probes, never + browser.wait on their text (a whole "frozen meter" scare was this + artifact: the waits matched instantly against unrelated text and + the samples landed within the same second). Live-proven on a + disposable test run (f42403f0, created/played/deleted, three real + glm-5.3 turns at effort max, zero console errors): chars tick, the + phase flips thinking->writing at the streaming boundary, the scale + re-anchors to her new longest after each turn. The REAL refine ran + 2026-11-17 end to end (GM-authorized): 13 models in 541s, the meter + behaved exactly to spec (curator thinking ticked 4k->17k chars + across polls), and the registry gained the effort measurements -- + defaults now glm-5.3-max (the deterministic lex re-pick, as + predicted; server.json still pins glm-5.3, which BEATS the registry + until the op edits it). + Watch: the effort defaults ride unset turns now, and the 2-sample + ladders are noisy (glm-5.3's argmax is max=291 while high=11 -- + within-bucket noise by design, but a fresh glm-5.3 run now sends + effort max where nothing rode before -- the test run's turns thought + 12k/3.9k/6.5k chars, an order over her prose). New ids this scrape: + auto (standard), glm-5.3-low (off), deepseek-v4.1-flash/-max + (standard, 1M/256k windows)/-nothink (off); the gev family still + fails the tool probe (no --enable-auto-tool-choice on that backend). + The debug server is RUNNING with the new code (port 7350, pid in + the temp pid file; restarted clean after the test run's deletion -- + runs/ holds only Chloe and Irene). Chloe's session is open-on-disk + (killed with the old server; the reconcile handles it at next + start). - **The reasoning-effort round is BUILT (2026-11-16, late night): the battery probes the effort ladder, the knob is first-class, hidden from the model, and its default SENDS.** The probe (discovery.mjs @@ -540,7 +617,9 @@ memory the agent owes itself across sessions. CLI note: the run summary is `report` now; `status` is the tier verb. - Postulates (GM, 2026-11-14): female PCs only (names are gendered; - DECISIONS #2 closed by it). Boutique: the GM emptied it wholesale + DECISIONS #2 closed by it). packages/detention is GM WIP (2026-11-17): + never commit it, never edit it unprompted -- it goes in when they say. + Boutique: the GM emptied it wholesale (2026-11-15 -- it kept being a noisy problem); placeholder files only, no content anywhere. Still do not fix or design it unprompted -- its design round is where content returns. The diff --git a/server/discovery.mjs b/server/discovery.mjs index d15dcd6..1e35a3e 100644 --- a/server/discovery.mjs +++ b/server/discovery.mjs @@ -133,12 +133,14 @@ async function thinkingTokens(ctx, id, params) { * 2026-11-16: maximum observable thinking by default, overridable * by the user). A model that shows no thinking, or that no level * moves, gets null -- nothing rides. - * @param {Ctx} ctx @param {string} id @returns {Promise<{ efforts: Record, effortDefault: ?string }>} */ -async function probeEfforts(ctx, id) { + * @param {Ctx} ctx @param {string} id @param {(s: string) => void} [say] + * @returns {Promise<{ efforts: Record, effortDefault: ?string }>} */ +async function probeEfforts(ctx, id, say = () => {}) { /** @type {Record} */ const efforts = {}; for (const level of EFFORT_LEVELS) { const xs = []; for (let i = 0; i < 2; i++) { + say(`${level}, sample ${i + 1}/2`); try { xs.push(await thinkingTokens(ctx, id, { reasoning_effort: level })); } catch { xs.push(0); } } efforts[level] = Math.round(xs.reduce((a, b) => a + b, 0) / xs.length); @@ -152,11 +154,13 @@ async function probeEfforts(ctx, id) { * exact request shape a player turn takes), the reasoning samples, * the off-switch probe, the effort ladder. Every failure is a * verdict, never an abort. - * @param {Ctx} ctx @param {RegistryModel} m @returns {Promise} */ -async function probeOne(ctx, m) { + * @param {Ctx} ctx @param {RegistryModel} m @param {(s: string) => void} [say] + * @returns {Promise} */ +async function probeOne(ctx, m, say = () => {}) { const base = { ...m }; delete base.status; // the scrape's mark -- a probed record is no longer unrefined if (ctx.mock) { + say('the canned battery'); // the canned battery: all three stand-ins are inference models; // mock and mock-tie are a deliberate tie pair (same deep bucket, // same windows -- only the lex rule can part them), the cheap @@ -170,6 +174,7 @@ async function probeOne(ctx, m) { efforts: { none: 0, minimal: 40, low: 100, medium: 200, high: 300, xhigh: 400, max: 500 }, effortDefault: 'max' }; } const t0 = Date.now(); + say('the tool probe'); try { await ctx.provider.chat(m.id, [{ role: 'user', content: 'Say OK.' }], [ASK_GM_TOOL], { max_tokens: 400 }); } catch (e) { @@ -179,12 +184,14 @@ async function probeOne(ctx, m) { const latency = Date.now() - t0; const samples = []; for (let i = 0; i < 2; i++) { + say(`the thinking samples, ${i + 1}/2`); try { samples.push(await thinkingTokens(ctx, m.id, {})); } catch { samples.push(0); } } const think = Math.max(...samples); /** @type {Record|null} */ let offSwitch = null; if (think > 0) { try { + say('the off-switch probe'); if (await thinkingTokens(ctx, m.id, { chat_template_kwargs: { enable_thinking: false } }) === 0) { offSwitch = { chat_template_kwargs: { enable_thinking: false } }; } @@ -194,7 +201,7 @@ async function probeOne(ctx, m) { /** @type {?string} */ let effortDefault = null; if (think > 0) { try { - ({ efforts, effortDefault } = await probeEfforts(ctx, m.id)); + ({ efforts, effortDefault } = await probeEfforts(ctx, m.id, (s) => say(`the effort ladder: ${s}`))); } catch { /* the ladder is optional knowledge -- absent on a flaky endpoint */ } } return { ...base, inference: true, think, reasoning: bucket(think), offSwitch, efforts, effortDefault, latency }; @@ -224,8 +231,9 @@ function rankSort(models) { * probed inference ids, no inventions; any violation discards the * whole output and the machine list stands. * @param {Ctx} ctx @param {RegistryModel[]} probed @param {RegistryModel} best @param {?Actor} user + * @param {?import('./provider.mjs').ProgressFn} [onProgress] @param {?(() => void)} [onRetry] * @returns {Promise<{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }>} */ -async function curate(ctx, probed, best, user) { +async function curate(ctx, probed, best, user, onProgress = null, onRetry = null) { if (ctx.mock) { return { list: [ @@ -252,11 +260,12 @@ async function curate(ctx, probed, best, user) { let data = null; for (let attempt = 0; attempt < 2; attempt++) { try { - data = await ctx.provider.chat(best.id, messages, undefined, {}); + data = await ctx.provider.chat(best.id, messages, undefined, {}, onProgress); break; } catch (e) { if (attempt === 1) throw e; console.log(`${new Date().toISOString().slice(11, 19)} curator call failed (${String(e.message ?? e).split('\n')[0]}) -- retrying once`); + onRetry?.(); } } if (!data) throw new Error('the curator call failed twice'); @@ -299,23 +308,63 @@ export function refine(ctx, user) { if (ctx.jobs.get(JOB_KEY)?.state === 'running') { throw new HttpError(409, 'a refine is already running'); } - const job = /** @type {JobState} */ ({ state: 'running', phase: 'refine', started: new Date().toISOString() }); + // the meter: one step per model's battery plus the curator's two + // (thinking, writing) -- the count is known the moment the scrape + // lands. No step has a duration to guess at (GM, 2026-11-17): the + // bar moves only on real completions, the label names the call + // running now, and every completion lands a receipt line -- the + // lines survive the job, so a rejected pass keeps its post-mortem + const t0 = Date.now(); + // the local view narrows steps/lines to present -- the job is born + // with them, and the reporter writes through this reference + const job = /** @type {JobState & { steps: { total: number, done: number, label: string, chars?: number }, lines: string[] }} */ ({ + state: 'running', phase: 'refine', started: new Date().toISOString(), + steps: { total: 0, done: 0, label: 'scraping the provider surface' }, lines: [], + }); ctx.jobs.set(JOB_KEY, job); + /** @param {string} s */ const say = (s) => { job.steps.label = s; }; + /** @param {string} s */ const line = (s) => { job.lines.push(`${Math.round((Date.now() - t0) / 1000)}s ${s}`); }; void (async () => { try { const scraped = await scrape(ctx); // fresh metadata -- ids can drift between discoveries + job.steps.total = scraped.length + 2; + /** @param {RegistryModel} m @returns {string} */ + const verdict = (m) => m.inference === false + ? `failed the tool probe -- ${m.fail}` + : `reasoning ${m.reasoning} \u00b7 ${m.think} think tokens \u00b7 ${m.offSwitch ? 'off switch' : 'no off switch'} \u00b7 ${m.latency}ms${m.effortDefault ? ` \u00b7 effort default ${m.effortDefault}` : ''}`; const probed = []; - for (const m of scraped) probed.push(await probeOne(ctx, m)); + for (const [i, m] of scraped.entries()) { + probed.push(await probeOne(ctx, m, (s) => say(`battery ${i + 1}/${scraped.length}: ${m.id} -- ${s}`))); + job.steps.done++; + line(`${m.id}: ${verdict(probed[i])}`); + } const passing = probed.filter((m) => m.inference); if (!passing.length) throw new Error('no model passed the inference battery -- the provider surface has nothing playable'); const best = rankSort(passing)[0]; /** @type {{ list: { id: string, family: ?string, label: ?string, description: ?string, player: boolean, housekeeper: boolean }[], note: string }} */ let curated = { list: [], note: 'fallback: not attempted' }; + // the curator's two steps, marked from real events: thinking + // completes at the first prose delta (the streaming boundary), + // writing at the call's resolve; a dead call closes both -- the + // attempt is over, and the fallback carries the job + let proseStarted = false; + say(`curator (${best.id}): thinking`); try { - curated = await curate(ctx, probed, best, user); + curated = await curate(ctx, probed, best, user, (p) => { + job.steps.chars = p.chars; + if (p.phase === 'prose' && !proseStarted) { + proseStarted = true; + job.steps.done++; + say('curator: writing'); + } + }, () => say(`curator (${best.id}): retrying -- thinking`)); } catch (e) { curated = { list: [], note: `fallback: the curator call failed (${String(e.message ?? e).split('\n')[0]})` }; } + job.steps.done = job.steps.total; // the attempt is over -- whatever remains closes with it + delete job.steps.chars; + say('writing the registry'); + line(curated.note === 'curated' ? `curator (${best.id}): curated \u00b7 ${curated.list.length} labeled` : `curator: ${curated.note}`); const byId = new Map(curated.list.map((c) => [c.id, c])); const models = probed.map((m) => { const c = m.inference ? byId.get(m.id) : undefined; @@ -338,6 +387,7 @@ export function refine(ctx, user) { models, curator: curated.note, })); + say('done'); job.state = 'applied'; } catch (e) { job.state = 'rejected'; diff --git a/server/loop.mjs b/server/loop.mjs index e6a6e5f..98dfdb0 100644 --- a/server/loop.mjs +++ b/server/loop.mjs @@ -159,10 +159,19 @@ async function runLoop(ctx, runId, user) { via = { model, params }; // attribution (#22): every LLM call names the acting user console.log(`${new Date().toISOString().slice(11, 19)} llm ${model} u:${user?.id ?? '?'}`); + // the turn meter's live record: one per provider call (a heal + // or tool round restarts it), fed by the streaming deltas + s.progress = { phase: 'thinking', thinking: 0, prose: 0, started: Date.now() }; let data; try { - data = await ctx.provider.chat(model, view, tools, params); + data = await ctx.provider.chat(model, view, tools, params, (p) => { + if (!s.progress) return; + s.progress.phase = p.phase; + if (p.phase === 'thinking') s.progress.thinking = p.chars; + else s.progress.prose = p.chars; + }); } catch (e) { + s.progress = null; s.append({ t: 'req', model, params, fail: String(e.message ?? e).split('\n')[0].slice(0, 200) }); throw e; } @@ -180,6 +189,7 @@ async function runLoop(ctx, runId, user) { s.pendingAsk = { callId: ask.id, question: q, calls: msg.tool_calls }; s.append({ t: 'note', kind: 'ask', question: q }); out.pendingAsk = q; + s.progress = null; return out; // the turn request returns with the question } for (const call of msg.tool_calls) { @@ -199,6 +209,7 @@ async function runLoop(ctx, runId, user) { try { vv = parseVariants(msg.content); } catch (e) { + s.progress = null; throw new HttpError(422, `the player emitted a malformed variants block -- nothing applied; the turn is lost, retry: ${e.message}`); } s.append({ t: 'msg', m: msg, via, ...(s.usage ? { usage: { prompt_tokens: s.usage.promptTokens, completion_tokens: s.usage.completionTokens } } : {}) }); @@ -259,6 +270,7 @@ async function runLoop(ctx, runId, user) { s.mind = Object.keys(mindNext).length ? mindNext : null; if (Object.keys(mindNext).length) s.append({ t: 'note', kind: 'mind', params: mindNext }); out.player = text; + s.progress = null; return out; } } diff --git a/server/main.mjs b/server/main.mjs index 7e72e0f..c6b7146 100644 --- a/server/main.mjs +++ b/server/main.mjs @@ -31,7 +31,7 @@ import * as bundle from './bundle.mjs'; import * as session from './session.mjs'; import * as housekeeping from './housekeeping.mjs'; import { effectiveContents } from './variants.mjs'; -import { gmTurn, answerAsk, openingCall, HttpError } from './loop.mjs'; +import { gmTurn, answerAsk, openingCall, HttpError, resolveParams } from './loop.mjs'; import * as users from './users.mjs'; import { forkRun } from './fork.mjs'; import * as discovery from './discovery.mjs'; @@ -938,6 +938,35 @@ route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => { return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user))) }; }); +// the turn meter's read (GM, 2026-11-17): the live progress record +// the streaming callback feeds, plus the scale the bar guesstimates +// against -- the only true budget is max_tokens when the knobs set +// one (reasoning counts inside it), else the session's own history: +// her longest past turn in characters (thinking and prose both, the +// units the meter counts). No history and no budget means no scale: +// the client falls back to the chunk-driven animation. Owner-only +// machinery; a plain read, never queued. +route('GET', '/api/runs/:id/progress', async ({ params, user }) => { + requireOwner(user, params.id); + const s = ctx.sessions.get(params.id); + if (!s) return { inFlight: false, scale: null }; + // the max_tokens layer mirrors the loop's own resolution (the mind + // rides over the run and deployment params); ~4 chars a token is + // the meter's rough exchange rate -- a meter, not a ledger + const eff = { ...resolveParams(ctx, params.id, 'player'), ...(s.mind ?? {}) }; + const budget = typeof eff.max_tokens === 'number' ? eff.max_tokens * 4 : null; + let high = 0; + for (const e of s.lines) { + if (e.t !== 'msg' || e.m.role !== 'assistant') continue; + const chars = (e.m.reasoning_content ?? '').length + (e.m.content ?? '').length; + if (chars > high) high = chars; + } + const scale = budget ?? (high > 0 ? high : null); + const scaleKind = budget ? 'budget' : (high > 0 ? 'history' : null); + if (!s.progress) return { inFlight: false, scale, scaleKind }; + return { inFlight: true, ...s.progress, scale, scaleKind }; +}); + // fork: any user, any run -- a mechanical atomic copy with the owner // replaced (server/fork.mjs). The source's activity lock is held, so // the copy is never taken mid-turn. diff --git a/server/provider.mjs b/server/provider.mjs index 5aa1eb9..c97edf7 100644 --- a/server/provider.mjs +++ b/server/provider.mjs @@ -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} [params] + * @param {?ToolDef[]} [tools] @param {Record} [params] + * @param {?ProgressFn} [onProgress] * @returns {Promise} */ - 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} */ + 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} */ @@ -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 }); diff --git a/server/session.mjs b/server/session.mjs index 980cfa0..57399f5 100644 --- a/server/session.mjs +++ b/server/session.mjs @@ -107,6 +107,7 @@ function makeSession(runId, n) { pendingAsk: null, // { callId, question, calls } -- the whole batch pauses mind: null, // the verb's one-shot layer, rebuilt by derive usage: null, // { promptTokens, completionTokens } from the last response + progress: null, // the turn meter's live record -- set per provider call, cleared at the turn's ends /** @param {LogEvent} entry */ append(entry) { this.lines.push(entry); diff --git a/server/shapes.mjs b/server/shapes.mjs index 20e76ec..d4605e4 100644 --- a/server/shapes.mjs +++ b/server/shapes.mjs @@ -82,7 +82,9 @@ export {}; * mind is the one-shot mind layer (the verb): the params her * NEXT turn rides at, cleared when that turn completes -- derived * from the last mind note, so a restart mid-window loses nothing. */ -/** @typedef {{ runId: string, n: number, stamp: string, file: string, lines: LogEvent[], pendingAsk: ?PendingAsk, mind: ?RoleParams, usage: ?{ promptTokens: number, completionTokens: number }, append: (entry: LogEvent) => void }} LiveSession */ +/** @typedef {{ runId: string, n: number, stamp: string, file: string, lines: LogEvent[], pendingAsk: ?PendingAsk, mind: ?RoleParams, usage: ?{ promptTokens: number, completionTokens: number }, progress: ?TurnProgress, append: (entry: LogEvent) => void }} LiveSession */ +/** The turn meter's live record: what the streaming callback knows. `phase` is what is arriving now; `started` is the provider call's epoch ms. */ +/** @typedef {{ phase: 'thinking'|'prose', thinking: number, prose: number, started: number }} TurnProgress */ /** run.json: lineage, ownership, per-run model overrides and knobs. */ /** @typedef {{ package: string, created?: string, owner?: ?string, forked?: number, models?: { player?: ?string, housekeeper?: ?string }, params?: { player?: ?RoleParams, housekeeper?: ?RoleParams } }} RunMeta */ @@ -124,7 +126,7 @@ export {}; /** The housekeeping job state (GET /housekeeping); discovery's refine * job reuses the shape under its own map key. */ -/** @typedef {{ state: 'idle'|'running'|'applied'|'pending'|'rejected', phase?: 'stop'|'rerun'|'refine', session?: number, target?: number, started?: string, stopped?: boolean, manifest?: string, reason?: string }} JobState */ +/** @typedef {{ state: 'idle'|'running'|'applied'|'pending'|'rejected', phase?: 'stop'|'rerun'|'refine', session?: number, target?: number, started?: string, stopped?: boolean, manifest?: string, reason?: string, steps?: { total: number, done: number, label: string, chars?: number }, lines?: string[] }} JobState */ /** The clerk boundary's result: exit code plus separated streams. */ /** @typedef {{ code: number, out: string, err: string }} ClerkResult */ @@ -133,7 +135,7 @@ export {}; /** @typedef {{ role: Role, content: ?string, tool_calls?: ToolCall[], tool_call_id?: string }} ViewMessage */ /** A chat completion response (OpenAI-compatible). */ -/** @typedef {{ choices: { message: WireMessage }[], usage?: Usage }} ChatResponse */ +/** @typedef {{ choices: { message: WireMessage, finish_reason: ?string }[], usage?: Usage }} ChatResponse */ /** An Error carrying an HTTP status (and optional detail payload) -- * the server's only error shape. */ diff --git a/test/smoke.mjs b/test/smoke.mjs index c6891bd..ceb9e59 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -124,6 +124,14 @@ for (let i = 0; i < 40; i++) { await new Promise((res) => setTimeout(res, 100)); } ok('refine applied', reg.data.job?.state === 'applied', JSON.stringify(reg.data.job ?? null)); +ok('the refine meter closed its steps', reg.data.job?.steps?.total === 5 && reg.data.job?.steps?.done === 5, + JSON.stringify(reg.data.job?.steps ?? null)); +ok('the refine receipt logged every battery and the curator', + (reg.data.job?.lines ?? []).length === 4 + && reg.data.job.lines.some((l) => l.includes('mock: reasoning deep')) + && reg.data.job.lines.some((l) => l.includes('mock-cheap: reasoning standard')) + && reg.data.job.lines.some((l) => l.includes('curator (mock-tie): curated')), + JSON.stringify(reg.data.job?.lines ?? null)); ok('the refined registry carries verdicts and curation', reg.data.phase === 'refined' && reg.data.models.some((m) => m.id === 'mock' && m.inference === true && m.reasoning === 'deep' && m.label === 'Mock' && m.family === 'mock') && reg.data.models.some((m) => m.id === 'mock-tie' && m.reasoning === 'deep' && m.label === 'Mock (tie)') @@ -149,6 +157,9 @@ r = await call(`/runs/${runId}`, { token: op }); ok('born dormant', r.data.phase === 'dormant' && r.data.sessions === 1 && r.data.draft === true, JSON.stringify({ phase: r.data.phase, sessions: r.data.sessions })); ok('the draft holds no rings yet (memory.json waits for the start gate)', r.data.fill.a === 0 && r.data.fill.b === 0, JSON.stringify(r.data.fill)); +r = await call(`/runs/${runId}/progress`, { token: op }); +ok('the turn meter on a dormant run: idle, no scale', r.status === 200 && r.data.inFlight === false && r.data.scale === null, + JSON.stringify(r.data)); r = await call(`/runs/${runId}/files`, { token: op }); ok('the draft editor surface', r.data.files['carryover.jsonl']?.mode === 'rw' && r.data.files['memory.json']?.mode === 'rw' && r.data.files['handbook.md']?.mode === 'rw', JSON.stringify(Object.fromEntries(Object.entries(r.data.files).map(([k, v]) => [k, v.mode])))); @@ -210,6 +221,10 @@ ok('the table carries only the picked variant', r.data.entries.every((e) => e.t ok('the picked turn is her turn on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && e.m.content.includes(`cuffed, belted, naked, barefoot, ${pickedStatus}`)), pickedStatus); ok('the table drops thinking', r.data.entries.every((e) => e.m?.reasoning_content === undefined)); ok('the variance metric', r.data.variance.picks === 1 && r.data.variance.offered === 2 && r.data.variance.maxVariants === 2, JSON.stringify(r.data.variance)); +r = await call(`/runs/${runId}/progress`, { token: op }); +ok('the turn meter reads idle between turns, scaled by her history', + r.status === 200 && r.data.inFlight === false && r.data.scaleKind === 'history' && typeof r.data.scale === 'number' && r.data.scale > 0, + JSON.stringify(r.data)); r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*She sets off.*' } }); ok('gm turn -> pending ask', r.status === 200 && !!r.data.pendingAsk, r.data.error ?? r.data.pendingAsk); @@ -346,6 +361,8 @@ r = await call(`/runs/${runId}/housekeeping/log`, { token: ash }); ok('ash housekeeping log 403', r.status === 403); r = await call(`/runs/${runId}/turn`, { method: 'POST', token: ash, body: { line: 'hi' } }); ok('ash turn 403', r.status === 403); +r = await call(`/runs/${runId}/progress`, { token: ash }); +ok('ash progress 403', r.status === 403); r = await call(`/runs/${runId}/notes`, { method: 'PUT', token: ash, body: { content: 'mine' } }); ok('ash notes write 403', r.status === 403); r = await call(`/runs/${runId}/story`, { token: ash }); diff --git a/web/index.html b/web/index.html index f57438c..8885849 100644 --- a/web/index.html +++ b/web/index.html @@ -50,6 +50,14 @@ + +
diff --git a/web/style.css b/web/style.css index d68e47a..937c198 100644 --- a/web/style.css +++ b/web/style.css @@ -66,6 +66,23 @@ body.play #context-meter { visibility: visible; } #context-fill { height: 100%; width: 0; background: var(--ok); transition: width 0.4s; } #context-fill.hot { background: var(--danger); } +#refine-progress { margin: 10px 0 2px; } +#refine-topline { display: flex; align-items: baseline; gap: 8px; font-size: 12px; margin-bottom: 4px; } +#refine-count { color: var(--accent); font-weight: 600; white-space: nowrap; } +#refine-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +#refine-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; } +#refine-fill { height: 100%; width: 0; background: var(--ok); } +#refine-lines { margin: 6px 0; font-size: 11px; color: var(--dim); max-height: 180px; overflow-y: auto; } +.refine-line { font-family: monospace; white-space: pre-wrap; } + +.turn-live { margin: 10px 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; } +.turn-live-line { font-size: 12px; margin-bottom: 6px; } +.turn-live-bar { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; } +.turn-live-fill { height: 100%; width: 0; background: var(--ok); } +.turn-live-segs { display: flex; gap: 4px; } +.turn-live-seg { flex: 1; height: 6px; border-radius: 3px; background: var(--line); } +.turn-live-seg.on { background: var(--ok); } + #diag-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); } #diag { position: fixed; diff --git a/web/transcript.mjs b/web/transcript.mjs index e045ed1..dd1ae10 100644 --- a/web/transcript.mjs +++ b/web/transcript.mjs @@ -200,7 +200,7 @@ function noteText(e) { // scroll around a content wipe (scroll anchoring re-anchoring after // the rebuild), so the position re-asserts on the next frame /** @param {HTMLElement} t */ -function stickBottom(t) { +export function stickBottom(t) { const sc = t.closest('main'); if (!sc) return; sc.scrollTop = sc.scrollHeight; diff --git a/web/view-home.mjs b/web/view-home.mjs index dd9b760..b0b9d63 100644 --- a/web/view-home.mjs +++ b/web/view-home.mjs @@ -132,6 +132,29 @@ function renderModelsAdmin(reg, seq) { /** @type {HTMLButtonElement} */ ($('models-discover')).disabled = running; /** @type {HTMLButtonElement} */ ($('models-refine')).disabled = running || reg.phase === 'none'; + // the refine meter: the bar moves only on real step completions + // (no speed to interpolate -- a stuck bar means a stuck step), the + // label names the call running now, and the lines are the receipt + // -- they survive the job, so a landed pass keeps its verdicts and + // a rejected one keeps its post-mortem + const meter = $('refine-progress'); + const linesBox = $('refine-lines'); + if (reg.job?.steps) { + const j = reg.job; + const st = j.steps ?? { total: 0, done: 0, label: '' }; + meter.hidden = false; + $('refine-count').textContent = `${st.done}/${st.total} \u00b7 ${j.state}`; + $('refine-label').textContent = j.state === 'running' + ? `${st.label}${st.chars != null ? ` \u00b7 ${st.chars} chars` : ''}` + : (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label); + /** @type {HTMLDivElement} */ ($('refine-fill')).style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`; + linesBox.textContent = ''; + for (const l of j.lines ?? []) linesBox.appendChild(el('div', 'refine-line', l)); + } else { + meter.hidden = true; + linesBox.textContent = ''; + } + const list = $('models-list'); list.textContent = ''; for (const m of reg.models) { diff --git a/web/view-play.mjs b/web/view-play.mjs index 4924a01..91755d9 100644 --- a/web/view-play.mjs +++ b/web/view-play.mjs @@ -17,7 +17,7 @@ import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chro import { navigate, render, runGone } from './router.mjs'; import { logEvent } from './log.mjs'; import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs'; -import { renderRaw, renderTranscript, viaLine } from './transcript.mjs'; +import { renderRaw, renderTranscript, stickBottom, viaLine } from './transcript.mjs'; // the table's two faces: the curated projection (the table) and the // raw audit log. Sticky across the re-renders a turn triggers; @@ -280,6 +280,7 @@ async function startRun() { const override = /** @type {HTMLInputElement} */ ($('hk-override')).checked; hideBanner(); setBusy(true, 'starting...'); + meterStart(); // the start can auto-send her opening turn -- meter it too /** @type {?string} */ let failed = null; let failedCls = undefined; try { @@ -296,6 +297,7 @@ async function startRun() { failed = e.message; } } + meterStop(); setBusy(false); render(); if (failed) banner(failed, failedCls); // render() clears the banner -- set it after @@ -335,6 +337,122 @@ function setInput(ok) { $('gm-stack').classList.toggle('off', !ok); // the overlay dims with the box } +// --- the turn meter ------------------------------------------------------ +// +// Her turn can run for minutes on a max-effort model, and a held-open +// request gives no sign of life. The progress route carries the +// streaming callback's live record (the phase in flight, its running +// chars) plus the scale the bar guesstimates against (GM, 2026-11-17: +// a guesstimate, but an informed one): the only true budget is +// max_tokens when the knobs set one (reasoning counts inside it), +// else her own history -- the longest turn she has completed in this +// session, in the same chars the meter counts. Reaching 100% and +// continuing pushes the bar back: the scale grows by quarters until +// the count fits, so the bar lands near 80% and climbs again -- the +// same arithmetic every poll, nothing accumulates. No scale at all +// (a fresh run, her opening turn) falls back to a chunk-driven +// animation: a segment strip that steps ONLY when characters +// actually arrived -- never a free-running spinner, which would +// claim liveness the stream may not have. + +let meterSeq = 0; +/** @type {?ReturnType} */ let meterTimer = null; +/** @type {?HTMLElement} */ let meterBox = null; +let meterSeg = 0; // the fallback strip's lit segment +let meterChars = 0; // the last seen count -- growth steps the strip + +/** @returns {void} */ +function meterStart() { + meterSeq++; + meterSeg = 0; + meterChars = 0; + meterSchedule(300); +} + +/** @returns {void} */ +function meterStop() { + meterSeq++; + if (meterTimer) clearTimeout(meterTimer ?? undefined); + meterTimer = null; + meterBox?.remove(); + meterBox = null; +} + +/** @param {number} delay @returns {void} */ +function meterSchedule(delay) { + const seq = meterSeq; + if (meterTimer) clearTimeout(meterTimer ?? undefined); + meterTimer = setTimeout(() => { void meterTick(seq); }, delay); +} + +/** @param {number} seq @returns {Promise} */ +async function meterTick(seq) { + if (seq !== meterSeq || !state.runId) return; + try { + const p = await api(`/runs/${state.runId}/progress`); + if (seq !== meterSeq) return; + meterDraw(p); + } catch { /* a missed poll keeps the last frame -- the next tick retries */ } + if (seq === meterSeq) meterSchedule(1000); +} + +/** One progress read. + * @typedef {{ inFlight: boolean, phase?: 'thinking'|'prose', thinking?: number, prose?: number, started?: number, scale?: ?number, scaleKind?: ?'budget'|'history' }} ProgressRead */ + +/** @param {ProgressRead} p @returns {void} */ +function meterDraw(p) { + const t = $('transcript'); + // a tab switch or a render wiped the transcript -- rebuild in place + const fresh = !meterBox || !meterBox.isConnected; + if (fresh) { + meterBox = el('div', 'turn-live'); + t.appendChild(meterBox); + } + const box = /** @type {HTMLElement} */ (meterBox); // the local carries the narrowing + // never yank the scroller: stick only if the GM was already at the + // bottom -- reading back while she writes stays put + const sc = /** @type {?HTMLElement} */ (t.closest('main')); + const atBottom = sc ? sc.scrollHeight - sc.scrollTop - sc.clientHeight < 40 : false; + box.textContent = ''; + const total = (p.thinking ?? 0) + (p.prose ?? 0); + const elapsed = p.started ? Math.max(0, Math.round((Date.now() - p.started) / 1000)) : 0; + const line = el('div', 'turn-live-line'); + const who = el('span', null, p.inFlight + ? `her turn -- ${p.phase === 'prose' ? 'writing' : 'thinking'}` + : 'her turn...'); + line.appendChild(who); + /** @type {string[]} */ const facts = []; + if (p.inFlight) facts.push(`${total} chars`, `${elapsed}s`); + if (p.inFlight && p.scale && p.scaleKind) { + // the push-back arithmetic: grow the scale by quarters until the + // count fits -- a 100% crossing lands the bar near 80% again + let s = p.scale; + while (s < total) s *= 1.25; + const pct = Math.round((100 * total) / s); + facts.push(`${pct}% of ${p.scaleKind === 'budget' ? 'the budget' : 'her longest'}`); + } + if (facts.length) line.appendChild(el('span', 'hint', ` \u00b7 ${facts.join(' \u00b7 ')}`)); + box.appendChild(line); + if (p.inFlight && p.scale) { + let s = p.scale; + while (s < total) s *= 1.25; + const bar = el('div', 'turn-live-bar'); + const fill = el('div', 'turn-live-fill'); + fill.style.width = `${Math.min(100, Math.round((100 * total) / s))}%`; + bar.appendChild(fill); + box.appendChild(bar); + } else if (p.inFlight) { + // the fallback strip: twelve segments, one lit, stepping only on + // real arrivals -- a stall shows as a stall + if (total > meterChars) meterSeg = (meterSeg + 1) % 12; + const segs = el('div', 'turn-live-segs'); + for (let i = 0; i < 12; i++) segs.appendChild(el('span', i === meterSeg ? 'turn-live-seg on' : 'turn-live-seg')); + box.appendChild(segs); + } + meterChars = total; + if (fresh || atBottom) stickBottom(t); +} + // --- actions ----------------------------------------------------------- /** @returns {Promise} */ @@ -354,6 +472,7 @@ async function sendTurn() { renderInputHl(); setInput(false); setBusy(true); + meterStart(); let failed = null; try { await api(`/runs/${state.runId}/turn`, { method: 'POST', body }); @@ -364,6 +483,7 @@ async function sendTurn() { /** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line renderInputHl(); } + meterStop(); setBusy(false); render(); if (failed) banner(failed); // render() clears the banner -- set it after (the runGone lesson) @@ -375,6 +495,7 @@ async function sendAnswer() { if (!answer || !state.runId) return; /** @type {HTMLInputElement} */ ($('ask-answer')).value = ''; setBusy(true); + meterStart(); let failed = null; try { await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } }); @@ -382,6 +503,7 @@ async function sendAnswer() { failed = e.message; /** @type {HTMLInputElement} */ ($('ask-answer')).value = answer; } + meterStop(); setBusy(false); render(); if (failed) banner(failed); // render() clears the banner -- set it after