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: agent bridge (sessions, approvals, Stop, resume) with scripted-worker tests
Niko1221597039b6cb2f
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjsnew file mode 100644index 000000000..0e76d0e3e--- /dev/null+++ b/apps/host/server/agent/agent-bridge.mjs@@ -0,0 +1,325 @@+/**+ * The agent bridge: Strata chats as Harness sessions.+ *+ * What it owns+ * - the pinned Harness process (one, lazily started, restarted only when a route it needs changed);+ * - the stable Strata-chat -> Harness-session map, persisted next to the host's other state;+ * - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders;+ * - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out;+ * - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended.+ *+ * What it deliberately does not do+ * - it never falls back to another model: a chat picks a route (local instance or saved API+ * connection) and a missing route is a typed error;+ * - it never implements Stop by killing the Harness (that would cancel every other chat);+ * - it never holds a secret outside the environment of the agent process it starts.+ */+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { GatewayClient } from './gateway-client.mjs';+import { HarnessProcess, resolveHarness, redact } from './harness-runtime.mjs';+import { buildProfile, routeFor } from './profile.mjs';+import { TurnProjector } from './events.mjs';++export class AgentUnavailable extends Error {+ constructor(message, code = 'agent-unavailable') { super(message); this.name = 'AgentUnavailable'; this.code = code; }+}++/** A timer that never keeps the process alive by itself. */+const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };+const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; };++/**+ * @param {object} options+ * @param {string} options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`)+ * @param {string|null} [options.componentsDir] where installed components live+ * @param {() => Array} options.localInstances ready local instances (see profile.mjs)+ * @param {() => Array} options.connections saved API connections WITH their keys (host-internal)+ * @param {NodeJS.ProcessEnv} [options.env]+ * @param {string} [options.nodePath] the Node runtime that runs the Harness+ * @param {(line:string)=>void} [options.log]+ */+export function createAgentBridge({ dataDir, componentsDir = null, localInstances, connections, 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');+ mkdirSync(root, { recursive: true });++ /** chatId -> { sessionId, cwd, createdAt } */+ let sessionMap = {};+ if (existsSync(sessionsFile)) {+ try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; }+ }+ const persist = () => {+ const temp = `${sessionsFile}.${randomUUID()}.tmp`;+ writeFileSync(temp, JSON.stringify(sessionMap, null, 2));+ renameSync(temp, sessionsFile);+ };++ /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */+ let rt = null;+ let generation = 0;+ let lastError = null;+ let starting = null;+ const chats = new Map(); // chatId -> { turn, route, routeGeneration }+ const pending = new Map(); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at }+ const idleWaiters = new Set();++ const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; };+ const activeTurns = () => [...chats.values()].filter(c => c.turn).length;+ const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } };+ const waitIdle = (signal, ms) => new Promise((resolve, reject) => {+ if (activeTurns() === 0) return resolve();+ const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still running a turn and the model list changed. Try again when it finishes.', 'agent-busy')); }, ms);+ const done = () => { clearTimeout(timer); resolve(); };+ idleWaiters.add(done);+ signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true });+ });++ function harnessInfo() { return resolveHarness({ env, componentsDir }); }++ /** The capability state the app shows. Never carries a token or a key. */+ function status() {+ const h = harnessInfo();+ if (!h.ok) return { state: 'unavailable', reason: h.reason, code: 'component-missing' };+ const profile = buildProfile({ local: localInstances(), connections: connections() });+ return {+ state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle',+ reason: lastError ?? null,+ harness: { version: h.version },+ runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null,+ routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })),+ activeTurns: activeTurns(),+ pendingApprovals: pending.size,+ };+ }++ async function startRuntime(profile) {+ const h = harnessInfo();+ if (!h.ok) throw new AgentUnavailable(h.reason, 'component-missing');+ mkdirSync(home, { recursive: true });+ const patchFile = join(root, `profile-${profile.signature}.patch.yml`);+ writeFileSync(patchFile, profile.patch);+ const workdir = join(root, 'run');+ const hp = new HarnessProcess({+ harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'),+ onExit: exit => {+ log(`agent · the Harness process exited (code ${exit.code})`);+ if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; }+ for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.');+ },+ });+ const info = await hp.start({ timeoutMs: startTimeoutMs });+ const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token });+ await gw.connect();+ const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null };+ next.events = gw.openStream('$events', {}, {+ onItem: value => onHostEvent(next, value),+ onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`),+ });+ rt = next;+ lastError = null;+ log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`);+ return next;+ }++ /** Make sure a runtime exists that knows the route this turn needs. */+ async function ensureRuntime(choice, signal) {+ for (;;) {+ if (starting) { await starting.catch(() => {}); continue; }+ const profile = buildProfile({ local: localInstances(), connections: connections() });+ const route = routeFor(profile, choice);+ if (!route) {+ throw new AgentUnavailable(choice?.connectionId+ ? 'This API model is no longer available. Choose another model in the chat picker.'+ : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable');+ }+ const known = rt?.hp.running && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp);+ if (known) return { rt, route };+ starting = (async () => {+ if (rt?.hp.running) {+ await waitIdle(signal, 120_000);+ const old = rt; rt = null;+ old.events?.close(); old.gw.close(); await old.hp.stop();+ }+ try { return await startRuntime(profile); } catch (e) { lastError = redact(String(e.message ?? e), Object.values(profile.env)); throw e; }+ })();+ try { await starting; } finally { starting = null; }+ }+ }++ function onHostEvent(runtime, value) {+ if (value.type === 'ready') { runtime.clientId = value.clientId; return; }+ if (value.type === 'waterfall' && value.event === 'approval/request') {+ const r = value.request ?? {};+ if (!r.callId) return;+ pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId });+ } else if (value.type === 'cancel') {+ for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k);+ }+ }++ async function sessionFor(c, cwd, runtime) {+ const known = sessionMap[c.id];+ if (known) return { sessionId: known.sessionId, fresh: false };+ const created = await runtime.gw.rpc('session/create', { request: { cwd } });+ sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() };+ persist();+ return { sessionId: created.sessionId, fresh: true };+ }++ /**+ * Run one agent turn for a Strata chat and stream it as frames.+ * `signal` means the client went away: the turn keeps running (that is not Stop).+ */+ async function runTurn({ chatId, message, workspacePath, choice = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal }) {+ const c = chat(chatId);+ if (c.turn) throw new AgentUnavailable('This chat is already running a turn.', 'turn-active');+ let send = onFrame;+ signal?.addEventListener('abort', () => { send = () => {}; }, { once: true });+ const emit = frame => { try { send(frame); } catch { send = () => {}; } };++ emit({ type: 'queued', requestId });+ const { rt: runtime, route } = await ensureRuntime(choice, signal);+ const { sessionId, fresh } = await sessionFor(c, workspacePath, runtime);++ if (c.route !== `${route.route}/${route.modelId}` || c.routeGeneration !== runtime.generation) {+ try {+ await runtime.gw.rpc('session/selectModel', { request: { sessionId, provider: route.route, model: route.modelId } });+ } catch (e) {+ if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); }+ throw new AgentUnavailable(`The agent could not use ${route.name}: ${e.message}`, 'model-unavailable');+ }+ c.route = `${route.route}/${route.modelId}`; c.routeGeneration = runtime.generation;+ }++ const projector = new TurnProjector();+ const turn = {+ sessionId, projector, route, requestId, live: false, lastSeq: -1,+ ended: deferred(), follow: null, snapshot: deferred(), finished: false,+ abortFromRuntime: reason => finishTurn(reason),+ };+ c.turn = turn;+ function finishTurn(failure) {+ if (turn.finished) return;+ turn.finished = true;+ turn.follow?.close();+ const frames = failure ? [{ type: 'error', message: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow });+ for (const f of frames) emit(f);+ c.turn = null;+ turn.ended.resolve({ reason: projector.ended, failure: failure ?? null });+ notifyIdle();+ }++ emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, sessionId, requestId, skills: [] });++ turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, {+ onItem: item => {+ if (item.type === 'snapshot') {+ if (turn.lastSeq < 0) turn.lastSeq = item.cursor;+ else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event });+ turn.snapshot.resolve();+ return;+ }+ handle(item);+ },+ onError: e => finishTurn(`The agent lost the session stream: ${e.message}`),+ });++ function handle(item) {+ if (turn.finished) return;+ if (item.type === 'event') {+ const e = item.event;+ if (e.seq <= turn.lastSeq) return;+ turn.lastSeq = e.seq;+ // The turn is ours from the user message that carries our request id. Until then an older,+ // detached turn on the same session may still be finishing; its events are not ours.+ if (!turn.live) {+ if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true;+ return;+ }+ } else if (!turn.live) return;+ for (const f of projector.consume(item)) emit(f);+ if (item.type === 'event' && item.event.type === 'turn/end') finishTurn(null);+ }++ const snapshotTimer = {};+ await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })])+ .catch(e => { finishTurn(e.message); })+ .finally(() => clearTimeout(snapshotTimer.t));+ if (turn.finished) return { error: true };++ let prompt = message;+ if (fresh && history.length) prompt = withEarlierConversation(history, message);+ try {+ await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } });+ } catch (e) {+ finishTurn(`The agent did not accept the message: ${e.message}`);+ return { error: true };+ }++ // 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 };+ return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut };+ }++ /** Answer one pending approval. `decision` is `approve` or `deny`. */+ async function approve({ chatId, callId, decision }) {+ const sessionId = sessionMap[chatId]?.sessionId;+ // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame+ // (which makes it answerable) travel on different streams; a fast click can beat the second one.+ let entry = sessionId ? pending.get(`${sessionId}:${callId}`) : null;+ for (let i = 0; !entry && sessionId && i < 40; i++) {+ await new Promise(r => setTimeout(r, 50));+ entry = pending.get(`${sessionId}:${callId}`);+ }+ if (!entry) throw new AgentUnavailable('This approval is no longer pending.', 'approval-gone');+ if (!rt?.hp.running) throw new AgentUnavailable('The agent is not running, so this approval has expired.', 'approval-gone');+ pending.delete(`${sessionId}:${callId}`);+ try {+ await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' });+ } catch (e) {+ throw new AgentUnavailable(`The answer was not accepted: ${e.message}`, 'approval-gone');+ }+ return { ok: true };+ }++ /**+ * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the+ * Harness acknowledges a cancel as admitted, not as done.+ */+ async function stop(chatId, { waitMs = 20_000 } = {}) {+ const c = chats.get(chatId);+ const turn = c?.turn;+ if (!turn || !rt) return { stopped: false, reason: 'no active turn' };+ const t0 = Date.now();+ await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } });+ let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]);+ clearTimeout(timer);+ if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' };+ return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 };+ }++ function pendingFor(chatId) {+ const sessionId = sessionMap[chatId]?.sessionId;+ return [...pending.values()].filter(p => p.sessionId === sessionId).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at }));+ }++ async function close() {+ const r = rt; rt = null;+ if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); }+ }++ return { status, runTurn, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };+}++/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */+export function withEarlierConversation(history, message) {+ const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12);+ if (!rows.length) return message;+ const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n');+ return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`;+}diff --git a/apps/host/tests/agent-bridge.test.mjs b/apps/host/tests/agent-bridge.test.mjsnew file mode 100644index 000000000..c9efb866b--- /dev/null+++ b/apps/host/tests/agent-bridge.test.mjs@@ -0,0 +1,241 @@+/**+ * Agent bridge, end to end against the real pinned Harness and a scripted worker.+ *+ * Needs the built Harness: set STRATA_HARNESS_DIR to a checkout built with `pnpm install` and+ * `pnpm run build:artifacts`. Without it these tests skip, loudly, rather than pass.+ *+ * The model is scripted (tests/helpers/scripted-worker.mjs). What is real: the Harness process, its+ * agent loop, its tool executor and approval gate, the gateway, the durable session, and the bridge.+ * A scripted model proves the path; it does not prove a model chooses tools well.+ */+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, mkdirSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createHash } from 'node:crypto';+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;++function cleanup(dir) {+ // The Harness's Windows sandbox adds access entries under the directories it works in, which can make a+ // plain recursive delete fail with EPERM. Cleanup is best effort; a leftover temp dir is not a failure.+ try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ }+}++const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length;++async function rig(t, { connections = [], dataDir } = {}) {+ const worker = await startScriptedWorker({});+ const dir = dataDir ?? mkdtempSync(join(tmpdir(), 'strata-agent-'));+ const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });+ const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }];+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => connections, env: process.env, startTimeoutMs: 90_000 });+ t.after(async () => { await bridge.close(); await worker.close(); if (!dataDir) cleanup(dir); });+ const run = (chatId, message, opts = {}) => {+ const frames = [];+ const answerWith = opts.answer; // 'approve' | 'deny' | undefined+ const promise = bridge.runTurn({+ chatId, message, workspacePath: ws, choice: opts.choice ?? null, history: opts.history ?? [],+ onFrame: f => {+ frames.push(f);+ opts.onFrame?.(f);+ if (answerWith && f.type === 'agent-tool' && f.tool.state === 'proposed') {+ void bridge.approve({ chatId, callId: f.tool.id, decision: answerWith }).catch(e => frames.push({ type: 'test-error', message: e.message }));+ }+ },+ signal: opts.signal,+ });+ return { frames, promise };+ };+ return { worker, bridge, dir, ws, run, local };+}++const states = (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('');++test('A01/A02 a turn streams reasoning and text, then finishes with usage', { skip }, async t => {+ const r = await rig(t);+ const { frames, promise } = r.run('chat-a01', 'SCRIPT:hello');+ await promise;+ assert.equal(frames[0].type, 'queued');+ const start = frames.find(f => f.type === 'start');+ assert.equal(start.agent, true); assert.equal(start.model, 'Scripted'); assert.equal(start.contextMax, 32768);+ assert.match(frames.filter(f => f.type === 'reasoning').map(f => f.text).join(''), /Considering a greeting/);+ assert.equal(text(frames), 'Hello from the scripted worker.');+ const done = frames.at(-1);+ assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'stop'); assert.equal(done.usageSource, 'reported');+ assert.ok(done.tokensIn > 0 && done.tokensOut > 0);+ assert.equal(frames.filter(f => f.type === 'error').length, 0);+ // The route is the declared local one, not a default the catalog would have chosen.+ assert.ok(r.worker.requests.every(q => q.model === 'scripted-model'));+});++test('A03 a tool runs exactly once, in the Harness, after the user approves', { skip }, async t => {+ const r = await rig(t);+ const { frames, promise } = r.run('chat-a03', 'SCRIPT:tool marker.txt hi', { answer: 'approve' });+ await promise;+ const calls = frames.filter(f => f.type === 'agent-tool' && f.tool.state === 'running');+ assert.ok(calls.length >= 1);+ const id = frames.find(f => f.type === 'agent-tool').tool.id;+ assert.deepEqual([...new Set(states(frames, id))], ['running', 'proposed', 'done']);+ assert.equal(frames.filter(f => f.type === 'test-error').length, 0);+ assert.equal(lines(join(r.ws, 'marker.txt')), 1, 'the marker must have exactly one line: the tool ran once');+ const card = frames.filter(f => f.type === 'agent-tool').at(-1).tool;+ assert.equal(card.scope, 'shell'); assert.match(card.preview, /marker\.txt/);+ assert.equal(frames.at(-1).type, 'done');+ // The worker only saw a transcript: it has no execution path, and it was asked twice (call, then result).+ assert.equal(r.worker.requests.filter(q => q.toolNames.length).length, 2);+ assert.match(text(frames), /Tool finished/);+});++test('A04 a denied tool never runs, and the agent is told', { skip }, async t => {+ const r = await rig(t);+ const { frames, promise } = r.run('chat-a04', 'SCRIPT:tool denied.txt nope', { answer: 'deny' });+ await promise;+ const id = frames.find(f => f.type === 'agent-tool').tool.id;+ assert.deepEqual([...new Set(states(frames, id))], ['running', 'proposed', 'denied']);+ assert.equal(existsSync(join(r.ws, 'denied.txt')), false, 'a denied tool must not run');+ assert.equal(frames.at(-1).type, 'done', 'the turn still settles');+ // The model got the denial back as a tool result it can read.+ assert.match(text(frames), /reject|denied|Tool finished/i);+});++test('A05 Stop cancels exactly that chat, waits for the turn to end, and leaves other chats running', { skip }, async t => {+ const r = await rig(t);+ const slowA = r.run('chat-a05-a', 'SCRIPT:slow 400');+ const slowB = r.run('chat-a05-b', 'SCRIPT:slow 60');+ // wait until A is demonstrably live+ for (let i = 0; i < 200 && slowA.frames.filter(f => f.type === 'delta').length < 3; i++) await new Promise(x => setTimeout(x, 50));+ assert.ok(slowA.frames.filter(f => f.type === 'delta').length >= 3, 'the turn must be live before Stop, or the test proves nothing');+ const stopped = await r.bridge.stop('chat-a05-a');+ assert.equal(stopped.stopped, true); assert.equal(stopped.ended, 'aborted');+ await slowA.promise;+ assert.equal(slowA.frames.at(-1).finishReason, 'aborted'); assert.equal(slowA.frames.at(-1).cancelled, true);+ assert.ok(slowA.frames.filter(f => f.type === 'delta').length < 400, 'the stream was cut short');+ assert.ok(r.worker.aborted >= 1, 'the model request was cancelled at the worker');+ assert.equal(r.bridge.isRunning('chat-a05-a'), false);+ // B was not touched and runs to its end.+ await slowB.promise;+ assert.equal(slowB.frames.at(-1).finishReason, 'stop');+ assert.equal(slowB.frames.filter(f => f.type === 'delta').length, 60);+ // And A can be used again.+ const again = r.run('chat-a05-a', 'SCRIPT:echo after stop'); await again.promise;+ assert.equal(text(again.frames), 'after stop');+});++test('A05b Stop while an approval is pending denies it and ends the turn', { skip }, async t => {+ const r = await rig(t);+ const { frames, promise } = r.run('chat-a05b', 'SCRIPT:tool never.txt x');+ for (let i = 0; i < 200 && !states(frames).includes('proposed'); i++) await new Promise(x => setTimeout(x, 50));+ assert.ok(states(frames).includes('proposed'));+ const stopped = await r.bridge.stop('chat-a05b');+ assert.equal(stopped.stopped, true);+ await promise;+ assert.equal(existsSync(join(r.ws, 'never.txt')), false);+ assert.equal(states(frames).at(-1), 'denied');+ assert.equal(r.bridge.pendingFor('chat-a05b').length, 0);+});++test('A06 reopening a chat resumes its Harness session without replaying a tool', { skip }, async t => {+ const dir = mkdtempSync(join(tmpdir(), 'strata-agent-resume-'));+ t.after(() => cleanup(dir));+ const first = await rig(t, { dataDir: dir });+ const turn1 = first.run('chat-a06', 'SCRIPT:tool resume.txt once', { answer: 'approve' });+ await turn1.promise;+ const sessionId = first.bridge.sessionOf('chat-a06');+ assert.ok(sessionId);+ assert.equal(lines(join(first.ws, 'resume.txt')), 1);+ await first.bridge.close(); // the host goes away; the Harness process with it++ // A new host process over the same data directory.+ const second = await rig(t, { dataDir: dir });+ assert.equal(second.bridge.sessionOf('chat-a06'), sessionId, 'the chat keeps its session id');+ const turn2 = second.run('chat-a06', 'SCRIPT:echo second turn');+ await turn2.promise;+ assert.equal(second.bridge.sessionOf('chat-a06'), sessionId);+ assert.equal(text(turn2.frames), 'second turn');+ assert.equal(turn2.frames.filter(f => f.type === 'agent-tool').length, 0, 'no tool card appears on resume');+ assert.equal(lines(join(second.ws, 'resume.txt')), 1, 'the earlier tool effect was not replayed');+ // The agent really carried the earlier conversation: its request holds the earlier turn too.+ const resumed = second.worker.requests.find(q => q.toolNames.length);+ assert.ok(resumed.messageCount > 5, `expected earlier messages in the request, saw ${resumed.messageCount}`);+});++test('A08 two chats run independently, each with its own session and approval', { skip }, async t => {+ const r = await rig(t);+ const a = r.run('chat-a08-a', 'SCRIPT:tool a.txt A'); // will wait on approval+ for (let i = 0; i < 200 && !states(a.frames).includes('proposed'); i++) await new Promise(x => setTimeout(x, 50));+ assert.ok(states(a.frames).includes('proposed'));+ const b = r.run('chat-a08-b', 'SCRIPT:hello');+ await b.promise; // B finishes while A is parked on an approval+ assert.equal(text(b.frames), 'Hello from the scripted worker.');+ assert.equal(states(a.frames).at(-1), 'proposed', 'A is still waiting');+ assert.notEqual(r.bridge.sessionOf('chat-a08-a'), r.bridge.sessionOf('chat-a08-b'));+ assert.equal(r.bridge.pendingFor('chat-a08-b').length, 0);+ assert.equal(r.bridge.pendingFor('chat-a08-a').length, 1);+ const callId = a.frames.find(f => f.type === 'agent-tool').tool.id;+ // An approval cannot be answered through the wrong chat.+ await assert.rejects(r.bridge.approve({ chatId: 'chat-a08-b', callId, decision: 'approve' }), /no longer pending/);+ await r.bridge.approve({ chatId: 'chat-a08-a', callId, decision: 'approve' });+ await a.promise;+ assert.equal(states(a.frames).at(-1), 'done');+ assert.equal(lines(join(r.ws, 'a.txt')), 1);+});++test('a second send to a chat that is mid-turn is refused', { skip }, async t => {+ const r = await rig(t);+ const first = r.run('chat-busy', 'SCRIPT:slow 80');+ for (let i = 0; i < 100 && !first.frames.some(f => f.type === 'delta'); i++) await new Promise(x => setTimeout(x, 50));+ await assert.rejects(r.run('chat-busy', 'SCRIPT:hello').promise, /already running/);+ await first.promise;+});++test('an API connection becomes a route; its key reaches the model by reference and nowhere else', { skip }, async t => {+ const secret = 'sk-test-SECRET-0123456789abcdef';+ const dir = mkdtempSync(join(tmpdir(), 'strata-agent-keys-'));+ t.after(() => cleanup(dir));+ const apiWorker = await startScriptedWorker({ model: 'cloud-model' });+ t.after(() => apiWorker.close());+ const connections = [{ id: 'abcd1234-conn', name: 'Cloud test', baseUrl: apiWorker.url, protocol: 'openai-chat', apiKey: secret, models: [{ id: 'cloud-model', name: 'Cloud model', contextMax: 64000 }] }];+ const r = await rig(t, { dataDir: dir, connections });+ const frames = [];+ await r.bridge.runTurn({ chatId: 'chat-api', message: 'SCRIPT:hello', workspacePath: r.ws, choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, onFrame: f => frames.push(f) });+ assert.equal(frames.find(f => f.type === 'start').remoteModel, true);+ assert.equal(frames.find(f => f.type === 'start').model, 'Cloud model');+ assert.equal(text(frames), 'Hello from the scripted worker.');+ // The chat used the API worker, the local worker was never asked.+ assert.ok(apiWorker.requests.length >= 1); assert.equal(r.worker.requests.length, 0);+ const expected = createHash('sha256').update(`Bearer ${secret}`).digest('hex');+ assert.ok(apiWorker.requests.every(q => q.authSha === expected), 'the key arrived as the bearer credential');+ // A different chat on the local default is unaffected by the first chat's choice.+ const local = []; await r.bridge.runTurn({ chatId: 'chat-local', message: 'SCRIPT:hello', workspacePath: r.ws, onFrame: f => local.push(f) });+ assert.equal(local.find(f => f.type === 'start').remoteModel, false);+ assert.ok(r.worker.requests.length >= 1);++ // The shell tool the agent runs must not see the key.+ const env = r.run('chat-api', 'SCRIPT:envdump envdump.txt', { choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, answer: 'approve' });+ await env.promise;+ assert.ok(existsSync(join(r.ws, 'envdump.txt')), 'the env dump tool must have run');+ const dump = readFileSync(join(r.ws, 'envdump.txt'), 'utf8');+ assert.match(dump, /^PATH=/im, 'the dump must really list the environment, or its silence about the key proves nothing');+ assert.ok(!dump.includes(secret), 'the agent shell must not inherit the key');+ // Nowhere on disk the host wrote: profile, logs, session map. (The compressed session store is checked by absence in frames.)+ const stack = [join(dir, 'agent')];+ while (stack.length) {+ const p = stack.pop();+ if (statSync(p).isDirectory()) { if (p.endsWith('home')) continue; for (const n of readdirSync(p)) stack.push(join(p, n)); continue; }+ assert.ok(!readFileSync(p).includes(secret), `${p} must not contain the key`);+ }+ assert.ok(!JSON.stringify(frames).includes(secret) && !JSON.stringify(r.bridge.status()).includes(secret));+});++test('a missing or removed connection is a typed error, never another model', { skip }, async t => {+ const r = await rig(t);+ await assert.rejects(r.bridge.runTurn({ chatId: 'chat-gone', message: 'SCRIPT:hello', workspacePath: r.ws, choice: { connectionId: 'nope', modelId: 'm' }, onFrame: () => {} }), err => err.code === 'model-unavailable');+ assert.equal(r.worker.requests.length, 0, 'nothing was sent to the local model instead');+});diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjsnew file mode 100644index 000000000..57494dc47--- /dev/null+++ b/apps/host/tests/helpers/scripted-worker.mjs@@ -0,0 +1,123 @@+/**+ * A scripted OpenAI-compatible chat-completions worker, for the agent-bridge tests.+ *+ * It stands in for the Strata API worker so that the Harness agent loop, the tool executor, the+ * approval gate and the host bridge are all real while the model is scripted. A scripted model proves+ * the integration path, not model quality; the real-model run is a separate step.+ *+ * Script selection is by a directive in the last user message (`SCRIPT:<name> <args>`), never by+ * request count: the Harness makes requests a script author does not plan for (a session title, a+ * re-ask after a tool result), and a counter would shift every later reply.+ *+ * SCRIPT:hello reasoning then a short text reply+ * SCRIPT:slow [n] n (default 400) text chunks, 40 ms apart: a window for Stop+ * SCRIPT:tool <file> <text> one shell call that appends <text> to <file>; it asks the sandbox for+ * wider access, so the approval gate is exercised+ * SCRIPT:plain <file> <text> the same call without the escalation (no approval needed)+ * SCRIPT:echo <text> replies with <text>+ * SCRIPT:envdump <file> one shell call that writes the shell's environment to <file>+ *+ * A request whose last message is a tool result is answered with a text that quotes the result.+ */+import { createServer } from 'node:http';+import { createHash } from 'node:crypto';++const delay = ms => new Promise(r => setTimeout(r, ms));++export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = 'scripted-model' } = {}) {+ const requests = [];+ let aborted = 0;+ const server = createServer(async (req, res) => {+ const url = new URL(req.url, 'http://x');+ const json = (code, body) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };+ if (req.method === 'GET' && url.pathname === '/health') return json(200, { ok: true });+ if (req.method === 'GET' && url.pathname === '/v1/models') return json(200, { object: 'list', data: [{ id: model, object: 'model' }] });+ if (req.method === 'GET' && url.pathname === '/__requests') return json(200, { requests, aborted });+ if (req.method !== 'POST' || !url.pathname.endsWith('/chat/completions')) return json(404, { error: 'no route' });+ let raw = '';+ for await (const c of req) raw += c;+ const body = JSON.parse(raw);+ const messages = body.messages ?? [];+ const last = messages[messages.length - 1] ?? {};+ const text = m => typeof m?.content === 'string' ? m.content : Array.isArray(m?.content) ? m.content.map(p => p.text ?? '').join(' ') : '';+ // The Harness appends runtime-context messages after the prompt, so the newest user message is not+ // the prompt: take the newest one that carries a directive.+ const directive = [...messages].reverse().filter(m => m.role === 'user')+ .map(m => /SCRIPT:(\w+)([^\n]*)/.exec(text(m))).find(Boolean);+ requests.push({+ at: Date.now(), model: body.model, stream: body.stream === true,+ toolNames: (body.tools ?? []).map(t => t.function?.name),+ lastRole: last.role, directive: directive?.[1] ?? null, messageCount: messages.length,+ authorization: req.headers.authorization ? 'present' : 'absent',+ authSha: req.headers.authorization ? createHash('sha256').update(req.headers.authorization).digest('hex') : null,+ promptChars: raw.length,+ });+ let closed = false;+ res.on('close', () => { if (!res.writableEnded) { closed = true; aborted++; } });++ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });+ const id = `chatcmpl-${requests.length}`;+ const send = (delta, finish = null, extra = {}) => res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);+ const finish = (reason, tokens = 10) => {+ send({}, reason);+ res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: 100 + messages.length, completion_tokens: tokens, total_tokens: 100 + messages.length + tokens } })}\n\n`);+ res.write('data: [DONE]\n\n'); res.end();+ };+ const say = async (parts, tokens) => {+ send({ role: 'assistant', content: '' });+ for (const p of parts) { if (closed) return; send({ content: p }); await delay(chunkDelayMs); }+ if (!closed) finish('stop', tokens ?? parts.length);+ };++ if (last.role === 'tool') {+ const result = text(last).replace(/\s+/g, ' ').slice(0, 120);+ return say(['Tool finished. ', `Result: ${result}`]);+ }+ 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 (name === 'slow') {+ const n = Number(args) || 400;+ return say(Array.from({ length: n }, (_, i) => `w${i} `));+ }+ if (name === 'echo') return say([args]);+ if (name === 'tool' || name === 'plain' || name === 'envdump') {+ const [file, ...rest] = args.split(/\s+/);+ const shell = (body.tools ?? []).find(t => ['bash', 'pwsh'].includes(t.function?.name))?.function?.name ?? 'bash';+ const value = rest.join(' ') || 'run';+ let command = shell === 'pwsh' ? `Add-Content -Path '${file}' -Value '${value}'` : `echo ${value} >> ${file}`;+ if (name === 'envdump') command = shell === 'pwsh' ? `Get-ChildItem Env: | ForEach-Object { $_.Name + '=' + $_.Value } | Set-Content -Path '${file}'` : `env > ${file}`;+ const call = { command, description: `Append one line to ${file}` };+ if (name === 'tool') {+ call.sandbox_permissions = 'danger-full-access';+ call.justification = 'The write must not be refused by the file sandbox.';+ }+ send({ role: 'assistant', content: '', reasoning_content: 'I will write the file with the shell.' });+ await delay(chunkDelayMs);+ const argsJson = JSON.stringify(call);+ send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: shell, arguments: '' } }] });+ // Fragment the arguments the way real servers do.+ for (let i = 0; i < argsJson.length; i += 17) {+ send({ tool_calls: [{ index: 0, function: { arguments: argsJson.slice(i, i + 17) } }] });+ await delay(5);+ }+ return finish('tool_calls', 30);+ }+ // hello, and the default for anything unscripted (including the Harness's own title request)+ send({ role: 'assistant', content: '', reasoning_content: 'Considering a greeting.' });+ await delay(chunkDelayMs);+ return say(['Hello ', 'from ', 'the ', 'scripted ', 'worker.']);+ });+ await new Promise(r => server.listen(port, '127.0.0.1', r));+ return {+ port: server.address().port,+ url: `http://127.0.0.1:${server.address().port}/v1`,+ requests, get aborted() { return aborted; },+ close: () => new Promise(r => { server.closeAllConnections?.(); server.close(r); }),+ };+}++if (import.meta.url === `file://${process.argv[1].replace(/\\/g, '/')}` || process.argv[1]?.endsWith('scripted-worker.mjs')) {+ const w = await startScriptedWorker({ port: Number(process.env.PORT ?? 0) });+ console.log(`scripted worker on ${w.url}`);+}