Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

host: route agent chats through the Harness (stream, approval, stop, status) with a visible fallback

Niko1221fad1ce55682b
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs
index 0e76d0e3e..1a0740755 100644
--- a/apps/host/server/agent/agent-bridge.mjs
+++ b/apps/host/server/agent/agent-bridge.mjs
@@ -262,7 +262,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
// Wait for the turn, or for the client to leave. Leaving does not stop the turn.
const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true }));
const outcome = await Promise.race([turn.ended.promise, gone]);
- if (outcome === 'detached') return { detached: true, sessionId };
+ if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) };
return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut };
}
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index 3b5a46a4d..c75d9a860 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -11,6 +11,7 @@ import { migrateSetup } from './setup.mjs';
import { skillEdit } from './skill-edits.mjs';
import { systemFonts } from './fonts.mjs';
import { tuningDir } from './platform-paths.mjs';
+import { createAgentBridge } from './agent/agent-bridge.mjs';
/**
* Strata engine host.
*
@@ -74,6 +75,19 @@ const hub = new EventHub();
const modelProviders = createModelProviders({ directory: store.DATA_DIR, changed: value => hub.send('providers', value) });
const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) });
const native=createNativeControl({directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});
+/* The agent: chats become DeepSeek Harness sessions when that component is installed. It is a separate
+ 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. */
+const agent = createAgentBridge({
+ dataDir: store.DATA_DIR,
+ componentsDir: process.env.STRATA_COMPONENTS_DIR ?? null,
+ localInstances: () => native.readyInstances().map(i => ({
+ id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId,
+ context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision,
+ })),
+ connections: () => modelProviders.withSecrets(),
+ log: line => console.log(line),
+});
let storageChanging = false;
let modelOperations = 0;
const requestQueue = new RequestQueue(n => monitor.queueWaiting(n));
@@ -433,6 +447,32 @@ async function runRemoteTurn({ selection, message, history, onFrame, signal, wor
}
}
+/** One agent turn for a chat, streamed to the caller as the NDJSON frames the chat already renders. */
+async function runAgentTurn({ res, controller, chatId, body, message, workspaceId }) {
+ const write = frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); };
+ const cwd = (workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE;
+ let choice, instance = null;
+ if (body.remoteModel) choice = { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) };
+ else {
+ try { instance = native.resolveInstance(body.nativeModelId ?? native.state().defaultId); }
+ catch (e) { write({ type: 'error', message: e.message }); return; }
+ choice = { instanceId: instance.id };
+ }
+ const started = Date.now();
+ // A turn the engine is serving must be visible to the rest of the host (Serving, unload guards).
+ const entry = instance ? serving.open({ client: 'Strata chat', endpoint: '/agent', model: instance.apiModelId, instanceId: instance.id, gpuIds: instance.gpus.map(String), cancel: () => { void agent.stop(chatId); } }) : null;
+ if (entry) serving.mark(entry.id, { state: 'generating' });
+ const settle = (tokensOut, error) => { if (entry) serving.finish(entry.id, { tokensOut, durationMs: Date.now() - started, ...(error ? { error } : {}) }); };
+ try {
+ const result = await agent.runTurn({ chatId, message, workspacePath: cwd, choice, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal });
+ if (result?.detached) void result.ended.then(r => settle(r?.tokensOut ?? null), () => settle(null));
+ else settle(result?.tokensOut ?? null, result?.error ? 'The agent turn failed.' : undefined);
+ } catch (err) {
+ write({ type: 'error', message: err.message, code: err.code ?? 'AGENT_ERROR' });
+ settle(null, err.message);
+ }
+}
+
async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='high' }) {
if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, onFrame, signal, workspaceId });
if(native.hasLive()||nativeModelId){
@@ -1280,6 +1320,27 @@ async function api(req, res, path, method, url) {
}
}
+ // --- agent --------------------------------------------------------------
+ if (path === '/api/agent/status' && method === 'GET') return json(res, 200, agent.status());
+ if (path === '/api/agent/pending' && method === 'GET') {
+ const chat = new URL(req.url, 'http://x').searchParams.get('chatId') ?? '';
+ return json(res, 200, { pending: agent.pendingFor(chat) });
+ }
+ /* Approve / Deny a tool the agent asked about. The answer reaches the Harness approval for exactly
+ that chat and call; a stale or foreign id is refused. */
+ if (path === '/api/chat/approval' && method === 'POST') {
+ const b = await readBody(req);
+ if (typeof b.sessionId !== 'string' || typeof b.toolId !== 'string' || !['approve', 'deny'].includes(b.decision)) return error(res, 400, 'sessionId, toolId and decision (approve or deny) are required');
+ try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); }
+ catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); }
+ }
+ /* Stop one chat's turn. Resolves once the turn has really ended, not when the cancel was admitted. */
+ if (path === '/api/chat/stop' && method === 'POST') {
+ const b = await readBody(req);
+ if (typeof b.sessionId !== 'string') return error(res, 400, 'sessionId is required');
+ try { return json(res, 200, await agent.stop(b.sessionId)); } catch (e) { return error(res, 502, e.message); }
+ }
+
// --- chat ---------------------------------------------------------------
if (path === '/api/chat/stream' && method === 'POST') {
const body = await readBody(req,12*1024*1024);
@@ -1299,6 +1360,27 @@ async function api(req, res, path, method, url) {
const controller = new AbortController();
res.on('close', () => { if (!res.writableEnded) controller.abort(); });
+ /* Agent turn, when the component is there and this request can use it. A client that disappears
+ detaches from the turn (it keeps running in the Harness); Stop is its own request. */
+ const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;
+ const agentSkip = process.env.STRATA_AGENT === 'off' ? 'The agent is turned off (STRATA_AGENT=off).'
+ : body.agent === false ? 'This chat runs without the agent.'
+ : !chatId ? 'This request did not name a chat.'
+ : images.length ? 'The agent does not take attached pictures yet; this message was sent directly.'
+ : !(body.remoteModel || native.hasLive()) ? 'The agent needs a loaded Strata model or an API model.'
+ : null;
+ if (chatId && !agentSkip) {
+ const capability = agent.status();
+ if (capability.state !== 'unavailable') {
+ await runAgentTurn({ res, controller, chatId, body, message, workspaceId });
+ res.end();
+ return undefined;
+ }
+ res.write(`${JSON.stringify({ type: 'notice', code: 'agent-unavailable', message: `${capability.reason} Chat is running without tools.` })}\n`);
+ } else if (agentSkip && chatId && body.agent !== false && process.env.STRATA_AGENT !== 'off') {
+ res.write(`${JSON.stringify({ type: 'notice', code: 'agent-skipped', message: agentSkip })}\n`);
+ }
+
await runTurn({
message,
history: Array.isArray(body.history) ? body.history : [],
@@ -1539,7 +1621,7 @@ const shutdown = async () => {
clearInterval(taskTimer);tasks.close();
const timeout=setTimeout(()=>process.exit(0),10000);timeout.unref();
server.close();server.closeAllConnections?.();
- await Promise.allSettled([localShare.stop(),cloudflare.stop(),native.close()]);
+ await Promise.allSettled([localShare.stop(),cloudflare.stop(),native.close(),agent.close()]);
process.exit(0);
};
process.on('SIGINT', shutdown);
diff --git a/apps/host/tests/agent-host.test.mjs b/apps/host/tests/agent-host.test.mjs
new file mode 100644
index 000000000..9761adf0a
--- /dev/null
+++ b/apps/host/tests/agent-host.test.mjs
@@ -0,0 +1,202 @@
+/**
+ * The host's HTTP surface for agent chats, against a real host process, the real Harness and a
+ * scripted worker standing in as an API model.
+ *
+ * Needs STRATA_HARNESS_DIR (a built Harness) for everything except the "component missing" test.
+ * What is exercised: /api/chat/stream (NDJSON), /api/chat/approval, /api/chat/stop, /api/agent/status,
+ * resume across a host restart, two chats at once, and the visible fallback when the component is absent.
+ */
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { createServer } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { startScriptedWorker } from './helpers/scripted-worker.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;
+const HOST = resolve(import.meta.dirname, '..', 'server', 'index.mjs');
+
+const freePort = () => new Promise(r => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); });
+const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } };
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+
+async function startHost(t, { home, ws, harness = HARNESS } = {}) {
+ const port = await freePort();
+ const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0' };
+ if (harness) env.STRATA_HARNESS_DIR = harness; else delete env.STRATA_HARNESS_DIR;
+ const child = spawn(process.execPath, [HOST], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
+ let log = '';
+ child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
+ const stop = async () => {
+ if (child.exitCode !== null) return;
+ if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
+ else child.kill('SIGTERM');
+ await new Promise(r => child.once('exit', r));
+ };
+ t.after(stop);
+ const base = `http://127.0.0.1:${port}`;
+ for (let i = 0; i < 100; i++) {
+ try { if ((await fetch(`${base}/api/agent/status`)).ok) break; } catch { /* not up yet */ }
+ if (child.exitCode !== null) throw new Error(`the host exited: ${log.slice(-500)}`);
+ await sleep(200);
+ }
+ const post = async (path, body) => { const res = await fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); return { status: res.status, body: await res.json().catch(() => null) }; };
+ /** Stream one chat turn; `onFrame` may react while it runs. Resolves with every frame. */
+ const chat = async (body, onFrame = () => {}) => {
+ const res = await fetch(`${base}/api/chat/stream`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ assert.equal(res.status, 200, `chat/stream: ${res.status}`);
+ const frames = []; let buffer = '';
+ const decoder = new TextDecoder();
+ for await (const chunk of res.body) {
+ buffer += decoder.decode(chunk, { stream: true });
+ let i;
+ while ((i = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, i).trim(); buffer = buffer.slice(i + 1);
+ if (line) { const f = JSON.parse(line); frames.push(f); onFrame(f); }
+ }
+ }
+ return frames;
+ };
+ return { base, port, post, chat, stop, log: () => log, status: async () => (await fetch(`${base}/api/agent/status`)).json() };
+}
+
+async function setup(t, { harness = HARNESS, reuse } = {}) {
+ const worker = reuse?.worker ?? await startScriptedWorker({ model: 'cloud-model' });
+ const home = reuse?.home ?? mkdtempSync(join(tmpdir(), 'strata-host-'));
+ const ws = join(home, 'workspace'); mkdirSync(ws, { recursive: true });
+ const host = await startHost(t, { home, ws, harness });
+ let connectionId = reuse?.connectionId;
+ if (!connectionId) {
+ const saved = await host.post('/api/model-providers', { kind: 'custom', name: 'Scripted API', baseUrl: worker.url, protocol: 'openai-chat', apiKey: 'sk-host-test-0123456789', models: [{ id: 'cloud-model', name: 'Cloud model', contextMax: 64000 }] });
+ assert.equal(saved.status, 200, JSON.stringify(saved.body));
+ connectionId = saved.body.connections[0].id;
+ }
+ if (!reuse) t.after(async () => { await worker.close(); cleanup(home); });
+ const remoteModel = { connectionId, modelId: 'cloud-model' };
+ const send = (host, sessionId, message, onFrame) => host.chat({ sessionId, message, remoteModel, workspaceId: null, history: [] }, onFrame);
+ return { worker, home, ws, host, connectionId, remoteModel, send: (sessionId, message, onFrame) => send(host, sessionId, message, onFrame) };
+}
+
+const toolStates = (frames, id) => frames.filter(f => f.type === 'agent-tool' && (!id || f.tool.id === id)).map(f => f.tool.state);
+const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
+const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length;
+
+test('status names the component and the routes, and carries no secret', { skip }, async t => {
+ const s = await setup(t);
+ const status = await s.host.status();
+ assert.equal(status.harness.version, '0.2.1-alpha.3');
+ assert.ok(status.routes.some(r => r.kind === 'api' && r.modelId === 'cloud-model'));
+ assert.ok(!JSON.stringify(status).includes('sk-host-test'));
+});
+
+test('A03 over HTTP: the card waits for Approve, the answer reaches the Harness, the tool runs once', { skip }, async t => {
+ const s = await setup(t);
+ let answered = false;
+ const frames = await s.send('chat-h-a03', 'SCRIPT:tool http.txt hi', async f => {
+ if (f.type === 'agent-tool' && f.tool.state === 'proposed' && !answered) {
+ answered = true;
+ const r = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a03', toolId: f.tool.id, decision: 'approve' });
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ }
+ });
+ assert.ok(answered, 'an approval request must have reached the client');
+ const id = frames.find(f => f.type === 'agent-tool').tool.id;
+ assert.deepEqual([...new Set(toolStates(frames, id))], ['running', 'proposed', 'done']);
+ assert.equal(lines(join(s.ws, 'http.txt')), 1);
+ assert.equal(frames.at(-1).type, 'done');
+ // A second answer to the same approval is refused: it is no longer pending.
+ const again = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a03', toolId: id, decision: 'approve' });
+ assert.equal(again.status, 409);
+});
+
+test('A04 over HTTP: Deny means the tool never runs', { skip }, async t => {
+ const s = await setup(t);
+ const frames = await s.send('chat-h-a04', 'SCRIPT:tool never-http.txt x', async f => {
+ if (f.type === 'agent-tool' && f.tool.state === 'proposed') await s.host.post('/api/chat/approval', { sessionId: 'chat-h-a04', toolId: f.tool.id, decision: 'deny' });
+ });
+ assert.equal(toolStates(frames).at(-1), 'denied');
+ assert.equal(existsSync(join(s.ws, 'never-http.txt')), false);
+ assert.equal(frames.at(-1).type, 'done');
+});
+
+test('A05 over HTTP: /api/chat/stop ends that chat only and answers after the turn ended', { skip }, async t => {
+ const s = await setup(t);
+ let live = 0, stopResult = null;
+ const slow = s.send('chat-h-a05-a', 'SCRIPT:slow 400', async f => {
+ if (f.type === 'delta' && ++live === 3) stopResult = await s.host.post('/api/chat/stop', { sessionId: 'chat-h-a05-a' });
+ });
+ const other = s.send('chat-h-a05-b', 'SCRIPT:slow 50');
+ const [a, b] = await Promise.all([slow, other]);
+ assert.equal(stopResult.status, 200);
+ assert.equal(stopResult.body.stopped, true); assert.equal(stopResult.body.ended, 'aborted');
+ assert.equal(a.at(-1).finishReason, 'aborted');
+ assert.equal(b.at(-1).finishReason, 'stop'); assert.equal(b.filter(f => f.type === 'delta').length, 50);
+ assert.ok(s.worker.aborted >= 1);
+ // Nothing to stop afterwards.
+ const none = await s.host.post('/api/chat/stop', { sessionId: 'chat-h-a05-a' });
+ assert.equal(none.body.stopped, false);
+});
+
+test('a client that disconnects does not stop the turn; the tool still waits for its approval', { skip }, async t => {
+ const s = await setup(t);
+ const controller = new AbortController();
+ const res = await fetch(`${s.host.base}/api/chat/stream`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal: controller.signal, body: JSON.stringify({ sessionId: 'chat-h-detach', message: 'SCRIPT:tool detach.txt d', remoteModel: s.remoteModel, history: [] }) });
+ const reader = res.body.getReader(); let seen = '';
+ while (!seen.includes('"proposed"')) { const { value, done } = await reader.read(); if (done) break; seen += new TextDecoder().decode(value); }
+ assert.match(seen, /"proposed"/);
+ controller.abort(); // the tab closes
+ await sleep(500);
+ assert.equal(existsSync(join(s.ws, 'detach.txt')), false, 'a closed tab is not an approval');
+ const pending = await (await fetch(`${s.host.base}/api/agent/pending?chatId=chat-h-detach`)).json();
+ assert.equal(pending.pending.length, 1, 'the approval is still waiting for someone');
+ // Someone comes back and answers it; the turn finishes in the background.
+ const r = await s.host.post('/api/chat/approval', { sessionId: 'chat-h-detach', toolId: pending.pending[0].callId, decision: 'approve' });
+ assert.equal(r.status, 200);
+ for (let i = 0; i < 100 && !existsSync(join(s.ws, 'detach.txt')); i++) await sleep(100);
+ assert.equal(lines(join(s.ws, 'detach.txt')), 1);
+});
+
+test('A06 over HTTP: after the host restarts, the same chat resumes its session and nothing is replayed', { skip }, async t => {
+ const first = await setup(t);
+ const frames1 = await first.send('chat-h-a06', 'SCRIPT:tool again.txt once', async f => {
+ if (f.type === 'agent-tool' && f.tool.state === 'proposed') await first.host.post('/api/chat/approval', { sessionId: 'chat-h-a06', toolId: f.tool.id, decision: 'approve' });
+ });
+ assert.equal(frames1.at(-1).type, 'done');
+ const sessionBefore = JSON.parse(readFileSync(join(first.home, 'data', 'agent', 'sessions.json'), 'utf8'))['chat-h-a06'].sessionId;
+ await first.host.stop();
+ const second = await setup(t, { reuse: { worker: first.worker, home: first.home, connectionId: first.connectionId } });
+ const frames2 = await second.send('chat-h-a06', 'SCRIPT:echo back again');
+ assert.equal(text(frames2), 'back again');
+ assert.equal(frames2.filter(f => f.type === 'agent-tool').length, 0);
+ assert.equal(lines(join(second.ws, 'again.txt')), 1, 'the first turn\'s tool did not run a second time');
+ const sessionAfter = JSON.parse(readFileSync(join(second.home, 'data', 'agent', 'sessions.json'), 'utf8'))['chat-h-a06'].sessionId;
+ assert.equal(sessionAfter, sessionBefore);
+ t.after(() => { cleanup(first.home); });
+ await first.worker.close().catch(() => {});
+});
+
+test('A08 over HTTP: two chats stream at the same time without mixing', { skip }, async t => {
+ const s = await setup(t);
+ const [a, b] = await Promise.all([s.send('chat-h-a08-a', 'SCRIPT:slow 30'), s.send('chat-h-a08-b', 'SCRIPT:echo only b')]);
+ assert.equal(a.filter(f => f.type === 'delta').length, 30);
+ assert.equal(text(b), 'only b');
+ assert.ok(!text(a).includes('only b') && !text(b).includes('w0'));
+ assert.notEqual(a.find(f => f.type === 'start').sessionId, b.find(f => f.type === 'start').sessionId);
+});
+
+test('without the agent component the chat says so and still uses the model the user chose', async t => {
+ const s = await setup(t, { harness: null });
+ const status = await s.host.status();
+ assert.equal(status.state, 'unavailable'); assert.match(status.reason, /agent component/i);
+ const frames = await s.send('chat-h-fallback', 'SCRIPT:hello');
+ const notice = frames.find(f => f.type === 'notice');
+ assert.equal(notice.code, 'agent-unavailable'); assert.match(notice.message, /without tools/);
+ assert.equal(frames.filter(f => f.type === 'agent-tool').length, 0);
+ assert.match(text(frames), /Hello from the scripted worker/);
+ // The direct path used the API model the chat picked, nothing else.
+ assert.ok(s.worker.requests.length >= 1 && s.worker.requests.every(q => q.model === 'cloud-model'));
+});
diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs
index 57494dc47..cd0c03f55 100644
--- a/apps/host/tests/helpers/scripted-worker.mjs
+++ b/apps/host/tests/helpers/scripted-worker.mjs
@@ -75,7 +75,7 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
}
const [name, args] = [directive?.[1], (directive?.[2] ?? '').trim()];
// The Harness's session-title request carries the same user text but offers no tools.
- if (!(body.tools ?? []).length && last.role !== 'tool') return say(['Scripted title']);
+ if (!(body.tools ?? []).length && messages.some(m => /concise title/i.test(text(m)))) return say(['Scripted title']);
if (name === 'slow') {
const n = Number(args) || 400;
return say(Array.from({ length: n }, (_, i) => `w${i} `));