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: agent tools, helper agents, one approval card in Manual, /goal, plain agent states, request-slot sizing

Niko12215a00c8fb64fc
diff --git a/apps/desktop/scripts/stage-harness.mjs b/apps/desktop/scripts/stage-harness.mjs
new file mode 100644
index 000000000..499bb8aca
--- /dev/null
+++ b/apps/desktop/scripts/stage-harness.mjs
@@ -0,0 +1,87 @@
+#!/usr/bin/env node
+/**
+ * Stage the DeepSeek Harness (pinned, MIT) as the installer's `harness/` folder: a pruned PRODUCTION install, built at
+ * build time, so nothing is fetched or compiled on the person's PC.
+ *
+ * node apps/desktop/scripts/stage-harness.mjs --src <built Harness checkout> [--out apps/desktop/src-tauri/resources/harness]
+ *
+ * <built Harness checkout> is a clone of the pinned commit after `pnpm install --frozen-lockfile` and `pnpm run build:artifacts`
+ * (see phaseA-tests/notes-split-s4a.md, step 1). The script never touches it: it runs `pnpm deploy --legacy --prod` into
+ * the output folder, removes what a running Harness does not read (sources, tests, maps, docs, other operating systems'
+ * prebuilt binaries, the LibreOffice document converter and the speech engine, which the app does not use), keeps the
+ * MIT licence and third-party notices, writes BUNDLE.json, and finally boots the staged copy once as proof.
+ *
+ * The host finds the result at `<install>/harness` (server/agent/harness-runtime.mjs), or in the component folder.
+ */
+import { spawnSync } from 'node:child_process';
+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join, resolve, sep } from 'node:path';
+import { createHash } from 'node:crypto';
+
+const args = process.argv.slice(2);
+const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : fallback; };
+const src = resolve(opt('src', process.env.STRATA_HARNESS_SRC ?? ''));
+const out = resolve(opt('out', join(import.meta.dirname, '..', 'src-tauri', 'resources', 'harness')));
+if (!opt('src', process.env.STRATA_HARNESS_SRC) || !existsSync(join(src, 'apps', 'cli', 'lib', 'bin.js'))) {
+ console.error('Give --src <a built Harness checkout> (apps/cli/lib/bin.js must exist).');
+ process.exit(2);
+}
+const platform = process.platform;
+const run = (cmd, argv, cwd, extra = {}) => {
+ const r = spawnSync(cmd, argv, { cwd, stdio: 'inherit', shell: false, ...extra });
+ if (r.status !== 0) { console.error(`${cmd} ${argv.join(' ')} failed (${r.status ?? r.error})`); process.exit(1); }
+};
+
+rmSync(out, { recursive: true, force: true });
+mkdirSync(out, { recursive: true });
+const pnpm = platform === 'win32' ? ['corepack.cmd', ['pnpm']] : ['corepack', ['pnpm']];
+run(pnpm[0], [...pnpm[1], 'deploy', '--legacy', '--prod', '--filter', '@deepseek-ai/dsh', out], src, { shell: platform === 'win32' });
+
+// --- prune ------------------------------------------------------------------------------------------------------------
+const OTHER_OS = platform === 'win32' ? /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i
+ : platform === 'darwin' ? /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i
+ : /(^|[\\/._-])(win32|darwin|android|freebsd)([\\/._-]|$)/i;
+/** Whole packages the app never loads: office-document conversion (hundreds of MB) and speech input. */
+const DROP_PACKAGES = [/libreoffice-kit/i, /sherpa-onnx/i];
+const DROP_DIRS = new Set(['test', 'tests', '__tests__', 'docs', 'doc', 'website', 'benchmarks', 'examples', 'example', '.github']);
+const DROP_FILES = /(\.map|\.md|\.markdown|\.pdb|\.ts\.map|\.tsbuildinfo)$/i;
+let removed = 0;
+function prune(dir) {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ if (e.isSymbolicLink()) continue;
+ if (e.isDirectory()) {
+ const inLib = p.split(sep).includes('lib');
+ if ((DROP_DIRS.has(e.name) && !inLib) || DROP_PACKAGES.some(r => r.test(e.name)) || (OTHER_OS.test(e.name) && /prebuild|bin|native|platform|-(win32|darwin|linux)/i.test(p))) {
+ rmSync(p, { recursive: true, force: true }); removed++; continue;
+ }
+ prune(p);
+ } else if (DROP_FILES.test(e.name) && !/^(README|LICENSE|NOTICE)/i.test(e.name) && !/\.d\.ts$/.test(e.name) ? true : false) {
+ if (!/^(LICENSE|THIRD_PARTY|NOTICE)/i.test(e.name)) { rmSync(p, { force: true }); removed++; }
+ }
+ }
+}
+prune(out);
+
+// --- licence: the MIT text and the third-party notices travel with the files ---------------------------------------------
+for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
+ if (existsSync(join(src, name))) cpSync(join(src, name), join(out, name));
+}
+const cli = JSON.parse(readFileSync(join(out, 'package.json'), 'utf8'));
+let commit = process.env.STRATA_HARNESS_COMMIT ?? null;
+if (!commit) { const r = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: src, encoding: 'utf8' }); if (r.status === 0) commit = r.stdout.trim(); }
+function size(dir) { let t = 0, n = 0; for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) { const s = size(p); t += s.bytes; n += s.files; } else if (e.isFile()) { t += statSync(p).size; n++; } } return { bytes: t, files: n }; }
+const total = size(out);
+writeFileSync(join(out, 'BUNDLE.json'), JSON.stringify({
+ component: 'deepseek-harness', version: cli.version, commit, license: 'MIT', platform, node: process.version,
+ bytes: total.bytes, files: total.files, entry: 'apps/cli/lib/bin.js', builtAt: new Date().toISOString(),
+ note: 'Pruned production install (pnpm deploy --prod). No package manager runs on the user\'s PC.',
+}, null, 2));
+
+// --- proof: the staged copy answers --version and boots the web profile once ----------------------------------------
+const bin = join(out, 'apps', 'cli', 'lib', 'bin.js');
+const entry = existsSync(bin) ? bin : join(out, 'lib', 'bin.js');
+const v = spawnSync(process.execPath, [entry, '--version'], { encoding: 'utf8' });
+if (v.status !== 0) { console.error('staged Harness does not start:', v.stderr); process.exit(1); }
+console.log(`staged ${cli.version} (${commit?.slice(0, 8) ?? 'no commit'}) in ${out}: ${(total.bytes / 1048576).toFixed(0)} MiB, ${total.files} files, ${removed} pruned items; --version -> ${v.stdout.trim()}`);
+console.log(`sha256(BUNDLE.json)=${createHash('sha256').update(readFileSync(join(out, 'BUNDLE.json'))).digest('hex')}`);
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs
index 35edc2818..6e423d756 100644
--- a/apps/host/server/agent/agent-bridge.mjs
+++ b/apps/host/server/agent/agent-bridge.mjs
@@ -20,10 +20,24 @@ import { randomUUID } from 'node:crypto';
import { GatewayClient } from './gateway-client.mjs';
import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs';
import { buildProfile, routeFor, MODE_PRESETS, modeOf } from './profile.mjs';
-import { TurnProjector } from './events.mjs';
+import { TurnProjector, parseArguments as parseArgs } from './events.mjs';
+import { ChildProjector } from './children.mjs';
+/**
+ * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical
+ * text for the Details disclosure (experts), already free of secrets.
+ */
export class AgentUnavailable extends Error {
- constructor(message, code = 'agent-unavailable') { super(message); this.name = 'AgentUnavailable'; this.code = code; }
+ constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; }
+}
+
+/** The plain sentence for a raw agent failure text, whatever produced it. */
+export function plainAgentFailure(raw) {
+ const text = String(raw ?? '');
+ if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.';
+ if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.';
+ if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.';
+ return text;
}
/** A timer that never keeps the process alive by itself. */
@@ -40,7 +54,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, localInstances, connections, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
+export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, 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');
@@ -71,22 +85,23 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
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 timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models 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 }); }
+ function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); }
/** 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() });
+ 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 });
return {
state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle',
- reason: lastError ?? null,
+ reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null,
+ detail: 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 })),
@@ -97,7 +112,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
async function startRuntime(profile) {
const h = harnessInfo();
- if (!h.ok) throw new AgentUnavailable(h.reason, 'component-missing');
+ if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason);
mkdirSync(home, { recursive: true });
const stale = stopStaleAgent(join(root, 'harness.pid'));
if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`);
@@ -130,7 +145,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
async function ensureRuntime(choice, signal) {
for (;;) {
if (starting) { await starting.catch(() => {}); continue; }
- const profile = buildProfile({ local: localInstances(), connections: connections() });
+ const profile = buildProfile({ local: localInstances(), connections: connections(), gate });
const route = routeFor(profile, choice);
if (!route) {
throw new AgentUnavailable(choice?.connectionId
@@ -145,7 +160,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
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 { return await startRuntime(profile); } catch (e) {
+ lastError = redact(String(e.message ?? e), Object.values(profile.env));
+ throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError);
+ }
})();
try { await starting; } finally { starting = null; }
}
@@ -187,13 +205,24 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
return r?.values?.permissions?.currentValue ?? null;
};
try {
- if (await read() === want) return;
- const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] });
- if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command');
- const now = await read();
- if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`);
+ if (await read() !== want) {
+ const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] });
+ if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command');
+ const now = await read();
+ if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`);
+ }
} catch (e) {
- throw new AgentUnavailable(`The agent could not switch this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran: ${e.message}`, 'mode-unavailable');
+ throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message);
+ }
+ // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start.
+ if (mode === 'manual' && !runtime.gateChecked) {
+ try {
+ const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] });
+ if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded');
+ runtime.gateChecked = true;
+ } catch (e) {
+ throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message);
+ }
}
}
@@ -203,13 +232,13 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
*/
async function runTurn(options) {
const c = chat(options.chatId);
- if (c.turn || c.starting) throw new AgentUnavailable('This chat is already running a turn.', 'turn-active');
+ if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active');
// From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start.
c.starting = true; c.cancelStart = false;
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 }) {
+ async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null }) {
let send = onFrame;
signal?.addEventListener('abort', () => { send = () => {}; }, { once: true });
const emit = frame => { try { send(frame); } catch { send = () => {}; } };
@@ -225,7 +254,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
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');
+ throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message);
}
c.route = `${route.route}/${route.modelId}`; c.routeGeneration = runtime.generation;
}
@@ -239,14 +268,19 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
const turn = {
sessionId, projector, route, requestId, live: false, lastSeq: -1,
ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false,
- abortFromRuntime: reason => finishTurn(reason),
+ abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure),
+ // 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,
};
c.turn = turn;
function finishTurn(failure) {
if (turn.finished) return;
turn.finished = true;
+ clearTimeout(turn.settleTimer);
turn.follow?.close();
- const frames = failure ? [{ type: 'error', message: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow });
+ for (const child of turn.children.values()) child.follow?.close();
+ if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };
+ const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: 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 });
@@ -282,9 +316,116 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
}
} 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);
+ if (item.type === 'event') watchParent(item.event);
}
+ // -- helper agents ---------------------------------------------------------------------------------------
+
+ const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() });
+ const emitRow = (child, force = false) => {
+ const now = Date.now();
+ if (!force && now - child.lastRow < 400) { child.rowPending = true; return; }
+ child.lastRow = now; child.rowPending = false;
+ emit(rowFrame(child));
+ };
+
+ function openChild(d) {
+ const id = d.childId;
+ if (!id || turn.children.has(id)) return;
+ const cp = new ChildProjector({ id, name: d.label || 'Helper' });
+ const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 };
+ turn.children.set(id, child);
+ emitRow(child, true);
+ const fold = item => {
+ if (turn.finished) return;
+ const { frames, row } = cp.consume(item);
+ for (const f of frames) emit(f);
+ if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; }
+ if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; }
+ if (row) emitRow(child);
+ };
+ child.follow = runtime.gw.openStream('session/follow', {
+ request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true },
+ }, {
+ onItem: item => {
+ if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; }
+ fold(item);
+ },
+ onError: e => {
+ log(`agent · helper stream ended: ${e.message}`);
+ if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); }
+ },
+ });
+ // A late reader still gets the final row: flush any row held back by the throttle.
+ child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); });
+ }
+
+ function watchParent(e) {
+ const d = e.data ?? {};
+ switch (e.type) {
+ case 'turn/start':
+ turn.parentOpen = true;
+ 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(() => {});
+ break;
+ case 'turn/end':
+ turn.parentOpen = false;
+ armSettle();
+ break;
+ case 'tool/call':
+ if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments));
+ break;
+ case 'subagent/catalog':
+ openChild(d);
+ break;
+ case 'tool/result': {
+ const call = turn.subagentCalls.get(d.message?.toolCallId);
+ const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' ');
+ const started = /started subagent ([0-9a-f-]{36})/i.exec(text);
+ const child = started ? turn.children.get(started[1]) : null;
+ if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); }
+ break;
+ }
+ case 'user/message':
+ if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) emit({ type: 'delta', text: `*Working on the goal, step ${d.source.round}*\n\n` });
+ // falls through
+ case 'agent/inbox/spliced': {
+ const hit = JSON.stringify(d);
+ if (!/Background subagent/.test(hit)) break;
+ for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true;
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ /**
+ * The run is over when the parent is idle and every helper has finished and reported back. A helper's report
+ * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run
+ * open (for a few seconds at most); after Stop nobody waits for reports.
+ */
+ function armSettle() {
+ clearTimeout(turn.settleTimer);
+ if (turn.finished) return;
+ turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => {
+ if (turn.finished || turn.parentOpen) return;
+ const open = [...turn.children.values()];
+ if (open.some(c => !c.done)) return;
+ if (!turn.stopping) {
+ if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; }
+ // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops.
+ const current = await goalGet();
+ if (turn.finished || turn.parentOpen) return;
+ if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; }
+ if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); }
+ }
+ finishTurn(null);
+ });
+ }
+ const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined);
+
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); })
@@ -292,13 +433,20 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
if (turn.finished) return { error: true };
if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: 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 };
+ if (goal) {
+ // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours.
+ turn.live = true; turn.goalRun = true;
+ try { await startGoal(runtime, sessionId, goal); }
+ catch (e) { finishTurn(plainGoalError(e)); return { error: true }; }
+ } else {
+ 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 };
+ }
}
turn.prompted = true;
if (turn.stopBeforePrompt) {
@@ -315,23 +463,105 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut };
}
+ // -- /goal -----------------------------------------------------------------------------------------------
+
+ /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */
+ async function startGoal(runtime, sessionId, goal) {
+ if (goal.action === 'create') {
+ const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) };
+ await runtime.gw.rpc('goals/create', { agentId: sessionId, request });
+ return;
+ }
+ const current = await runtime.gw.rpc('goals/get', { agentId: sessionId });
+ if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none');
+ await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });
+ }
+
+ async function pauseGoal(runtime, sessionId) {
+ try {
+ const current = await runtime.gw.rpc('goals/get', { agentId: sessionId });
+ if (current && current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });
+ } catch { /* no goal service, or nothing to pause */ }
+ }
+
+ /** The goal's state in plain words. */
+ function describeGoal(view) {
+ if (!view) return 'No goal is set. Start one with /goal followed by what you want done.';
+ const steps = `step ${view.roundsStarted} of at most ${view.maxGoalRounds}`;
+ const what = `"${view.objective}"`;
+ if (view.phase === 'active') return `Working on the goal ${what} (${steps}).`;
+ if (view.phase === 'paused') return `The goal ${what} is paused (${steps}). Type /goal resume to go on.`;
+ if (view.phase === 'complete') return `The goal ${what} is complete.`;
+ return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`;
+ }
+
+ /**
+ * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal,
+ * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and
+ * streams them like a chat turn (Stop pauses the goal); every other verb answers at once.
+ */
+ async function goalCommand(options) {
+ const { chatId, line, onFrame } = options;
+ const text = String(line ?? '').trim();
+ const verb = text.split(/\s+/)[0]?.toLowerCase() ?? '';
+ const rest = text.slice(verb.length).trim();
+ const say = reply => {
+ onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` });
+ onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] });
+ onFrame({ type: 'delta', text: reply });
+ onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 });
+ return { goal: true };
+ };
+ const known = sessionMap[chatId]?.sessionId;
+ const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status');
+ let runtime = rt;
+ if (quick) {
+ if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.');
+ const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined);
+ const ref = current ? { id: current.id, revision: current.revision } : null;
+ try {
+ if (verb === '' || verb === 'status') return say(describeGoal(current));
+ if (!ref) return say('There is no goal in this chat yet.');
+ if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); }
+ if (verb === 'pause') {
+ if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref });
+ return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known })));
+ }
+ if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); }
+ if (verb === 'edit') {
+ if (!rest) return say('Type /goal edit followed by the new wording of the goal.');
+ await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } });
+ return say(`The goal now reads: "${rest}".`);
+ }
+ } catch (e) { return say(plainGoalError(e)); }
+ }
+ if (verb === 'resume') return runTurn({ ...options, goal: { action: 'resume' } });
+ // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words.
+ return runTurn({ ...options, goal: { action: 'create', objective: text } });
+ }
+
/** Answer one pending approval. `decision` is `approve` or `deny`. */
async function approve({ chatId, callId, decision }) {
const sessionId = sessionMap[chatId]?.sessionId;
+ // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to
+ // THIS chat's run can be answered from this chat.
+ const [maybeChild] = String(callId).split(':');
+ const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild);
+ const key = ownHelper ? callId : `${sessionId}:${callId}`;
// 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;
+ let entry = sessionId ? pending.get(key) : null;
for (let i = 0; !entry && sessionId && i < 40; i++) {
await new Promise(r => setTimeout(r, 50));
- entry = pending.get(`${sessionId}:${callId}`);
+ entry = pending.get(key);
}
- 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}`);
+ if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone');
+ if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone');
+ pending.delete(key);
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');
+ throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message);
}
return { ok: true };
}
@@ -352,7 +582,13 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]);
if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 };
}
- await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } });
+ turn.stopping = true;
+ await pauseGoal(rt, turn.sessionId);
+ // Helpers first: a helper still working would otherwise report back and wake the parent again.
+ await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' })));
+ await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; });
+ // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down.
+ if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); }
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' };
@@ -361,7 +597,9 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
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 }));
+ const helpers = chats.get(chatId)?.turn?.children;
+ return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId))
+ .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at }));
}
async function close() {
@@ -369,7 +607,31 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance
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 }) };
+ return { status, runTurn, goalCommand, approve, 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. */
+export function plainBlocker(reason) {
+ if (!reason) return 'it could not go on.';
+ if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.';
+ return String(reason.message ?? 'it could not go on.');
+}
+
+/** What a goal run says when it ends. */
+export function goalEnding(view) {
+ if (view.phase === 'complete') return '\n\n*The goal is complete.*';
+ if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`;
+ if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*';
+ return '';
+}
+
+/** A goal request the Harness refused, as a sentence. */
+export function plainGoalError(e) {
+ const message = String(e?.message ?? e);
+ if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.';
+ if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.';
+ if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.';
+ return 'The goal could not be changed right now. Try again in a moment.';
}
/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */
diff --git a/apps/host/server/agent/children.mjs b/apps/host/server/agent/children.mjs
new file mode 100644
index 000000000..c88a120b0
--- /dev/null
+++ b/apps/host/server/agent/children.mjs
@@ -0,0 +1,185 @@
+/**
+ * Helper agents (the Harness's subagents) as the rows the chat already has.
+ *
+ * A helper is a child session of the chat's Harness session. This module is the pure part: it folds one child's
+ * `session/follow` items into
+ * - an `agent` frame (the shape `apps/host/src/lib/agents.ts updateAgent` merges into the chat's existing rows:
+ * id, name, description, status, durationMs, tokens, updatedAt), and
+ * - tool cards, but only for a helper's request that needs the person (an approval). Everything else a helper does
+ * stays in its row; the transcript is not filled with the work of four helpers at once.
+ *
+ * A helper's approval card is the same card a direct request gets (state `proposed`, answered with the same
+ * Approve/Deny route). Its id is `<childSessionId>:<callId>`, which is also the key the bridge keeps the pending
+ * question under, so the answer finds the helper that asked and no other chat can answer it.
+ *
+ * Wording is for the person reading the row, not for a log: no session ids, no tool internals.
+ */
+import { friendlyFailure, parseArguments, presentTool, resultText, toolScope } from './events.mjs';
+
+const clip = (value, max) => {
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
+};
+
+/** What a helper is doing, in words (shown as the row's description while it works). */
+export function activityOf(name, args = {}) {
+ const scope = toolScope(name);
+ if (scope === 'shell') return 'Running a command';
+ if (scope === 'write') return 'Changing files';
+ if (name === 'web_fetch' || name === 'web_search') return 'Looking something up online';
+ if (name === 'read' || name === 'glob' || name === 'grep' || name === 'read_image') return 'Reading files';
+ if (name === 'subagent' || name === 'subagent_fork') return 'Handing work to another helper';
+ if (scope === 'read') return 'Looking through the project';
+ return 'Using a tool';
+}
+
+export class ChildProjector {
+ /**
+ * @param {{id:string, name?:string, task?:string, now?:()=>number}} options
+ */
+ constructor({ id, name = 'Helper', task = '', now = () => Date.now() }) {
+ this.id = id;
+ this.name = clip(name, 60) || 'Helper';
+ this.task = clip(task, 140);
+ this.now = now;
+ this.startedAt = now();
+ this.status = 'queued';
+ this.tokens = 0;
+ this.sawUsage = false;
+ this.activity = null;
+ this.closing = ''; // the helper's last words, shown once it finished
+ this.failure = null;
+ this.endedAt = null;
+ this.tools = new Map(); // callId -> { card, calledAt, asked }
+ this.asked = new Map(); // approval id -> callId
+ this.lastEmit = 0;
+ }
+
+ /** The row as the UI merges it. */
+ agent() {
+ const at = this.now();
+ const done = this.status === 'completed' || this.status === 'failed' || this.status === 'cancelled';
+ let description = this.task;
+ if (this.status === 'working' && this.activity) description = this.activity;
+ if (this.status === 'completed') description = this.closing ? clip(this.closing, 140) : 'Finished.';
+ if (this.status === 'failed') description = this.failure ?? 'Stopped because something went wrong.';
+ if (this.status === 'cancelled') description = 'Stopped.';
+ return {
+ id: this.id, name: this.name, description, status: this.status,
+ durationMs: Math.max(0, (done ? this.endedAt : at) - this.startedAt), tokens: this.tokens, updatedAt: at,
+ };
+ }
+
+ #cardId(callId) { return `${this.id}:${callId}`; }
+
+ #card(callId, patch) {
+ const entry = this.tools.get(callId);
+ if (!entry) return null;
+ entry.card = { ...entry.card, ...patch };
+ return { type: 'agent-tool', tool: entry.card };
+ }
+
+ /**
+ * Fold one follow item. Returns `{ frames, row }`: card frames to send now, and whether the row changed
+ * (the caller decides when to send it, so a stream of usage chunks does not flood the page).
+ */
+ consume(item) {
+ const frames = [];
+ let row = false;
+ const set = (status) => { if (this.status !== status) { this.status = status; row = true; } };
+
+ if (item.type === 'assistant-stream') {
+ const f = item.frame;
+ if (f.type === 'chunk' && f.chunk?.type === 'usage' && f.chunk.usage) {
+ this.sawUsage = true;
+ this.tokens += (Number(f.chunk.usage.inputTokens) || 0) + (Number(f.chunk.usage.outputTokens) || 0);
+ row = true;
+ } else if (f.type === 'chunk' && (f.chunk?.type === 'text-delta' || f.chunk?.type === 'reasoning-delta')) {
+ if (this.status === 'queued') set('working');
+ }
+ return { frames, row };
+ }
+ if (item.type !== 'event') return { frames, row };
+ const e = item.event;
+ const d = e.data ?? {};
+ switch (e.type) {
+ case 'step/start':
+ case 'turn/start':
+ // A helper that was finished and got a new message works again.
+ if (this.status !== 'working') { this.endedAt = null; this.failure = null; set('working'); }
+ break;
+ case 'assistant/message': {
+ const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join('').trim();
+ if (text) this.closing = text;
+ break;
+ }
+ case 'tool/call': {
+ const args = parseArguments(d.arguments);
+ const card = { ...presentTool({ callId: this.#cardId(d.callId), name: d.name, args }), state: 'running', agentName: this.name };
+ this.tools.set(d.callId, { card, calledAt: e.time, asked: false });
+ this.activity = activityOf(d.name, args);
+ set('working');
+ row = true;
+ break;
+ }
+ case 'approval/asked': {
+ if (!d.callId || !this.tools.has(d.callId)) break;
+ this.asked.set(d.id, d.callId);
+ const entry = this.tools.get(d.callId);
+ entry.asked = true;
+ const frame = this.#card(d.callId, { state: 'proposed', effect: clip(`${this.name} asks: ${d.reason ?? 'to use a tool'}`, 400) });
+ if (frame) frames.push(frame);
+ break;
+ }
+ case 'approval/decided': {
+ const callId = this.asked.get(d.id);
+ const entry = callId ? this.tools.get(callId) : null;
+ if (!entry) break;
+ const frame = d.outcome === 'allowed-once'
+ ? this.#card(callId, { state: 'running', approved: true })
+ : this.#card(callId, { state: 'denied', result: d.outcome === 'rejected' ? 'Denied. Nothing ran.' : 'Cancelled. Nothing ran.' });
+ if (frame) frames.push(frame);
+ break;
+ }
+ case 'tool/result': {
+ const callId = d.message?.toolCallId;
+ const entry = this.tools.get(callId);
+ if (!entry) break;
+ if (entry.asked) {
+ const wasDenied = entry.card.state === 'denied';
+ const frame = this.#card(callId, {
+ state: wasDenied ? 'denied' : d.message?.isError === true ? 'error' : 'done',
+ result: wasDenied ? entry.card.result : resultText(d.message),
+ durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt),
+ });
+ if (frame) frames.push(frame);
+ }
+ this.activity = null;
+ row = true;
+ break;
+ }
+ case 'turn/end': {
+ const reason = d.reason ?? { kind: 'completed' };
+ this.endedAt = this.now();
+ if (reason.kind === 'aborted') set('cancelled');
+ else if (reason.kind === 'error') { this.failure = clip(friendlyFailure(reason.error), 140); set('failed'); }
+ else if (reason.kind === 'blocked' || reason.kind === 'interrupted') { this.failure = 'Stopped before it finished.'; set('failed'); }
+ else set('completed');
+ // A request still waiting when its helper ended can no longer be answered.
+ for (const [callId, entry] of this.tools) {
+ if (entry.asked && entry.card.state === 'proposed') {
+ const frame = this.#card(callId, { state: 'denied', result: 'Cancelled. Nothing ran.' });
+ if (frame) frames.push(frame);
+ }
+ }
+ row = true;
+ break;
+ }
+ default:
+ break;
+ }
+ return { frames, row };
+ }
+
+ get finished() { return this.status === 'completed' || this.status === 'failed' || this.status === 'cancelled'; }
+}
diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs
index 6ed6bb055..7dfa80221 100644
--- a/apps/host/server/agent/events.mjs
+++ b/apps/host/server/agent/events.mjs
@@ -11,6 +11,9 @@ const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']);
const WRITE = new Set(['write', 'edit']);
const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']);
+/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */
+export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']);
+
export function toolScope(name) {
if (SHELL.has(name)) return 'shell';
if (WRITE.has(name)) return 'write';
@@ -31,18 +34,63 @@ export function parseArguments(raw) {
try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; }
}
+/**
+ * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its
+ * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments.
+ */
+const WORDS = {
+ read: a => ['Reads a file.', a.file_path ?? a.path],
+ glob: a => ['Looks for files by name.', a.pattern],
+ grep: a => ['Searches inside files.', a.pattern ?? a.query],
+ read_image: a => ['Looks at a picture.', a.file_path ?? a.path],
+ working_directory: () => ['Checks which folder it is working in.', ''],
+ todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''],
+ skill: a => ['Uses a saved skill.', a.name ?? a.skill],
+ present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title],
+ create_goal: a => ['Sets a goal to work towards.', a.objective],
+ update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''],
+ get_goal: () => ['Checks the current goal.', ''],
+ web_fetch: a => ['Opens a web page.', a.url],
+ web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query],
+ workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''],
+ job_list: () => ['Checks the background tasks.', ''],
+ job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id],
+ job_kill: a => ['Stops a background task.', a.job_id ?? a.id],
+ lsp: a => ['Looks up how the code fits together.', a.file_path],
+};
+
/** The ToolCall fields the card needs, from one Harness tool call. */
export function presentTool({ callId, name, args, reason = null }) {
const scope = toolScope(name);
- const preview = scope === 'shell' ? args.command ?? ''
+ const words = WORDS[name]?.(args);
+ const preview = scope === 'shell' && !words ? args.command ?? ''
: scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? ''
- : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.query ?? JSON.stringify(args);
- const effect = reason ?? (scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.')
+ : words ? words[1] ?? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.query ?? JSON.stringify(args);
+ const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.')
: scope === 'write' ? 'Changes a file in the workspace.'
: scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.');
return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope };
}
+/** A tool's failure in plain words, or null when there is nothing better than the original text. */
+export function plainToolError(text) {
+ const t = String(text ?? '');
+ if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.';
+ if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.';
+ if (/unknown or no longer available/i.test(t)) return 'That skill is not available.';
+ if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.';
+ if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.';
+ if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.';
+ if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.';
+ return null;
+}
+
+/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */
+export function withPlain(raw) {
+ const plain = plainToolError(raw);
+ return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw;
+}
+
/** Text of a tool-result message, bounded. */
export function resultText(message) {
const parts = Array.isArray(message?.content) ? message.content : [];
@@ -91,6 +139,7 @@ export class TurnProjector {
const c = f.chunk;
if (c.type === 'text-delta' && c.text) {
this.firstTokenAt ??= Date.now();
+ this.emittedAny = true;
this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length);
out.push({ type: 'delta', text: c.text });
} else if (c.type === 'reasoning-delta' && c.text) {
@@ -117,6 +166,7 @@ export class TurnProjector {
break;
}
case 'tool/call': {
+ if (NO_CARD.has(d.name)) break;
const args = parseArguments(d.arguments);
const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' };
this.tools.set(d.callId, { card, calledAt: e.time });
@@ -153,12 +203,18 @@ export class TurnProjector {
const denied = this.denied.has(callId);
const frame = this.#card(callId, {
state: denied ? 'denied' : isError ? 'error' : 'done',
- result: this.byPolicy.has(callId) ? NOT_IN_MODE : resultText(d.message),
+ // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them.
+ result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : resultText(d.message),
durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt),
});
if (frame) out.push(frame);
break;
}
+ case 'turn/start':
+ // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph.
+ this.ended = null;
+ if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' });
+ break;
case 'turn/end':
this.ended = d.reason ?? { kind: 'completed' };
break;
diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs
index 135aa91c2..4a1b0d8bc 100644
--- a/apps/host/server/agent/harness-runtime.mjs
+++ b/apps/host/server/agent/harness-runtime.mjs
@@ -36,15 +36,18 @@ export function agentEnvironment(base = process.env, extra = {}) {
* Find a usable Harness. Returns `{ ok:true, dir, bin, version }` or `{ ok:false, reason }`; the reason
* is user-readable because it becomes the capability state shown in the app.
*/
-export function resolveHarness({ env = process.env, componentsDir = null } = {}) {
- const candidates = [env.STRATA_HARNESS_DIR, componentsDir ? join(componentsDir, 'harness') : null].filter(Boolean);
+export function resolveHarness({ env = process.env, componentsDir = null, bundledDir = null } = {}) {
+ // Order: an explicit folder, the folder the installer ships next to the host, then the user's component folder.
+ const candidates = [env.STRATA_HARNESS_DIR, bundledDir, componentsDir ? join(componentsDir, 'harness') : null].filter(Boolean);
if (!candidates.length) return { ok: false, reason: 'The agent component (DeepSeek Harness) is not installed.' };
for (const dir of candidates.map(c => resolve(c))) {
- const bin = join(dir, 'apps', 'cli', 'lib', 'bin.js');
+ // A source checkout keeps the CLI in apps/cli; the installer's pruned production copy IS the CLI package.
+ const nested = join(dir, 'apps', 'cli', 'lib', 'bin.js');
+ const bin = existsSync(nested) ? nested : join(dir, 'lib', 'bin.js');
if (!existsSync(bin)) continue;
if (!existsSync(join(dir, 'node_modules'))) return { ok: false, reason: `The agent component at ${dir} has no installed dependencies.` };
let version = null;
- try { version = JSON.parse(readFileSync(join(dir, 'apps', 'cli', 'package.json'), 'utf8')).version ?? null; } catch { /* version is informational */ }
+ try { version = JSON.parse(readFileSync(existsSync(nested) ? join(dir, 'apps', 'cli', 'package.json') : join(dir, 'package.json'), 'utf8')).version ?? null; } catch { /* version is informational */ }
return { ok: true, dir, bin, version };
}
return { ok: false, reason: `The agent component was not found at ${candidates.join(' or ')}. Install or repair it.` };
@@ -139,7 +142,7 @@ export function stopStaleAgent(pidFile) {
try { pid = Number(JSON.parse(readFileSync(pidFile, 'utf8')).pid); } catch { /* unreadable record */ }
rmSync(pidFile, { force: true });
const cmd = commandLineOf(pid);
- if (!cmd || !/apps[\\/]cli[\\/]lib[\\/]bin\.js/.test(cmd) || !/--profile web/.test(cmd)) return null;
+ if (!cmd || !/lib[\\/]bin\.js/.test(cmd) || !/--profile web/.test(cmd)) return null;
if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
else { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } }
return pid;
diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjs
new file mode 100644
index 000000000..0663d85d3
--- /dev/null
+++ b/apps/host/server/agent/plugins/strata-gate.mjs
@@ -0,0 +1,155 @@
+/**
+ * The Strata approval gate: a small Harness plugin (plain ESM, no imports, loaded by absolute path from the profile).
+ *
+ * Why it exists. The Harness only asks a person when a tool escalates its sandbox. With the sandbox read-only that
+ * produced a blocked attempt first (a card full of sandbox and PowerShell errors) and the real Approve/Deny card
+ * only on the model's second try. In Manual mode this plugin asks BEFORE a change runs, through the Harness's own
+ * approval service, so the person sees exactly one card per change and nothing has run when it appears.
+ *
+ * How it works. It listens to `tools/pre-execute` (the same seam the Harness's own Auto-review layer uses). For a
+ * session whose effective preset is Manual it returns an `ask` decision for every call that is not known to be
+ * read-only. The Harness then asks, runs the tool only after an approval, and records the answer. Manual runs with
+ * the sandbox open, so an approved change can really happen anywhere the person agreed to; the approval is the
+ * control, which is why anything this file cannot prove is read-only asks (fail closed).
+ *
+ * Children. A subagent's approval policy is pinned to `never` by the Harness (its requests are rejected on the
+ * spot). For a child of a Manual chat that would hide the card and the child could not do anything. The gate
+ * writes `ask` into that child's log, so the child's request reaches the same single Approve/Deny card.
+ * Plan and Bypass children are untouched.
+ *
+ * The status command `/strata-gate` lets the host confirm the gate is really loaded before it lets a Manual turn
+ * start (a Manual chat with no gate would be a chat with the sandbox open and nobody asking).
+ */
+
+export const name = 'strata-gate';
+export const inject = ['approval', 'permissionPresets', 'sessions', 'tools'];
+
+/** Preset key the host writes for Manual (apps/host/server/agent/profile.mjs MODE_PRESETS). */
+export const MANUAL_PRESET = 'strata-manual';
+
+/** Tools that cannot change anything on this computer. Everything else asks. */
+export const READ_ONLY_TOOLS = new Set([
+ 'read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'skill', 'present', 'lsp',
+ 'get_goal', 'create_goal', 'update_goal', 'list_agents', 'list_subagent_models', 'job_list', 'job_output',
+ 'ask_user_question', 'exit_plan_mode',
+ // Reading the internet is part of what the app promises; changing nothing here.
+ 'web_fetch', 'web_search',
+ // Delegation: the child it starts is governed by this same gate.
+ 'subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'workflow',
+]);
+
+const SHELL_TOOLS = new Set(['pwsh', 'bash']);
+
+/** Commands that only look. Matched against the first word of every pipeline segment. */
+const SAFE_COMMANDS = new Set([
+ // PowerShell
+ 'get-childitem', 'gci', 'ls', 'dir', 'get-content', 'gc', 'cat', 'type', 'get-item', 'gi', 'get-location', 'pwd', 'gl',
+ 'select-string', 'sls', 'measure-object', 'measure', 'select-object', 'select', 'where-object', 'where', 'sort-object', 'sort',
+ 'format-table', 'ft', 'format-list', 'fl', 'out-string', 'test-path', 'resolve-path', 'get-filehash', 'get-date', 'get-command',
+ 'get-process', 'get-itemproperty', 'write-output', 'echo', 'hostname', 'whoami', 'get-host', 'get-psdrive', 'get-help',
+ 'group-object', 'group', 'convertto-json', 'convertfrom-json', 'select-xml', 'compare-object', 'get-unique', 'tee-object-none',
+ // POSIX
+ 'head', 'tail', 'wc', 'grep', 'rg', 'egrep', 'fgrep', 'stat', 'file', 'du', 'df', 'uname', 'which', 'basename', 'dirname',
+ 'realpath', 'readlink', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'date', 'id', 'env-none', 'tree',
+]);
+
+/** git subcommands that only read. */
+const SAFE_GIT = new Set(['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']);
+const SAFE_VERSION = /^(node|python|python3|py|npm|pnpm|git|dotnet|cargo|rustc|go|java|pip|pip3)\s+(--version|-v|-version|version)$/i;
+
+/** Anything that can chain, redirect, expand or start something else is not read-only. */
+const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|\bsh\b|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i;
+
+/**
+ * Whether a shell command only reads. Conservative by design: one unrecognised word and the answer is no.
+ * @param {string} command
+ * @returns {boolean}
+ */
+export function isReadOnlyShell(command) {
+ const text = String(command ?? '').trim();
+ if (!text || text.length > 600) return false;
+ if (SAFE_VERSION.test(text)) return true;
+ if (UNSAFE_SYNTAX.test(text)) return false;
+ const segments = text.split('|').map(s => s.trim());
+ return segments.every((segment) => {
+ if (!segment) return false;
+ const words = segment.split(/\s+/);
+ const first = words[0].toLowerCase().replace(/^\.\\/, '');
+ if (first === 'git') {
+ // `git config` and `git tag`/`branch`/`remote` can write when given a value; only the bare listing forms are safe.
+ const sub = (words[1] ?? '').toLowerCase();
+ if (!SAFE_GIT.has(sub)) return false;
+ if (['config', 'tag', 'branch', 'remote'].includes(sub)) {
+ const rest = words.slice(2).filter(w => !w.startsWith('-') || /^(-l|-a|-v|-vv|--list|--all|--show-current|--get|--get-all)$/i.test(w));
+ return rest.length === 0 || (sub === 'config' && words[2] === '--get') || (sub === 'remote' && words[2] === '-v');
+ }
+ return !words.some(w => /^--(output|ext-diff|textconv)\b/i.test(w));
+ }
+ return SAFE_COMMANDS.has(first) && !words.some(w => /^-(delete|exec|execdir|fprint|fls|ok)$/i.test(w));
+ });
+}
+
+const clip = (value, max) => {
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
+};
+
+/**
+ * The decision for one call in Manual mode, or null when it needs no question.
+ * @param {{name:string, arguments:any}} exec
+ * @returns {{kind:'ask', reason:string}|null}
+ */
+export function manualDecision(exec) {
+ const tool = String(exec.name ?? '');
+ const args = exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {};
+ if (READ_ONLY_TOOLS.has(tool)) return null;
+ if (SHELL_TOOLS.has(tool)) {
+ if (isReadOnlyShell(args.command)) return null;
+ const what = args.description ? clip(args.description, 160) : clip(args.command, 160);
+ return { kind: 'ask', reason: `Run a command that may change things: ${what}` };
+ }
+ if (tool === 'write') return { kind: 'ask', reason: `Create or replace the file ${clip(args.file_path ?? args.path, 200)}` };
+ if (tool === 'edit') return { kind: 'ask', reason: `Change the file ${clip(args.file_path ?? args.path, 200)}` };
+ if (tool === 'job_kill') return { kind: 'ask', reason: 'Stop a background task' };
+ if (tool.startsWith('mcp__')) return { kind: 'ask', reason: `Use the connected tool ${tool.split('__').slice(1).join(' / ')}` };
+ return { kind: 'ask', reason: `Use the tool ${tool}` };
+}
+
+export function apply(ctx) {
+ /** The preset a session is really working under: a child follows the chat that started it. */
+ const effectivePreset = (session, depth = 0) => {
+ const parentId = session.header?.parentSession;
+ if (session.header?.origin === 'subagent' && parentId && depth < 6) {
+ const parent = ctx.sessions.get(parentId);
+ if (parent) return effectivePreset(parent, depth + 1);
+ }
+ return ctx.permissionPresets.current(session);
+ };
+
+ ctx.on('tools/pre-execute', async (exec, next) => {
+ const agent = exec.agent;
+ if (!agent || exec.name === 'run_code') return next();
+ let preset;
+ try { preset = effectivePreset(agent.session); } catch { return next(); }
+ if (preset !== MANUAL_PRESET) return next();
+ const gate = manualDecision(exec);
+ if (!gate) return next();
+ // A child's approval policy is pinned to `never` by the Harness; asking is how its request reaches the person.
+ if (agent.session.header?.origin === 'subagent' && ctx.approval.overrideOf(agent.session) !== 'ask') {
+ agent.session.append('approval/policy', { policy: 'ask' });
+ }
+ const downstream = await next();
+ if (downstream.kind !== 'allow') return downstream;
+ return { kind: 'ask', reason: gate.reason, displayReason: { en: gate.reason } };
+ }, { prepend: true });
+
+ // Lets the host prove the gate is live before it starts a Manual turn.
+ ctx.inject(['commands'], (commandCtx) => {
+ commandCtx.commands.register({
+ definitionId: 'strata-gate',
+ name: 'strata-gate',
+ description: 'Reports that the Strata approval gate is active',
+ handler: () => ({ kind: 'success', text: 'strata-gate active' }),
+ });
+ });
+}
diff --git a/apps/host/server/agent/preset.mjs b/apps/host/server/agent/preset.mjs
new file mode 100644
index 000000000..d52052217
--- /dev/null
+++ b/apps/host/server/agent/preset.mjs
@@ -0,0 +1,76 @@
+/**
+ * The agent preset the app's chats run under: the Harness's `standard` preset (pinned 57190202,
+ * packages/bundle/web-app/presets/standard.patch.yml) with the differences the app needs, and nothing else.
+ *
+ * A patch replaces the whole preset row, so the list is restated here. `tests/agent-tools.test.mjs` compares this list
+ * with the pinned Harness's own file (when STRATA_HARNESS_DIR is set), so a Harness update that adds or renames a
+ * plugin fails a test instead of silently dropping a tool.
+ *
+ * Differences from `standard`, each with its reason:
+ * - `tool-schedule` removed: the app has one scheduler (server/tasks.mjs, the Tasks screen); a second set of
+ * reminder tools would run behind its back.
+ * - `web_search` removed (tool-web with `search:false`): every search backend the Harness has needs a service key
+ * the app does not have, so the tool could only fail. `web_fetch` stays. (`searchProvider` can switch it back on.)
+ * - `tool-ask-user` removed: the app has no place to show the agent's own questions, so the tool could only fail;
+ * the agent asks in plain text instead.
+ * - the `planning` group (Harness plan mode and `exit_plan_mode`) removed: the app's Plan mode is the permission
+ * preset (nothing can change); the Harness's plan mode needs an interactive review the app does not have.
+ * - `tool-bash` / `tool-pwsh`: exactly one, by operating system (the Harness chooses the same at load).
+ * - `tool-plugin-manager` stays disabled, as in `standard`.
+ */
+
+/** Plugin ids of the pinned Harness `standard` preset, in its order (the drift check). */
+export const STANDARD_PLUGIN_IDS = [
+ 'persona', 'agent-instructions', 'time-context', 'tool-bash', 'tool-pwsh', 'tool-fs', 'tool-fs-search', 'tool-jobs',
+ 'tool-schedule', 'skill-filesystem', 'tool-skill', 'command-goal', 'tool-goal', 'planning', 'compaction', 'delegation',
+ 'tool-ask-user', 'tool-todo', 'tool-web', 'present', 'tool-plugin-manager',
+];
+/** What we leave out of it. */
+export const REMOVED_PLUGIN_IDS = ['tool-schedule', 'tool-ask-user', 'planning'];
+
+/**
+ * @param {{platform?: string, search?: boolean}} [options]
+ * @returns {object} the `config` of the `preset-standard` row
+ */
+export function standardPreset({ platform = process.platform, search = false } = {}) {
+ const windows = platform === 'win32';
+ const plugins = [
+ { id: 'persona', name: '@deepseek-ai/dsh-persona', config: { prefix: 'You are a coding agent powered by the {{model}} model.' } },
+ { id: 'agent-instructions', name: '@deepseek-ai/dsh-agent-instructions', config: { maxBytes: 65536 } },
+ { id: 'time-context', name: '@deepseek-ai/dsh-time-context' },
+ windows
+ ? { id: 'tool-pwsh', name: '@deepseek-ai/dsh-tool-pwsh' }
+ : { id: 'tool-bash', name: '@deepseek-ai/dsh-tool-bash' },
+ { id: 'tool-fs', name: '@deepseek-ai/dsh-tool-fs' },
+ { id: 'tool-fs-search', name: '@deepseek-ai/dsh-tool-fs-search', config: { sampleOverCapGlobResults: false } },
+ { id: 'tool-jobs', name: '@deepseek-ai/dsh-tool-jobs' },
+ { id: 'skill-filesystem', name: '@deepseek-ai/dsh-skill-filesystem' },
+ { id: 'tool-skill', name: '@deepseek-ai/dsh-tool-skill' },
+ { id: 'command-goal', name: '@deepseek-ai/dsh-command-goal' },
+ { id: 'tool-goal', name: '@deepseek-ai/dsh-tool-goal' },
+ {
+ id: 'compaction', name: 'cordis:group', group: true, isolate: { compaction: true, toolResultPruner: true },
+ config: [
+ { id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic' },
+ { 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 } },
+ ],
+ },
+ {
+ id: 'delegation', name: 'cordis:group', group: true, isolate: { workflowEngine: true },
+ config: [
+ { id: 'tool-subagent-control', name: '@deepseek-ai/dsh-tool-subagent-control' },
+ { id: 'tool-subagent-list-agents', name: '@deepseek-ai/dsh-tool-subagent-control/list-agents' },
+ { id: 'tool-subagent', name: '@deepseek-ai/dsh-tool-subagent', config: { provider: 'spawn', toolName: 'subagent', modelSelectionSettings: true } },
+ { id: 'tool-subagent-fork', name: '@deepseek-ai/dsh-tool-subagent', config: { provider: 'fork', toolName: 'subagent_fork' } },
+ { id: 'workflow-ptc', name: '@deepseek-ai/dsh-workflow-ptc', config: { provider: 'spawn' } },
+ { id: 'tool-workflow', name: '@deepseek-ai/dsh-tool-workflow' },
+ ],
+ },
+ { id: 'tool-todo', name: '@deepseek-ai/dsh-tool-todo', config: { allowParallelInProgress: true } },
+ { id: 'tool-web', name: '@deepseek-ai/dsh-tool-web', config: { fetch: true, search, searchTimeoutMs: 60000 } },
+ { id: 'present', name: '@deepseek-ai/dsh-tool-present' },
+ { id: 'tool-plugin-manager', name: '@deepseek-ai/dsh-plugin-manager/tools', disabled: true },
+ ];
+ return { id: 'standard', order: 1, plugins };
+}
diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs
index 00fe18adf..1a5c585d7 100644
--- a/apps/host/server/agent/profile.mjs
+++ b/apps/host/server/agent/profile.mjs
@@ -18,6 +18,8 @@
* the profile file, a prompt, or a log.
*/
import { createHash } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { standardPreset } from './preset.mjs';
const PROTOCOL = { 'openai-chat': 'openai-completions', 'openai-responses': 'openai-responses', anthropic: 'anthropic-messages' };
@@ -27,19 +29,24 @@ export const ASSUMED_API_CONTEXT = 128_000;
/**
* The three chat modes as Harness permission presets (see README, "Modes"). A preset is a
* sandbox mode plus an approval policy; the Harness switches them with its own `/permission` command.
- * manual read-only sandbox + ask: any change is denied by the sandbox until the user approves a one-shot widening
+ * manual open sandbox + ask: the Strata gate (plugins/strata-gate.mjs) asks BEFORE any change runs; nothing is denied first
* plan read-only sandbox + never: nothing can change, and the agent is told not to ask
* bypass danger-full-access + never: the Harness's own full-access, never-ask bundle (its `danger-full-access` preset)
*/
export const MODE_PRESETS = Object.freeze({
- manual: { key: 'strata-manual', sandbox: 'read-only', approval: 'ask', name: 'Manual', description: 'Asks before changing a file or running a command that changes anything.' },
+ manual: { key: 'strata-manual', sandbox: 'danger-full-access', approval: 'ask', name: 'Manual', description: 'Asks before changing a file or running a command that changes anything.' },
plan: { key: 'strata-plan', sandbox: 'read-only', approval: 'never', name: 'Plan', description: 'Read-only. Nothing is changed and no approval prompts appear.' },
bypass: { key: 'strata-bypass', sandbox: 'danger-full-access', approval: 'never', name: 'Bypass', description: 'Full access without approval prompts. Files and commands anywhere on this computer run without asking.' },
});
export const DEFAULT_MODE = 'manual';
+/** Helper agents running at once when no local engine sets the limit (the Harness's own default). */
+export const DEFAULT_API_HELPERS = 8;
/** The preset for a chat's stored mode. Anything unknown (older values such as `auto`) gets the strictest ask-first mode. */
export const modeOf = value => (Object.hasOwn(MODE_PRESETS, value) ? value : DEFAULT_MODE);
+/** The approval gate plugin (plain ESM, loaded by absolute path). */
+export const GATE_PLUGIN = fileURLToPath(new URL('./plugins/strata-gate.mjs', import.meta.url));
+
const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'x';
/** Identity of one route's wire configuration, secret included by hash only. */
@@ -55,15 +62,17 @@ export function outputBudget(context) {
/**
* @param {object} input
- * @param {Array<{id:string,label?:string,baseUrl:string,modelId:string,context?:number,key?:string,vision?:boolean}>} input.local
+ * @param {Array<{id:string,label?:string,baseUrl:string,modelId:string,context?:number,key?:string,vision?:boolean,slots?:number}>} input.local
* ready local instances; the first is the default route (`strata-local`)
* @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<string,string>, routes:Array, defaultRoute:object|null, signature:string}}
*/
-export function buildProfile({ local = [], connections = [] }) {
+export function buildProfile({ local = [], connections = [], gate = true }) {
const providers = {};
const env = {};
const routes = [];
+ // Helper agents run at most as many at once as the engine has request slots (a local model); API models take the Harness's own limit.
+ let slots = 0;
local.forEach((inst, index) => {
const route = index === 0 ? 'strata-local' : `strata-local-${slug(inst.id)}`;
@@ -83,6 +92,7 @@ export function buildProfile({ local = [], connections = [] }) {
input: inst.vision ? ['text', 'image'] : ['text'],
}],
};
+ 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 });
});
@@ -115,6 +125,11 @@ export function buildProfile({ local = [], connections = [] }) {
{ id: 'llm-pi-ai', name: '@deepseek-ai/dsh-llm-pi-ai', config: { providers } },
// The chat modes. Replacing the table also drops the Harness's own three presets: a chat is always in one of ours.
{ id: 'permission', config: { presets: Object.fromEntries(Object.values(MODE_PRESETS).map(({ key, sandbox, approval, name, description }) => [key, { sandbox, approval, name, description }])), defaultPreset: MODE_PRESETS[DEFAULT_MODE].key } },
+ { id: 'subagent', config: { maxActiveSubagents: slots > 0 ? slots : DEFAULT_API_HELPERS } },
+ // Manual asks before a change runs, so the person sees one Approve/Deny card and nothing has happened yet.
+ ...(gate ? [{ insert: [{ id: 'strata-gate', name: GATE_PLUGIN }] }] : []),
+ // The reminder tools would be a second scheduler beside the app's Tasks; web search needs a search-service key the app has none of.
+ { id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset() },
// 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/server/index.mjs b/apps/host/server/index.mjs
index ebd1313e7..4c0302ca6 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -87,9 +87,13 @@ const native=createNativeControl({control,directory:store.DATA_DIR,modelsDirecto
const agent = createAgentBridge({
dataDir: store.DATA_DIR,
componentsDir: process.env.STRATA_COMPONENTS_DIR ?? null,
+ // The installer ships the Harness next to the host (<install>/host/server -> <install>/harness).
+ bundledDir: resolve(HERE, '..', '..', 'harness'),
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,
+ // The engine's request slots: helper agents never outnumber them.
+ slots: i.metrics?.live?.slots?.length || i.parallel || 1,
})),
connections: () => modelProviders.withSecrets(),
log: line => console.log(line),
@@ -470,11 +474,14 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI
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, mode: typeof body.mode === 'string' ? body.mode : null, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal });
+ // "/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 turnOptions = { chatId, message, workspacePath: cwd, choice, mode: typeof body.mode === 'string' ? body.mode : null, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal };
+ const result = 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));
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' });
+ write({ type: 'error', message: err.message, ...(err.details ? { details: err.details } : {}), code: err.code ?? 'AGENT_ERROR' });
settle(null, err.message);
}
}
@@ -1404,7 +1411,7 @@ async function api(req, res, path, method, url) {
res.end();
return undefined;
}
- res.write(`${JSON.stringify({ type: 'notice', code: 'agent-unavailable', message: `${capability.reason} Chat is running without tools.` })}\n`);
+ res.write(`${JSON.stringify({ type: 'notice', code: 'agent-unavailable', message: `${capability.reason}`, ...(capability.detail ? { details: capability.detail } : {}) })}\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`);
}
diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs
index 0b7c7c5ab..009db8165 100644
--- a/apps/host/server/native-control.mjs
+++ b/apps/host/server/native-control.mjs
@@ -1,5 +1,6 @@
/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */
import { spawn } from 'node:child_process';
+import {chooseParallel,applyParallel,withoutParallel,FALLBACK_NOTE} from './native-parallel.mjs';
import { randomBytes, randomUUID, createHash } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';
import { join, resolve, dirname, basename } from 'node:path';
@@ -99,6 +100,10 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}
if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};
for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.');
+ /* Installed app: several requests at once by default (4, fewer where the card has no room), unless a number was chosen. */
+ const parallelChoice=packaged?chooseParallel({config:cfg,values:args.values??{},hardware:snapshot.hardware}):null;
+ let parallelNote=null;
+ if(parallelChoice){const applied=applyParallel(cfg,parallelChoice);for(const k of Object.keys(cfg))if(!(k in applied.cfg))delete cfg[k];Object.assign(cfg,applied.cfg);parallelNote=applied.note;}
const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex');
const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement));
if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id};
@@ -113,13 +118,19 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);
if(job.state!=='running')return;
writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});
- const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};
+ const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',parallel:cfg.parallel??1,key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};
let proc=null,started=null;
if(packaged){
/* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */
const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot;
instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();
- started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300}));
+ started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})).catch(async error=>{
+ if(!(cfg.parallel>1)||parallelChoice?.explicit||job.state!=='running')throw error;
+ append(id,'Loading with several requests at once failed; trying again with one: '+error.message);
+ Object.keys(cfg).forEach(k=>delete cfg[k]);Object.assign(cfg,withoutParallel(JSON.parse(readFileSync(configPath,'utf8'))));
+ writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});parallelNote=FALLBACK_NOTE;instance.parallel=1;
+ await control.stop(instance.profile).catch(()=>{});await control.saveProfile(instance.profile,configPath);await control.start(instance.profile,{waitSeconds:300});
+ });
started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});
try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;}
} else {
@@ -130,7 +141,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
}
const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){
if(instance.status==='error')throw new Error(instance.error);
- try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();return {summary:`${instance.label} is ready.`,instanceId:id};}}catch{}
+ try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();instance.parallelNote=parallelNote;return {summary:`${instance.label} is ready.${parallelNote?' '+parallelNote:''}`,instanceId:id};}}catch{}
await new Promise(resolve=>setTimeout(resolve,1200));
}
if(job.state!=='running'){await unload(id);return;}
diff --git a/apps/host/server/native-parallel.mjs b/apps/host/server/native-parallel.mjs
new file mode 100644
index 000000000..0275e51c4
--- /dev/null
+++ b/apps/host/server/native-parallel.mjs
@@ -0,0 +1,111 @@
+/**
+ * Several requests at once (the engine's batch slots) for the installed app.
+ *
+ * The app is for people who run a chat, a helper agent and a second chat side by side, so a model loads with
+ * 4 request slots by default instead of making them queue. Two engine facts decide how far that can go:
+ *
+ * - Every slot keeps its OWN conversation state in graphics memory at the model's full context
+ * (docs/BATCHING.md, "What a slot costs"): the context is per slot, so 4 slots cost 4 times one slot.
+ * - Without `--batch-mtp` the slots decode WITHOUT the draft layer. With it, each slot verifies one draft per window
+ * (docs/BATCHING.md), at the price of a little more memory per slot. A request that runs alone still takes the
+ * engine's solo path, so a single chat is not slower for having slots.
+ *
+ * Recommend, never force: a number the person sets (Expert mode, or a value already in the model's saved settings)
+ * is kept exactly. The default only fills in what nobody chose. If the card has no room for 4 it is fewer, and the
+ * person is told in plain words; a load that fails with several slots is tried again with one before it is reported.
+ *
+ * The engine does the final fitting itself ("it never refuses a count it cannot run": it logs what it could do).
+ * This module keeps the request realistic so the expert cache is not squeezed for a count that could not run.
+ */
+
+export const DEFAULT_SLOTS = 4;
+/** The most the engine's batch window holds without grouped MTP. */
+export const MAX_SLOTS = 8;
+/**
+ * THE one-line policy.
+ * 'fit' the default aims for 4 and takes fewer where the slots would take more than SLOT_SHARE of the card's memory
+ * (measured on a 12 GB RTX 3060, 32K: 4 slots took 3.7 GiB, left 0.35 GiB free and cost a single chat 37%)
+ * 'fixed' the default is always DEFAULT_SLOTS, whatever the card (the engine still fits what it can)
+ */
+export const PARALLEL_POLICY = 'fit';
+/** Share of ALL the graphics memory the slots' sessions may take together under the 'fit' policy. */
+export const SLOT_SHARE = 0.2;
+
+const argValue = (args, flag) => { const at = args.indexOf(flag); return at >= 0 ? args[at + 1] : undefined; };
+
+/** Graphics memory (GB) one slot's session takes at `context` tokens. Flash-Next: 12 attention layers; Qwen3.6: 45 KB per token. */
+export function slotGb({ context, kv = 'int8', family = 'flash' }) {
+ const ctx = Number(context) > 0 ? Number(context) : 32768;
+ if (family === 'q36') return (ctx * 45_000) / 1e9 + 0.07;
+ return (ctx * 12 * (kv === 'q4_0' ? 1150 : 2100)) / 1e9 + 0.17; // measured on the 0.1.45 engine: 0.92 GiB per slot at 32K
+}
+
+/** What the saved settings say about the engine, read from the config (never from the screen). */
+export function engineFacts(config = {}) {
+ const args = Array.isArray(config.args) ? config.args.map(String) : [];
+ const context = Number(argValue(args, '--max-context') ?? argValue(args, '--context') ?? config.max_context ?? config.context) || null;
+ const kv = /q4/i.test(argValue(args, '--kv') ?? argValue(args, '--kv-type') ?? '') ? 'q4_0' : 'int8';
+ const family = /qwen3\.6|qwen36|35b-a3b/i.test(`${config.model_name ?? ''} ${args.join(' ')}`) ? 'q36' : 'flash';
+ const gpus = Array.isArray(config.gpu) ? config.gpu : config.gpu === undefined || config.gpu === null ? [0] : [config.gpu];
+ return {
+ args, context, kv, family, gpus,
+ mtp: args.includes('--mtp'),
+ batchMtp: args.includes('--batch-mtp'),
+ explicitBatch: args.includes('--batch') || args.includes('--slots'),
+ };
+}
+
+/**
+ * @param {object} input
+ * @param {object} input.config the model's saved settings (args, gpu, parallel, ...)
+ * @param {object} [input.values] what the person set for this load (Expert mode's "Concurrent requests")
+ * @param {object} [input.hardware] the host's hardware read (`gpus[{index, vram_gb}]`)
+ * @param {number} [input.requested] the default to aim for
+ * @returns {{slots:number, batchMtp:boolean, explicit:boolean, requested:number, note:string|null, slotGb:number}}
+ */
+export function chooseParallel({ config = {}, values = {}, hardware = null, requested = DEFAULT_SLOTS }) {
+ const facts = engineFacts(config);
+ const slot = slotGb({ context: facts.context, kv: facts.kv, family: facts.family });
+ const chosen = values.parallel !== undefined && values.parallel !== null ? Number(values.parallel)
+ : config.parallel !== undefined && config.parallel !== null ? Number(config.parallel) : null;
+ // A number someone chose (including 1) is the person's decision, and so is an explicit --batch in the engine arguments.
+ if (facts.explicitBatch || (chosen !== null && Number.isFinite(chosen))) {
+ const slots = facts.explicitBatch ? null : Math.max(1, Math.min(1024, Math.trunc(chosen)));
+ return { slots: slots ?? 0, batchMtp: false, explicit: true, requested, note: null, slotGb: slot };
+ }
+ const cards = (hardware?.gpus ?? []).filter(g => facts.gpus.includes(g.index)).map(g => Number(g.vram_gb)).filter(n => Number.isFinite(n) && n > 0);
+ // Without a hardware read the engine's own fitting is all there is: ask for the default and let it say what it can run.
+ if (!cards.length) return { slots: requested, batchMtp: facts.mtp && facts.gpus.length === 1, explicit: false, requested, note: null, slotGb: slot };
+ const total = cards.reduce((a, b) => a + b, 0);
+ let slots = requested;
+ if (PARALLEL_POLICY === 'fit') while (slots > 1 && slots * slot > SLOT_SHARE * total) slots -= 1;
+ const note = slots < requested
+ ? (slots > 1
+ ? `Your graphics card has room for ${slots} requests at once with this context size, so Strata set that. A smaller context size leaves room for more.`
+ : 'Your graphics card has no spare room for several requests at once with this context size, so Strata set it to one at a time. A smaller context size leaves room for more.')
+ : null;
+ return { slots, batchMtp: slots > 1 && facts.mtp && !facts.batchMtp && facts.gpus.length === 1, explicit: false, requested, note, slotGb: slot };
+}
+
+/**
+ * Apply a choice to the run configuration that is about to be saved. Never touches a number the person chose.
+ * Returns the configuration and the plain-words note (or null).
+ */
+export function applyParallel(cfg, choice) {
+ if (choice.explicit) return { cfg, note: null };
+ const next = { ...cfg };
+ if (choice.slots > 1) next.parallel = choice.slots; else delete next.parallel;
+ if (choice.batchMtp) next.args = [...(next.args ?? []), '--batch-mtp'];
+ return { cfg: next, note: choice.note };
+}
+
+/** The same configuration with one request at a time, for the second try after a load that failed with several. */
+export function withoutParallel(cfg) {
+ const next = { ...cfg };
+ delete next.parallel;
+ next.args = (next.args ?? []).filter(a => a !== '--batch-mtp');
+ return next;
+}
+
+/** What to say when the second try worked. */
+export const FALLBACK_NOTE = 'The model could not start with several requests at once on this PC, so Strata loaded it for one request at a time. Everything still works; helper agents and a second chat wait their turn.';
diff --git a/apps/host/tests/agent-bridge.test.mjs b/apps/host/tests/agent-bridge.test.mjs
index 2ebb5d7a2..b724983d3 100644
--- a/apps/host/tests/agent-bridge.test.mjs
+++ b/apps/host/tests/agent-bridge.test.mjs
@@ -180,7 +180,7 @@ test('A08 two chats run independently, each with its own session and approval',
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 assert.rejects(r.bridge.approve({ chatId: 'chat-a08-b', callId, decision: 'approve' }), /no longer waiting/);
await r.bridge.approve({ chatId: 'chat-a08-a', callId, decision: 'approve' });
await a.promise;
assert.equal(states(a.frames).at(-1), 'done');
@@ -191,7 +191,7 @@ 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 assert.rejects(r.run('chat-busy', 'SCRIPT:hello').promise, /still working/);
await first.promise;
});
diff --git a/apps/host/tests/agent-children.test.mjs b/apps/host/tests/agent-children.test.mjs
new file mode 100644
index 000000000..7dc21a97e
--- /dev/null
+++ b/apps/host/tests/agent-children.test.mjs
@@ -0,0 +1,198 @@
+/**
+ * Helper agents (the Harness's subagents) in the chat: rows, concurrency, one approval card, Stop, and /goal.
+ *
+ * Pure tests always run; the rest need a built Harness (STRATA_HARNESS_DIR) and skip loudly without it.
+ * The model is scripted; the Harness, its subagent runtime, its approval service, the gate and the bridge are real.
+ */
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { startScriptedWorker } from './helpers/scripted-worker.mjs';
+import { createAgentBridge, plainBlocker, goalEnding, plainGoalError } from '../server/agent/agent-bridge.mjs';
+import { resolveHarness } from '../server/agent/harness-runtime.mjs';
+import { ChildProjector, activityOf } from '../server/agent/children.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 cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
+const fwd = p => p.replaceAll('\\', '/');
+
+// ---------------------------------------------------------------------------------------------------------- pure
+
+const ev = (type, data, extra = {}) => ({ type: 'event', event: { seq: 1, time: extra.time ?? 1000, type, data } });
+
+test('a helper row follows its helper: queued, working, completed with its closing words, tokens counted', () => {
+ let t = 0;
+ const cp = new ChildProjector({ id: 'c1', name: 'Check the tests', task: 'Run the unit tests and report', now: () => (t += 100) });
+ assert.equal(cp.agent().status, 'queued');
+ assert.equal(cp.agent().description, 'Run the unit tests and report');
+ cp.consume(ev('step/start', { turn: 1, step: 1 }));
+ assert.equal(cp.agent().status, 'working');
+ cp.consume({ type: 'assistant-stream', frame: { type: 'chunk', chunk: { type: 'usage', usage: { inputTokens: 100, outputTokens: 20 } } } });
+ assert.equal(cp.agent().tokens, 120);
+ cp.consume(ev('assistant/message', { message: { content: [{ type: 'text', text: 'All 12 tests pass.' }] } }));
+ cp.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } }));
+ const row = cp.agent();
+ assert.equal(row.status, 'completed'); assert.equal(row.description, 'All 12 tests pass.');
+ assert.ok(row.durationMs > 0);
+ assert.ok(['id', 'name', 'description', 'status', 'durationMs', 'tokens', 'updatedAt'].every(k => k in row), 'exactly the fields the existing rows read');
+});
+
+test('a helper that failed or was stopped says so in plain words', () => {
+ const failed = new ChildProjector({ id: 'f', name: 'A' });
+ failed.consume(ev('step/start', {}));
+ failed.consume(ev('turn/end', { reason: { kind: 'error', error: { message: 'fetch failed: ECONNREFUSED' } } }));
+ assert.equal(failed.agent().status, 'failed'); assert.match(failed.agent().description, /not reachable/);
+ const stopped = new ChildProjector({ id: 's', name: 'B' });
+ stopped.consume(ev('turn/end', { reason: { kind: 'aborted' } }));
+ assert.deepEqual([stopped.agent().status, stopped.agent().description], ['cancelled', 'Stopped.']);
+});
+
+test('only a helper request that needs the person becomes a card, and its id names the helper', () => {
+ const cp = new ChildProjector({ id: 'child-1', name: 'Writer' });
+ assert.deepEqual(cp.consume(ev('tool/call', { callId: 'k1', name: 'read', arguments: '{"file_path":"a"}' })).frames, [], 'a read is not a card');
+ cp.consume(ev('tool/result', { message: { toolCallId: 'k1', content: [{ type: 'text', text: 'x' }] } }));
+ cp.consume(ev('tool/call', { callId: 'k2', name: 'write', arguments: '{"file_path":"C:/a.txt","content":"x"}' }));
+ const asked = cp.consume(ev('approval/asked', { id: 'a1', callId: 'k2', reason: 'Create or replace the file C:/a.txt' })).frames[0].tool;
+ assert.equal(asked.id, 'child-1:k2'); assert.equal(asked.state, 'proposed'); assert.match(asked.effect, /^Writer asks: Create or replace the file/);
+ assert.equal(cp.consume(ev('approval/decided', { id: 'a1', outcome: 'rejected' })).frames[0].tool.result, 'Denied. Nothing ran.');
+ const done = cp.consume(ev('tool/result', { message: { toolCallId: 'k2', isError: true, content: [{ type: 'text', text: 'Error: the user rejected tool "write"' } ] } })).frames[0].tool;
+ assert.equal(done.state, 'denied'); assert.equal(done.result, 'Denied. Nothing ran.');
+ assert.equal(activityOf('pwsh'), 'Running a command');
+});
+
+test('goal wording: plain, never a code', () => {
+ assert.match(plainBlocker({ code: 'round-limit' }), /most steps/);
+ assert.match(goalEnding({ phase: 'complete' }), /complete/);
+ assert.match(plainGoalError(new Error('goal "x" is not finished; an unfinished goal must be edited')), /already has a goal/);
+ assert.doesNotMatch(plainGoalError(new Error('boom')), /boom/);
+});
+
+// ------------------------------------------------------------------------------------------------- real Harness
+
+async function rig(t, { slots = 4 } = {}) {
+ const worker = await startScriptedWorker({});
+ const dir = mkdtempSync(join(tmpdir(), 'strata-kids-'));
+ const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
+ const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }];
+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
+ t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
+ const run = async (chatId, message, { mode = 'bypass', answer, onFrame, goal } = {}) => {
+ const frames = [];
+ const on = f => {
+ frames.push({ ...f, at: Date.now() }); onFrame?.(f);
+ if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message }));
+ };
+ const result = goal ? await bridge.runTurn({ chatId, workspacePath: ws, mode, goal, onFrame: on }) : await bridge.runTurn({ chatId, message, workspacePath: ws, mode, onFrame: on });
+ return { frames, result };
+ };
+ return { worker, bridge, dir, ws, run };
+}
+const rows = frames => { const m = new Map(); for (const f of frames.filter(x => x.type === 'agent')) m.set(f.agent.id, [...(m.get(f.agent.id) ?? []), f.agent]); return m; };
+const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
+
+test('two helpers run at the same time as two rows, the run ends when both have reported, and the delegation tool shows no raw card', { skip }, async (t) => {
+ const r = await rig(t);
+ const { frames } = await r.run('kids', 'SCRIPT:spawn 2 slow 40');
+ const byId = rows(frames);
+ assert.equal(byId.size, 2);
+ const names = [...byId.values()].map(history => history.at(-1).name).sort();
+ assert.deepEqual(names, ['Helper 1', 'Helper 2']);
+ for (const history of byId.values()) {
+ assert.ok(history.some(a => a.status === 'working'), 'it worked');
+ assert.equal(history.at(-1).status, 'completed');
+ assert.ok(history.at(-1).tokens > 0 && history.at(-1).durationMs > 0);
+ assert.match(history[1]?.description ?? history[0].description, /SCRIPT:slow 40/, 'the row names its task');
+ }
+ // concurrent: both were working before either finished
+ const firstDone = Math.min(...frames.filter(f => f.type === 'agent' && f.agent.status === 'completed').map(f => f.at));
+ const bothWorking = [...byId.values()].every(history => history.some(a => a.status === 'working'));
+ assert.ok(bothWorking && frames.filter(f => f.type === 'agent' && f.agent.status === 'working').every(f => f.at < firstDone + 50));
+ assert.equal(frames.filter(f => f.type === 'agent-tool').length, 0, 'no card for the delegation tool itself');
+ assert.match(text(frames), /Noted/, 'the parent answered after the helpers reported back');
+ assert.equal(frames.at(-1).type, 'done');
+ assert.ok(frames.at(-1).at >= Math.max(...frames.filter(f => f.type === 'agent' && f.agent.status === 'completed').map(f => f.at)), 'done comes after the last helper');
+ assert.equal(r.bridge.isRunning('kids'), false);
+ assert.equal(r.worker.requests.filter(q => q.directive === 'slow').length, 2);
+});
+
+test('helpers never outnumber the engine slots', { skip }, async (t) => {
+ const r = await rig(t, { slots: 2 });
+ const { frames } = await r.run('few', 'SCRIPT:spawn 3 slow 30');
+ assert.equal(rows(frames).size, 2, 'the third was refused by the Harness limit, which matches the slot count');
+});
+
+test('Manual: a helper that wants to change a file reaches the person as the same single Approve card, and the answer is honoured', { skip }, async (t) => {
+ const r = await rig(t);
+ const approved = join(r.ws, 'from-helper.txt'), denied = join(r.ws, 'denied.txt');
+ const ok = await r.run('kid-ok', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(approved), content: 'by helper' })}`, { mode: 'manual', answer: 'approve' });
+ const okCards = ok.frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
+ assert.deepEqual([...new Set(okCards.map(c => c.state))], ['proposed', 'running', 'done']);
+ assert.equal(new Set(okCards.map(c => c.id)).size, 1); assert.match(okCards[0].id, /^[0-9a-f-]{36}:/);
+ assert.match(okCards[0].effect, /^Helper 1 asks: Create or replace the file/);
+ assert.equal(readFileSync(approved, 'utf8').trim(), 'by helper');
+ const no = await r.run('kid-no', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(denied), content: 'x' })}`, { mode: 'manual', answer: 'deny' });
+ assert.equal(existsSync(denied), false);
+ assert.equal(no.frames.filter(f => f.type === 'agent-tool').at(-1).tool.state, 'denied');
+ assert.equal(no.frames.filter(f => f.type === 'agent-tool').at(-1).tool.result, 'Denied. Nothing ran.');
+ assert.equal(rows(no.frames).size, 1);
+});
+
+test("a chat cannot answer another chat's helper question", { skip }, async (t) => {
+ const r = await rig(t);
+ let asked = null;
+ const file = join(r.ws, 'x.txt');
+ const run = r.run('owner', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(file), content: 'x' })}`, { mode: 'manual', onFrame: f => { if (f.type === 'agent-tool' && f.tool.state === 'proposed') asked = f.tool; } });
+ for (let i = 0; i < 200 && !asked; i++) await new Promise(res => setTimeout(res, 50));
+ assert.ok(asked, 'the question reached the person');
+ await assert.rejects(r.bridge.approve({ chatId: 'someone-else', callId: asked.id, decision: 'approve' }), /no longer waiting/);
+ assert.equal(r.bridge.pendingFor('owner').length, 1);
+ await r.bridge.approve({ chatId: 'owner', callId: asked.id, decision: 'deny' });
+ await run;
+ assert.equal(existsSync(file), false);
+});
+
+test('Stop on the chat stops its helpers, ends the run quickly and starts no further turn', { skip }, async (t) => {
+ const r = await rig(t);
+ const started = Date.now();
+ let stopped = null;
+ const { frames } = await r.run('stopper', 'SCRIPT:spawn 2 slow 400', { onFrame: f => {
+ if (f.type === 'agent' && f.agent.status === 'working' && !stopped) stopped = new Promise(res => setTimeout(res, 300)).then(() => r.bridge.stop('stopper'));
+ } });
+ const result = await stopped;
+ assert.equal(result.stopped, true);
+ const final = [...rows(frames).values()].map(h => h.at(-1).status);
+ assert.deepEqual(final, ['cancelled', 'cancelled']);
+ assert.ok(Date.now() - started < 12_000, 'seconds, not the 16 s the helpers would have taken');
+ const done = frames.at(-1);
+ assert.equal(done.type, 'done'); assert.equal(done.cancelled, true);
+ assert.equal(r.bridge.isRunning('stopper'), false);
+ assert.ok(!/Noted/.test(text(frames)), 'the parent was not woken to comment on stopped helpers');
+});
+
+test('/goal: sets a goal, runs its rounds in the chat, says how it ended, refuses a second unfinished goal, and Stop pauses it', { skip }, async (t) => {
+ const r = await rig(t);
+ const frames = [];
+ const say = line => { const out = []; return r.bridge.goalCommand({ chatId: 'g', line, workspacePath: r.ws, mode: 'bypass', onFrame: f => { out.push(f); frames.push(f); } }).then(() => out); };
+ assert.match(text(await say('')), /No goal is set/);
+ const ran = await r.run('g', null, { goal: { action: 'create', objective: 'say hello a few times', maxRounds: 3 } });
+ assert.match(text(ran.frames), /Working on the goal, step 1[\s\S]*step 2[\s\S]*step 3/);
+ assert.match(text(ran.frames), /The goal stopped: it worked for the most steps/);
+ assert.equal(ran.frames.at(-1).type, 'done');
+ assert.match(text(await say('')), /stopped/);
+ assert.match((await say('a different goal')).find(f => f.type === 'error').message, /already has a goal/);
+ assert.match(text(await say('clear')), /cleared/);
+ // a long goal is paused by Stop, and can be resumed
+ const slowGoal = r.run('g2', null, { goal: { action: 'create', objective: 'keep going', maxRounds: 50 } });
+ r.worker.requests.length = 0;
+ await new Promise(res => setTimeout(res, 3500));
+ const stop = await r.bridge.stop('g2');
+ assert.equal(stop.stopped, true);
+ await slowGoal;
+ const before = r.worker.requests.length;
+ await new Promise(res => setTimeout(res, 1500));
+ assert.equal(r.worker.requests.length, before, 'no further round starts after Stop');
+ assert.match(text(await r.bridge.goalCommand({ chatId: 'g2', line: '', workspacePath: r.ws, mode: 'bypass', onFrame: f => frames.push(f) }).then(() => frames.filter(f => f.type === 'delta').slice(-1))), /paused/);
+});
diff --git a/apps/host/tests/agent-host.test.mjs b/apps/host/tests/agent-host.test.mjs
index 7335f89fd..f4f797783 100644
--- a/apps/host/tests/agent-host.test.mjs
+++ b/apps/host/tests/agent-host.test.mjs
@@ -191,7 +191,7 @@ test('A08 over HTTP: two chats stream at the same time without mixing', { skip }
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);
+ assert.equal(status.state, 'unavailable'); assert.match(status.reason, /coding assistant/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/);
diff --git a/apps/host/tests/agent-modes.test.mjs b/apps/host/tests/agent-modes.test.mjs
index 455cf4003..2edbabe87 100644
--- a/apps/host/tests/agent-modes.test.mjs
+++ b/apps/host/tests/agent-modes.test.mjs
@@ -56,18 +56,20 @@ async function rig(t) {
return { worker, bridge, dir, ws, run, preset };
}
-test('mode mapping: three presets, the strictest by default, unknown values fall back to Manual', () => {
+test('mode mapping: three presets, Manual by default, unknown values fall back to Manual', () => {
assert.deepEqual(Object.keys(MODE_PRESETS), ['manual', 'plan', 'bypass']);
- assert.deepEqual([MODE_PRESETS.manual.sandbox, MODE_PRESETS.manual.approval], ['read-only', 'ask']);
+ // Manual leaves the sandbox open and asks BEFORE a change through the Strata gate (plugins/strata-gate.mjs).
+ assert.deepEqual([MODE_PRESETS.manual.sandbox, MODE_PRESETS.manual.approval], ['danger-full-access', 'ask']);
assert.deepEqual([MODE_PRESETS.plan.sandbox, MODE_PRESETS.plan.approval], ['read-only', 'never']);
assert.deepEqual([MODE_PRESETS.bypass.sandbox, MODE_PRESETS.bypass.approval], ['danger-full-access', 'never']);
for (const v of ['manual', 'plan', 'bypass']) assert.equal(modeOf(v), v);
for (const v of [undefined, null, '', 'auto', 'accept-edits', 'danger-full-access', 'constructor']) assert.equal(modeOf(v), 'manual', String(v));
- // Only Bypass gives full access, and the profile names our three and nothing else.
+ // Only Bypass gives full access WITHOUT asking, and the profile names our three and nothing else.
const entry = JSON.parse(buildProfile({ local: [] }).patch.split('\n').slice(1).join('\n')).find(e => e.id === 'permission');
assert.deepEqual(Object.keys(entry.config.presets), ['strata-manual', 'strata-plan', 'strata-bypass']);
assert.equal(entry.config.defaultPreset, 'strata-manual');
- assert.deepEqual(Object.entries(entry.config.presets).filter(([, p]) => p.sandbox === 'danger-full-access').map(([k]) => k), ['strata-bypass']);
+ assert.deepEqual(Object.entries(entry.config.presets).filter(([, p]) => p.sandbox === 'danger-full-access' && p.approval === 'never').map(([k]) => k), ['strata-bypass']);
+ assert.deepEqual(Object.entries(entry.config.presets).filter(([, p]) => p.sandbox !== 'danger-full-access').map(([k]) => k), ['strata-plan']);
});
test('projection: under "never" no card ever offers Approve; "ask" marks the approved card', () => {
@@ -209,7 +211,7 @@ test('MODE changing the mode while a turn runs does not touch that turn', { skip
assert.ok(frames.filter(f => f.type === 'delta').length >= 3, 'the turn must be live first');
// The person flips the menu to Bypass and sends again. The second send is refused (a chat runs one turn at a time) and,
// because it is refused before anything is applied, the running turn's permissions do not move.
- await assert.rejects(r.bridge.runTurn({ chatId: 'm-mid', message: 'SCRIPT:echo x', workspacePath: r.ws, mode: 'bypass', onFrame: () => {} }), /already running a turn/);
+ await assert.rejects(r.bridge.runTurn({ chatId: 'm-mid', message: 'SCRIPT:echo x', workspacePath: r.ws, mode: 'bypass', onFrame: () => {} }), /still working/);
assert.equal(await r.preset('m-mid'), MODE_PRESETS.manual.key);
// Another chat in another mode is its own session and does not move this one either.
await r.run('m-mid-other', 'SCRIPT:echo y', { mode: 'bypass' });
diff --git a/apps/host/tests/agent-tools.test.mjs b/apps/host/tests/agent-tools.test.mjs
new file mode 100644
index 000000000..88a920d0e
--- /dev/null
+++ b/apps/host/tests/agent-tools.test.mjs
@@ -0,0 +1,188 @@
+/**
+ * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card.
+ *
+ * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness
+ * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is
+ * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge.
+ */
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } 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, GATE_PLUGIN } from '../server/agent/profile.mjs';
+import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs';
+import { isReadOnlyShell, manualDecision, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs';
+import { plainToolError, withPlain } from '../server/agent/events.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 cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } };
+const fwd = p => p.replaceAll('\\', '/');
+
+// ---------------------------------------------------------------------------------------------------------- pure
+
+test('the gate: only commands that provably just look are allowed without a question', () => {
+ for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) {
+ assert.equal(isReadOnlyShell(ok), true, ok);
+ }
+ for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) {
+ assert.equal(isReadOnlyShell(bad), false, bad);
+ }
+ assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted');
+});
+
+test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => {
+ for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name);
+ for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name);
+ assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null);
+ assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/);
+ assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/);
+ assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command');
+});
+
+test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => {
+ const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id);
+ assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash'));
+ assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh'));
+ const web = standardPreset().plugins.find(p => p.id === 'tool-web').config;
+ assert.equal(web.fetch, true); assert.equal(web.search, false);
+ assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true, 'a search key can switch it back on');
+ assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler');
+});
+
+test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => {
+ const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 3, key: 'sekret-key-123' }] });
+ const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n'));
+ assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN }]);
+ assert.ok(existsSync(GATE_PLUGIN));
+ assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 3);
+ assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false);
+ assert.ok(!p.patch.includes('sekret-key-123'));
+ const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] });
+ assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit');
+});
+
+test('tool failures are said in plain words with the original text kept after them', () => {
+ assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/);
+ assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/);
+ assert.equal(plainToolError('something unusual'), null);
+ const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid');
+ assert.match(text, /^That web page could not be opened/);
+ assert.match(text, /Details: web fetch failed/);
+});
+
+// ------------------------------------------------------------------------------------------------- real Harness
+
+async function rig(t) {
+ const worker = await startScriptedWorker({});
+ const dir = mkdtempSync(join(tmpdir(), 'strata-tools-'));
+ const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
+ const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }];
+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
+ t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
+ const run = async (chatId, message, { mode = 'bypass', answer } = {}) => {
+ const frames = [];
+ await bridge.runTurn({
+ chatId, message, workspacePath: ws, mode,
+ onFrame: f => {
+ frames.push(f);
+ if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message }));
+ },
+ });
+ return frames;
+ };
+ const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options);
+ return { worker, bridge, dir, ws, run, call };
+}
+const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
+const last = frames => cards(frames).at(-1);
+
+test('the agent is offered exactly these tools: everything useful, no scheduler, no search without a key, no unanswerable question', { skip }, async (t) => {
+ const r = await rig(t);
+ await r.run('inv', 'SCRIPT:echo hi');
+ const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort();
+ assert.deepEqual(offered, ['create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'workflow', 'working_directory', 'write'].sort());
+ assert.ok(!offered.some(n => n.startsWith('schedule_')) && !offered.includes('web_search') && !offered.includes('ask_user_question') && !offered.includes('exit_plan_mode'));
+});
+
+test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => {
+ const r = await rig(t);
+ const file = join(r.ws, 'notes.txt');
+ writeFileSync(file, 'alpha\nneedle here\nomega\n');
+ const f = fwd(file);
+ // read-only family
+ assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/);
+ assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/);
+ assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/);
+ assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done');
+ assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done');
+ // plan / goal / list family
+ assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done');
+ const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' }));
+ assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.');
+ // write family (Bypass: no card asks)
+ const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' });
+ assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made');
+ await r.call('fam-fs', 'read', { file_path: f });
+ const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' });
+ assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/);
+ // shell family
+ assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/);
+ // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it
+ const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' }));
+ assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /);
+ assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/');
+ // no card shows raw JSON as its explanation
+ for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{'));
+});
+
+test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => {
+ const r = await rig(t);
+ const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt');
+ // approve a file write
+ let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' });
+ assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']);
+ assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place');
+ assert.equal(readFileSync(a, 'utf8').trim(), 'hello');
+ // deny a file write
+ frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' });
+ assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']);
+ assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error');
+ assert.equal(existsSync(b), false);
+ // a shell command that changes things
+ frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' });
+ assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']);
+ assert.ok(existsSync(c));
+ // a shell command that only looks needs no question
+ frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' });
+ assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']);
+ // nowhere in any of it does the person see the sandbox talking
+ const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]);
+ assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300));
+});
+
+test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => {
+ const r = await rig(t);
+ const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt');
+ const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' });
+ assert.equal(existsSync(p), false);
+ assert.ok(!cards(planned).some(x => x.state === 'proposed'));
+ const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' });
+ assert.equal(existsSync(q), true);
+ assert.ok(!cards(free).some(x => x.state === 'proposed'));
+});
+
+test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => {
+ // A Harness started without the gate plugin (the bridge's `gate: false`).
+ const worker = await startScriptedWorker({});
+ const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-'));
+ mkdirSync(join(dir, 'ws'), { recursive: true });
+ const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }];
+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 });
+ t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
+ await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message));
+});
diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs
index fbda13a8b..076780705 100644
--- a/apps/host/tests/helpers/scripted-worker.mjs
+++ b/apps/host/tests/helpers/scripted-worker.mjs
@@ -21,6 +21,9 @@
* an escalation, retry once with `sandbox_permissions: workspace-write`
* SCRIPT:retryshell <file> <text> the same with the shell tool (an in-workspace append)
* SCRIPT:read <file> the `read` tool on <file>
+ * SCRIPT:spawn <n> <script...> n `subagent` calls in one reply; each child's prompt is SCRIPT:<script...>. When a child's
+ * completion notice wakes the parent, it answers with a short text quoting the notice.
+ * SCRIPT:call <tool> <json> one call to any tool with the given JSON arguments
*
* A request whose last message is a tool result is answered with a text that quotes the result.
*/
@@ -104,7 +107,7 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
// 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') {
- const n = Number(args) || 400;
+ const n = parseInt(args, 10) || 400;
return say(Array.from({ length: n }, (_, i) => `w${i} `));
}
if (name === 'echo') return say([args]);
@@ -117,6 +120,30 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
: toolCall(shellName(), { command: shellCommand(file, value), description: `Append one line to ${file}` });
}
if (name === 'read') return toolCall('read', { file_path: args });
+ if (name === 'call') {
+ // This prompt's one call already ran (the Harness may add a context message after its result): answer, never call twice.
+ if (toolMessages.length) return say(['Tool finished. ', `Result: ${text(toolMessages[toolMessages.length - 1]).replace(/\s+/g, ' ').slice(0, 120)}`]);
+ const at = args.indexOf(' ');
+ let callArgs = {};
+ try { callArgs = JSON.parse(at < 0 ? '{}' : args.slice(at + 1).replace(/\s+#\d+.*$/, '')); } catch { /* an unparsable script argument is a test bug; send no arguments */ }
+ return toolCall(at < 0 ? args : args.slice(0, at), callArgs);
+ }
+ if (name === 'spawn') {
+ // A settlement notice (or any later user-role message) after this prompt already got its tool round: just answer.
+ if (messages.slice(promptAt + 1).some(m => m.role === 'assistant') && last.role === 'user') {
+ return say(['Noted: ', text(last).replace(/\s+/g, ' ').slice(0, 90)]);
+ }
+ const [count, ...script] = args.split(/\s+/);
+ const n = Math.max(1, Number(count) || 1);
+ send({ role: 'assistant', content: '', reasoning_content: `I will start ${n} helper agents.` });
+ await delay(chunkDelayMs);
+ for (let i = 0; i < n; i++) {
+ const argsJson = JSON.stringify({ description: `Helper ${i + 1}`, prompt: `SCRIPT:${script.join(' ') || 'echo done'} #${i + 1}` });
+ send({ tool_calls: [{ index: i, id: `call_${requests.length}_${i}`, type: 'function', function: { name: 'subagent', arguments: '' } }] });
+ for (let k = 0; k < argsJson.length; k += 23) { send({ tool_calls: [{ index: i, function: { arguments: argsJson.slice(k, k + 23) } }] }); await delay(2); }
+ }
+ return finish('tool_calls', 40 * n);
+ }
if (name === 'ask') {
send({ role: 'assistant', content: '' });
send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'ask_user_question', arguments: JSON.stringify({ questions: [{ id: 'q1', question: 'Which colour?', options: [{ label: 'Red' }, { label: 'Blue' }] }] }) } }] });