From c6a86ce168e22d0ba82fa0285c14787a02fe817d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 18:44:43 +0200 Subject: [PATCH 1/8] Local models compact automatically: reply room is half the window and compaction headroom fits the window --- apps/host/server/agent/preset.mjs | 4 +- apps/host/server/agent/profile.mjs | 21 ++++++++- apps/host/tests/agent-compaction.test.mjs | 51 +++++++++++++++++++++ apps/host/tests/agent-events.test.mjs | 2 +- apps/host/tests/helpers/scripted-worker.mjs | 2 + 5 files changed, 75 insertions(+), 5 deletions(-) create mode 100644 apps/host/tests/agent-compaction.test.mjs diff --git a/apps/host/server/agent/preset.mjs b/apps/host/server/agent/preset.mjs index bd36e68c..40ebbfdb 100644 --- a/apps/host/server/agent/preset.mjs +++ b/apps/host/server/agent/preset.mjs @@ -50,7 +50,7 @@ export const AGENT_PROMPT = [ * @param {{platform?: string, search?: boolean}} [options] * @returns {object} the `config` of the `preset-standard` row */ -export function standardPreset({ platform = process.platform, search = false, off = new Set(), skillsDir = null } = {}) { +export function standardPreset({ platform = process.platform, search = false, off = new Set(), skillsDir = null, compaction = [] } = {}) { const windows = platform === 'win32'; const plugins = [ { id: 'persona', name: '@deepseek-ai/dsh-persona', config: { prefix: AGENT_PROMPT, complete: true, includeRuntimeContext: false } }, @@ -70,7 +70,7 @@ export function standardPreset({ platform = process.platform, search = false, of { id: 'compaction', name: 'cordis:group', group: true, isolate: { compaction: true, toolResultPruner: true }, config: [ - { id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic' }, + { id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic', ...(compaction.length ? { config: { modelPolicies: compaction } } : {}) }, { id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' }, { id: 'tool-result-pruner', name: '@deepseek-ai/dsh-compaction-tool-result-pruner', config: { thresholdChars: 8192, headChars: 4096, tailChars: 1024 } }, ], diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index 3d076838..b7772224 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -104,7 +104,20 @@ function fingerprint(provider, secret) { */ export function localOutputBudget(context) { const c = Number.isFinite(context) && context > 0 ? context : 32768; - return Math.max(8192, c - 4096); + // Half the window, at most 32K: still far more than the old 8192 that cut big answers off, and it leaves the other half for the + // conversation. The Harness's automatic compaction reads this number as the room the reply reserves: with nearly the whole window + // reserved it had no room left to measure pressure in, and a long chat or a long helper task never compacted. + return Math.max(4096, Math.min(32768, Math.floor(c / 2))); +} + +/** + * When the Harness's automatic compaction starts condensing old history, for one model: its own default keeps 64K tokens of headroom, + * which on a local window of 32K to 128K leaves no room at all (it then reports a configuration error once and never compacts). A quarter + * of what the window has left after the reply's room works from 16K up to the largest windows. Compaction then starts at about 70 percent. + */ +export function compactionHeadroom(context, outputBudget) { + const room = Math.max(0, (Number.isFinite(context) && context > 0 ? context : 32768) - outputBudget); + return Math.max(512, Math.min(65536, Math.floor(room * 0.25))); } /** @@ -144,6 +157,8 @@ export function buildProfile({ local = [], connections = [], gate = true, tools const mcpEnv = {}; // Helper agents: at least as many as the engine has request slots (a local model); API models take the Harness's own limit. let slots = 0; + /** Per-model compaction timing (see compactionHeadroom). */ + const compaction = []; local.forEach((inst, index) => { const route = index === 0 ? 'strata-local' : `strata-local-${slug(inst.id)}`; @@ -166,6 +181,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools reasoning: true, reasoningEfforts: LOCAL_EFFORTS, }], }; + compaction.push({ provider: route, model: inst.modelId, headroomTokens: compactionHeadroom(context, localOutputBudget(context)) }); slots = Math.max(slots, Number.isFinite(inst.slots) && inst.slots >= 1 ? Math.floor(inst.slots) : 1); routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', instanceId: inst.id, modelId: inst.modelId, name: inst.label || inst.modelId, contextWindow: context }); }); @@ -194,6 +210,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools })), }; const fp = fingerprint(providers[route], conn.apiKey ?? ''); + for (const m of conn.models) { const ctx = m.contextMax ?? ASSUMED_API_CONTEXT; compaction.push({ provider: route, model: m.id, headroomTokens: compactionHeadroom(ctx, outputBudget(ctx, m.maxOutput)) }); } for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT }); }); @@ -226,7 +243,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools ...(mcp.length || ownRows.length ? [{ insert: [...mcp, ...ownRows] }] : []), ...webRows, // The reminder tools would be a second scheduler beside the app's Tasks. The tool groups the person switched off in Settings -> Tools are left out. - { id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir }) }, + { id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset({ off: tools.off, search: searchOn, skillsDir, compaction }) }, // Strata names its chats itself; the Harness's own title request would be an extra model call on // every first prompt (and, for an API route, an unrequested one). { id: 'session-title-llm', disabled: true }, diff --git a/apps/host/tests/agent-compaction.test.mjs b/apps/host/tests/agent-compaction.test.mjs new file mode 100644 index 00000000..e6c3cd5b --- /dev/null +++ b/apps/host/tests/agent-compaction.test.mjs @@ -0,0 +1,51 @@ +// Automatic compaction for a LOCAL model: it starts before the window is full, the chat goes on after it, and helpers get it too. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { buildProfile, compactionHeadroom, localOutputBudget } from '../server/agent/profile.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; + +test('the reply keeps half the window (at most 32K) and compaction gets a headroom that fits, for every window size', () => { + assert.equal(localOutputBudget(32768), 16384); assert.equal(localOutputBudget(262144), 32768); assert.equal(localOutputBudget(8192), 4096); assert.equal(localOutputBudget(undefined), 16384); + for (const w of [8192, 16384, 32768, 65536, 131072, 262144, 1_000_000]) { + const out = localOutputBudget(w), head = compactionHeadroom(w, out); + const threshold = Math.floor(Math.min(w * 0.8, w - out - head)); + assert.ok(threshold > 0, `window ${w}: a positive start point (${threshold})`); + assert.ok(threshold >= (w - out) * 0.5, `window ${w}: compaction starts after at least half of the room the conversation has (${threshold})`); + assert.ok(Math.floor((w - out) * 0.16) < threshold, `window ${w}: the verbatim tail is smaller than the start point`); + } + const profile = buildProfile({ local: [{ id: 'a', modelId: 'm', baseUrl: 'http://x', context: 32768 }], connections: [] }); + assert.match(profile.patch, /"modelPolicies": \[\s*\{\s*"provider": "strata-local",\s*"model": "m",\s*"headroomTokens": 4096/); +}); + +test('a long chat on a small window compacts before it overflows, and the conversation goes on', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-compact-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 16384, slots: 2 }], connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); + const big = 'alpha '.repeat(1500); + const replies = []; + for (let i = 0; i < 6; i++) { + const frames = []; + await bridge.runTurn({ chatId: 'long', message: `SCRIPT:echo round${i} ${big}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) }); + replies.push(frames.filter(f => f.type === 'delta').map(f => f.text).join('').slice(0, 12)); + assert.equal(frames.at(-1).type, 'done', `round ${i} ended normally`); + } + assert.ok(replies.every(r => /^round\d/.test(r)), 'every round was answered: ' + replies.join(' | ')); + const reqs = worker.requests; + const summaries = reqs.filter(r => r.summary); + assert.ok(summaries.length >= 1, 'the Harness asked for a summary of the old history'); + const answers = reqs.filter(r => !r.summary && r.toolNames.length); + const peak = Math.max(...answers.map(r => r.promptChars)); + assert.ok(peak < 16384 * 4, `no request was bigger than the window (about ${Math.round(peak / 4)} tokens of 16384)`); + const lastRoundPrompt = answers.at(-1).promptChars; + assert.ok(lastRoundPrompt < answers[Math.min(4, answers.length - 1)].promptChars + 1, 'the prompt stopped growing'); +}); diff --git a/apps/host/tests/agent-events.test.mjs b/apps/host/tests/agent-events.test.mjs index 71ad0983..401fc412 100644 --- a/apps/host/tests/agent-events.test.mjs +++ b/apps/host/tests/agent-events.test.mjs @@ -18,7 +18,7 @@ test('the generated profile names credentials, never carries them, and declares const providers = entries.find(e => e.id === 'llm-pi-ai').config.providers; assert.deepEqual(Object.keys(providers).sort(), ['api-c0nn-1234-ab', 'strata-local']); assert.equal(providers['strata-local'].models[0].contextWindow, 32768); - assert.equal(providers['strata-local'].models[0].maxTokens, 28672, 'a local model may use nearly the whole window (it was 8192, which cut big answers off)'); + assert.equal(providers['strata-local'].models[0].maxTokens, 16384, 'a local model gets half its window for a reply (it was 8192, which cut big answers off) and the rest stays for the conversation, so the Harness can compact it'); assert.equal(providers['strata-local'].models[0].reasoning, true); assert.equal(providers['strata-local'].compat.thinkingFormat, 'chat-template'); assert.equal(providers['api-c0nn-1234-ab'].models[1].contextWindow, ASSUMED_API_CONTEXT, 'an unknown API window is a stated assumption, not a catalog default'); diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs index c3a15b10..0ff247bf 100644 --- a/apps/host/tests/helpers/scripted-worker.mjs +++ b/apps/host/tests/helpers/scripted-worker.mjs @@ -123,6 +123,8 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = return say(['Tool finished. ', `Result: ${result}`]); } const [name, args] = [directive?.[1], (directive?.[2] ?? '').trim()]; + // The Harness's compaction request (its summarizer prompt asks for the person's evolving goals): answer with a short summary. + if (messages.some(m => /evolving goals/.test(text(m)))) { requests.at(-1).summary = true; return say(['Summary of the earlier conversation: the person asked for echoes of a word and got them.']); } // The Harness's session-title request carries the same user text but offers no tools. if (!(body.tools ?? []).length && messages.some(m => /concise title/i.test(text(m)))) return say(['Scripted title']); if (name === 'slow') { From 998e9df95976f287860ac85165cd92162b0a55f7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 18:52:45 +0200 Subject: [PATCH 2/8] /research: web search and page reading with a structured answer and sources; http driver commands for plan, mode switch and long chats --- apps/host/scripts/agent-http.mjs | 64 +++++++++++++++++++++++-- apps/host/server/agent/agent-bridge.mjs | 18 +++++-- apps/host/server/agent/plan.mjs | 41 ++++++++++++++++ apps/host/server/index.mjs | 2 + apps/host/tests/agent-plan.test.mjs | 20 ++++++++ 5 files changed, 138 insertions(+), 7 deletions(-) diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs index 2f18b0bd..cd111a30 100644 --- a/apps/host/scripts/agent-http.mjs +++ b/apps/host/scripts/agent-http.mjs @@ -32,8 +32,8 @@ async function model() { } /** One chat stream; returns the frames. `print` shows a compact line per frame, deltas and reasoning as counters. */ -async function stream(body, { quiet = false } = {}) { - const res = await fetch(BASE + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); +async function stream(body, { quiet = false, path = '/api/chat/stream', onFrame = null } = {}) { + const res = await fetch(BASE + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); if (!res.ok) throw new Error(`stream -> ${res.status} ${await res.text()}`); const frames = []; let buffer = '', text = 0, reasoning = 0, lastLine = ''; const flushCounters = () => { if (text || reasoning) { console.log(`${stamp()} ... ${reasoning} reasoning chars, ${text} answer chars`); text = 0; reasoning = 0; } }; @@ -45,6 +45,7 @@ async function stream(body, { quiet = false } = {}) { const lines = buffer.split('\n'); buffer = lines.pop() ?? ''; for (const line of lines.filter(Boolean)) { const f = JSON.parse(line); f._at = Date.now(); frames.push(f); + try { onFrame?.(f); } catch (e) { console.log('onFrame error', e.message); } if (f.type === 'delta') { text += (f.text ?? '').length; continue; } if (f.type === 'reasoning') { reasoning += (f.text ?? '').length; continue; } if (f.type === 'stats') continue; @@ -57,6 +58,10 @@ async function stream(body, { quiet = false } = {}) { // ANSWER=approve|deny answers every card that asks (the card is the real Approve/Deny card of Manual mode) if (f.tool.state === 'proposed' && process.env.ANSWER) void j('/api/chat/approval', { sessionId: body.sessionId, toolId: f.tool.id, decision: process.env.APPROVE_MATCH && new RegExp(process.env.APPROVE_MATCH, 'i').test(`${f.tool.target} ${f.tool.effect}`) ? 'approve' : process.env.ANSWER }).then(() => console.log(`${stamp()} -> ${process.env.ANSWER} ${f.tool.id}`), e => console.log(`${stamp()} answer failed: ${e.message}`)); } + else if (f.type === 'plan') out = `PLAN ${f.event} ${f.plan.state} "${f.plan.title}" steps=${f.plan.steps.map(x => x.state[0] + ':' + x.text.slice(0, 40)).join(' | ')}`; + else if (f.type === 'plan-step') out = `PLAN-STEP ${f.line}${f.summary ? ' | summary: ' + f.summary : ''}`; + else if (f.type === 'queued-message') out = `QUEUED-MESSAGE ${f.state} "${f.message.text.slice(0, 50)}" deliverAt=${f.message.deliverAt}${f.afterStep ? ' afterStep=' + f.afterStep : ''} queue=${f.queue.length}`; + else if (f.type === 'queued-release') out = `QUEUED-RELEASE ${f.messages.map(m => m.text.slice(0, 40)).join(' | ')}`; else if (f.type === 'done') out = `done ${f.finishReason} tokensOut=${f.tokensOut}`; else if (f.type === 'error') out = `ERROR ${f.message}`; if (!quiet && out !== lastLine) console.log(`${stamp()} ${out}`); @@ -71,7 +76,7 @@ async function stream(body, { quiet = false } = {}) { if (command === 'connect') { const [baseUrl, modelId] = rest; - await j('/api/model-providers', { kind: 'custom', name: 'Cloud model', baseUrl, protocol: 'openai-chat', apiKey: '', models: [{ id: modelId, name: 'Test model' }] }); + await j('/api/model-providers', { kind: 'custom', name: 'Cloud model', baseUrl, protocol: 'openai-chat', apiKey: '', models: [{ id: modelId, name: 'Test model', ...(process.env.CTX ? { contextMax: Number(process.env.CTX) } : {}), ...(process.env.MAXOUT ? { maxOutput: Number(process.env.MAXOUT) } : {}) }] }); console.log('saved'); } else if (command === 'stream') { const [message, mode = 'bypass'] = rest; @@ -134,6 +139,57 @@ if (command === 'connect') { } await sleep(4000); } +} else if (command === 'plan') { + // /plan , then (unless STOP_AT_PLAN) Start as goal with an optional queued message: plan "" [""] + const [task, queued] = rest; + const chat = process.env.CHAT ?? `pl-${Date.now()}`; + const common = { sessionId: chat, mode: process.env.MODE ?? 'manual', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID }; + console.log(`${stamp()} -- /plan`); + const frames = await stream({ ...common, message: `/plan ${task}`}); + const plan = frames.find(f => f.type === 'plan')?.plan; + if (!plan) { console.log('NO PLAN FRAME (the reply stays plain text)'); process.exit(1); } + console.log(JSON.stringify(plan.steps.map(x => x.text))); + console.log(`${stamp()} -- GET /api/plan`, (await j(`/api/plan?sessionId=${chat}`)).plan?.state); + if (process.env.EDIT_LAST) { const steps = plan.steps.map(x => x.text); steps.push(process.env.EDIT_LAST); console.log(`${stamp()} -- edit`, (await j('/api/plan/edit', { sessionId: chat, planId: plan.id, steps })).plan.steps.length, 'steps'); } + if (process.env.STOP_AT_PLAN) { console.log(`${stamp()} -- ${process.env.STOP_AT_PLAN}`, JSON.stringify((await j('/api/plan/' + process.env.STOP_AT_PLAN, { sessionId: chat, planId: plan.id })).plan.state)); process.exit(0); } + console.log(`${stamp()} -- start as goal`); + let sent = false; + const run = stream({ ...common, planId: plan.id }, { path: '/api/plan/start-goal', onFrame: f => { + if (queued && !sent && f.type === 'plan-step' && f.state === 'running') { sent = true; setTimeout(async () => { try { console.log(`${stamp()} -- queue`, JSON.stringify((await j('/api/chat/queue', { sessionId: chat, message: queued })).message)); } catch (e) { console.log('queue failed', e.message); } }, Number(process.env.QUEUE_AFTER ?? 8) * 1000); } + } }); + await run; + console.log(`${stamp()} -- final plan`, JSON.stringify((await j(`/api/plan?sessionId=${chat}`)).plan?.steps.map(x => x.state + ':' + x.text.slice(0, 30)))); +} else if (command === 'modeswitch') { + // Manual run that needs several approvals; after the first card the chat is switched to Bypass: no further card may ask. + const [message] = rest; + const chat = process.env.CHAT ?? `ms-${Date.now()}`; + const common = { sessionId: chat, mode: 'manual', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID }; + let asked = 0, switched = false; + const frames = await stream({ ...common, message }, { onFrame: async f => { + if (f.type === 'agent-tool' && f.tool.state === 'proposed') { + asked++; + if (!switched) { switched = true; console.log(`${stamp()} -- switching to Bypass`, JSON.stringify(await j('/api/chat/mode', { sessionId: chat, mode: 'bypass' }))); } + } + } }); + const done = frames.filter(f => f.type === 'agent-tool' && f.tool.state === 'done').length; + console.log(`${stamp()} RESULT cards that asked=${asked} (expected 1), tools done=${done}`); +} else if (command === 'long') { + // Fill the context with long pastes so the Harness has to compact, then ask about the first one: long + const [rounds = '6', chars = '16000'] = rest; + const chat = process.env.CHAT ?? `lg-${Date.now()}`; + const common = { sessionId: chat, mode: 'bypass', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID }; + const filler = n => Array.from({ length: Math.ceil(Number(chars) / 60) }, (_, i) => `Entry ${n}-${i}: the quick brown fox number ${i * 7 + n} jumps over the lazy dog.`).join('\n'); + let frames = await stream({ ...common, message: 'Remember this code word for later: PAGODA-7731. Reply with just OK.' }, { quiet: true }); + console.log(`${stamp()} round 0 done, ctx=${frames.at(-1).contextTokens ?? "?"}`); + for (let n = 1; n <= Number(rounds); n++) { + frames = await stream({ ...common, message: `Here is log chunk ${n}. Reply with just the word OK. + +${filler(n)}`}, { quiet: true }); + const d = frames.at(-1); + console.log(`${stamp()} round ${n} ${d.type} ${d.finishReason ?? d.message ?? ""} tokensIn=${d.tokensIn} ctx=${d.contextTokens ?? d.context ?? "?"}`); + } + frames = await stream({ ...common, message: 'What was the code word I asked you to remember at the very start? Answer with the code word only.' }, { quiet: true }); + console.log(`${stamp()} ANSWER: ${frames.filter(f => f.type === "delta").map(f => f.text).join("").trim().slice(0, 120)}`); } else { - console.error('commands: connect | stream | goal | timeskip'); process.exit(2); + console.error('commands: connect | stream | goal | timeskip | plan | modeswitch | long'); process.exit(2); } diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 68ed4a5a..01e82113 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -23,7 +23,7 @@ import { StatusReporter } from './status.mjs'; import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf } from './profile.mjs'; import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; import { ChildProjector } from './children.mjs'; -import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, planAsPrompt, editedSteps, planView } from './plan.mjs'; +import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, planAsPrompt, editedSteps, planView, researchPrompt, parseSources } from './plan.mjs'; /** * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical @@ -246,7 +246,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = try { return await runTurnInner(c, options); } finally { c.starting = false; } } - async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, planTask = null, planRun = null }) { + async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, planTask = null, planRun = null, researchTopic = null }) { let send = onFrame; let attached = true; signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. @@ -306,6 +306,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; reporter.clear(); const extra = []; + if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } for (const f of extra) emit(f); const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow }); @@ -788,6 +789,17 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' }); } + /** + * "/research ": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, + * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. + */ + async function researchCommand(options) { + const topic = String(options.line ?? '').trim(); + if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.'); + if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.'); + return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic }); + } + const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone'); function planOf(chatId, planId) { const plan = plans.get(chatId); @@ -976,7 +988,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } - return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; + return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; } /** A goal that stopped by itself, in words. */ diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index 9302f3dc..aeca3248 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -187,3 +187,44 @@ export class PlanStore { /** What the page gets: a copy with no host-only fields. */ export const planView = plan => (plan ? JSON.parse(JSON.stringify(plan)) : null); + +// ---- /research ------------------------------------------------------------------------------------------------------------------ + +/** The instruction a research turn gets in front of the person's topic. */ +export function researchPrompt(topic) { + return [ + `Research this topic for me using the web: ${topic}`, + '', + 'How to work:', + '1. Search the web with the web_search tool (try two or three different searches).', + '2. Open the most useful pages with the web_fetch tool and read them. Use at least three different sources when you can find them.', + '3. Write only what the pages say. If sources disagree or you could not find something, say so plainly.', + '', + 'Then write your answer in exactly this shape, in plain words:', + '## Summary', + 'Three to five sentences.', + '## Key findings', + '- One finding per line, each ending with its source number in square brackets, like [1].', + '## Sources', + '1. Page title - web address', + '2. Page title - web address', + ].join('\n'); +} + +/** The numbered sources at the end of a research answer: [{ n, title, url }]. Empty when there are none. */ +export function parseSources(text) { + const lines = String(text ?? '').replace(/\r/g, '').split('\n'); + const at = lines.map(l => /^\s{0,3}#{1,6}\s*sources\b/i.test(l) || /^\s*\*{0,2}sources\*{0,2}:?\s*$/i.test(l)).lastIndexOf(true); + if (at < 0) return []; + const out = []; + for (const line of lines.slice(at + 1)) { + if (/^\s{0,3}#{1,6}\s/.test(line)) break; + const url = /(https?:\/\/[^\s)>\]"']+)/.exec(line)?.[1]?.replace(/[.,;]+$/, ''); + if (!url) continue; + const md = /\[([^\]]+)\]\(https?:\/\//.exec(line); + const before = line.slice(0, line.indexOf(url)).replace(/^\s*(?:\d+[.)]|[-*•])\s*/, '').replace(/[\s\-–—:(<[]+$/, '').replace(/\*\*|`/g, '').trim(); + const title = clean(md?.[1] ?? before) || (() => { try { return new URL(url).hostname; } catch { return url; } })(); + if (!out.some(s => s.url === url)) out.push({ n: out.length + 1, title: clip(title, 120), url }); + } + return out.slice(0, 20); +} diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 6688b728..39144594 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -524,8 +524,10 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI // "/goal ..." is the Harness's goal command (set, show, pause, resume, clear); everything else is a message. const goalLine = /^\/goal(?:\s+([\s\S]*))?$/i.exec(message.trim()); const planLine = /^\/plan(?:\s+([\s\S]*))?$/i.exec(message.trim()); + const researchLine = /^\/research(?:\s+([\s\S]*))?$/i.exec(message.trim()); const turnOptions = { chatId, message, workspacePath: cwd, choice, mode: typeof body.mode === 'string' ? body.mode : null, thinking: typeof body.thinking === 'string' ? body.thinking : null, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal }; const result = typeof body.planId === 'string' && body.message === '/plan start' ? await agent.planGoal({ ...turnOptions, planId: body.planId }) + : researchLine ? await agent.researchCommand({ ...turnOptions, line: researchLine[1] ?? '' }) : planLine ? await agent.planCommand({ ...turnOptions, line: planLine[1] ?? '' }) : goalLine ? await agent.goalCommand({ ...turnOptions, line: goalLine[1] ?? '' }) : await agent.runTurn(turnOptions); if (result?.detached) void result.ended.then(r => settle(r?.tokensOut ?? null), () => settle(null)); diff --git a/apps/host/tests/agent-plan.test.mjs b/apps/host/tests/agent-plan.test.mjs index 02418c57..9f9fd164 100644 --- a/apps/host/tests/agent-plan.test.mjs +++ b/apps/host/tests/agent-plan.test.mjs @@ -78,3 +78,23 @@ test('plans survive a restart', () => { b.clear('chat-1'); assert.equal(new PlanStore(file).get('chat-1'), null); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +import { parseSources, researchPrompt } from '../server/agent/plan.mjs'; + +test('research: the answer shape is asked for, and the sources are read back as [{n, title, url}]', () => { + assert.ok(researchPrompt('heat pumps').includes('web_search') && researchPrompt('heat pumps').includes('## Sources')); + const answer = [ + '## Summary', 'Heat pumps move heat.', '## Key findings', '- They are efficient [1].', '- They cost more up front [2].', + '## Sources', + '1. Heat pump basics - https://energy.example.org/heat-pumps', + '2. [Costs explained](https://costs.example.com/page?x=1).', + '3. https://plain.example.net/a', + '4. Heat pump basics - https://energy.example.org/heat-pumps', + ].join('\n'); + assert.deepEqual(parseSources(answer), [ + { n: 1, title: 'Heat pump basics', url: 'https://energy.example.org/heat-pumps' }, + { n: 2, title: 'Costs explained', url: 'https://costs.example.com/page?x=1' }, + { n: 3, title: 'plain.example.net', url: 'https://plain.example.net/a' }, + ]); + assert.deepEqual(parseSources('No sources section here, see https://x.example'), []); +}); From c937aeb1df89199299b9929785bbbdab90db365c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:04:25 +0200 Subject: [PATCH 3/8] /research gathers first (notes hidden), nudges once when no page was opened, then writes the answer in the fixed shape; /research in the slash menu --- apps/host/scripts/agent-http.mjs | 2 ++ apps/host/server/agent/agent-bridge.mjs | 23 +++++++++++-- apps/host/server/agent/plan.mjs | 44 +++++++++++++++++++------ apps/host/src/screens/Chat.tsx | 1 + apps/host/tests/agent-plan-run.test.mjs | 20 +++++++++++ apps/host/tests/agent-plan.test.mjs | 3 +- 6 files changed, 80 insertions(+), 13 deletions(-) diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs index cd111a30..6779e1c7 100644 --- a/apps/host/scripts/agent-http.mjs +++ b/apps/host/scripts/agent-http.mjs @@ -62,6 +62,7 @@ async function stream(body, { quiet = false, path = '/api/chat/stream', onFrame else if (f.type === 'plan-step') out = `PLAN-STEP ${f.line}${f.summary ? ' | summary: ' + f.summary : ''}`; else if (f.type === 'queued-message') out = `QUEUED-MESSAGE ${f.state} "${f.message.text.slice(0, 50)}" deliverAt=${f.message.deliverAt}${f.afterStep ? ' afterStep=' + f.afterStep : ''} queue=${f.queue.length}`; else if (f.type === 'queued-release') out = `QUEUED-RELEASE ${f.messages.map(m => m.text.slice(0, 40)).join(' | ')}`; + else if (f.type === 'research') out = `RESEARCH sources=${f.sources.map(x => x.n + ':' + x.url).join(' ')}`; else if (f.type === 'done') out = `done ${f.finishReason} tokensOut=${f.tokensOut}`; else if (f.type === 'error') out = `ERROR ${f.message}`; if (!quiet && out !== lastLine) console.log(`${stamp()} ${out}`); @@ -71,6 +72,7 @@ async function stream(body, { quiet = false, path = '/api/chat/stream', onFrame if (done) break; } flushCounters(); + if (process.env.SHOWTEXT && !quiet) console.log(['---- answer text ----', frames.filter(f => f.type === 'delta').map(f => f.text).join(''), '---- end ----'].join(String.fromCharCode(10))); return frames; } diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 01e82113..d335601f 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -23,7 +23,7 @@ import { StatusReporter } from './status.mjs'; import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf } from './profile.mjs'; import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; import { ChildProjector } from './children.mjs'; -import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, planAsPrompt, editedSteps, planView, researchPrompt, parseSources } from './plan.mjs'; +import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; /** * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical @@ -248,11 +248,13 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, planTask = null, planRun = null, researchTopic = null }) { let send = onFrame; let attached = true; + // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. + let hideDeltas = !!researchTopic; signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. const written = { all: '', step: '' }; const emit = frame => { - if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; } + if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; } if (frame.own) { const { own, ...rest } = frame; frame = rest; } try { send(frame); } catch { send = () => {}; attached = false; } }; @@ -295,6 +297,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = // Helper agents (subagents) the Harness started for this chat, and the state of the run around them. children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode, plan: null, advancing: false, goalRun: false, + research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null, }; c.turn = turn; function finishTurn(failure) { @@ -404,6 +407,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = switch (e.type) { case 'turn/start': turn.parentOpen = true; + if (turn.research) turn.research.waitingStart = false; clearTimeout(turn.settleTimer); // After Stop, a helper's report would start a new turn that nobody asked for. if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); @@ -547,6 +551,21 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = const current = await goalGet(); if (turn.finished || turn.parentOpen) return; if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } + // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. + if (turn.research && !turn.stopping) { + const r = turn.research; + if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; } + const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length; + const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic); + if (prompt) { + if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true; + r.waitingStart = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); } + catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } + } // A plan step's goal is complete: record it, deliver queued messages, start the next step. if (turn.plan && current && current.phase === 'complete' && !turn.advancing) { turn.advancing = true; diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index aeca3248..f2b07247 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -190,24 +190,34 @@ export const planView = plan => (plan ? JSON.parse(JSON.stringify(plan)) : null) // ---- /research ------------------------------------------------------------------------------------------------------------------ -/** The instruction a research turn gets in front of the person's topic. */ +/** The first research prompt: find and read pages, take notes. What the assistant writes here is not shown; the answer is written in a second step. */ export function researchPrompt(topic) { return [ - `Research this topic for me using the web: ${topic}`, + `Research task: ${topic}`, '', - 'How to work:', - '1. Search the web with the web_search tool (try two or three different searches).', - '2. Open the most useful pages with the web_fetch tool and read them. Use at least three different sources when you can find them.', - '3. Write only what the pages say. If sources disagree or you could not find something, say so plainly.', - '', - 'Then write your answer in exactly this shape, in plain words:', + 'Do these steps in order. Do not skip a step.', + '1. Call web_search to find pages about the task.', + '2. Call web_fetch to open at least two of the pages you found, and read them. Do not rely on the search results alone.', + '3. When you have read them, reply with short notes: the facts you found, each with the web address of the page it came from.', + ].join('\n'); +} + +/** Sent when the assistant answered without opening pages. */ +export const RESEARCH_NUDGE = 'You have not opened enough pages yet. Call web_fetch now on at least two of the pages from your search, read them, then reply with short notes and the web address of each page.'; + +/** The second research prompt: write the answer in the fixed shape. */ +export function researchWritePrompt(topic) { + return [ + `Now write the final answer to the research task: ${topic}`, + 'Use only what you read on the pages. Do not call any tool. Start your reply with the line "## Summary" and use exactly these three headings:', '## Summary', - 'Three to five sentences.', + 'Three to five sentences, in plain words. If the sources disagree or something could not be found, say so.', '## Key findings', '- One finding per line, each ending with its source number in square brackets, like [1].', '## Sources', '1. Page title - web address', '2. Page title - web address', + 'List only pages you opened.', ].join('\n'); } @@ -215,7 +225,7 @@ export function researchPrompt(topic) { export function parseSources(text) { const lines = String(text ?? '').replace(/\r/g, '').split('\n'); const at = lines.map(l => /^\s{0,3}#{1,6}\s*sources\b/i.test(l) || /^\s*\*{0,2}sources\*{0,2}:?\s*$/i.test(l)).lastIndexOf(true); - if (at < 0) return []; + if (at < 0) return linkSources(text); const out = []; for (const line of lines.slice(at + 1)) { if (/^\s{0,3}#{1,6}\s/.test(line)) break; @@ -228,3 +238,17 @@ export function parseSources(text) { } return out.slice(0, 20); } + +/** No Sources section: the pages the answer links to, in the order they appear, so the page can still list where it came from. */ +function linkSources(text) { + const out = []; + const re = /\[([^\]]{1,160})\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s)>\]"']+)/g; + let m; + while ((m = re.exec(String(text ?? ''))) && out.length < 8) { + const url = (m[2] ?? m[3]).replace(/[.,;]+$/, ''); + if (out.some(x => x.url === url)) continue; + let host = url; try { host = new URL(url).hostname; } catch { /* keep the address */ } + out.push({ n: out.length + 1, title: clip(clean(m[1] ?? '') || host, 120), url }); + } + return out; +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 9a1f7eb4..1b898ef3 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -424,6 +424,7 @@ function useSlashCommands(clear: () => void, setDraft: (value: string) => void): { id: 'time-skip', label: '/time-skip', hint: 'Try a change on a copy, check it, and keep it only if it is better', icon: 'branch', run: () => setDraft('/time-skip ') }, { id: 'goal', label: '/goal', hint: 'Set a goal and let the assistant keep working until it is done', icon: 'bolt', run: () => setDraft('/goal ') }, { id: 'plan', label: '/plan', hint: 'Have the assistant write a plan first; nothing runs until you approve it', icon: 'check', run: () => setDraft('/plan ') }, + { id: 'research', label: '/research', hint: 'Search the web, read the pages and answer with sources', icon: 'search', run: () => setDraft('/research ') }, { id: 'loop', label: '/loop', hint: 'Repeat a message every few minutes while this chat is open', icon: 'refresh', run: () => setDraft('/loop 10m ') }, { id: 'website', label: '/website', hint: 'Open a website in the preview sidebar', icon: 'link', run: () => { clear(); window.dispatchEvent(new Event('strata:open-website')); } }, { id: 'preview', label: '/preview', hint: 'Open a local file in the preview sidebar', icon: 'file', run: () => { clear(); window.dispatchEvent(new Event('strata:open-preview')); } }, diff --git a/apps/host/tests/agent-plan-run.test.mjs b/apps/host/tests/agent-plan-run.test.mjs index c2ccdd87..147eb117 100644 --- a/apps/host/tests/agent-plan-run.test.mjs +++ b/apps/host/tests/agent-plan-run.test.mjs @@ -132,3 +132,23 @@ test('Stop in the middle of a plan pauses it with the finished steps kept; Resum await r.bridge.stop('p4'); await second; assert.equal(r.bridge.planState('p4').state, 'paused'); }); + +test('/research: gathering is not shown, a run that opened no pages is sent back once, and the answer is written in a second step with its sources listed', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.researchCommand({ ...r.base('rs1', f => out.push(f)), line: 'SCRIPT:echo Fact one [1]. https://a.example/x' }); + const shown = words(out); + assert.equal(shown.split('Fact one').length - 1, 1, 'only the final answer is shown, not the notes of the first two replies: ' + JSON.stringify(shown)); + const asked = r.worker.requests.filter(q => q.raw.includes('Research task:') || q.raw.includes('You have not opened enough pages') || q.raw.includes('Now write the final answer')); + assert.ok(asked.length >= 3, 'gather, nudge (no pages were opened), write'); + const last = r.worker.requests.at(-1).raw; + assert.ok(last.includes('Now write the final answer to the research task') && last.includes('## Summary'), 'the last request carries the writing prompt'); + const research = out.find(f => f.type === 'research'); + assert.deepEqual(research.sources, [{ n: 1, title: 'a.example', url: 'https://a.example/x' }]); + assert.ok(out.findIndex(f => f.type === 'research') < out.findIndex(f => f.type === 'done')); + assert.equal(out.at(-1).type, 'done'); + // without a topic, or with search turned off, nothing runs + const help = []; + await r.bridge.researchCommand({ ...r.base('rs2', f => help.push(f)), line: '' }); + assert.match(words(help), /Type \/research followed by/); +}); diff --git a/apps/host/tests/agent-plan.test.mjs b/apps/host/tests/agent-plan.test.mjs index 9f9fd164..85b76f9a 100644 --- a/apps/host/tests/agent-plan.test.mjs +++ b/apps/host/tests/agent-plan.test.mjs @@ -96,5 +96,6 @@ test('research: the answer shape is asked for, and the sources are read back as { n: 2, title: 'Costs explained', url: 'https://costs.example.com/page?x=1' }, { n: 3, title: 'plain.example.net', url: 'https://plain.example.net/a' }, ]); - assert.deepEqual(parseSources('No sources section here, see https://x.example'), []); + assert.deepEqual(parseSources('No sources section here, see https://x.example'), [{ n: 1, title: 'x.example', url: 'https://x.example' }], 'without a Sources section the linked pages are listed'); + assert.deepEqual(parseSources('Nothing to link.'), []); }); From b6b546ae13137b73852181190810d7af4e164ea5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:09:54 +0200 Subject: [PATCH 4/8] Response settings reach agent turns (thinking budget, Expert sampling) through a local forwarding endpoint; step summaries from what the step changed; plan title heading --- apps/host/scripts/agent-http.mjs | 28 +++++- apps/host/server/agent/agent-bridge.mjs | 36 +++++-- apps/host/server/agent/llm-shape.mjs | 118 +++++++++++++++++++++++ apps/host/server/agent/plan.mjs | 19 ++++ apps/host/server/agent/profile.mjs | 25 ++++- apps/host/server/index.mjs | 10 +- apps/host/tests/agent-plan.test.mjs | 14 ++- apps/host/tests/agent-shape.test.mjs | 120 ++++++++++++++++++++++++ 8 files changed, 351 insertions(+), 19 deletions(-) create mode 100644 apps/host/server/agent/llm-shape.mjs create mode 100644 apps/host/tests/agent-shape.test.mjs diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs index 6779e1c7..6e75e2a7 100644 --- a/apps/host/scripts/agent-http.mjs +++ b/apps/host/scripts/agent-http.mjs @@ -192,6 +192,32 @@ ${filler(n)}`}, { quiet: true }); } frames = await stream({ ...common, message: 'What was the code word I asked you to remember at the very start? Answer with the code word only.' }, { quiet: true }); console.log(`${stamp()} ANSWER: ${frames.filter(f => f.type === "delta").map(f => f.text).join("").trim().slice(0, 120)}`); +} else if (command === 'effort') { + // The same question at each reasoning level (and optional thinking budget): what really changes is the thinking the model did. + const [question = 'What is 17 times 23, and is the result divisible by 3? Explain briefly.', budget = '0'] = rest; + const rows = []; + for (const level of ['Off', 'Low', 'Medium', 'High', 'Max']) { + const t = Date.now(); + const frames = await stream({ sessionId: `ef-${level}-${Date.now()}`, message: question, mode: 'bypass', remoteModel: await model(), thinking: level, thinkingBudget: Number(budget), agent: process.env.PLAIN ? false : undefined }, { quiet: true }); + const reasoning = frames.filter(x => x.type === 'reasoning').map(x => x.text ?? '').join('').length; + const answer = frames.filter(x => x.type === 'delta').map(x => x.text ?? '').join(''); + const done = frames.at(-1); + rows.push({ level, budget: Number(budget), reasoningChars: reasoning, answerChars: answer.length, tokensOut: done.tokensOut, seconds: Math.round((Date.now() - t) / 1000), answer: answer.replace(/\s+/g, ' ').slice(0, 90) }); + console.log(JSON.stringify(rows.at(-1))); + } +} else if (command === 'sampling') { + // Set Expert sampling through the engine settings route (as the Response settings dialog does), then ask for a random word a few times. + const [temp = '0', seed = '1', n = '3'] = rest; + const before = await j('/api/engine'); + const set = async values => j('/api/engine', { expert: Object.entries(values).map(([id, value]) => ({ id, value })) }, 'PATCH'); + await set({ 'sample.temp': Number(temp), 'sample.seed': Number(seed) }); + const words = []; + for (let i = 0; i < Number(n); i++) { + const frames = await stream({ sessionId: `sm-${Date.now()}-${i}`, message: 'Reply with one random everyday English word and nothing else.', mode: 'bypass', remoteModel: await model(), thinking: 'Off' }, { quiet: true }); + words.push(frames.filter(x => x.type === 'delta').map(x => x.text ?? '').join('').trim().slice(0, 30)); + } + console.log(JSON.stringify({ temp: Number(temp), seed: Number(seed), words })); + await set({ 'sample.temp': 0.6, 'sample.seed': -1 }); } else { - console.error('commands: connect | stream | goal | timeskip | plan | modeswitch | long'); process.exit(2); + console.error('commands: connect | stream | goal | timeskip | plan | modeswitch | long | effort | sampling'); process.exit(2); } diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index d335601f..feb9f186 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -23,7 +23,8 @@ import { StatusReporter } from './status.mjs'; import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf } from './profile.mjs'; import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; import { ChildProjector } from './children.mjs'; -import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; +import { nearestBudget } from './llm-shape.mjs'; +import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; /** * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical @@ -56,7 +57,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve * @param {string} [options.nodePath] the Node runtime that runs the Harness * @param {(line:string)=>void} [options.log] */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, expertSampling = () => null, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { const root = join(dataDir, 'agent'); const home = join(root, 'home'); const sessionsFile = join(root, 'sessions.json'); @@ -97,6 +98,15 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true }); }); + /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ + let shapeTargets = {}; + function buildProfileNow() { + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase }); + shapeTargets = profile.shapeTargets ?? {}; + return profile; + } + const llmTarget = key => shapeTargets[key] ?? null; + function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); } /** Where the agent component is (the browser tool server lives inside it), or null. */ const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; }; @@ -105,7 +115,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = function status() { const h = harnessInfo(); if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' }; - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir() }); + const profile = buildProfileNow(); return { state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle', reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null, @@ -153,7 +163,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = async function ensureRuntime(choice, signal) { for (;;) { if (starting) { await starting.catch(() => {}); continue; } - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir() }); + const profile = buildProfileNow(); const route = routeFor(profile, choice); if (!route) { throw new AgentUnavailable(choice?.connectionId @@ -246,7 +256,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = try { return await runTurnInner(c, options); } finally { c.starting = false; } } - async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, planTask = null, planRun = null, researchTopic = null }) { + async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, planTask = null, planRun = null, researchTopic = null }) { let send = onFrame; let attached = true; // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. let hideDeltas = !!researchTopic; @@ -271,9 +281,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. const level = effortOf(thinking ?? 'Medium'); // the menu's default is Medium - const wanted = `${route.route}/${route.modelId}/${level ?? ''}`; + // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding + // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. + const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget); + const sampling = proxyBase && route.shaped ? expertSampling() : null; + const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route; + const wanted = `${provider}/${route.modelId}/${level ?? ''}`; if (c.route !== wanted || c.routeGeneration !== runtime.generation) { - const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider: route.route, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); + const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); try { try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); } } catch (e) { @@ -487,7 +502,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; }); const now = plans.get(chatId); await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } }); - written.step = ''; + written.step = ''; written.stepAt = Date.now(); emit(stepFrame(now, index)); emit(publishPlan('step', now)); const st = now.steps[index]; @@ -501,7 +516,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = if (!run || !plan || plan.id !== run.id) return false; const at = currentStep(plan); if (at < 0) return false; - const summary = firstSentence(written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); + const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card); + const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; }); let now = plans.get(chatId); emit(stepFrame(now, at)); @@ -1007,7 +1023,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } - return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; + return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; } /** A goal that stopped by itself, in words. */ diff --git a/apps/host/server/agent/llm-shape.mjs b/apps/host/server/agent/llm-shape.mjs new file mode 100644 index 00000000..e0e4f03d --- /dev/null +++ b/apps/host/server/agent/llm-shape.mjs @@ -0,0 +1,118 @@ +/** + * Response settings for agent turns. + * + * The chat's own path sends the Expert sampling (temperature, top-p, top-k, repeat penalty, seed) and the composer's thinking budget with + * every request. The agent's requests are made by the Harness, which has no place for either, so they never reached the model. When a + * person has changed one of them, the agent's model route goes through the small forwarding endpoint below (on this computer only), which + * adds exactly the fields that differ from the defaults and passes everything else through untouched. With every setting at its default the + * agent talks to the model directly, byte for byte as before. + * + * Only a local model, or an OpenAI-style server on this computer or this network, is shaped: a cloud service would reject fields it does not know. + */ + +import http from 'node:http'; +import https from 'node:https'; + +/** The thinking budgets the composer offers (0 = no limit is not a budget). */ +export const BUDGETS = Object.freeze([2048, 8192, 32768]); +/** The offered budget nearest to what a chat asks for (0 stays 0). */ +export function nearestBudget(value) { + const n = Number(value); + if (!Number.isFinite(n) || n <= 0) return 0; + return BUDGETS.reduce((best, b) => (Math.abs(b - n) < Math.abs(best - n) ? b : best), BUDGETS[0]); +} + +/** Expert setting id -> request field, and the default each one has (the catalog's recommended value). */ +const SAMPLING = Object.freeze({ + 'sample.temp': ['temperature', 0.6], + 'sample.topP': ['top_p', 0.95], + 'sample.topK': ['top_k', 40], + 'sample.repeat': ['repeat_penalty', 1.05], + 'sample.seed': ['seed', -1], +}); + +/** The request fields for the Expert settings that are not at their default, or null when all are. */ +export function samplingFromExpert(expert) { + const out = {}; + for (const [id, [field, recommended]] of Object.entries(SAMPLING)) { + const v = expert?.[id]; + if (typeof v === 'number' && Number.isFinite(v) && v !== recommended) out[field] = v; + } + if (expert?.['sample.speedProjection'] === false) out.experimental_speed_projection = false; + const cap = Number(expert?.['sample.maxTokens']); + if (Number.isFinite(cap) && cap > 0) out.max_tokens = Math.floor(cap); + return Object.keys(out).length ? out : null; +} + +/** + * The request body with the person's settings added. A field the request already carries is left alone (the Harness's own wins), the + * thinking budget is only added while thinking is on, and an output cap only ever lowers the request's own. + */ +export function shapeBody(body, { sampling = null, budget = 0 } = {}) { + if (!body || typeof body !== 'object' || Array.isArray(body)) return body; + const out = { ...body }; + for (const [field, value] of Object.entries(sampling ?? {})) { + if (field === 'max_tokens' || field === 'max_completion_tokens') continue; + if (out[field] === undefined) out[field] = value; + } + if (sampling?.max_tokens) { + for (const key of ['max_tokens', 'max_completion_tokens']) if (Number.isFinite(out[key])) out[key] = Math.min(out[key], sampling.max_tokens); + if (out.max_tokens === undefined && out.max_completion_tokens === undefined) out.max_tokens = sampling.max_tokens; + } + const thinkingOff = out.chat_template_kwargs?.enable_thinking === false; + if (budget > 0 && !thinkingOff && out.reasoning_budget_tokens === undefined) out.reasoning_budget_tokens = budget; + return out; +} + +/** An address on this computer or on a private network: where the person's own model servers live. */ +export function isPrivateHost(url) { + let host; + try { host = new URL(url).hostname.toLowerCase(); } catch { return false; } + host = host.replace(/^\[|\]$/g, ''); + if (host === 'localhost' || host === '::1' || host.endsWith('.local') || host.endsWith('.lan')) return true; + const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(host); + if (!m) return false; + const [a, b] = [Number(m[1]), Number(m[2])]; + return a === 127 || a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127); +} + +const HOP = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'upgrade', 'proxy-connection']); + +/** + * The forwarding endpoint. `targetOf(key)` gives the real base address of a shaped route (or null), `samplingNow()` the Expert fields that + * differ from the defaults right now. Called for `/api/internal/agent-llm//`; this computer's own address only. + */ +export function createLlmProxy({ targetOf, samplingNow }) { + return function handle(req, res, key, rest) { + const remote = req.socket?.remoteAddress ?? ''; + if (!/^(::1|127\.|::ffff:127\.)/.test(remote)) { res.writeHead(403, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'This endpoint is for the assistant on this computer only.' })); return; } + const base = targetOf(key); + if (!base) { res.writeHead(404, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Unknown model route.' })); return; } + const chunks = []; + req.on('data', c => chunks.push(c)); + req.on('error', () => res.destroy()); + req.on('end', () => { + let body = Buffer.concat(chunks); + const budget = nearestBudget(req.headers['x-strata-budget']); + if (req.method === 'POST' && /\/chat\/completions\/?$/.test(rest) && body.length) { + try { body = Buffer.from(JSON.stringify(shapeBody(JSON.parse(body.toString('utf8')), { sampling: samplingNow(), budget }))); } catch { /* not JSON: pass it on untouched */ } + } + // The route's address is the model's own base (it ends in /v1): the assistant's /v1 is that same prefix. + const target = new URL(base.replace(/\/+$/, '') + rest.replace(/^\/v1(?=\/|$|\?)/, '')); + const headers = {}; + for (const [k, v] of Object.entries(req.headers)) if (!HOP.has(k) && !k.startsWith('x-strata-')) headers[k] = v; + headers['content-length'] = String(body.length); + const lib = target.protocol === 'https:' ? https : http; + const upstream = lib.request(target, { method: req.method, headers }, reply => { + const out = { ...reply.headers }; delete out['transfer-encoding']; delete out.connection; + res.writeHead(reply.statusCode ?? 502, out); + reply.pipe(res); + reply.on('error', () => res.destroy()); + }); + upstream.on('error', e => { if (!res.headersSent) { res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: `The model server could not be reached: ${e.message}` })); } else res.destroy(); }); + // The assistant stopped waiting (Stop): stop the model too. + res.on('close', () => { if (!res.writableEnded) upstream.destroy(); }); + upstream.end(body); + }); + }; +} diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index f2b07247..7e4ee35d 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -36,6 +36,7 @@ export function planPrompt(task) { return [ 'Make a plan for the request below. Do not change anything: you may only look (read files, list folders, search).', 'When you have looked enough, end your reply with the plan as a numbered list: one short line per step, in the order they should be done.', + 'Put a short heading line right before the list, like "## Pagoda page" (two to five words that name the plan).', 'You may add the reason after a dash. Use 3 to 8 steps. Write nothing after the list.', '', `Request: ${task}`, @@ -131,6 +132,24 @@ export function firstSentence(text, max = 140) { return clip(m ? m[1] : s, max); } +/** + * The short summary of a finished step: what it changed (from the tool cards: "Wrote pagoda.html, Changed style.css"), else the first + * sentence of its closing words when that reads as a result. A sentence about what is NOT done, or about later steps, is never a summary. + */ +export function stepSummary(cards, closing) { + const done = []; + for (const c of cards ?? []) { + const verb = /^(Wrote|Changed|Created|Edited|Deleted|Removed|Moved|Renamed)\b/.exec(String(c?.verb ?? ''))?.[1]; + const target = String(c?.target ?? '').split(/[\\/]/).filter(Boolean).at(-1); + if (!verb || !target) continue; + const line = verb + ' ' + clip(target, 40); + if (!done.includes(line)) done.push(line); + } + if (done.length) return clip(done.slice(0, 3).join(', ') + (done.length > 3 ? ' and more' : ''), 140); + const s = firstSentence(closing); + return s && !/not done|not yet|remaining|handled separately|next steps?|later steps?|still (?:need|to)|todo/i.test(s) ? s : null; +} + /** The words a person sees for the plan, as one message the model can carry out (the plain Approve path). */ export function planAsPrompt(plan) { return ['Carry out this plan, step by step, and tell me briefly when each step is done.', '', plan.title ? `Plan: ${plan.title}` : '', ...plan.steps.map((s, i) => `${i + 1}. ${s.text}${s.detail ? ` (${s.detail})` : ''}`)].filter((l, i) => l !== '' || i === 1).join('\n'); diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index b7772224..4afda2c5 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -20,6 +20,7 @@ import { createHash } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { standardPreset } from './preset.mjs'; +import { BUDGETS, isPrivateHost } from './llm-shape.mjs'; import { DDG_PROVIDER_ID } from '../web-search-ddg.mjs'; const PROTOCOL = { 'openai-chat': 'openai-completions', 'openai-responses': 'openai-responses', anthropic: 'anthropic-messages' }; @@ -150,7 +151,7 @@ export function outputBudget(context, maxOutput = null) { * @param {Array<{id:string,name:string,baseUrl:string,protocol:string,apiKey?:string,models:Array<{id:string,name?:string,contextMax?:number|null}>}>} input.connections * @returns {{patch:string, env:Record, routes:Array, defaultRoute:object|null, signature:string}} */ -export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null }) { +export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) { const providers = {}; const env = {}; const routes = []; @@ -159,6 +160,20 @@ export function buildProfile({ local = [], connections = [], gate = true, tools let slots = 0; /** Per-model compaction timing (see compactionHeadroom). */ const compaction = []; + /** Routes the person's Response settings can reach: a copy of the provider whose address is this host's forwarding endpoint (see llm-shape.mjs). */ + const shapeTargets = {}; + function addShaped(route, def, realBase) { + if (!proxyBase) return null; + const keys = {}; + for (const budget of [0, ...BUDGETS]) { + const key = `${route}~s${budget}`; + providers[key] = { ...def, displayName: `${def.displayName} (with your response settings)`, baseURL: `${proxyBase}/${key}/v1`, ...(budget ? { headers: { ...(def.headers ?? {}), 'x-strata-budget': String(budget) } } : {}) }; + shapeTargets[key] = realBase; + for (const m of def.models) { const w = m.contextWindow, out = m.maxTokens; compaction.push({ provider: key, model: m.id, headroomTokens: compactionHeadroom(w, out) }); } + keys[budget] = key; + } + return keys; + } local.forEach((inst, index) => { const route = index === 0 ? 'strata-local' : `strata-local-${slug(inst.id)}`; @@ -183,7 +198,8 @@ export function buildProfile({ local = [], connections = [], gate = true, tools }; compaction.push({ provider: route, model: inst.modelId, headroomTokens: compactionHeadroom(context, localOutputBudget(context)) }); slots = Math.max(slots, Number.isFinite(inst.slots) && inst.slots >= 1 ? Math.floor(inst.slots) : 1); - routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', instanceId: inst.id, modelId: inst.modelId, name: inst.label || inst.modelId, contextWindow: context }); + const shaped = addShaped(route, providers[route], inst.baseUrl); + routes.push({ route, fp: fingerprint(providers[route], env[keyEnv]), kind: 'local', instanceId: inst.id, modelId: inst.modelId, name: inst.label || inst.modelId, contextWindow: context, ...(shaped ? { shaped } : {}) }); }); connections.forEach(conn => { @@ -210,8 +226,9 @@ export function buildProfile({ local = [], connections = [], gate = true, tools })), }; const fp = fingerprint(providers[route], conn.apiKey ?? ''); + const shaped = protocol === 'openai-completions' && isPrivateHost(baseURL) ? addShaped(route, providers[route], baseURL) : null; for (const m of conn.models) { const ctx = m.contextMax ?? ASSUMED_API_CONTEXT; compaction.push({ provider: route, model: m.id, headroomTokens: compactionHeadroom(ctx, outputBudget(ctx, m.maxOutput)) }); } - for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT }); + for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, ...(shaped ? { shaped } : {}) }); }); const defaultRoute = routes.find(r => r.kind === 'local') ?? null; @@ -260,7 +277,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools // What the agent is offered (tool groups, web search, tool servers, the person's own tools) decides whether a running agent must be // restarted for the next message; the routes are compared separately (a changed context size alone does not restart it). const toolsSignature = createHash('sha256').update(JSON.stringify([mcp, ownRows, webRows, entries.find(e => e.id === 'preset-standard'), env.STRATA_SEARCH_KEY ?? '', mcpEnv])).digest('hex').slice(0, 16); - return { patch, env, routes, defaultRoute, signature, toolsSignature }; + return { patch, env, routes, defaultRoute, signature, toolsSignature, shapeTargets }; } /** Find the route for a chat's model choice. */ diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 39144594..41280332 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -50,6 +50,7 @@ import { EventHub, error, json, readBody, uid } from './util.mjs'; import { RequestQueue } from './request-queue.mjs'; import { selectSkills, skillInstructions } from './skill-selection.mjs'; import { createModelProviders } from './model-providers.mjs'; +import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs'; import { checkUpdates, checkComponentUpdates } from './updates.mjs'; import { createAppUpdater } from './app-updater.mjs'; import { createImageModels } from './image-models.mjs'; @@ -110,12 +111,16 @@ const native=createNativeControl({control,appUpdater,hardwareProbe:()=>(hardware pinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capability state and the chat falls back to the direct path with a notice, never silently to another model. */ // What the person chose in Settings -> Tools (tool groups, web search service and key, the browser, their own tools). +const llmProxy = createLlmProxy({ targetOf: key => agent.llmTarget(key), samplingNow: () => samplingFromExpert(store.get().expert) }); const agentTools = createAgentTools({ read: () => store.get().agentTools, write: value => store.update({ agentTools: value }), dataDir: store.DATA_DIR, browser: () => ({ ...findBrowser(), cli: findPlaywrightMcp(agent.harnessDir()) }) }); agentTools.ensureFile(); const agent = createAgentBridge({ tools: () => agentTools.profileView(), skillsDir: () => AGENT_SKILLS, onGoal: (chatId, goal) => hub.send('goal', { chatId, goal }), + // The person's Response settings (thinking budget, Expert sampling) reach the agent's model through this host's own forwarding endpoint. + proxyBase: `http://127.0.0.1:${PORT}/api/internal/agent-llm`, + expertSampling: () => samplingFromExpert(store.get().expert), onPlan: (chatId, event, plan) => hub.send('plan', { chatId, event, plan }), onQueue: (chatId, queue) => hub.send('queue', { chatId, queue }), dataDir: store.DATA_DIR, @@ -525,7 +530,7 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI const goalLine = /^\/goal(?:\s+([\s\S]*))?$/i.exec(message.trim()); const planLine = /^\/plan(?:\s+([\s\S]*))?$/i.exec(message.trim()); const researchLine = /^\/research(?:\s+([\s\S]*))?$/i.exec(message.trim()); - const turnOptions = { chatId, message, workspacePath: cwd, choice, mode: typeof body.mode === 'string' ? body.mode : null, thinking: typeof body.thinking === 'string' ? body.thinking : null, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal }; + const turnOptions = { chatId, message, workspacePath: cwd, choice, mode: typeof body.mode === 'string' ? body.mode : null, thinking: typeof body.thinking === 'string' ? body.thinking : null, thinkingBudget: Number.isFinite(body.thinkingBudget) ? body.thinkingBudget : 0, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal }; const result = typeof body.planId === 'string' && body.message === '/plan start' ? await agent.planGoal({ ...turnOptions, planId: body.planId }) : researchLine ? await agent.researchCommand({ ...turnOptions, line: researchLine[1] ?? '' }) : planLine ? await agent.planCommand({ ...turnOptions, line: planLine[1] ?? '' }) @@ -1605,6 +1610,9 @@ async function api(req, res, path, method, url) { // --- agent -------------------------------------------------------------- if (path === '/api/agent/status' && method === 'GET') return json(res, 200, agent.status()); + // The assistant's model requests, with the person's Response settings added (llm-shape.mjs). This computer only. + const llmRoute = /^\/api\/internal\/agent-llm\/([A-Za-z0-9_.~-]+)(\/.*)$/.exec(path); + if (llmRoute) { llmProxy(req, res, llmRoute[1], llmRoute[2] + (url.search ?? '')); return undefined; } // The goal bar (notes-split-agent3.md): the state, and the instant actions. Resume runs rounds, so it is a chat stream with {goalAction:'resume'}. if (path === '/api/goal' && method === 'GET') { try { return json(res, 200, { goal: await agent.goalState(url.searchParams.get('chatId') ?? '') }); } catch (e) { return error(res, 400, e.message); } diff --git a/apps/host/tests/agent-plan.test.mjs b/apps/host/tests/agent-plan.test.mjs index 85b76f9a..2ce90ab3 100644 --- a/apps/host/tests/agent-plan.test.mjs +++ b/apps/host/tests/agent-plan.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parsePlan, parsePoints, stepObjective, stepLine, firstSentence, editedSteps, planAsPrompt, PlanStore, planPrompt } from '../server/agent/plan.mjs'; +import { stepSummary, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, editedSteps, planAsPrompt, PlanStore, planPrompt } from '../server/agent/plan.mjs'; test('a plan is the last numbered list of the reply, with reasons after a dash and indented detail kept', () => { const p = parsePlan([ @@ -58,6 +58,13 @@ test('a step goal names its step, what is done and what is not its job', () => { assert.equal(firstSentence(' '), null); }); +test('a step summary says what it changed, and is empty rather than wrong', () => { + assert.equal(stepSummary([{ verb: 'Wrote a file', target: 'C:\\work\\pagoda.html' }, { verb: 'Changed a file', target: 'style.css' }, { verb: 'Read a file', target: 'a.txt' }, { verb: 'Wrote a file', target: 'pagoda.html' }], 'Done.'), 'Wrote pagoda.html, Changed style.css'); + assert.equal(stepSummary([], 'The roof is tiled and checked. Next I will glow.'), 'The roof is tiled and checked.'); + assert.equal(stepSummary([], 'Not done yet (these are the remaining steps, which will be handled separately): the CSS.'), null); + assert.equal(stepSummary([], ''), null); +}); + test('an edit keeps order, drops empty lines and refuses an empty plan', () => { const steps = editedSteps([' one ', '', { text: 'two', detail: 'why' }, { text: ' ' }]); assert.deepEqual(steps.map(s => [s.id, s.text, s.detail]), [['s1', 'one', ''], ['s2', 'two', 'why']]); @@ -79,10 +86,11 @@ test('plans survive a restart', () => { } finally { rmSync(dir, { recursive: true, force: true }); } }); -import { parseSources, researchPrompt } from '../server/agent/plan.mjs'; +import { parseSources, researchPrompt, researchWritePrompt } from '../server/agent/plan.mjs'; test('research: the answer shape is asked for, and the sources are read back as [{n, title, url}]', () => { - assert.ok(researchPrompt('heat pumps').includes('web_search') && researchPrompt('heat pumps').includes('## Sources')); + assert.ok(researchPrompt('heat pumps').includes('web_search') && researchPrompt('heat pumps').includes('web_fetch')); + assert.ok(researchWritePrompt('heat pumps').includes('## Sources') && researchWritePrompt('heat pumps').includes('## Summary')); const answer = [ '## Summary', 'Heat pumps move heat.', '## Key findings', '- They are efficient [1].', '- They cost more up front [2].', '## Sources', diff --git a/apps/host/tests/agent-shape.test.mjs b/apps/host/tests/agent-shape.test.mjs new file mode 100644 index 00000000..b97e6826 --- /dev/null +++ b/apps/host/tests/agent-shape.test.mjs @@ -0,0 +1,120 @@ +// Response settings (thinking effort, thinking budget, Expert sampling) reach the agent's model request, and nothing changes while they are at their defaults. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { BUDGETS, createLlmProxy, isPrivateHost, nearestBudget, samplingFromExpert, shapeBody } from '../server/agent/llm-shape.mjs'; +import { buildProfile } from '../server/agent/profile.mjs'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; + +test('only the Expert settings that differ from their defaults are sent; the thinking budget only while thinking is on', () => { + assert.equal(samplingFromExpert({}), null); + assert.equal(samplingFromExpert({ 'sample.temp': 0.6, 'sample.topP': 0.95, 'sample.topK': 40, 'sample.repeat': 1.05, 'sample.seed': -1, 'sample.speedProjection': true, 'sample.maxTokens': 0 }), null, 'all defaults: nothing'); + assert.deepEqual(samplingFromExpert({ 'sample.temp': 0.2, 'sample.topK': 10, 'sample.seed': 7, 'sample.maxTokens': 500, 'sample.speedProjection': false }), + { temperature: 0.2, top_k: 10, seed: 7, max_tokens: 500, experimental_speed_projection: false }); + const body = { model: 'm', messages: [], max_tokens: 4096, chat_template_kwargs: { enable_thinking: true, reasoning_effort: 'high' } }; + assert.deepEqual(shapeBody(body, {}), body, 'no settings: the request is the same'); + const shaped = shapeBody(body, { sampling: { temperature: 0.2, max_tokens: 500 }, budget: 8192 }); + assert.equal(shaped.temperature, 0.2); assert.equal(shaped.max_tokens, 500, 'an output cap only lowers the request'); assert.equal(shaped.reasoning_budget_tokens, 8192); + assert.equal(shapeBody({ ...body, max_tokens: 100 }, { sampling: { max_tokens: 500 } }).max_tokens, 100); + assert.equal(shapeBody({ ...body, temperature: 1 }, { sampling: { temperature: 0.2 } }).temperature, 1, 'a field the request already has wins'); + assert.equal(shapeBody({ ...body, chat_template_kwargs: { enable_thinking: false } }, { budget: 8192 }).reasoning_budget_tokens, undefined, 'thinking off: no budget'); + assert.deepEqual(BUDGETS, [2048, 8192, 32768]); assert.equal(nearestBudget(0), 0); assert.equal(nearestBudget(5000), 2048); assert.equal(nearestBudget(7000), 8192); assert.equal(nearestBudget('32768'), 32768); +}); + +test('only this computer and private networks are shaped, never a cloud address', () => { + for (const ok of ['http://127.0.0.1:8080/v1', 'http://localhost:11434/v1', 'http://192.168.1.20:8080', 'http://10.0.0.5/v1', 'http://172.20.1.1/v1', 'http://z440.local:8080', 'http://[::1]:9/v1']) assert.equal(isPrivateHost(ok), true, ok); + for (const no of ['https://api.openai.com/v1', 'http://8.8.8.8/v1', 'http://172.32.0.1/v1', 'http://example.com', 'nonsense']) assert.equal(isPrivateHost(no), false, no); +}); + +test('the profile adds a response-settings copy of each shapeable route (local, or an OpenAI-style server on this network) and never of a cloud route', () => { + const profile = buildProfile({ + local: [{ id: 'a', modelId: 'm', baseUrl: 'http://127.0.0.1:9001', context: 65536 }], + connections: [ + { id: 'lan', name: 'LAN', baseUrl: 'http://192.168.1.9:8080/v1', protocol: 'openai-chat', apiKey: '', models: [{ id: 'x' }] }, + { id: 'cloud', name: 'Cloud', baseUrl: 'https://api.deepseek.com', protocol: 'openai-chat', apiKey: 'k', models: [{ id: 'y' }] }, + ], + proxyBase: 'http://127.0.0.1:8791/api/internal/agent-llm', + }); + const local = profile.routes.find(r => r.kind === 'local'); + assert.deepEqual(Object.keys(local.shaped), ['0', '2048', '8192', '32768']); + assert.equal(local.shaped[8192], 'strata-local~s8192'); + assert.deepEqual(Object.keys(profile.shapeTargets).sort(), [...Object.values(local.shaped), ...Object.values(profile.routes.find(r => r.connectionId === 'lan').shaped)].sort()); + assert.equal(profile.shapeTargets['strata-local~s0'], 'http://127.0.0.1:9001'); + assert.equal(profile.routes.find(r => r.connectionId === 'cloud').shaped, undefined); + assert.match(profile.patch, /"baseURL": "http:\/\/127\.0\.0\.1:8791\/api\/internal\/agent-llm\/strata-local~s8192\/v1"/); + assert.match(profile.patch, /"x-strata-budget": "8192"/); + assert.match(profile.patch, /"provider": "strata-local~s8192"/, 'compaction keeps its timing on the copy too'); + const plain = buildProfile({ local: [{ id: 'a', modelId: 'm', baseUrl: 'http://127.0.0.1:9001', context: 65536 }], connections: [] }); + assert.equal(plain.routes[0].shaped, undefined); assert.ok(!/~s/.test(plain.patch), 'without a forwarding address nothing changes'); +}); + +test('the forwarding endpoint adds the settings, streams the reply back and passes the key through', async (t) => { + const seen = []; + const upstream = http.createServer((req, res) => { + let raw = ''; req.on('data', c => { raw += c; }); req.on('end', () => { + seen.push({ url: req.url, auth: req.headers.authorization, internal: req.headers['x-strata-budget'], body: raw ? JSON.parse(raw) : null }); + res.writeHead(200, { 'content-type': 'text/event-stream' }); res.write('data: one\n\n'); setTimeout(() => { res.write('data: two\n\n'); res.end(); }, 30); + }); + }); + await new Promise(r => upstream.listen(0, '127.0.0.1', r)); + let expert = null; + const proxy = createLlmProxy({ targetOf: key => (key === 'k1' ? `http://127.0.0.1:${upstream.address().port}/v1` : null), samplingNow: () => expert }); + const front = http.createServer((req, res) => { const m = /^\/api\/internal\/agent-llm\/([^/]+)(\/.*)$/.exec(req.url); proxy(req, res, m[1], m[2]); }); + await new Promise(r => front.listen(0, '127.0.0.1', r)); + t.after(() => { front.close(); upstream.close(); }); + const call = (key, headers = {}) => new Promise((resolve, reject) => { + const r = http.request({ host: '127.0.0.1', port: front.address().port, path: `/api/internal/agent-llm/${key}/v1/chat/completions`, method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer abc', ...headers } }, res => { let t2 = ''; res.on('data', c => { t2 += c; }); res.on('end', () => resolve({ status: res.statusCode, text: t2 })); }); + r.on('error', reject); r.end(JSON.stringify({ model: 'm', stream: true, messages: [], max_tokens: 100 })); + }); + const a = await call('k1'); + assert.equal(a.status, 200); assert.match(a.text, /one[\s\S]*two/); + assert.deepEqual(seen[0].body, { model: 'm', stream: true, messages: [], max_tokens: 100 }, 'defaults: the body is untouched'); assert.equal(seen[0].auth, 'Bearer abc'); assert.equal(seen[0].url, '/v1/chat/completions'); assert.equal(seen[0].internal, undefined, 'our own header is not forwarded'); + expert = { temperature: 0.1 }; + await call('k1', { 'x-strata-budget': '8192' }); + assert.equal(seen[1].body.temperature, 0.1); assert.equal(seen[1].body.reasoning_budget_tokens, 8192); + assert.equal((await call('nope')).status, 404); +}); + +test('a turn uses the response-settings route only when a setting is changed: the model receives the sampling and the budget; defaults go straight to the model', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-shape-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + let expert = null; let front; let bridge; + const proxy = createLlmProxy({ targetOf: key => bridge.llmTarget(key), samplingNow: () => expert }); + front = http.createServer((req, res) => { const m = /^\/api\/internal\/agent-llm\/([^/]+)(\/.*)$/.exec(req.url); proxy(req, res, m[1], m[2]); }); + await new Promise(r => front.listen(0, '127.0.0.1', r)); + bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }], connections: () => [], env: process.env, startTimeoutMs: 90_000, + proxyBase: `http://127.0.0.1:${front.address().port}/api/internal/agent-llm`, expertSampling: () => expert }); + t.after(async () => { await bridge.close(); await worker.close(); front.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); + const run = (chatId, extra = {}) => bridge.runTurn({ chatId, message: 'SCRIPT:echo hello', workspacePath: ws, mode: 'bypass', onFrame: () => {}, ...extra }); + const last = () => worker.requests.filter(r => r.directive === 'echo').at(-1).params; + + await run('s1', { thinking: 'High' }); + assert.equal(last().temperature, undefined, 'defaults: no sampling sent'); assert.equal(last().reasoning_budget_tokens, undefined); + assert.equal(last().chat_template_kwargs.reasoning_effort, 'high', 'the reasoning level reaches the request'); + await run('s2', { thinking: 'Low' }); + assert.equal(last().chat_template_kwargs.reasoning_effort, 'low'); + await run('s3', { thinking: 'Off' }); + assert.equal(last().chat_template_kwargs.enable_thinking, false, 'Off turns thinking off'); + await run('s4', { thinking: 'High', thinkingBudget: 8192 }); + assert.equal(last().reasoning_budget_tokens, 8192, 'the composer budget reaches the request'); + assert.equal(last().chat_template_kwargs.reasoning_effort, 'high'); + await run('s5', { thinking: 'Off', thinkingBudget: 8192 }); + assert.equal(last().reasoning_budget_tokens, undefined, 'a budget is not sent while thinking is off'); + expert = { temperature: 0.2, top_k: 12, seed: 5 }; + await run('s6', { thinking: 'Medium' }); + assert.equal(last().temperature, 0.2); assert.equal(last().top_k, 12); assert.equal(last().seed, 5); assert.equal(last().reasoning_budget_tokens, undefined); + await run('s7', { thinking: 'Medium', thinkingBudget: 2048 }); + assert.equal(last().temperature, 0.2); assert.equal(last().reasoning_budget_tokens, 2048); + expert = null; + await run('s8', { thinking: 'Medium' }); + assert.equal(last().temperature, undefined, 'back to defaults: straight to the model again'); +}); From 2b54cf4fbdb2b8384521689c5790760e84ebb9f8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:23:03 +0200 Subject: [PATCH 5/8] Model servers on this network get the thinking vocabulary of a local model (the Reasoning menu did nothing for them); effort and sampling drivers --- apps/host/scripts/agent-http.mjs | 2 +- apps/host/server/agent/profile.mjs | 12 ++++++++++-- apps/host/tests/agent-shape.test.mjs | 5 +++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjs index 6e75e2a7..cdafa03e 100644 --- a/apps/host/scripts/agent-http.mjs +++ b/apps/host/scripts/agent-http.mjs @@ -196,7 +196,7 @@ ${filler(n)}`}, { quiet: true }); // The same question at each reasoning level (and optional thinking budget): what really changes is the thinking the model did. const [question = 'What is 17 times 23, and is the result divisible by 3? Explain briefly.', budget = '0'] = rest; const rows = []; - for (const level of ['Off', 'Low', 'Medium', 'High', 'Max']) { + for (const level of (process.env.LEVELS ? process.env.LEVELS.split(',') : ['Off', 'Low', 'Medium', 'High', 'Max'])) { const t = Date.now(); const frames = await stream({ sessionId: `ef-${level}-${Date.now()}`, message: question, mode: 'bypass', remoteModel: await model(), thinking: level, thinkingBudget: Number(budget), agent: process.env.PLAIN ? false : undefined }, { quiet: true }); const reasoning = frames.filter(x => x.type === 'reasoning').map(x => x.text ?? '').join('').length; diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index 4afda2c5..c6b2d0b0 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -151,6 +151,9 @@ export function outputBudget(context, maxOutput = null) { * @param {Array<{id:string,name:string,baseUrl:string,protocol:string,apiKey?:string,models:Array<{id:string,name?:string,contextMax?:number|null}>}>} input.connections * @returns {{patch:string, env:Record, routes:Array, defaultRoute:object|null, signature:string}} */ +/** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */ +const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } }; + export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) { const providers = {}; const env = {}; @@ -189,7 +192,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools apiKeyEnv: keyEnv, // The Strata server reads the thinking level from `chat_template_kwargs` (enable_thinking, reasoning_effort) or from a top-level // reasoning_effort; a top-level `enable_thinking` (pi-ai's `qwen` format) is ignored, so the model went on thinking with the menu on Off. - compat: { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } }, + compat: THINKING_COMPAT, models: [{ id: inst.modelId, name: inst.label || inst.modelId, contextWindow: context, maxTokens: localOutputBudget(context), input: inst.vision ? ['text', 'image'] : ['text'], @@ -214,19 +217,24 @@ export function buildProfile({ local = [], connections = [], gate = true, tools else if (keyless) env[keyEnv] = 'not-needed'; let baseURL = conn.baseUrl; if (protocol === 'anthropic-messages') baseURL = baseURL.replace(/\/v1\/?$/, ''); + // A model server on this computer or network (another Strata PC, llama.cpp, LM Studio) takes the same thinking vocabulary as a local model: + // without it the Reasoning menu did nothing for a connection to another Strata machine. + const ownServer = protocol === 'openai-completions' && isPrivateHost(baseURL); providers[route] = { displayName: conn.name, api: protocol, baseURL, ...(conn.apiKey || keyless ? { apiKeyEnv: keyEnv } : {}), + ...(ownServer ? { compat: THINKING_COMPAT } : {}), models: conn.models.map(m => ({ id: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, maxTokens: outputBudget(m.contextMax ?? ASSUMED_API_CONTEXT, m.maxOutput), input: ['text'], + ...(ownServer ? { reasoning: true, reasoningEfforts: LOCAL_EFFORTS } : {}), })), }; const fp = fingerprint(providers[route], conn.apiKey ?? ''); - const shaped = protocol === 'openai-completions' && isPrivateHost(baseURL) ? addShaped(route, providers[route], baseURL) : null; + const shaped = ownServer ? addShaped(route, providers[route], baseURL) : null; for (const m of conn.models) { const ctx = m.contextMax ?? ASSUMED_API_CONTEXT; compaction.push({ provider: route, model: m.id, headroomTokens: compactionHeadroom(ctx, outputBudget(ctx, m.maxOutput)) }); } for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, ...(shaped ? { shaped } : {}) }); }); diff --git a/apps/host/tests/agent-shape.test.mjs b/apps/host/tests/agent-shape.test.mjs index b97e6826..cc2e70af 100644 --- a/apps/host/tests/agent-shape.test.mjs +++ b/apps/host/tests/agent-shape.test.mjs @@ -49,6 +49,11 @@ test('the profile adds a response-settings copy of each shapeable route (local, assert.deepEqual(Object.keys(profile.shapeTargets).sort(), [...Object.values(local.shaped), ...Object.values(profile.routes.find(r => r.connectionId === 'lan').shaped)].sort()); assert.equal(profile.shapeTargets['strata-local~s0'], 'http://127.0.0.1:9001'); assert.equal(profile.routes.find(r => r.connectionId === 'cloud').shaped, undefined); + const doc = JSON.parse(profile.patch.slice(profile.patch.indexOf('['))); + const providers = doc.find(e => e.id === 'llm-pi-ai').config.providers; + assert.equal(providers['api-lan'].compat.thinkingFormat, 'chat-template', 'a model server on this network gets the thinking vocabulary of a local model'); + assert.equal(providers['api-lan'].models[0].reasoning, true); + assert.equal(providers['api-cloud'].compat, undefined, 'a cloud service does not'); assert.match(profile.patch, /"baseURL": "http:\/\/127\.0\.0\.1:8791\/api\/internal\/agent-llm\/strata-local~s8192\/v1"/); assert.match(profile.patch, /"x-strata-budget": "8192"/); assert.match(profile.patch, /"provider": "strata-local~s8192"/, 'compaction keeps its timing on the copy too'); From f37abb13654a077ae9dedd6eea077605ab45f9b4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:25:32 +0200 Subject: [PATCH 6/8] Tests follow the new reply room; the queued-message test waits for the goal to be running --- apps/host/tests/agent-plan-run.test.mjs | 7 +++++-- apps/host/tests/agent-tools.test.mjs | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/host/tests/agent-plan-run.test.mjs b/apps/host/tests/agent-plan-run.test.mjs index 147eb117..29f17670 100644 --- a/apps/host/tests/agent-plan-run.test.mjs +++ b/apps/host/tests/agent-plan-run.test.mjs @@ -92,8 +92,11 @@ test('a message typed while a goal without points runs is queued, can be taken b assert.throws(() => r.bridge.queueMessage({ chatId: 'q1', text: 'hello' }), /No goal is running/); const out = []; const run = r.bridge.runTurn({ ...r.base('q1', f => out.push(f)), goal: { action: 'create', objective: 'keep going', maxRounds: 50 } }); - await wait(3000); - const a = r.bridge.queueMessage({ chatId: 'q1', text: 'first thing' }); + // the goal turn may take a while to start on a busy machine: queue as soon as it runs + let a = null; + for (let i = 0; i < 150 && !a; i++) { try { a = r.bridge.queueMessage({ chatId: 'q1', text: 'first thing' }); } catch { await wait(100); } } + assert.ok(a, 'the goal was running'); + await wait(500); const b = r.bridge.queueMessage({ chatId: 'q1', text: 'second thing' }); assert.equal(a.message.deliverAt, 'end'); assert.deepEqual(b.queue.map(m => m.text), ['first thing', 'second thing']); const back = r.bridge.cancelQueued({ chatId: 'q1', id: b.message.id }); diff --git a/apps/host/tests/agent-tools.test.mjs b/apps/host/tests/agent-tools.test.mjs index a35986fb..baffeb31 100644 --- a/apps/host/tests/agent-tools.test.mjs +++ b/apps/host/tests/agent-tools.test.mjs @@ -237,7 +237,7 @@ test('the output budget is not the old 8192, and the Reasoning menu reaches the const off = await ask('think-off', 'Off'); assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); - assert.ok(off.max_completion_tokens > 40000, `budget ${off.max_completion_tokens} (the window minus the prompt, never the old 8192)`); + assert.ok(off.max_completion_tokens >= 32000 && off.max_completion_tokens <= 32768, `budget ${off.max_completion_tokens} (half the window, at most 32K: never the old 8192, and room is left for the conversation to be compacted)`); const high = await ask('think-high', 'High'); assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); const low = await ask('think-low', 'Low'); From 87d70909a855e8f0bd6ecde2696e347510b741af Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:29:57 +0200 Subject: [PATCH 7/8] Time-skip: the made page first in the compare list, housekeeping files (browser profile, caches) last and unread, never the whole result --- apps/host/server/timeskip.mjs | 53 ++++++++++++++++--- .../tests/timeskip-compare-server.test.mjs | 21 ++++++++ 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index de6cf5db..f21dc82c 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -195,14 +195,42 @@ export function runImagePath(record, relPath, version) { try { const st = statSync(full); return st.isFile() && st.size <= MAX_IMAGE_BYTES ? full : null; } catch { return null; } } +/** + * Files that are the program's own housekeeping, not the person's work: a browser profile, a cache folder, a tool's hidden folder. They are + * still listed when they changed (never hidden from the person), but last, and without their contents, so the comparison opens on the work + * that was asked for and not on a cache file. + */ +const NOISE_DIR = /^(?:\.[^.]|__pycache__$|node_modules$|cache$|gpucache$|code cache$|crashpad$|shadercache$)/i; +export const isNoisePath = path => String(path).split('/').slice(0, -1).some(seg => NOISE_DIR.test(seg)); +const NOISE_LISTED = 5; + +/** Order in the Compare view: the page or document that was made first, other readable work next, pictures, then everything else, then housekeeping. */ +function rankOf(entry) { + if (entry.noise) return 4; + const ext = String(entry.path).split('.').pop().toLowerCase(); + if (entry.unreadable) return 3; + if (ext === 'html' || ext === 'htm') return 0; + if (entry.image) return 2; + return 1; +} + export function diffRun(record) { // A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt. const { baseRoot, updatedRoot, useAttempt, last } = runRoots(record); if (!baseRoot || !updatedRoot) return { files: [], applyAttempt: null, more: 0 }; const paths = [...new Set([...walkFiles(baseRoot), ...walkFiles(updatedRoot)])].sort(); - const files = []; - let withText = 0, more = 0; + const found = []; for (const path of paths) { + const noise = isNoisePath(path); + // Housekeeping is compared as bytes only (never read as text): a browser profile can hold thousands of files. + if (noise) { + const A = join(baseRoot, path), B = join(updatedRoot, path); + const inA = existsSync(A), inB = existsSync(B); + let differs = !inA || !inB; + if (!differs) { try { differs = statSync(A).size !== statSync(B).size || !readFileSync(A).equals(readFileSync(B)); } catch { differs = true; } } + if (differs) found.push({ path, status: !inA ? 'added' : !inB ? 'removed' : 'changed', unreadable: true, noise: true }); + continue; + } const a = readText(join(baseRoot, path)), b = readText(join(updatedRoot, path)); const status = a.missing ? 'added' : b.missing ? 'removed' : null; const same = !status && a.text !== undefined && a.text === b.text; @@ -212,20 +240,31 @@ export function diffRun(record) { let differs = true; try { differs = a.missing || b.missing || !readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path))); } catch { /* treat as changed */ } if (!differs) continue; - if (files.length >= MAX_LISTED) { more += 1; continue; } - files.push({ path, status: status ?? 'changed', image: true }); + found.push({ path, status: status ?? 'changed', image: true }); continue; } if (!status && !a.text && !b.text && !a.big && !b.big) { // Both binary: compare sizes only. try { if (statSync(join(baseRoot, path)).size === statSync(join(updatedRoot, path)).size && readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path)))) continue; } catch { /* treat as changed */ } } - if (files.length >= MAX_LISTED) { more += 1; continue; } const entry = { path, status: status ?? 'changed' }; const textual = (a.text !== undefined || a.missing) && (b.text !== undefined || b.missing); - if (textual && withText < MAX_WITH_TEXT) { entry.original = a.text ?? ''; entry.updated = b.text ?? ''; withText += 1; } + if (textual) entry._text = { original: a.text ?? '', updated: b.text ?? '' }; else entry.unreadable = true; - files.push(entry); + found.push(entry); + } + // Only housekeeping changed (a cache, a browser profile): the assistant changed nothing the person asked about. + if (found.length && found.every(e => e.noise)) return { files: [], applyAttempt: useAttempt ? (last?.index ?? null) : null, more: 0, housekeeping: found.length }; + found.sort((x, y) => rankOf(x) - rankOf(y) || (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)); + const files = []; + let withText = 0, more = 0, noiseListed = 0; + for (const entry of found) { + if (entry.noise && noiseListed >= NOISE_LISTED) { more += 1; continue; } + if (files.length >= MAX_LISTED) { more += 1; continue; } + if (entry.noise) noiseListed += 1; + const { _text, ...rest } = entry; + if (_text) { if (withText < MAX_WITH_TEXT) { rest.original = _text.original; rest.updated = _text.updated; withText += 1; } else rest.unreadable = true; } + files.push(rest); } return { files, applyAttempt: useAttempt ? (last?.index ?? null) : null, more }; } diff --git a/apps/host/tests/timeskip-compare-server.test.mjs b/apps/host/tests/timeskip-compare-server.test.mjs index dc3a0e98..17afecd8 100644 --- a/apps/host/tests/timeskip-compare-server.test.mjs +++ b/apps/host/tests/timeskip-compare-server.test.mjs @@ -44,3 +44,24 @@ test('a picture is served only from inside the run, only as a picture', () => { assert.equal(imageTypeOf('a/b/C.JPG'), 'image/jpeg'); assert.equal(imageTypeOf('a.txt'), null); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test('the page that was made comes first; a browser profile and other housekeeping come last, without their contents', () => { + const dir = mkdtempSync(join(tmpdir(), 'strata-ts-rank-')); + try { + const base = join(dir, 'base'), cand = join(dir, 'cand'); + for (const root of [base, cand]) { mkdirSync(join(root, '.chrome-profile', 'Default', 'Cache'), { recursive: true }); mkdirSync(join(root, 'notes'), { recursive: true }); } + for (let i = 0; i < 12; i++) { writeFileSync(join(base, '.chrome-profile', 'Default', 'Cache', 'f' + i), 'a' + i); writeFileSync(join(cand, '.chrome-profile', 'Default', 'Cache', 'f' + i), 'b' + i); } + writeFileSync(join(cand, 'voxel-pagoda.html'), ''); + writeFileSync(join(base, 'notes', 'a.md'), 'old'); writeFileSync(join(cand, 'notes', 'a.md'), 'new'); + const found = diffRun({ checkpoints: [{ id: 'cp1-baseline', label: 'baseline', path: base }], selected_checkpoint: 'cp1-baseline', attempts: [{ index: 1, path: cand }] }); + assert.deepEqual(found.files.slice(0, 2).map(f => f.path), ['voxel-pagoda.html', 'notes/a.md'], 'the page first, then other readable work'); + assert.equal(found.files[0].updated, ''); + const noise = found.files.filter(f => f.noise); + assert.equal(noise.length, 5, 'only a few housekeeping files are listed'); assert.ok(noise.every(f => f.unreadable && f.original === undefined)); + assert.equal(found.more, 7, 'the rest is counted, not listed'); + assert.ok(found.files.findIndex(f => f.noise) > 1, 'housekeeping is last'); + rmSync(join(cand, 'voxel-pagoda.html')); writeFileSync(join(cand, 'notes', 'a.md'), 'old'); + const onlyNoise = diffRun({ checkpoints: [{ id: 'cp1-baseline', label: 'baseline', path: base }], selected_checkpoint: 'cp1-baseline', attempts: [{ index: 1, path: cand }] }); + assert.deepEqual(onlyNoise.files, [], 'when only housekeeping changed nothing is shown as changed'); assert.equal(onlyNoise.housekeeping, 12); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); From 0b871e2d79264d40d6f1999ba51552b496a2ca6f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 19:34:49 +0200 Subject: [PATCH 8/8] Time-skip: a big file that did not change is not listed as changed --- apps/host/server/timeskip.mjs | 12 ++++++++++++ apps/host/tests/timeskip-compare-server.test.mjs | 14 ++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index f21dc82c..959a402b 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -118,6 +118,16 @@ function readText(path) { } catch { return { missing: true }; } } +/** Whether two files hold the same bytes (a big file that did not change must not be listed as changed). Files over 64 MB are treated as changed. */ +function sameBytes(a, b) { + try { + const sa = statSync(a), sb = statSync(b); + if (sa.size !== sb.size) return false; + if (sa.size > 64 * 1024 * 1024) return false; + return readFileSync(a).equals(readFileSync(b)); + } catch { return false; } +} + /** What the assistant is told for one revision attempt. It works on a copy, so it is told to stay in it and to say what it did. */ export function timeskipRevisionMessage(request) { return [ @@ -235,6 +245,8 @@ export function diffRun(record) { const status = a.missing ? 'added' : b.missing ? 'removed' : null; const same = !status && a.text !== undefined && a.text === b.text; if (same) continue; + // A file too big to read as text is the same file when its bytes are the same: it must not show up as a change. + if (!status && (a.big || b.big) && sameBytes(join(baseRoot, path), join(updatedRoot, path))) continue; if (imageTypeOf(path)) { // A picture is compared as bytes and shown from the file itself, never read as text. let differs = true; diff --git a/apps/host/tests/timeskip-compare-server.test.mjs b/apps/host/tests/timeskip-compare-server.test.mjs index 17afecd8..63ef0c11 100644 --- a/apps/host/tests/timeskip-compare-server.test.mjs +++ b/apps/host/tests/timeskip-compare-server.test.mjs @@ -65,3 +65,17 @@ test('the page that was made comes first; a browser profile and other housekeepi assert.deepEqual(onlyNoise.files, [], 'when only housekeeping changed nothing is shown as changed'); assert.equal(onlyNoise.housekeeping, 12); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test('a big file that did not change is not listed as changed; one that did is', () => { + const dir = mkdtempSync(join(tmpdir(), 'strata-ts-big-')); + try { + const base = join(dir, 'base'), cand = join(dir, 'cand'); mkdirSync(base); mkdirSync(cand); + const big = Buffer.alloc(400 * 1024, 7); + writeFileSync(join(base, 'archive.bin'), big); writeFileSync(join(cand, 'archive.bin'), big); + writeFileSync(join(base, 'data.json'), Buffer.alloc(300 * 1024, 65)); writeFileSync(join(cand, 'data.json'), Buffer.alloc(300 * 1024, 66)); + writeFileSync(join(cand, 'page.html'), '

x

'); + const found = diffRun({ checkpoints: [{ id: 'cp1-baseline', label: 'baseline', path: base }], selected_checkpoint: 'cp1-baseline', attempts: [{ index: 1, path: cand }] }); + assert.deepEqual(found.files.map(f => f.path), ['page.html', 'data.json'], 'the untouched big file is gone from the list; the changed one is last (too big to show)'); + assert.equal(found.files[1].unreadable, true); + } finally { rmSync(dir, { recursive: true, force: true }); } +});